answer
stringlengths 17
10.2M
|
|---|
package org.mcupdater.instance;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Instance {
private String mcversion;
private String revision;
private String hash = "";
private List<FileInfo> instanceFiles = new ArrayList<>();
private List<FileInfo> jarMods = new ArrayList<>();
private Map<String, Boolean> optionalMods = new HashMap<>();
public List<FileInfo> getInstanceFiles() {
return instanceFiles;
}
public void setInstanceFiles(List<FileInfo> instanceFiles) {
this.instanceFiles = instanceFiles;
}
public Map<String, Boolean> getOptionalMods() {
return this.optionalMods;
}
public void setOptionalMods(Map<String,Boolean> optionalMods) {
this.optionalMods = optionalMods;
}
public Boolean getModStatus(String key) {
return this.optionalMods.get(key);
}
public void setModStatus(String key, Boolean value) {
this.optionalMods.put(key, value);
}
public String getMCVersion() {
return mcversion;
}
public void setMCVersion(String mcversion) {
this.mcversion = mcversion;
}
public String getRevision() {
return revision;
}
public void setRevision(String revision) {
this.revision = revision;
}
public List<FileInfo> getJarMods() {
return jarMods;
}
public void setJarMods(List<FileInfo> jarMods) {
this.jarMods = jarMods;
}
public FileInfo findJarMod(String id) {
for (FileInfo entry : this.jarMods) {
if (entry.getModId().equals(id)) {
return entry;
}
}
return null;
}
public void addJarMod(String id, String md5) {
FileInfo entry = new FileInfo();
entry.setModId(id);
entry.setMD5(md5);
this.jarMods.add(entry);
}
public void addMod(String id, String md5, String filename) {
FileInfo entry = new FileInfo();
entry.setModId(id);
entry.setMD5(md5);
entry.setFilename(filename);
this.instanceFiles.add(entry);
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
@Override
public String toString() {
StringBuilder serializer = new StringBuilder();
serializer.append("{");
serializer.append("mcversion:").append(this.mcversion).append(";");
serializer.append("revision:").append(this.revision).append(";");
serializer.append("hash:").append(this.hash).append(";");
serializer.append("instanceFiles:[");
for (FileInfo entry : instanceFiles) {
serializer.append(entry.toString()).append(";");
}
serializer.append("];");
serializer.append("jarMods:[");
for (FileInfo entry : jarMods) {
serializer.append(entry.toString()).append(";");
}
serializer.append("];");
serializer.append("optionalMods:[");
for (Map.Entry<String,Boolean> entry : optionalMods.entrySet()) {
serializer.append("{key:").append(entry.getKey()).append(";value:").append(entry.getValue().toString()).append("};");
}
serializer.append("];");
serializer.append("}");
return serializer.toString();
}
}
|
package org.minimalj.frontend.form;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.Frontend.FormContent;
import org.minimalj.frontend.Frontend.IComponent;
import org.minimalj.frontend.form.element.BigDecimalFormElement;
import org.minimalj.frontend.form.element.CheckBoxFormElement;
import org.minimalj.frontend.form.element.CodeFormElement;
import org.minimalj.frontend.form.element.Enable;
import org.minimalj.frontend.form.element.EnumFormElement;
import org.minimalj.frontend.form.element.EnumSetFormElement;
import org.minimalj.frontend.form.element.FormElement;
import org.minimalj.frontend.form.element.IntegerFormElement;
import org.minimalj.frontend.form.element.LocalDateFormElement;
import org.minimalj.frontend.form.element.LocalDateTimeFormElement;
import org.minimalj.frontend.form.element.LocalTimeFormElement;
import org.minimalj.frontend.form.element.LongFormElement;
import org.minimalj.frontend.form.element.PasswordFormElement;
import org.minimalj.frontend.form.element.SelectionFormElement;
import org.minimalj.frontend.form.element.SmallCodeListFormElement;
import org.minimalj.frontend.form.element.StringFormElement;
import org.minimalj.frontend.form.element.TextFormElement;
import org.minimalj.frontend.form.element.UnknownFormElement;
import org.minimalj.model.Code;
import org.minimalj.model.Keys;
import org.minimalj.model.Selection;
import org.minimalj.model.annotation.Enabled;
import org.minimalj.model.properties.ChainedProperty;
import org.minimalj.model.properties.Properties;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.model.validation.ValidationMessage;
import org.minimalj.security.model.Password;
import org.minimalj.util.ChangeListener;
import org.minimalj.util.CloneHelper;
import org.minimalj.util.Codes;
import org.minimalj.util.EqualsHelper;
import org.minimalj.util.ExceptionUtils;
import org.minimalj.util.FieldUtils;
import org.minimalj.util.mock.Mocking;
public class Form<T> {
private static Logger logger = Logger.getLogger(Form.class.getSimpleName());
public static final boolean EDITABLE = true;
public static final boolean READ_ONLY = false;
public static final int DEFAULT_COLUMN_WIDTH = 100;
public static final Object GROW_FIRST_ELEMENT = new Object();
protected final boolean editable;
private final int columns;
private final FormContent formContent;
private final LinkedHashMap<PropertyInterface, FormElement<?>> elements = new LinkedHashMap<>();
private final FormChangeListener formChangeListener = new FormChangeListener();
private ChangeListener<Form<?>> changeListener;
private boolean changeFromOutside;
private final Map<String, List<PropertyInterface>> dependencies = new HashMap<>();
@SuppressWarnings("rawtypes")
private final Map<PropertyInterface, Map<PropertyInterface, PropertyUpdater>> propertyUpdater = new HashMap<>();
private T object;
public Form() {
this(EDITABLE);
}
public Form(boolean editable) {
this(editable, 1);
}
public Form(int columns) {
this(EDITABLE, columns);
}
public Form(boolean editable, int columns) {
this(editable, columns, DEFAULT_COLUMN_WIDTH);
}
public Form(boolean editable, int columns, int columnWidth) {
this.editable = editable;
this.columns = columns;
this.formContent = Frontend.getInstance().createFormContent(columns, columnWidth);
}
// Methods to create the form
public FormContent getContent() {
return formContent;
}
protected FormElement<?> createElement(Object key) {
FormElement<?> element = null;
PropertyInterface property;
boolean forcedReadonly = false;
if (key instanceof ReadOnlyWrapper) {
forcedReadonly = true;
key = ((ReadOnlyWrapper) key).key;
}
if (key == null) {
throw new NullPointerException("Key must not be null");
} else if (key instanceof FormElement) {
element = (FormElement<?>) key;
property = element.getProperty();
if (property == null) throw new IllegalArgumentException(IComponent.class.getSimpleName() + " has no key");
} else {
property = Keys.getProperty(key);
if (property != null) {
boolean editable = !forcedReadonly && this.editable
&& !(FieldUtils.isAllowedPrimitive(property.getClazz()) && property.isFinal());
element = createElement(property, editable);
}
}
return element;
}
@SuppressWarnings("rawtypes")
protected FormElement<?> createElement(PropertyInterface property, boolean editable) {
Class<?> fieldClass = property.getClazz();
if (fieldClass == String.class) {
return editable ? new StringFormElement(property) : new TextFormElement(property);
} else if (fieldClass == Boolean.class) {
return new CheckBoxFormElement(property, editable);
} else if (fieldClass == Integer.class) {
return new IntegerFormElement(property, editable);
} else if (fieldClass == Long.class) {
return new LongFormElement(property, editable);
} else if (fieldClass == BigDecimal.class) {
return new BigDecimalFormElement(property, editable);
} else if (fieldClass == LocalDate.class) {
return new LocalDateFormElement(property, editable);
} else if (fieldClass == LocalTime.class) {
return new LocalTimeFormElement(property, editable);
} else if (fieldClass == LocalDateTime.class) {
return new LocalDateTimeFormElement(property, editable);
} else if (Code.class.isAssignableFrom(fieldClass)) {
return editable ? new CodeFormElement(property) : new TextFormElement(property);
} else if (Enum.class.isAssignableFrom(fieldClass)) {
return editable ? new EnumFormElement(property) : new TextFormElement(property);
} else if (fieldClass == Set.class) {
return new EnumSetFormElement(property, editable);
} else if (fieldClass == List.class && Codes.isCode(property.getGenericClass())) {
return new SmallCodeListFormElement(property, editable);
} else if (fieldClass == Password.class) {
return new PasswordFormElement(new ChainedProperty(property, Keys.getProperty(Password.$.getPassword())));
} else if (fieldClass == Selection.class) {
return new SelectionFormElement(property);
}
logger.severe("No FormElement could be created for: " + property.getName() + " of class " + fieldClass.getName());
return new UnknownFormElement(property);
}
public void line(Object... keys) {
if (keys[0] == GROW_FIRST_ELEMENT) {
assertColumnCount(keys.length - 1);
for (int i = 1; i < keys.length; i++) {
int elementSpan = i == 1 ? columns - keys.length + 2 : 1;
add(keys[i], elementSpan);
}
} else {
assertColumnCount(keys.length);
int span = columns / keys.length;
int rest = columns;
for (int i = 0; i < keys.length; i++) {
int elementSpan = i < keys.length - 1 ? span : rest;
add(keys[i], elementSpan);
rest = rest - elementSpan;
}
}
}
private void assertColumnCount(int elementCount) {
if (elementCount > columns) {
logger.severe("This form was constructed for " + columns + " column(s) but should be filled with " + elementCount + " form elements");
logger.fine("The solution is most probably to add/set the correct number of columns when calling the Form constructor");
throw new IllegalArgumentException("Not enough columns (" + columns + ") for form elements (" + elementCount + ")");
}
}
private void add(Object key, int elementSpan) {
FormElement<?> element = createElement(key);
if (element != null) {
add(element, elementSpan);
} else {
formContent.add(null, Frontend.getInstance().createText("" + key), null, elementSpan);
}
}
private void add(FormElement<?> element, int span) {
formContent.add(element.getCaption(), element.getComponent(), element.getConstraint(), span);
registerNamedElement(element);
addDependencies(element);
}
public static Object readonly(Object key) {
ReadOnlyWrapper wrapper = new ReadOnlyWrapper();
wrapper.key = key;
return wrapper;
}
private static class ReadOnlyWrapper {
private Object key;
}
public void addTitle(String text) {
IComponent label = Frontend.getInstance().createTitle(text);
formContent.add(null, label, null, -1);
}
/**
* Declares that if the <i>from</i> property changes all
* the properties with <i>to</i> could change. This is normally used
* if the to <i>to</i> property is a getter that calculates something that
* depends on the <i>from</i> in some way.
*
* @param from the key or property of the field triggering the update
* @param to the field possible changed its value implicitly
*/
public void addDependecy(Object from, Object... to) {
PropertyInterface fromProperty = Keys.getProperty(from);
if (!dependencies.containsKey(fromProperty.getPath())) {
dependencies.put(fromProperty.getPath(), new ArrayList<>());
}
List<PropertyInterface> list = dependencies.get(fromProperty.getPath());
for (Object key : to) {
list.add(Keys.getProperty(key));
}
}
private void addDependecy(PropertyInterface fromProperty, PropertyInterface to) {
addDependecy(fromProperty.getPath(), to);
}
private void addDependecy(String fromPropertyPath, PropertyInterface to) {
if (!dependencies.containsKey(fromPropertyPath)) {
dependencies.put(fromPropertyPath, new ArrayList<>());
}
List<PropertyInterface> list = dependencies.get(fromPropertyPath);
list.add(to);
}
/**
* Declares that if the key or property <i>from</i> changes the specified
* updater should be called and after its return the <i>to</i> key or property
* could have changed.<p>
*
* This is used if there is a more complex relation between two fields.
*
* @param <FROM> the type (class) of the fromKey / field
* @param <TO> the type (class) of the toKey / field
* @param from the field triggering the update
* @param updater the updater doing the change of the to field
* @param to the changed field by the updater
*/
public <FROM, TO> void addDependecy(FROM from, PropertyUpdater<FROM, TO, T> updater, TO to) {
PropertyInterface fromProperty = Keys.getProperty(from);
if (!propertyUpdater.containsKey(fromProperty)) {
propertyUpdater.put(fromProperty, new HashMap<>());
}
PropertyInterface toProperty = Keys.getProperty(to);
propertyUpdater.get(fromProperty).put(toProperty, updater);
addDependecy(from, to);
}
@FunctionalInterface
public interface PropertyUpdater<FROM, TO, EDIT_OBJECT> {
/**
*
* @param input The new value of the property that has changed
* @param copyOfEditObject The current object of the This reference should <b>not</b> be changed.
* It should be treated as a read only version or a copy of the object.
* It's probably not a real copy as it is to expensive to copy the object for every call.
* @return The new value the updater wants to set to the toKey property
*/
public TO update(FROM input, EDIT_OBJECT copyOfEditObject);
}
private void registerNamedElement(FormElement<?> field) {
elements.put(field.getProperty(), field);
field.setChangeListener(formChangeListener);
}
private void addDependencies(FormElement<?> field) {
PropertyInterface property = field.getProperty();
List<PropertyInterface> dependencies = Keys.getDependencies(property);
for (PropertyInterface dependency : dependencies) {
addDependecy(dependency, field.getProperty());
}
// a.b.c
String path = property.getPath();
while (path != null && path.contains(".")) {
int pos = path.lastIndexOf('.');
addDependecy(path.substring(0, pos), property);
path = path.substring(0, pos);
}
}
public final void mock() {
changeFromOutside = true;
try {
fillWithDemoData(object);
} catch (Exception x) {
logger.log(Level.SEVERE, "Fill with demo data failed", x);
} finally {
readValueFromObject();
changeFromOutside = false;
}
}
protected void fillWithDemoData(T object) {
for (FormElement<?> field : elements.values()) {
PropertyInterface property = field.getProperty();
if (field instanceof Mocking) {
Mocking demoEnabledElement = (Mocking) field;
demoEnabledElement.mock();
property.setValue(object, field.getValue());
}
}
}
/**
*
* @return Collection provided by a LinkedHashMap so it will be a ordered set
*/
public Collection<PropertyInterface> getProperties() {
return elements.keySet();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void set(PropertyInterface property, Object value) {
FormElement element = elements.get(property);
try {
element.setValue(value);
} catch (Exception x) {
ExceptionUtils.logReducedStackTrace(logger, x);
}
}
private void setValidationMessage(PropertyInterface property, List<String> validationMessages) {
FormElement<?> field = elements.get(property);
formContent.setValidationMessages(field.getComponent(), validationMessages);
}
public void setObject(T object) {
if (editable && changeListener == null) throw new IllegalStateException("Listener has to be set on a editable Form");
changeFromOutside = true;
this.object = object;
readValueFromObject();
changeFromOutside = false;
}
private void readValueFromObject() {
for (PropertyInterface property : getProperties()) {
Object propertyValue = property.getValue(object);
set(property, propertyValue);
}
updateEnable();
}
private String getName(FormElement<?> field) {
PropertyInterface property = field.getProperty();
return property.getName();
}
public void setChangeListener(ChangeListener<Form<?>> changeListener) {
this.changeListener = Objects.requireNonNull(changeListener);
}
private class FormChangeListener implements ChangeListener<FormElement<?>> {
@Override
public void changed(FormElement<?> changedField) {
if (changeFromOutside) return;
if (changeListener == null) {
if (editable) logger.severe("Editable Form must have a listener");
return;
}
logger.fine("ChangeEvent from " + getName(changedField));
PropertyInterface property = changedField.getProperty();
Object newValue = changedField.getValue();
HashSet<PropertyInterface> changedProperties = new HashSet<>();
setValue(property, newValue, changedProperties);
if (!changedProperties.isEmpty()) {
// don't need to update the form where the change comes from
changedProperties.remove(property);
// propagate all possible changed values to the form elements
updateDependingFormElements(changedProperties);
// update enable/disable status of the form elements
updateEnable();
changeListener.changed(Form.this);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void updateDependingFormElements(HashSet<PropertyInterface> changedProperties) {
for (PropertyInterface changedProperty : changedProperties) {
for (FormElement formElement : elements.values()) {
PropertyInterface formElementProperty = formElement.getProperty();
String formElementPath = formElementProperty.getPath();
String changedPropertyPath = changedProperty.getPath();
if (formElementPath.equals(changedPropertyPath) || formElementPath.startsWith(changedPropertyPath) && formElementPath.charAt(changedPropertyPath.length()) == '.') {
Object newValue = formElementProperty.getValue(object);
formElement.setValue(newValue);
}
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void executeUpdater(PropertyInterface property, Object updaterInput, Object clonedObject, HashSet<PropertyInterface> changedProperties) {
if (propertyUpdater.containsKey(property)) {
Map<PropertyInterface, PropertyUpdater> updaters = propertyUpdater.get(property);
for (Map.Entry<PropertyInterface, PropertyUpdater> entry : updaters.entrySet()) {
Object updaterOutput = entry.getValue().update(updaterInput, clonedObject);
setValue(entry.getKey(), updaterOutput, changedProperties);
}
}
}
private void setValue(PropertyInterface property, Object newValue, HashSet<PropertyInterface> changedProperties) {
Object oldToValue = property.getValue(object);
if (!EqualsHelper.equals(oldToValue, newValue)) {
Object clonedObject = CloneHelper.clone(object);
property.setValue(object, newValue);
executeUpdater(property, newValue, clonedObject, changedProperties);
addChangedPropertyRecurive(property, changedProperties);
}
}
private void addChangedPropertyRecurive(PropertyInterface property, HashSet<PropertyInterface> changedProperties) {
if (!changedProperties.contains(property)) {
changedProperties.add(property);
if (dependencies.containsKey(property.getName())) {
for (PropertyInterface dependingProperty : dependencies.get(property.getName())) {
addChangedPropertyRecurive(dependingProperty, changedProperties);
}
}
}
}
}
private void updateEnable() {
for (Map.Entry<PropertyInterface, FormElement<?>> element : elements.entrySet()) {
PropertyInterface property = element.getKey();
boolean enabled = true;
if (property instanceof ChainedProperty) {
enabled = isEnabled(object, (ChainedProperty) property);
} else {
Enabled enabledAnnotation = property.getAnnotation(Enabled.class);
enabled = enabledAnnotation == null || isEnabled(object, property, enabledAnnotation);
}
if (element.getValue() instanceof Enable) {
((Enable) element.getValue()).setEnabled(enabled);
} else if (!enabled) {
if (editable) {
logger.severe("element " + property.getPath() + " should implement Enable");
} else {
logger.fine("element " + property.getPath() + " should maybe implement Enable");
}
}
}
}
// TODO move to properties package, remove use of getPath, write tests
static boolean isEnabled(Object object, ChainedProperty property) {
String fieldPath = property.getPath();
while (fieldPath.contains(".")) {
if (object == null) {
return false;
}
int pos = fieldPath.indexOf(".");
PropertyInterface p2 = Properties.getProperty(object.getClass(), fieldPath.substring(0, pos));
Enabled enabledAnnotation = p2.getAnnotation(Enabled.class);
if (enabledAnnotation != null) {
if (!isEnabled(object, p2, enabledAnnotation)) {
return false;
}
}
object = p2.getValue(object);
fieldPath = fieldPath.substring(pos + 1);
}
return true;
}
// TODO move to properties package, write tests
static boolean isEnabled(Object object, PropertyInterface property, Enabled enabledAnnotation) {
String methodName = enabledAnnotation.value();
boolean invert = methodName.startsWith("!");
if (invert)
methodName = methodName.substring(1);
try {
Class<?> clazz = object.getClass();
Method method = clazz.getMethod(methodName);
if (!((Boolean) method.invoke(object) ^ invert)) {
return false;
}
} catch (Exception x) {
String fieldName = property.getName();
if (!fieldName.equals(property.getPath())) {
fieldName += " (" + property.getPath() + ")";
}
logger.log(Level.SEVERE, "Update enable of " + fieldName + " failed", x);
}
return true;
}
public boolean indicate(List<ValidationMessage> validationMessages) {
boolean relevantValidationMessage = false;
for (PropertyInterface property : getProperties()) {
List<String> filteredValidationMessages = ValidationMessage.filterValidationMessage(validationMessages, property);
setValidationMessage(property, filteredValidationMessages);
relevantValidationMessage |= !filteredValidationMessages.isEmpty();
}
return relevantValidationMessage;
}
}
|
package org.ocelotds.resolvers;
import org.ocelotds.spi.DataServiceException;
import org.ocelotds.spi.DataServiceResolver;
import org.ocelotds.spi.IDataServiceResolver;
import org.ocelotds.Constants;
import org.ocelotds.annotations.DataService;
import org.ocelotds.spi.Scope;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.naming.Binding;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Resolver of EJB
*
* @author hhfrancois
*/
@DataServiceResolver(Constants.Resolver.EJB)
public class EJBResolver implements IDataServiceResolver {
private static final Logger logger = LoggerFactory.getLogger(EJBResolver.class);
private static final Map<String, String> jndiMap = new HashMap<>();
private String jndiPath = "";
String getJndiPath() {
return jndiPath;
}
@Inject
private InitialContext initialContext;
@PostConstruct
void initJNDIPath() {
logger.debug("Initializing context ...");
try {
jndiPath = JndiConstant.PREFIX + (String) initialContext.lookup(JndiConstant.APP_NAME);
} catch (NamingException ex) {
logger.error("InitialContext initialisation Failed ", ex);
}
}
@Override
public <T> T resolveDataService(Class<T> clazz) throws DataServiceException {
return clazz.cast(resolveDataService(clazz.getName()));
}
private Object resolveDataService(String name) throws DataServiceException {
Object obj;
if (jndiMap.containsKey(name)) {
String jndi = jndiMap.get(name);
try {
obj = initialContext.lookup(jndi);
} catch (NamingException ex) {
throw new DataServiceException(name, ex);
}
} else {
obj = findEJB(jndiPath, name);
}
if (null == obj) {
throw new DataServiceException(name);
}
return obj;
}
private Object findEJB(String jndi, String name) {
Object result;
try {
NamingEnumeration<Binding> list = initialContext.listBindings(jndi);
while (list != null && list.hasMore()) {
try {
Binding item = list.next();
String itemName = item.getName();
if (itemName.endsWith(name)) {
try {
result = initialContext.lookup(jndi + JndiConstant.PATH_SEPARATOR + itemName);
if (result != null) {
jndiMap.put(name, jndi + JndiConstant.PATH_SEPARATOR + itemName);
}
return result;
} catch (NamingException e) {
logger.debug("{} list.next() {} : {}", new Object[]{e.getClass().getSimpleName(), name, e.getMessage()});
}
}
result = findEJB(jndi + JndiConstant.PATH_SEPARATOR + itemName, name);
if (result != null) {
return result;
}
} catch (NamingException e) {
logger.debug("{} list.next() {} : {}", new Object[]{e.getClass().getSimpleName(), name, e.getMessage()});
}
}
} catch (Throwable e) {
}
return null;
}
@Override
public Scope getScope(Class clazz) {
for (Annotation anno : clazz.getAnnotations()) {
if (!anno.annotationType().equals(DataService.class)) {
String annoName = anno.annotationType().getName();
switch (annoName) {
case "javax.ejb.Stateful":
return Scope.SESSION;
default:
}
}
}
return Scope.MANAGED;
}
private interface JndiConstant {
String PREFIX = "java:global/";
String APP_NAME = "java:app/AppName";
String PATH_SEPARATOR = "/";
}
}
|
package org.myrobotlab.service;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.myrobotlab.codec.CodecUtils;
import org.myrobotlab.framework.Instantiator;
import org.myrobotlab.framework.Message;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.image.Util;
import org.myrobotlab.logging.Appender;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.swing.ServiceGui;
import org.myrobotlab.swing.SwingGuiGui;
import org.myrobotlab.swing.Welcome;
import org.myrobotlab.swing.widget.AboutDialog;
import org.myrobotlab.swing.widget.Console;
import org.myrobotlab.swing.widget.DockableTab;
import org.myrobotlab.swing.widget.DockableTabPane;
import org.slf4j.Logger;
import com.mxgraph.model.mxCell;
import com.mxgraph.view.mxGraph;
public class SwingGui extends Service implements WindowListener, ActionListener, Serializable, DocumentListener {
private static final long serialVersionUID = 1L;
transient public final static Logger log = LoggerFactory.getLogger(SwingGui.class);
String graphXML = "";
boolean fullscreen;
public int closeTimeout = 0;
// TODO - make MTOD !! from internet
// TODO - spawn thread callback / subscribe / promise - for new version
transient JFrame frame;
transient DockableTabPane tabs;// is loaded = new DockableTabPane(this);
transient SwingGuiGui guiServiceGui;
transient JPanel tabPanel;
Map<String, String> userDefinedServiceTypeColors = new HashMap<String, String>();
/**
* the all important 2nd stage routing map after the message gets back to the
* gui service the 'rest' of the callback is handled with this data structure
*
* <pre>
* "serviceName.method" --> List<ServiceGui>
* Map<{name}.{method}, List<ServiceGui>>> nameMethodCallbackMap
*
* </pre>
*
* The same mechanism is employed in mrl.js to handle all call-backs to
* ServiceGui.js derived panels.
*
* FIXME / TODO ? - "Probably" should be Map<{name}, Map<{method}, List
* <ServiceGui>>>
*
*/
transient Map<String, List<ServiceGui>> nameMethodCallbackMap;
transient JTextField status = new JTextField("status:");
transient JButton statusClear = new JButton("clear");
transient final JTextField search = new JTextField();
boolean active = false;
/**
* used for "this" reference in anonymous swing utilities calls
*/
transient SwingGui self;
static public void attachJavaConsole() {
JFrame j = new JFrame("Java Console");
j.setSize(500, 550);
Console c = new Console();
j.add(c.getScrollPane());
j.setVisible(true);
c.startLogging();
}
static public void console() {
attachJavaConsole();
}
public static List<Component> getAllComponents(final Container c) {
Component[] comps = c.getComponents();
List<Component> compList = new ArrayList<Component>();
for (Component comp : comps) {
compList.add(comp);
if (comp instanceof Container)
compList.addAll(getAllComponents((Container) comp));
}
return compList;
}
public void setColor(String serviceType, String hexColor) {
userDefinedServiceTypeColors.put(serviceType, hexColor);
}
public static Color getColorFromURI(Object uri) {
StringBuffer sb = new StringBuffer(String.format("%d", Math.abs(uri.hashCode())));
Color c = new Color(Color.HSBtoRGB(Float.parseFloat("0." + sb.reverse().toString()), 0.8f, 0.7f));
return c;
}
public Color getColorHash(String uri) {
if (userDefinedServiceTypeColors.containsKey(uri)) {
// e.g. "#FFCCEE"
return Color.decode(userDefinedServiceTypeColors.get(uri));
}
StringBuffer sb = new StringBuffer(String.format("%d", Math.abs(uri.hashCode())));
Color c = new Color(Color.HSBtoRGB(Float.parseFloat("0." + sb.reverse().toString()), 0.4f, 0.95f));
return c;
}
static public void restart() {
JFrame frame = new JFrame();
frame.setLocationByPlatform(true);
int ret = JOptionPane.showConfirmDialog(frame, "<html>New components have been added,<br>" + " it is necessary to restart in order to use them.</html>", "restart",
JOptionPane.YES_NO_OPTION);
if (ret == JOptionPane.OK_OPTION) {
log.info("restarting");
// Runtime.restart(restartScript);
Runtime.getInstance().restart(); // <-- FIXME WRONG need to send
// message - may be remote !!
} else {
log.info("chose not to restart");
return;
}
}
public SwingGui(String n) {
super(n);
this.self = this;
status.setEditable(false);
if (tabs == null) {
tabs = new DockableTabPane(this);
} else {
tabs.setStateSaver(this);
}
log.info("tabs size {}", tabs.size());
for (String title : tabs.keySet()) {
DockableTab tab = tabs.get(title);
log.info("{} ({},{}) w={} h={}", title, tab.getX(), tab.getY(), tab.getWidth(), tab.getHeight());
}
// subscribe to services being added and removed
// we want to know about new services registered or released
// we create explicit mappings vs just [
// subscribe(Runtime.getRuntimeName(), "released") ]
// because we would 'mask' the Runtime's service subscriptions -
// intercept and mask them
// new service --go--> addTab
// remove service --go--> removeTab
subscribe(Runtime.getRuntimeName(), "released", getName(), "removeTab");
subscribe(Runtime.getRuntimeName(), "registered", getName(), "addTab");
}
public void about() {
new AboutDialog(this);
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
Object o = e.getSource();
if (statusClear == o) {
status.setForeground(Color.black);
status.setOpaque(false);
status.setText("status:");
}
if ("unhide all".equals(cmd)) {
unhideAll();
} else if ("hide all".equals(cmd)) {
hideAll();
} else if (cmd.equals(Appender.FILE)) {
Logging logging = LoggingFactory.getInstance();
logging.addAppender(Appender.FILE);
} else if (cmd.equals(Appender.NONE)) {
Logging logging = LoggingFactory.getInstance();
logging.addAppender(Appender.NONE);
} else if ("explode".equals(cmd)) {
explode();
} else if ("collapse".equals(cmd)) {
collapse();
} else if ("about".equals(cmd)) {
new AboutDialog(this);
// display();
} else {
log.info("unknown command {}", cmd);
}
}
/**
* add a service tab to the SwingGui
*
* @param sw
* - name of service to add
*
* FIXME - full parameter of addTab(final String serviceName, final
* String serviceType, final String lable) then overload
*/
synchronized public void addTab(final ServiceInterface sw) {
// scroll.addItem(sw.getName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String name = sw.getName();
// change tab color based on name
// it is better to add a new interfaced method I think ?
String guiClass = String.format("org.myrobotlab.swing.%sGui", sw.getClass().getSimpleName());
log.debug("createTab {} {}", name, guiClass);
ServiceGui newGui = null;
newGui = (ServiceGui) Instantiator.getNewInstance(guiClass, name, self);
if (newGui == null) {
log.info("could not construct a {} object - creating generic template", guiClass);
newGui = (ServiceGui) Instantiator.getNewInstance("org.myrobotlab.swing.NoGui", name, self);
}
// serviceGuiMap.put(name, newGui);
// subscribeToServiceMethod(name, newGui); - not needed as the key
// is "more" unique and called each time a subscribe
// is used by a ServiceGui
newGui.subscribeGui();
// state and status are both subscribed for the service here
// these are messages going to the services of interest
subscribe(name, "publishStatus");
subscribe(name, "publishState");
// this is preparing our routing map for callback
// so when we receive our callback message we know where to route it
subscribeToServiceMethod(String.format("%s.%s", name, CodecUtils.getCallBackName("publishStatus")), newGui);
subscribeToServiceMethod(String.format("%s.%s", name, CodecUtils.getCallBackName("publishState")), newGui);
// send a publishState to the service
// to initialize the ServiceGui - good for remote stuffs
send(name, "publishState");
if (getName().equals(name) && guiServiceGui == null) {
guiServiceGui = (SwingGuiGui) newGui;
guiServiceGui.rebuildGraph();
}
// newGui.getDisplay().setBackground(Color.CYAN);
tabs.addTab(name, newGui.getDisplay(), Runtime.getService(name).getDescription());
tabs.getTabs().setBackgroundAt(tabs.size() - 1, getColorHash(sw.getClass().getSimpleName()));
tabs.get(name).transitDockedColor = tabs.getTabs().getBackgroundAt(tabs.size() - 1);
// pack(); FIXED THE EVIL BLACK FROZEN GUI ISSUE !!!!
}
});
}
public JFrame createJFrame(boolean fullscreen) {
if (frame != null) {
frame.dispose();
}
frame = new JFrame();
if (!fullscreen) {
frame.addWindowListener(this);
frame.setTitle("myrobotlab - " + getName() + " " + Runtime.getVersion().trim());
frame.add(tabPanel);
URL url = getClass().getResource("/resource/mrl_logo_36_36.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
frame.setIconImage(img);
// menu
frame.setJMenuBar(createMenu());
frame.setVisible(true);
frame.pack();
} else {
frame.add(tabPanel);
frame.setJMenuBar(createMenu());
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setVisible(true);
}
return frame;
}
public void maximize() {
frame.setExtendedState( frame.getExtendedState() | JFrame.MAXIMIZED_BOTH );
}
/*
* Build the menu for display.
*/
public JMenuBar createMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu help = new JMenu("help");
JMenuItem about = new JMenuItem("about");
about.addActionListener(this);
help.add(about);
menuBar.add(search);
menuBar.add(Box.createHorizontalGlue());
menuBar.add(help);
search.getDocument().addDocumentListener(this);
// search.addActionListener(this);
return menuBar;
}
/*
* puts unique service.method and ServiceGui into map also in mrl.js
*
* the format of the key needs to be {name}.method
*
*/
public void subscribeToServiceMethod(String key, ServiceGui sg) {
List<ServiceGui> list = null;
if (nameMethodCallbackMap.containsKey(key)) {
list = nameMethodCallbackMap.get(key);
} else {
list = new ArrayList<ServiceGui>();
nameMethodCallbackMap.put(key, list);
}
boolean found = false;
for (int i = 0; i < list.size(); ++i) {
ServiceGui existingSg = list.get(i);
if (existingSg == sg) {
found = true;
}
}
if (!found) {
list.add(sg); // that was easy ;)
}
}
/*
* closes window and puts the panel back into the tabbed pane
*/
public void dockTab(final String title) {
tabs.dockTab(title);
}
public HashMap<String, mxCell> getCells() {
return guiServiceGui.serviceCells;
}
public String getDstMethodName() {
return guiServiceGui.dstMethodName.getText();
}
public String getDstServiceName() {
return guiServiceGui.dstServiceName.getText();
}
public JFrame getFrame() {
return frame;
}
public mxGraph getGraph() {
return guiServiceGui.graph;
}
public String getGraphXML() {
return graphXML;
}
public String getSrcMethodName() {
return guiServiceGui.srcMethodName.getText();
}
public String getSrcServiceName() {
return guiServiceGui.srcServiceName.getText();
}
/**
* set the main status bar with Status information
*
* @param inStatus
*/
public void setStatus(Status inStatus) {
if (inStatus.isError()) {
status.setOpaque(true);
status.setForeground(Color.white);
status.setBackground(Color.red);
} else if (inStatus.isWarn()) {
status.setOpaque(true);
status.setForeground(Color.black);
status.setBackground(Color.yellow);
} else {
status.setForeground(Color.black);
status.setOpaque(false);
}
if (inStatus.detail != null && inStatus.detail.length() > 128) {
status.setText(inStatus.detail.substring(128));
} else {
status.setText(inStatus.detail);
}
}
public void hideAll() {
log.info("hideAll");
for (String key : tabs.keySet()) {
hideTab(key);
}
}
public void hideTab(final String title) {
tabs.hideTab(title);
}
public void noWorky() {
// String img =
// SwingGui.class.getResource("/resource/expert.jpg").toString();
String logon = (String) JOptionPane.showInputDialog(getFrame(),
"<html>This will send your myrobotlab.log file<br><p align=center>to our crack team of experts,<br> please type your myrobotlab.org user</p></html>", "No Worky!",
JOptionPane.WARNING_MESSAGE, Util.getResourceIcon("expert.jpg"), null, null);
if (logon == null || logon.length() == 0) {
return;
}
try {
if (Runtime.noWorky(logon).isInfo()) {
JOptionPane.showMessageDialog(getFrame(), "log file sent, Thank you", "Sent !", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(getFrame(), "could not send log file :(", "DOH !", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(getFrame(), Service.stackToString(e1), "DOH !", JOptionPane.ERROR_MESSAGE);
}
}
public void pack() {
if (frame != null) {
frame.pack();
frame.repaint();
}
}
@Override
public boolean preProcessHook(Message m) {
// FIXME - problem with collisions of this service's methods
// and dialog methods ?!?!?
// if the method name is == to a method in the SwingGui
if (methodSet.contains(m.method)) {
// process the message like a regular service
return true;
}
// otherwise send the message to the dialog with the senders name
// key is now for callback is {name}.method
String key = String.format("%s.%s", m.sender, m.method);
List<ServiceGui> sgs = nameMethodCallbackMap.get(key);
if (sgs == null) {
log.error("attempting to update derived ServiceGui with - callback " + key + " not available in map " + getName());
} else {
// FIXME - NORMALIZE - Instantiator or Service - not both !!!
// Instantiator.invokeMethod(serviceGuiMap.get(m.sender), m.method,
// m.data);
for (int i = 0; i < sgs.size(); ++i) {
ServiceGui sg = sgs.get(i);
invokeOn(sg, m.method, m.data);
}
}
return false;
}
// FIXME - when a service is 'being' released Runtime should
// manage the releasing of the subscriptions !!!
synchronized public void removeTab(final ServiceInterface si) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String name = si.getName();
tabs.removeTab(name);
if (guiServiceGui != null) {
guiServiceGui.rebuildGraph();
}
frame.pack();
frame.repaint();
}
});
}
public void setArrow(String s) {
guiServiceGui.arrow0.setText(s);
}
public void setDstMethodName(String d) {
guiServiceGui.dstMethodName.setText(d);
}
public void setDstServiceName(String d) {
guiServiceGui.dstServiceName.setText(d);
}
public void setGraphXML(String xml) {
graphXML = xml;
}
public void setPeriod0(String s) {
guiServiceGui.period0.setText(s);
}
public void setPeriod1(String s) {
guiServiceGui.period1.setText(s);
}
public void setSrcMethodName(String d) {
guiServiceGui.srcMethodName.setText(d);
}
public void setSrcServiceName(String d) {
guiServiceGui.srcServiceName.setText(d);
}
@Override
synchronized public void startService() {
super.startService();
// FIXME - silly - some of these should be initialized in the constructor or
// before !!
if (!active) {
active = true;
nameMethodCallbackMap = new HashMap<String, List<ServiceGui>>();
// builds all the service tabs for the first time called when
// SwingGui
// starts
// add welcome table - weird - this needs to be involved in display
tabs.addTab("Welcome", new Welcome("welcome", this).getDisplay());
// subscribeToServiceMethod("Welcome", new Welcome("welcome", this,
// tabs));
/**
* pack() repaint() works on current selected (non-hidden) tab welcome is
* the first panel when the UI starts - therefore this controls the
* initial size .. however the largest panel typically at this point is
* the RuntimeGui - so we set it to the rough size of that panel
*/
Map<String, ServiceInterface> services = Runtime.getRegistry();
log.info("buildTabPanels service count " + Runtime.getRegistry().size());
TreeMap<String, ServiceInterface> sortedMap = new TreeMap<String, ServiceInterface>(services);
Iterator<String> it = sortedMap.keySet().iterator();
tabPanel = new JPanel(new BorderLayout());
tabPanel.add(tabs.getTabs(), BorderLayout.CENTER);
JPanel statusPanel = new JPanel(new BorderLayout());
statusPanel.add(status, BorderLayout.CENTER);
statusPanel.add(statusClear, BorderLayout.EAST);
tabPanel.add(statusPanel, BorderLayout.SOUTH);
statusClear.addActionListener(this);
status.setOpaque(true);
while (it.hasNext()) {
String serviceName = it.next();
addTab(Runtime.getService(serviceName));
}
// frame.repaint(); not necessary - pack calls repaint
// pick out a reference to our own gui
List<ServiceGui> sgs = nameMethodCallbackMap.get(getName());
if (sgs != null) {
for (int i = 0; i < sgs.size(); ++i) {
// another potential bug :(
guiServiceGui = (SwingGuiGui) sgs.get(i);
}
}
// create gui parts
createJFrame(fullscreen);
}
}
@Override
public void stopService() {
if (frame != null) {
frame.dispose();
}
active = false;
super.stopService();
}
public void explode() {
tabs.explode();
}
public void collapse() {
tabs.collapse();
}
public void fullscreen(boolean b) {
if (fullscreen != b) {
fullscreen = b;
createJFrame(b);
save(); // request to alter fullscreen
}
}
public void undockTab(final String title) {
tabs.undockTab(title);
}
public void unhideAll() {
log.info("unhideAll");
for (String key : tabs.keySet()) {
unhideTab(key);
}
}
// must handle docked or undocked & re-entrant for unhidden
public void unhideTab(final String title) {
tabs.unhideTab(title);
}
// @Override - only in Java 1.6
@Override
public void windowActivated(WindowEvent e) {
// log.info("windowActivated");
}
// @Override - only in Java 1.6
@Override
public void windowClosed(WindowEvent e) {
// log.info("windowClosed");
}
// @Override - only in Java 1.6
@Override
public void windowClosing(WindowEvent e) {
// save all necessary serializations
/**
* WRONG - USE ONLY RUNTIME TO SHUTDOWN !!! save(); Runtime.releaseAll();
* System.exit(1); // the Big Hamm'r
*/
Runtime.shutdown(closeTimeout);
}
// @Override - only in Java 1.6
@Override
public void windowDeactivated(WindowEvent e) {
// log.info("windowDeactivated");
}
// @Override - only in Java 1.6
@Override
public void windowDeiconified(WindowEvent e) {
// log.info("windowDeiconified");
}
// @Override - only in Java 1.6
@Override
public void windowIconified(WindowEvent e) {
// log.info("windowActivated");
}
// @Override - only in Java 1.6
@Override
public void windowOpened(WindowEvent e) {
// log.info("windowOpened");
}
public static void main(String[] args) throws ClassNotFoundException, URISyntaxException {
LoggingFactory.getInstance().configure();
Logging logging = LoggingFactory.getInstance();
try {
logging.setLevel(Level.INFO);
// Runtime.start("i01", "InMoov");
// Runtime.start("mac", "Runtime");
// Runtime.start("python", "Python");
// RemoteAdapter remote = (RemoteAdapter)Runtime.start("remote",
// "RemoteAdapter");
// remote.setDefaultPrefix("raspi");
// remote.connect("tcp://127.0.0.1:6767");
SwingGui gui = (SwingGui) Runtime.start("gui", "SwingGui");
// Runtime.start("python", "Python");
for (int i = 0; i < 40; ++i) {
Runtime.start(String.format("servo%d", i), "Servo");
}
} catch (Exception e) {
Logging.logError(e);
}
}
public void setActiveTab(String title) {
// we need to wait a little after Runtime.start to select an active tab
// TODO understand why we need a sleep(1000);
this.tabs.getTabs().setSelectedIndex(tabs.getTabs().indexOfTab(title));
}
/**
* 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(SwingGui.class.getCanonicalName());
meta.addDescription("Service used to graphically display and control other services");
meta.addCategory("display");
meta.includeServiceInOneJar(true);
meta.addDependency("com.fifesoft", "rsyntaxtextarea", "2.0.5.1");
meta.addDependency("com.fifesoft", "autocomplete", "2.0.5.1");
meta.addDependency("com.jidesoft", "jide-oss", "3.6.18");
meta.addDependency("com.mxgraph", "jgraphx", "1.10.4.2");
return meta;
}
public Component getDisplay() {
return (Component) tabs.getTabs();
}
public void setDesktop(String name) {
tabs.setDesktop(name);
}
public void resetDesktop(String name) {
tabs.resetDesktop(name);
}
@Override
public void changedUpdate(DocumentEvent e) {
// log.info("changedUpdate");
}
@Override
public void insertUpdate(DocumentEvent e) {
// log.info("insertUpdate");
Map<String, DockableTab> m = tabs.getDockableTabs();
String type = search.getText().toLowerCase();
for (DockableTab t : m.values()) {
if (t.getTitleLabel().getText().toString().toLowerCase().contains(type)) {
t.unhideTab();
} else {
t.hideTab();
}
}
}
@Override
public void removeUpdate(DocumentEvent e) {
String type = search.getText();
Map<String, DockableTab> m = tabs.getDockableTabs();
if (type == null || type.length() == 0) {
for (DockableTab t : m.values()) {
t.unhideTab();
}
}
}
}
|
package org.nnsoft.sameas4j.cache;
/**
* Simple cache interface for sameas service.
*/
public interface Cache {
/**
* Add a new entry in the cache.
*
* @param <T> The stored object type
* @param cacheKey The cache key
* @param cacheValue The stored object
*/
<T> void put(CacheKey cacheKey, T cacheValue);
/**
* Retrieves an object from the cache.
*
* @param <T> The stored object type
* @param cacheKey The cache key
* @param type The stored object
* @return The stored object if any, null otherwise
*/
<T> T get(CacheKey cacheKey, Class<T> type);
}
|
package org.folio.okapi.util;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import java.util.Collection;
import java.util.Collections;
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 org.folio.okapi.bean.InterfaceDescriptor;
import org.folio.okapi.bean.ModuleDescriptor;
import org.folio.okapi.bean.TenantModuleDescriptor;
import static org.folio.okapi.common.ErrorType.*;
import org.folio.okapi.common.ExtendedAsyncResult;
import org.folio.okapi.common.Failure;
import org.folio.okapi.common.Messages;
import org.folio.okapi.common.ModuleId;
import org.folio.okapi.common.OkapiLogger;
import org.folio.okapi.common.Success;
public class DepResolution {
private static Logger logger = OkapiLogger.get();
private static Messages messages = Messages.getInstance();
private DepResolution() {
throw new IllegalAccessError("DepResolution");
}
/**
* Check one dependency.
*
* @param md module to check
* @param req required dependency
* @param pInts the list to provided interface as returned by getProvidedInterfaces
* @return null if ok, or error message
*/
private static String checkOneDependency(ModuleDescriptor md, InterfaceDescriptor req,
Map<String, List<InterfaceDescriptor>> pInts, Collection<ModuleDescriptor> modList) {
Map<String, InterfaceDescriptor> seenVersions = new HashMap<>();
List<InterfaceDescriptor> pIntsList = pInts.get(req.getId());
if (pIntsList != null) {
for (InterfaceDescriptor pi : pIntsList) {
logger.debug("Checking dependency of " + md.getId() + ": "
+ req.getId() + " " + req.getVersion()
+ " against " + pi.getId() + " " + pi.getVersion());
if (req.getId().equals(pi.getId())) {
if (pi.isCompatible(req)) {
logger.debug("Dependency OK");
return null;
}
seenVersions.put(pi.getVersion(), pi);
}
}
}
if (seenVersions.isEmpty()) {
return messages.getMessage("10200", md.getId(), req.getId(), req.getVersion());
}
StringBuilder moduses = new StringBuilder();
for (InterfaceDescriptor seenVersion : seenVersions.values()) {
moduses.append(seenVersion.getVersion());
for (ModuleDescriptor mdi : modList) {
for (InterfaceDescriptor reqi : mdi.getRequiresList()) {
if (req.getId().equals(reqi.getId()) && seenVersion.isCompatible(reqi)) {
moduses.append("/");
moduses.append(mdi.getId());
}
}
}
}
return messages.getMessage("10201", md.getId(), req.getId(),
req.getVersion(), moduses.toString());
}
/**
* Check that the dependencies are satisfied.
*
* @param md Module to be checked
* @return empty list if if no problems, or list of error messages
*
* This could be done like we do conflicts, by building a map and checking
* against that...
*/
public static List<String> checkDependencies(ModuleDescriptor md,
Map<String, ModuleDescriptor> modList) {
return checkDependencies(md, modList, getProvidedInterfaces(modList.values()));
}
private static List<String> checkDependencies(ModuleDescriptor md,
Map<String, ModuleDescriptor> modlist, Map<String, List<InterfaceDescriptor>> pInts) {
List<String> list = new LinkedList<>(); // error messages (empty=no errors)
logger.debug("Checking dependencies of " + md.getId());
for (InterfaceDescriptor req : md.getRequiresList()) {
String res = checkOneDependency(md, req, pInts, modlist.values());
if (res != null) {
list.add(res);
}
}
return list;
}
private static Map<String, List<InterfaceDescriptor>> getProvidedInterfaces(Collection<ModuleDescriptor> modList) {
Map<String, List<InterfaceDescriptor>> pInts = new HashMap<>();
for (ModuleDescriptor md : modList) {
for (InterfaceDescriptor req : md.getProvidesList()) {
final String version = req.getVersion();
boolean found = false;
List<InterfaceDescriptor> iList = pInts.get(req.getId());
if (iList == null) {
iList = new LinkedList<>();
} else {
for (InterfaceDescriptor nInt : iList) {
String existingVersion = nInt.getVersion();
if (existingVersion.equals(version)) {
found = true;
}
}
}
if (!found) {
iList.add(req);
pInts.put(req.getId(), iList);
}
}
}
return pInts;
}
/**
* Check that all dependencies are satisfied. Usually called with a copy of
* the modules list, after making some change.
*
* @param modlist list to check
* @return error message, or "" if all is ok
*/
public static String checkAllDependencies(Map<String, ModuleDescriptor> modlist) {
Map<String, List<InterfaceDescriptor>> pInts = getProvidedInterfaces(modlist.values());
List<String> list = new LinkedList<>();
for (ModuleDescriptor md : modlist.values()) {
List<String> res = checkDependencies(md, modlist, pInts);
list.addAll(res);
}
if (list.isEmpty()) {
return "";
} else {
return String.join(". ", list);
}
}
/**
* Check a module list for conflicts.
*
* @param modlist modules to be checked
* @return error message listing conflicts, or "" if no problems
*/
public static String checkAllConflicts(Map<String, ModuleDescriptor> modlist) {
Map<String, String> provs = new HashMap<>(); // interface name to module name
List<String> conflicts = new LinkedList<>();
for (ModuleDescriptor md : modlist.values()) {
InterfaceDescriptor[] provides = md.getProvidesList();
for (InterfaceDescriptor mi : provides) {
if (mi.isRegularHandler()) {
String confl = provs.get(mi.getId());
if (confl == null || confl.isEmpty()) {
provs.put(mi.getId(), md.getId());
} else {
String msg = messages.getMessage("10202", mi.getId(), md.getId(), confl);
conflicts.add(msg);
}
}
}
}
return String.join(". ", conflicts);
}
private static TenantModuleDescriptor getNextTM(Map<String, ModuleDescriptor> modsEnabled,
List<TenantModuleDescriptor> tml) {
Iterator<TenantModuleDescriptor> it = tml.iterator();
TenantModuleDescriptor tm = null;
while (it.hasNext()) {
tm = it.next();
TenantModuleDescriptor.Action action = tm.getAction();
String id = tm.getId();
logger.info("getNextTM: loop id=" + id + " action=" + action.name());
if (action == TenantModuleDescriptor.Action.enable && !modsEnabled.containsKey(id)) {
logger.info("getNextMT: return tm for action=enable");
return tm;
}
if (action == TenantModuleDescriptor.Action.disable && modsEnabled.containsKey(id)) {
logger.info("getNextTM: return tm for action=disable");
return tm;
}
}
logger.info("getNextTM done null");
return null;
}
public static void installSimulate(Map<String, ModuleDescriptor> modsAvailable,
Map<String, ModuleDescriptor> modsEnabled,
List<TenantModuleDescriptor> tml,
Handler<ExtendedAsyncResult<Boolean>> fut) {
List<String> errors = new LinkedList<>();
for (TenantModuleDescriptor tm : tml) {
String id = tm.getId();
ModuleId moduleId = new ModuleId(id);
if (tm.getAction() == TenantModuleDescriptor.Action.enable) {
if (!moduleId.hasSemVer()) {
id = moduleId.getLatest(modsAvailable.keySet());
tm.setId(id);
}
if (!modsAvailable.containsKey(id)) {
errors.add(messages.getMessage("10801", id));
}
if (modsEnabled.containsKey(id)) {
tm.setAction(TenantModuleDescriptor.Action.uptodate);
}
}
if (tm.getAction() == TenantModuleDescriptor.Action.disable) {
if (!moduleId.hasSemVer()) {
id = moduleId.getLatest(modsEnabled.keySet());
tm.setId(id);
}
if (!modsEnabled.containsKey(id)) {
errors.add(messages.getMessage("10801", id));
}
}
}
if (!errors.isEmpty()) {
fut.handle(new Failure<>(USER, String.join(". ", errors)));
return;
}
final int lim = tml.size();
for (int i = 0; i <= lim; i++) {
logger.info("outer loop i=" + i + " tml.size=" + tml.size());
TenantModuleDescriptor tm = getNextTM(modsEnabled, tml);
if (tm == null) {
break;
}
if (tmAction(tm, modsAvailable, modsEnabled, tml, fut)) {
return;
}
}
String s = DepResolution.checkAllDependencies(modsEnabled);
if (!s.isEmpty()) {
logger.warn("installModules.checkAllDependencies: " + s);
fut.handle(new Failure<>(USER, s));
return;
}
logger.info("installModules.returning OK");
fut.handle(new Success<>(Boolean.TRUE));
}
private static boolean tmAction(TenantModuleDescriptor tm,
Map<String, ModuleDescriptor> modsAvailable,
Map<String, ModuleDescriptor> modsEnabled, List<TenantModuleDescriptor> tml,
Handler<ExtendedAsyncResult<Boolean>> fut) {
String id = tm.getId();
TenantModuleDescriptor.Action action = tm.getAction();
if (null == action) {
fut.handle(new Failure<>(INTERNAL, messages.getMessage("10404", "null")));
return true;
} else {
switch (action) {
case enable:
return tmEnable(id, modsAvailable, modsEnabled, tml, fut);
case uptodate:
return false;
case disable:
return tmDisable(id, modsAvailable, modsEnabled, tml, fut);
default:
fut.handle(new Failure<>(INTERNAL, messages.getMessage("10404", action.name())));
return true;
}
}
}
private static boolean tmEnable(String id, Map<String, ModuleDescriptor> modsAvailable,
Map<String, ModuleDescriptor> modsEnabled, List<TenantModuleDescriptor> tml,
Handler<ExtendedAsyncResult<Boolean>> fut) {
List<String> ret = addModuleDependencies(modsAvailable.get(id), modsAvailable,
modsEnabled, tml);
if (ret.isEmpty()) {
return false;
}
fut.handle(new Failure<>(USER, "enable " + id + " failed: " + String.join(". ", ret)));
return true;
}
private static boolean tmDisable(String id, Map<String, ModuleDescriptor> modsAvailable,
Map<String, ModuleDescriptor> modsEnabled, List<TenantModuleDescriptor> tml,
Handler<ExtendedAsyncResult<Boolean>> fut) {
List<String> ret = removeModuleDependencies(modsAvailable.get(id),
modsEnabled, tml);
if (ret.isEmpty()) {
return false;
}
fut.handle(new Failure<>(USER, "disable " + id + " failed: " + String.join(". ", ret)));
return true;
}
private static List<String> checkInterfaceDependency(ModuleDescriptor md, InterfaceDescriptor req,
Map<String, ModuleDescriptor> modsAvailable, Map<String, ModuleDescriptor> modsEnabled,
List<TenantModuleDescriptor> tml) {
List<String> ret = new LinkedList<>();
// check if already enabled
if (checkInterfaceDepAlreadyEnabled(modsEnabled, req)) {
return ret;
}
// check if mentioned already in other install action
ModuleDescriptor foundMd = checkInterfaceDepOtherInstall(tml, modsAvailable, req);
if (foundMd != null) {
return addModuleDependencies(foundMd, modsAvailable, modsEnabled, tml);
}
Map<String,ModuleDescriptor> productMd = checkInterfaceDepAvailable(modsAvailable, req);
if (productMd.isEmpty()) {
String s = "interface " + req.getId() + " required by module " + md.getId() + " not found";
ret.add(s);
return ret;
} else if (productMd.size() == 1) {
Set<String> s = productMd.keySet();
String k = s.iterator().next();
foundMd = productMd.get(k);
} else {
String s = "interface " + req.getId() + " required by module " + md.getId() + " is provided by multiple products: "
+ String.join(", ", productMd.keySet());
ret.add(s);
return ret;
}
return addModuleDependencies(foundMd, modsAvailable, modsEnabled, tml);
}
private static Map<String, ModuleDescriptor> checkInterfaceDepAvailable(Map<String, ModuleDescriptor> modsAvailable,
InterfaceDescriptor req) {
Set<String> replaceProducts = new HashSet<>();
Map<String, ModuleDescriptor> productMd = new HashMap<>();
for (Map.Entry<String, ModuleDescriptor> entry : modsAvailable.entrySet()) {
ModuleDescriptor md = entry.getValue();
String product = md.getProduct();
for (InterfaceDescriptor pi : md.getProvidesList()) {
if (pi.isRegularHandler() && pi.isCompatible(req)) {
if (md.getReplaces() != null) {
for (String replaceProduct : md.getReplaces()) {
replaceProducts.add(replaceProduct);
}
}
if (productMd.containsKey(product)) {
ModuleDescriptor fMd = productMd.get(product);
if (md.compareTo(fMd) > 0) {
productMd.put(product, md);
}
} else {
productMd.put(product, md);
}
}
}
}
for (String replaceProduct : replaceProducts) {
productMd.remove(replaceProduct);
}
return productMd;
}
private static ModuleDescriptor checkInterfaceDepOtherInstall(List<TenantModuleDescriptor> tml,
Map<String, ModuleDescriptor> modsAvailable, InterfaceDescriptor req) {
ModuleDescriptor foundMd = null;
Iterator<TenantModuleDescriptor> it = tml.iterator();
while (it.hasNext()) {
TenantModuleDescriptor tm = it.next();
ModuleDescriptor md = modsAvailable.get(tm.getId());
if (md != null && tm.getAction() == TenantModuleDescriptor.Action.enable) {
for (InterfaceDescriptor pi : md.getProvidesList()) {
if (pi.isRegularHandler() && pi.isCompatible(req)) {
it.remove();
logger.info("Dependency OK for existing enable id=" + md.getId());
foundMd = md;
}
}
}
}
return foundMd;
}
private static boolean checkInterfaceDepAlreadyEnabled(Map<String, ModuleDescriptor> modsEnabled, InterfaceDescriptor req) {
for (Map.Entry<String, ModuleDescriptor> entry : modsEnabled.entrySet()) {
ModuleDescriptor md = entry.getValue();
for (InterfaceDescriptor pi : md.getProvidesList()) {
if (pi.isRegularHandler() && pi.isCompatible(req)) {
logger.info("Dependency OK already enabled id=" + md.getId());
return true;
}
}
}
return false;
}
private static int resolveModuleConflicts(ModuleDescriptor md, Map<String, ModuleDescriptor> modsEnabled,
List<TenantModuleDescriptor> tml, List<ModuleDescriptor> fromModule) {
int v = 0;
Iterator<String> it = modsEnabled.keySet().iterator();
while (it.hasNext()) {
String runningmodule = it.next();
ModuleDescriptor rm = modsEnabled.get(runningmodule);
if (md.getProduct().equals(rm.getProduct())) {
logger.info("resolveModuleConflicts from " + runningmodule);
it.remove();
fromModule.add(rm);
v++;
} else {
for (InterfaceDescriptor pi : rm.getProvidesList()) {
if (pi.isRegularHandler()) {
String confl = pi.getId();
for (InterfaceDescriptor mi : md.getProvidesList()) {
if (mi.getId().equals(confl)
&& mi.isRegularHandler()
&& modsEnabled.containsKey(runningmodule)) {
logger.info("resolveModuleConflicts remove " + runningmodule);
TenantModuleDescriptor tm = new TenantModuleDescriptor();
tm.setAction(TenantModuleDescriptor.Action.disable);
tm.setId(runningmodule);
tml.add(tm);
it.remove();
v++;
}
}
}
}
}
}
return v;
}
private static void addOrReplace(List<TenantModuleDescriptor> tml, ModuleDescriptor md,
TenantModuleDescriptor.Action action, ModuleDescriptor fm) {
logger.info("addOrReplace md.id=" + md.getId());
Iterator<TenantModuleDescriptor> it = tml.iterator();
boolean found = false;
while (it.hasNext()) {
TenantModuleDescriptor tm = it.next();
if (tm.getAction().equals(action) && tm.getId().equals(md.getId())) {
it.remove();
} else if (fm != null && tm.getAction() == TenantModuleDescriptor.Action.enable && tm.getId().equals(fm.getId())) {
logger.info("resolveConflict .. patch id=" + md.getId());
tm.setId(md.getId());
found = true;
}
}
if (found) {
return;
}
TenantModuleDescriptor t = new TenantModuleDescriptor();
t.setAction(action);
t.setId(md.getId());
if (fm != null) {
t.setFrom(fm.getId());
}
tml.add(t);
}
private static List<String> addModuleDependencies(ModuleDescriptor md,
Map<String, ModuleDescriptor> modsAvailable, Map<String, ModuleDescriptor> modsEnabled,
List<TenantModuleDescriptor> tml) {
List<String> ret = new LinkedList<>();
logger.info("addModuleDependencies " + md.getId());
for (InterfaceDescriptor req : md.getRequiresList()) {
ret.addAll(checkInterfaceDependency(md, req, modsAvailable, modsEnabled, tml));
}
if (!ret.isEmpty()) {
return ret;
}
List<ModuleDescriptor> fromModule = new LinkedList<>();
resolveModuleConflicts(md, modsEnabled, tml, fromModule);
modsEnabled.put(md.getId(), md);
addOrReplace(tml, md, TenantModuleDescriptor.Action.enable, fromModule.isEmpty() ? null : fromModule.get(0));
return ret;
}
private static List<String> removeModuleDependencies(ModuleDescriptor md,
Map<String, ModuleDescriptor> modsEnabled,
List<TenantModuleDescriptor> tml) {
logger.info("removeModuleDependencies " + md.getId());
List<String> ret = new LinkedList<>();
if (modsEnabled.containsKey(md.getId())) {
InterfaceDescriptor[] provides = md.getProvidesList();
for (InterfaceDescriptor prov : provides) {
if (prov.isRegularHandler()) {
Iterator<String> it = modsEnabled.keySet().iterator();
while (it.hasNext()) {
String runningmodule = it.next();
ModuleDescriptor rm = modsEnabled.get(runningmodule);
InterfaceDescriptor[] requires = rm.getRequiresList();
for (InterfaceDescriptor ri : requires) {
if (prov.getId().equals(ri.getId())) {
ret.addAll(removeModuleDependencies(rm, modsEnabled, tml));
it = modsEnabled.keySet().iterator();
}
}
}
}
}
if (!ret.isEmpty()) {
return ret;
}
modsEnabled.remove(md.getId());
addOrReplace(tml, md, TenantModuleDescriptor.Action.disable, null);
}
return ret;
}
public static List<ModuleDescriptor> getLatestProducts(int limit, List<ModuleDescriptor> mdl) {
Collections.sort(mdl, Collections.reverseOrder());
Iterator<ModuleDescriptor> it = mdl.listIterator();
String product = "";
int no = 0;
while (it.hasNext()) {
ModuleDescriptor md = it.next();
if (!product.equals(md.getProduct())) {
product = md.getProduct();
no = 0;
} else if (no >= limit) {
it.remove();
}
no++;
}
return mdl;
}
}
|
package hudson.matrix;
import hudson.model.Build;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.Calendar;
import java.util.Map.Entry;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.Ancestor;
/**
* Execution of {@link MatrixConfiguration}.
*
* @author Kohsuke Kawaguchi
*/
public class MatrixRun extends Build<MatrixConfiguration,MatrixRun> {
public MatrixRun(MatrixConfiguration job) throws IOException {
super(job);
}
public MatrixRun(MatrixConfiguration job, Calendar timestamp) {
super(job, timestamp);
}
public MatrixRun(MatrixConfiguration project, File buildDir) throws IOException {
super(project, buildDir);
}
public String getDisplayName() {
StaplerRequest req = Stapler.getCurrentRequest();
if(req!=null) {
List<Ancestor> ancs = req.getAncestors();
for( int i=1; i<ancs.size(); i++) {
if(ancs.get(i).getObject()==this) {
if(ancs.get(i-1).getObject() instanceof MatrixBuild) {
return getParent().getCombination().toCompactString(getParent().getParent().getAxes());
}
}
}
}
return super.getDisplayName();
}
@Override
public Map<String,String> getBuildVariables() {
// pick up user axes
return new HashMap<String,String>(getParent().getCombination());
}
@Override
public MatrixConfiguration getParent() {// don't know why, but javac wants this
return super.getParent();
}
}
|
package org.scijava.io;
import java.io.IOException;
import org.scijava.event.EventService;
import org.scijava.io.event.DataOpenedEvent;
import org.scijava.io.event.DataSavedEvent;
import org.scijava.log.LogService;
import org.scijava.plugin.AbstractHandlerService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.service.Service;
/**
* Default implementation of {@link IOService}.
*
* @author Curtis Rueden
*/
@Plugin(type = Service.class)
public final class DefaultIOService
extends AbstractHandlerService<String, IOPlugin<?>> implements IOService
{
@Parameter
private LogService log;
@Parameter
private EventService eventService;
// -- IOService methods --
@Override
public IOPlugin<?> getOpener(final String source) {
for (final IOPlugin<?> handler : getInstances()) {
if (handler.supportsOpen(source)) return handler;
}
return null;
}
@Override
public <D> IOPlugin<D> getSaver(final D data, final String destination) {
for (final IOPlugin<?> handler : getInstances()) {
if (handler.supportsSave(data, destination)) {
@SuppressWarnings("unchecked")
final IOPlugin<D> typedHandler = (IOPlugin<D>) handler;
return typedHandler;
}
}
return null;
}
@Override
public Object open(final String source) throws IOException {
final IOPlugin<?> opener = getOpener(source);
if (opener == null) return null; // no appropriate IOPlugin
final Object data = opener.open(source);
if (data == null) return null; // IOPlugin returned no data; canceled?
eventService.publish(new DataOpenedEvent(source, data));
return data;
}
@Override
public void save(final Object data, final String destination)
throws IOException
{
IOPlugin<Object> saver = getSaver(data, destination);
if (saver != null) {
saver.save(data, destination);
}
eventService.publish(new DataSavedEvent(destination, data));
}
// -- HandlerService methods --
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Class<IOPlugin<?>> getPluginType() {
return (Class) IOPlugin.class;
}
@Override
public Class<String> getType() {
return String.class;
}
}
|
package org.tendiwa.inflectible;
/**
* Grammar of a natural language. Knows grammemes by their name.
* @author Georgy Vlasov (suseika@tendiwa.org)
* @version $Id$
* @since 0.1.0
*/
public interface Grammar {
/**
* Returns a grammeme by its name.
* @param name Name of a grammeme
* @return Grammeme
* @throws Exception If could not get grammeme with such name
*/
Grammeme grammemeByName(String name) throws Exception;
/**
* Returns a part of speech by its name.
* @param text Name of a part of speech
* @return Part of speech
* @throws Exception If could not get part of speech with such name
*/
PartOfSpeech partOfSpeechByName(String text) throws Exception;
}
|
package org.testng.internal;
import org.testng.IClass;
import org.testng.IMethodSelector;
import org.testng.IObjectFactory;
import org.testng.IObjectFactory2;
import org.testng.ITestObjectFactory;
import org.testng.TestNGException;
import org.testng.TestRunner;
import org.testng.annotations.IFactoryAnnotation;
import org.testng.annotations.IParametersAnnotation;
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import org.testng.collections.Sets;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.junit.IJUnitTestRunner;
import org.testng.log4testng.Logger;
import org.testng.xml.XmlTest;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
/**
* Utility class for different class manipulations.
*/
public final class ClassHelper {
private static final String JUNIT_TESTRUNNER= "org.testng.junit.JUnitTestRunner";
private static final String JUNIT_4_TESTRUNNER = "org.testng.junit.JUnit4TestRunner";
/** The additional class loaders to find classes in. */
private static final List<ClassLoader> classLoaders = new Vector<>();
private static final String CANNOT_INSTANTIATE_CLASS = "Cannot instantiate class ";
private static final String CLASS_HELPER = ClassHelper.class.getSimpleName();
private static final String SKIP_CALLER_CLS_LOADER = "skip.caller.clsLoader";
/**
* When given a file name to form a class name, the file name is parsed and divided
* into segments. For example, "c:/java/classes/com/foo/A.class" would be divided
* into 6 segments {"C:" "java", "classes", "com", "foo", "A"}. The first segment
* actually making up the class name is [3]. This value is saved in lastGoodRootIndex
* so that when we parse the next file name, we will try 3 right away. If 3 fails we
* will take the long approach. This is just a optimization cache value.
*/
private static int lastGoodRootIndex = -1;
/** Hide constructor. */
private ClassHelper() {
// Hide Constructor
}
/** Add a class loader to the searchable loaders. */
public static void addClassLoader(final ClassLoader loader) {
classLoaders.add(loader);
}
public static <T> T newInstance(Class<T> clazz) {
try {
return clazz.newInstance();
} catch(IllegalAccessException | InstantiationException | ExceptionInInitializerError | SecurityException e) {
throw new TestNGException(CANNOT_INSTANTIATE_CLASS + clazz.getName(), e);
}
}
public static <T> T newInstanceOrNull(Class<T> clazz) {
try {
Constructor<T> constructor = clazz.getConstructor();
return newInstance(constructor);
} catch(ExceptionInInitializerError | SecurityException e) {
throw new TestNGException(CANNOT_INSTANTIATE_CLASS + clazz.getName(), e);
} catch (NoSuchMethodException e) {
return null;
}
}
public static <T> T newInstance(Constructor<T> constructor, Object... parameters) {
try {
return constructor.newInstance(parameters);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new TestNGException(CANNOT_INSTANTIATE_CLASS + constructor.getDeclaringClass().getName(), e);
}
}
/**
* Tries to load the specified class using the context ClassLoader or if none,
* than from the default ClassLoader. This method differs from the standard
* class loading methods in that it does not throw an exception if the class
* is not found but returns null instead.
*
* @param className the class name to be loaded.
*
* @return the class or null if the class is not found.
*/
public static Class<?> forName(final String className) {
List<ClassLoader> allClassLoaders = Lists.newArrayList();
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null) {
allClassLoaders.add(contextClassLoader);
}
allClassLoaders.addAll(classLoaders);
for (ClassLoader classLoader : allClassLoaders) {
if (null == classLoader) {
continue;
}
try {
return classLoader.loadClass(className);
}
catch(ClassNotFoundException ex) {
// With additional class loaders, it is legitimate to ignore ClassNotFoundException
if (classLoaders.isEmpty()) {
logClassNotFoundError(className, ex);
}
}
}
if (Boolean.parseBoolean(System.getProperty(SKIP_CALLER_CLS_LOADER))) {
return null;
}
try {
return Class.forName(className);
}
catch(ClassNotFoundException cnfe) {
logClassNotFoundError(className, cnfe);
return null;
}
}
private static void logClassNotFoundError(String className, Exception ex) {
Utils.log(CLASS_HELPER, 2, "Could not instantiate " + className
+ " : Class doesn't exist (" + ex.getMessage() + ")");
}
/**
* For the given class, returns the method annotated with @Factory or null
* if none is found. This method does not search up the superclass hierarchy.
* If more than one method is @Factory annotated, a TestNGException is thrown.
* @param cls The class to search for the @Factory annotation.
* @param finder The finder (JDK 1.4 or JDK 5.0+) use to search for the annotation.
*
* @return the @Factory <CODE>methods</CODE>
*/
public static List<ConstructorOrMethod> findDeclaredFactoryMethods(Class<?> cls,
IAnnotationFinder finder) {
List<ConstructorOrMethod> result = new ArrayList<>();
for (Method method : getAvailableMethods(cls)) {
IFactoryAnnotation f = finder.findAnnotation(method, IFactoryAnnotation.class);
if (f != null) {
ConstructorOrMethod factory = new ConstructorOrMethod(method);
factory.setEnabled(f.getEnabled());
result.add(factory);
}
}
for (Constructor constructor : cls.getDeclaredConstructors()) {
IFactoryAnnotation f = finder.findAnnotation(constructor, IFactoryAnnotation.class);
if (f != null) {
ConstructorOrMethod factory = new ConstructorOrMethod(constructor);
factory.setEnabled(f.getEnabled());
result.add(factory);
}
}
return result;
}
/**
* Extract all callable methods of a class and all its super (keeping in mind
* the Java access rules).
*/
public static Set<Method> getAvailableMethods(Class<?> clazz) {
Map<String, Set<Method>> methods = Maps.newHashMap();
for (final Method declaredMethod : clazz.getDeclaredMethods()) {
appendMethod(methods, declaredMethod);
}
Class<?> parent = clazz.getSuperclass();
while (null != parent) {
Set<Map.Entry<String, Set<Method>>> extractedMethods = extractMethods(clazz, parent, methods).entrySet();
for (Map.Entry<String, Set<Method>> extractedMethod : extractedMethods){
Set<Method> m = methods.get(extractedMethod.getKey());
if (m == null) {
methods.put(extractedMethod.getKey(), extractedMethod.getValue());
} else {
m.addAll(extractedMethod.getValue());
}
}
parent = parent.getSuperclass();
}
Set<Method> returnValue = Sets.newHashSet();
for (Set<Method> each : methods.values()) {
returnValue.addAll(each);
}
return returnValue;
}
public static IJUnitTestRunner createTestRunner(TestRunner runner) {
IJUnitTestRunner tr = null;
try {
//try to get runner for JUnit 4 first
Class.forName("org.junit.Test");
Class<?> clazz = ClassHelper.forName(JUNIT_4_TESTRUNNER);
if (clazz != null) {
tr = (IJUnitTestRunner) clazz.newInstance();
tr.setTestResultNotifier(runner);
}
} catch (Throwable t) {
Utils.log(CLASS_HELPER, 2, "JUnit 4 was not found on the classpath");
try {
//fallback to JUnit 3
Class.forName("junit.framework.Test");
Class<?> clazz =ClassHelper.forName(JUNIT_TESTRUNNER);
if (clazz != null) {
tr = (IJUnitTestRunner) clazz.newInstance();
tr.setTestResultNotifier(runner);
}
} catch (Exception ex) {
Utils.log(CLASS_HELPER, 2, "JUnit 3 was not found on the classpath");
//there's no JUnit on the classpath
throw new TestNGException("Cannot create JUnit runner", ex);
}
} finally {
return tr;
}
}
private static void appendMethod(Map<String, Set<Method>> methods, Method declaredMethod) {
Set<Method> declaredMethods = methods.get(declaredMethod.getName());
if (declaredMethods == null) {
declaredMethods = Sets.newHashSet();
methods.put(declaredMethod.getName(), declaredMethods);
}
declaredMethods.add(declaredMethod);
}
private static Map<String, Set<Method>> extractMethods(Class<?> childClass, Class<?> clazz,
Map<String, Set<Method>> collected) {
Map<String, Set<Method>> methods = Maps.newHashMap();
Method[] declaredMethods = clazz.getDeclaredMethods();
Package childPackage = childClass.getPackage();
Package classPackage = clazz.getPackage();
boolean isSamePackage = isSamePackage(childPackage, classPackage);
for (Method method : declaredMethods) {
if (canInclude(isSamePackage, method, collected)) {
appendMethod(methods, method);
}
}
return methods;
}
private static boolean canInclude(boolean isSamePackage, Method method, Map<String, Set<Method>> collected) {
int methodModifiers = method.getModifiers();
boolean visible = (Modifier.isPublic(methodModifiers) || Modifier.isProtected(methodModifiers))
|| (isSamePackage && !Modifier.isPrivate(methodModifiers));
boolean hasNoInheritanceTraits = !isOverridden(method, collected) && !Modifier.isAbstract(methodModifiers);
return visible && hasNoInheritanceTraits;
}
private static boolean isSamePackage(Package childPackage, Package classPackage) {
boolean isSamePackage = false;
if ((null == childPackage) && (null == classPackage)) {
isSamePackage = true;
}
if ((null != childPackage) && (null != classPackage)) {
isSamePackage = childPackage.getName().equals(classPackage.getName());
}
return isSamePackage;
}
private static boolean isOverridden(Method method, Map<String, Set<Method>> methodsByName) {
Set<Method> collectedMethods = methodsByName.get(method.getName());
if (collectedMethods == null) {
return false;
}
Class<?> methodClass = method.getDeclaringClass();
Class<?>[] methodParams = method.getParameterTypes();
for (Method m: collectedMethods) {
Class<?>[] paramTypes = m.getParameterTypes();
if (methodClass.isAssignableFrom(m.getDeclaringClass()) && methodParams.length == paramTypes.length) {
boolean sameParameters = true;
for (int i= 0; i < methodParams.length; i++) {
if (!methodParams[i].equals(paramTypes[i])) {
sameParameters = false;
break;
}
}
if (sameParameters) {
return true;
}
}
}
return false;
}
public static IMethodSelector createSelector(org.testng.xml.XmlMethodSelector selector) {
try {
Class<?> cls = Class.forName(selector.getClassName());
return (IMethodSelector) cls.newInstance();
}
catch(Exception ex) {
throw new TestNGException("Couldn't find method selector : " + selector.getClassName(), ex);
}
}
/**
* Create an instance for the given class.
*/
public static Object createInstance(Class<?> declaringClass,
Map<Class<?>, IClass> classes,
XmlTest xmlTest,
IAnnotationFinder finder,
ITestObjectFactory objectFactory)
{
if (objectFactory instanceof IObjectFactory) {
return createInstance1(declaringClass, classes, xmlTest, finder,
(IObjectFactory) objectFactory);
} else if (objectFactory instanceof IObjectFactory2) {
return createInstance2(declaringClass, (IObjectFactory2) objectFactory);
} else {
throw new AssertionError("Unknown object factory type:" + objectFactory);
}
}
private static Object createInstance2(Class<?> declaringClass, IObjectFactory2 objectFactory) {
return objectFactory.newInstance(declaringClass);
}
public static Object createInstance1(Class<?> declaringClass,
Map<Class<?>, IClass> classes,
XmlTest xmlTest,
IAnnotationFinder finder,
IObjectFactory objectFactory) {
Object result = null;
try {
// Any annotated constructor?
Constructor<?> constructor = findAnnotatedConstructor(finder, declaringClass);
if (null != constructor) {
IParametersAnnotation parametersAnnotation = finder.findAnnotation(constructor, IParametersAnnotation.class);
if (parametersAnnotation != null) { // null if the annotation is @Factory
String[] parameterNames = parametersAnnotation.getValue();
Object[] parameters = Parameters.createInstantiationParameters(constructor,
"@Parameters",
finder,
parameterNames,
xmlTest.getAllParameters(),
xmlTest.getSuite());
result = objectFactory.newInstance(constructor, parameters);
}
}
// No, just try to instantiate the parameterless constructor (or the one
// with a String)
else {
// If this class is a (non-static) nested class, the constructor contains a hidden
// parameter of the type of the enclosing class
Class<?>[] parameterTypes = new Class[0];
Object[] parameters = new Object[0];
Class<?> ec = getEnclosingClass(declaringClass);
boolean isStatic = 0 != (declaringClass.getModifiers() & Modifier.STATIC);
// Only add the extra parameter if the nested class is not static
if ((null != ec) && !isStatic) {
parameterTypes = new Class[] { ec };
// Create an instance of the enclosing class so we can instantiate
// the nested class (actually, we reuse the existing instance).
IClass enclosingIClass = classes.get(ec);
Object[] enclosingInstances;
if (null != enclosingIClass) {
enclosingInstances = enclosingIClass.getInstances(false);
if ((null == enclosingInstances) || (enclosingInstances.length == 0)) {
Object o = objectFactory.newInstance(ec.getConstructor(parameterTypes));
enclosingIClass.addInstance(o);
enclosingInstances = new Object[] { o };
}
}
else {
enclosingInstances = new Object[] { ec.newInstance() };
}
Object enclosingClassInstance = enclosingInstances[0];
parameters = new Object[] { enclosingClassInstance };
} // isStatic
Constructor<?> ct;
try {
ct = declaringClass.getDeclaredConstructor(parameterTypes);
}
catch (NoSuchMethodException ex) {
ct = declaringClass.getDeclaredConstructor(String.class);
parameters = new Object[] { "Default test name" };
// If ct == null here, we'll pass a null
// constructor to the factory and hope it can deal with it
}
result = objectFactory.newInstance(ct, parameters);
}
}
catch (TestNGException ex) {
throw ex;
}
catch (NoSuchMethodException ex) {
//Empty catch block
}
catch (Throwable cause) {
// Something else went wrong when running the constructor
throw new TestNGException("An error occurred while instantiating class "
+ declaringClass.getName() + ": " + cause.getMessage(), cause);
}
if (result == null && ! Modifier.isPublic(declaringClass.getModifiers())) {
//result should not be null
throw new TestNGException("An error occurred while instantiating class "
+ declaringClass.getName() + ". Check to make sure it can be accessed/instantiated.");
}
return result;
}
/**
* Class.getEnclosingClass() only exists on JDK5, so reimplementing it
* here.
*/
private static Class<?> getEnclosingClass(Class<?> declaringClass) {
Class<?> result = null;
String className = declaringClass.getName();
int index = className.indexOf('$');
if (index != -1) {
String ecn = className.substring(0, index);
try {
result = Class.forName(ecn);
}
catch (ClassNotFoundException e) {
Logger.getLogger(ClassHelper.class).error(e.getMessage(),e);
}
}
return result;
}
/**
* Find the best constructor given the parameters found on the annotation
*/
private static Constructor<?> findAnnotatedConstructor(IAnnotationFinder finder,
Class<?> declaringClass) {
Constructor<?>[] constructors = declaringClass.getDeclaredConstructors();
for (Constructor<?> result : constructors) {
IParametersAnnotation parametersAnnotation = finder.findAnnotation(result, IParametersAnnotation.class);
if (parametersAnnotation != null) {
String[] parameters = parametersAnnotation.getValue();
Class<?>[] parameterTypes = result.getParameterTypes();
if (parameters.length != parameterTypes.length) {
throw new TestNGException("Parameter count mismatch: " + result + "\naccepts "
+ parameterTypes.length
+ " parameters but the @Test annotation declares "
+ parameters.length);
}
return result;
}
IFactoryAnnotation factoryAnnotation = finder.findAnnotation(result, IFactoryAnnotation.class);
if (factoryAnnotation != null) {
return result;
}
}
return null;
}
public static <T> T tryOtherConstructor(Class<T> declaringClass) {
T result;
try {
// Special case for inner classes
if (declaringClass.getModifiers() == 0) {
return null;
}
Constructor<T> ctor = declaringClass.getConstructor(String.class);
result = ctor.newInstance("Default test name");
}
catch (Exception e) {
String message = e.getMessage();
if ((message == null) && (e.getCause() != null)) {
message = e.getCause().getMessage();
}
String error = "Could not create an instance of class " + declaringClass
+ ((message != null) ? (": " + message) : "")
+ ".\nPlease make sure it has a constructor that accepts either a String or no parameter.";
throw new TestNGException(error);
}
return result;
}
/**
* Returns the Class object corresponding to the given name. The name may be
* of the following form:
* <ul>
* <li>A class name: "org.testng.TestNG"</li>
* <li>A class file name: "/testng/src/org/testng/TestNG.class"</li>
* <li>A class source name: "d:\testng\src\org\testng\TestNG.java"</li>
* </ul>
*
* @param file
* the class name.
* @return the class corresponding to the name specified.
*/
public static Class<?> fileToClass(String file) {
Class<?> result = null;
if(!file.endsWith(".class") && !file.endsWith(".java")) {
// Doesn't end in .java or .class, assume it's a class name
if (file.startsWith("class ")) {
file = file.substring("class ".length());
}
result = ClassHelper.forName(file);
if (null == result) {
throw new TestNGException("Cannot load class from file: " + file);
}
return result;
}
int classIndex = file.lastIndexOf(".class");
if (-1 == classIndex) {
classIndex = file.lastIndexOf(".java");
}
// Transforms the file name into a class name.
// Remove the ".class" or ".java" extension.
String shortFileName = file.substring(0, classIndex);
// Split file name into segments. For example "c:/java/classes/com/foo/A"
String[] segments = shortFileName.split("[/\\\\]", -1);
// Check if the last good root index works for this one. For example, if the previous
// name was "c:/java/classes/com/foo/A.class" then lastGoodRootIndex is 3 and we
// try to make a class name ignoring the first lastGoodRootIndex segments (3). This
// will succeed rapidly if the path is the same as the one from the previous name.
if (-1 != lastGoodRootIndex) {
StringBuilder className = new StringBuilder(segments[lastGoodRootIndex]);
for (int i = lastGoodRootIndex + 1; i < segments.length; i++) {
className.append(".").append(segments[i]);
}
result = ClassHelper.forName(className.toString());
if (null != result) {
return result;
}
}
// We haven't found a good root yet, start by resolving the class from the end segment
// and work our way up. For example, if we start with "c:/java/classes/com/foo/A"
// we'll start by resolving "A", then "foo.A", then "com.foo.A" until something
// resolves. When it does, we remember the path we are at as "lastGoodRoodIndex".
StringBuilder className = new StringBuilder();
for (int i = segments.length - 1; i >= 0; i
if (className.length() == 0) {
className.append(segments[i]);
}
else {
className.append(segments[i]).append(".").append(className);
}
result = ClassHelper.forName(className.toString());
if (null != result) {
lastGoodRootIndex = i;
break;
}
}
if (null == result) {
throw new TestNGException("Cannot load class from file: " + file);
}
return result;
}
}
|
package org.eclipse.jgit.revwalk;
import java.util.AbstractList;
/**
* An ordered list of {@link RevObject} subclasses.
*
* @param <E>
* type of subclass of RevObject the list is storing.
*/
public class RevObjectList<E extends RevObject> extends AbstractList<E> {
static final int BLOCK_SHIFT = 8;
static final int BLOCK_SIZE = 1 << BLOCK_SHIFT;
/**
* Items stored in this list.
* <p>
* If {@link Block#shift} = 0 this block holds the list elements; otherwise
* it holds pointers to other {@link Block} instances which use a shift that
* is {@link #BLOCK_SHIFT} smaller.
*/
protected Block contents = new Block(0);
/** Current number of elements in the list. */
protected int size = 0;
/** Create an empty object list. */
public RevObjectList() {
// Initialized above.
}
public void add(final int index, final E element) {
if (index != size)
throw new UnsupportedOperationException("Not add-at-end: " + index);
set(index, element);
size++;
}
public E set(int index, E element) {
Block s = contents;
while (index >> s.shift >= BLOCK_SIZE) {
s = new Block(s.shift + BLOCK_SHIFT);
s.contents[0] = contents;
contents = s;
}
while (s.shift > 0) {
final int i = index >> s.shift;
index -= i << s.shift;
if (s.contents[i] == null)
s.contents[i] = new Block(s.shift - BLOCK_SHIFT);
s = (Block) s.contents[i];
}
final Object old = s.contents[index];
s.contents[index] = element;
return (E) old;
}
public E get(int index) {
Block s = contents;
if (index >> s.shift >= 1024)
return null;
while (s != null && s.shift > 0) {
final int i = index >> s.shift;
index -= i << s.shift;
s = (Block) s.contents[i];
}
return s != null ? (E) s.contents[index] : null;
}
public int size() {
return size;
}
@Override
public void clear() {
contents = new Block(0);
size = 0;
}
/** One level of contents, either an intermediate level or a leaf level. */
protected static class Block {
final Object[] contents = new Object[BLOCK_SIZE];
final int shift;
Block(final int s) {
shift = s;
}
}
}
|
package sds.assemble.controlflow;
import java.util.Set;
import java.util.Comparator;
import java.util.concurrent.ConcurrentSkipListSet;
import sds.assemble.LineInstructions;
import sds.classfile.bytecode.OpcodeInfo;
/**
* This class is for node of control flow graph.
* @author inagaki
*/
public class CFNode {
private Set<CFNode> dominators;
private Set<CFEdge> parents;
private Set<CFEdge> children;
private CFNode immediateDominator;
private OpcodeInfo start;
private OpcodeInfo end;
CFNodeType nodeType;
/**
* constructor.
* @param inst instrcutions of a line.
*/
public CFNode(LineInstructions inst) {
this.nodeType = CFNodeType.getType(inst.getOpcodes());
Comparator<CFEdge> edgeComparator
= (CFEdge x, CFEdge y) -> (x.getDest().start.getPc() - y.getDest().start.getPc());
Comparator<CFNode> nodeComparator
= (CFNode x, CFNode y) -> (x.start.getPc() - y.start.getPc());
this.dominators = new ConcurrentSkipListSet<>(nodeComparator);
this.parents = new ConcurrentSkipListSet<>(edgeComparator);
this.children = new ConcurrentSkipListSet<>(edgeComparator);
this.start = inst.get(inst.getTable().getStartPc());
this.end = inst.get(inst.getTable().getEndPc());
}
/**
* returns node type.
* @return node type
*/
public CFNodeType getType() {
return nodeType;
}
/**
* adds parent node of this.
* @param parent parent node
*/
public void addParent(CFNode parent) {
if(!isRoot()) {
this.immediateDominator = parent;
} else {
if(immediateDominator != null && !immediateDominator.equals(parent)) {
this.immediateDominator = null;
}
if(!parents.contains(new CFEdge(this, parent))) {
parents.add(new CFEdge(this, parent));
}
}
}
/**
* adds child node of this.
* @param child child node
*/
public void addChild(CFNode child) {
CFEdge edge = new CFEdge(this, child);
children.add(edge);
}
/**
* returns whether this node exist dominator nodes.
* @return if this node exist dominator nodes, this method returns true.<br>
* Otherwise, this method returns false.
*/
public boolean existDominators() {
return !dominators.isEmpty();
}
/**
* returns whether specified pc is in range of opcode pc of this opcodes.
* @param pc index into code array
* @return if specified pc is in range of opcode pc, this method returns true.<br>
* Otherwise, this method returns false.
*/
public boolean isInPcRange(int pc) {
return start.getPc() <= pc && pc <= end.getPc();
}
/**
* returns whether this node is root.
* @return if this node is root, this method returns true.<br>
* Otherwise, this method returns false.
*/
public boolean isRoot() {
return immediateDominator == null && parents.isEmpty();
}
/**
* returns start opcode of instructions of this node.
* @return start opcode
*/
public OpcodeInfo getStart() {
return start;
}
/**
* returns end opcode of instructions of this node.
* @return end opcode
*/
public OpcodeInfo getEnd() {
return end;
}
}
|
package MWC.GUI.Shapes.Symbols.SVG;
import java.awt.Point;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import MWC.GUI.CanvasType;
import MWC.GUI.Shapes.Symbols.PlainSymbol;
import MWC.GUI.Shapes.Symbols.SymbolFactory;
import MWC.GenericData.WorldLocation;
import MWC.Utilities.Errors.Trace;
public class SVGShape extends PlainSymbol
{
private static final String SVG_SYMBOL_FOLDER = "svg_symbols";
/**
* Version ID.
*/
private static final long serialVersionUID = 1L;
/**
* our symbol type
*
*/
private final String _svgFileName;
/**
* Elements of the shape (Cache)
*/
private List<SVGElement> _elements;
/**
* True if we can rotate the SVG.
*/
private boolean _canRotate;
/**
* the origin, at which we centre the symbol
*
*/
private Point _origin;
/**
*
* @param svgFileName
* SVG File name without extension or path.
*/
public SVGShape(final String svgFileName)
{
_svgFileName = svgFileName;
}
public boolean canRotate()
{
return _canRotate;
}
public void setCanRotate(boolean _canRotate)
{
this._canRotate = _canRotate;
}
@Override
public String getType()
{
return _svgFileName;
}
@Override
public java.awt.Dimension getBounds()
{
final int sWid = (int) (getScaleVal());
return new java.awt.Dimension(10 * sWid, 10 * sWid);
}
@Override
public void paint(CanvasType dest, WorldLocation theCentre)
{
paint(dest, theCentre, .0);
}
@Override
public void paint(final CanvasType dest, final WorldLocation center,
final double direction)
{
if (_elements == null)
{
// get the XML document
final Document doc = getDocument();
if (doc != null)
{
// parse the XML document
_elements = parseDocument(doc);
}
}
// At this point, we have our file loaded (pre-cached)
if (_elements == null)
{
Trace.trace("Failed to parse SVG file for: " + _svgFileName);
}
else
{
double directionToUse = .0;
if (_canRotate)
{
directionToUse = direction;
}
// create our centre point
final Point centre = dest.toScreen(center);
for (SVGElement element : _elements)
{
element.render(dest, getScaleVal() / 2d, centre, directionToUse, _origin,
getColor());
}
}
}
/**
* Returns the Elements of the symbol
*
* @return
*/
public List<SVGElement> getElements()
{
return _elements;
}
/**
* retrieve the nodes from the SVG document
*
* @param doc
* @return
*/
private List<SVGElement> parseDocument(final Document doc)
{
final Element svgRoot = doc.getDocumentElement();
ArrayList<SVGElement> elements = new ArrayList<SVGElement>();
for (int i = 0; i < svgRoot.getChildNodes().getLength(); i++)
{
Node element = svgRoot.getChildNodes().item(i);
if (element.getNodeType() == Node.ELEMENT_NODE)
{
// check it's not the origin node
Node id = element.getAttributes().getNamedItem("id");
if (id != null && "origin".equals(id.getNodeValue()))
{
// ok, it's the origin marker. get the origin coords
parseOrigin(element);
// and determine if the shape should rotate
parseRotation(element);
}
else
{
SVGElement newElement = getInstance((Element) element);
// We are ignoring unknown elements for now.
if (newElement != null)
{
elements.add(newElement);
}
}
}
}
return elements;
}
private static SVGElement getInstance(final Element svgElement)
{
final SVGElement answer;
switch (svgElement.getNodeName())
{
case "rect":
answer = new SVGRectangle(svgElement);
break;
case "polygon":
answer = new SVGPoligon(svgElement);
break;
case "circle":
answer = new SVGCircle(svgElement);
break;
case "line":
answer = new SVGLine(svgElement);
break;
case "ellipse":
answer = new SVGEllipse(svgElement);
break;
case "polyline":
answer = new SVGPolyline(svgElement);
break;
default:
// We have an unknown type.
Trace.trace("Unknown SVG element type encountered:" + svgElement);
answer = null;
break;
}
return answer;
}
/**
* retrieve the SVG document
*
* @return
*/
private Document getDocument()
{
// remove the svg: prefix, if necesary
final String fName = _svgFileName.contains("svg:") ? _svgFileName
.substring(4) : _svgFileName;
final String filePath = "/" + fName + SymbolFactory.SVG_EXTENSION;
final String svgPath = filePath;
InputStream pluginResource = SVGShape.class.getResourceAsStream("/" + SVG_SYMBOL_FOLDER + filePath);
try (InputStream inputStream = pluginResource!=null ? pluginResource : SVGShape.class.getResourceAsStream(svgPath);) {
if (inputStream == null)
{
// Resource doesn't exist
Trace.trace(new FileNotFoundException(_svgFileName), "Failed to open SVG file " + _svgFileName + " from " + svgPath);
return null;
}
else
{
final DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
try
{
final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
final Document doc = dBuilder.parse(inputStream);
// read this -
doc.getDocumentElement().normalize();
return doc;
}
catch (ParserConfigurationException e)
{
Trace.trace(e, "While configuring parser");
return null;
}
catch (SAXException e)
{
Trace.trace(e, "While parsing SVG file");
return null;
}
}
}
catch (IOException e)
{
Trace.trace(e, "While reading document");
return null;
}
}
private void parseOrigin(Node element)
{
final int x = (int) Double.parseDouble(element.getAttributes().getNamedItem(
"cx").getNodeValue());
final int y = (int) Double.parseDouble(element.getAttributes().getNamedItem(
"cy").getNodeValue());
_origin = new Point(x, y);
}
private void parseRotation(Node element)
{
final String style = element.getAttributes().getNamedItem("style")
.getNodeValue();
if (style == null || style.length() == 0)
{
Trace.trace("Style parameter missing for " + _svgFileName);
}
else
{
final boolean rotates;
if ("fill: rgb(255, 0, 0);".equals(style))
{
// red - doesn't rotate
rotates = false;
}
else
{
// green = does rotate
rotates = true;
}
_canRotate = rotates;
}
}
@Override
public PlainSymbol create()
{
return new SVGShape(_svgFileName);
}
public static class SVGShapeTest extends junit.framework.TestCase
{
static public final String TEST_ALL_TEST_TYPE = "UNIT";
public SVGShapeTest(final String val)
{
super(val);
}
public void testLoadingFileDoesntExit()
{
final String fileDoesntExist = "fileDoesntExit";
SVGShape svgShape = new SVGShape(fileDoesntExist);
svgShape.paint(null, null, 0);
assertTrue(svgShape.getElements() == null);
}
}
}
|
package seedu.unburden.model;
import javafx.collections.ObservableList;
import seedu.unburden.model.tag.Tag;
import seedu.unburden.commons.exceptions.*;
import seedu.unburden.model.tag.UniqueTagList;
import seedu.unburden.model.task.ReadOnlyTask;
import seedu.unburden.model.task.Task;
import seedu.unburden.model.task.UniqueTaskList;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* Wraps all data at the address-book level
* Duplicates are not allowed (by .equals comparison)
*/
public class ListOfTask implements ReadOnlyListOfTask {
private final UniqueTaskList tasks;
private final UniqueTagList tags;
public static int todayCounter;
public static int tomorrowCounter;
public static int doneCounter;
public static int undoneCounter;
public static int overdueCounter;
private Calendar calendar = Calendar.getInstance();
private Calendar calendar_tmr = Calendar.getInstance();
//private Calendar calendar_nextWeek = Calendar.getInstance();
private static final SimpleDateFormat DATEFORMATTER = new SimpleDateFormat("dd-MM-yyyy");
{
tasks = new UniqueTaskList();
tags = new UniqueTagList();
}
public ListOfTask() {}
/**
* Persons and Tags are copied into this addressbook
*/
public ListOfTask(ReadOnlyListOfTask toBeCopied) {
this(toBeCopied.getUniqueTaskList(), toBeCopied.getUniqueTagList());
}
/**
* Persons and Tags are copied into this addressbook
*/
public ListOfTask(UniqueTaskList persons, UniqueTagList tags) {
resetData(persons.getInternalList(), tags.getInternalList());
}
public static ReadOnlyListOfTask getEmptyAddressBook() {
return new ListOfTask();
}
//// list overwrite operations
public ObservableList<Task> getTasks() {
return tasks.getInternalList();
}
public void setTasks(List<Task> tasks) {
this.tasks.getInternalList().setAll(tasks);
}
public void setTags(Collection<Tag> tags) {
this.tags.getInternalList().setAll(tags);
}
public void resetData(Collection<? extends ReadOnlyTask> newPersons, Collection<Tag> newTags) {
setTasks(newPersons.stream().map(t -> {
try {
return new Task(t);
} catch (IllegalValueException e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList()));
setTags(newTags);
}
public void resetData(ReadOnlyListOfTask newData) {
resetData(newData.getTaskList(), newData.getTagList());
Counter();
}
//// person-level operations
/**
* Adds a person to the address book.
* Also checks the new person's tags and updates {@link #tags} with any new tags found,
* and updates the Tag objects in the person to point to those in {@link #tags}.
*
* @throws UniqueTaskList.DuplicatePersonException if an equivalent person already exists.
*/
public void addTask(Task p) throws UniqueTaskList.DuplicateTaskException {
syncTagsWithMasterList(p);
tasks.add(p);
Counter();
}
/**
* Ensures that every tag in this person:
* - exists in the master list {@link #tags}
* - points to a Tag object in the master list
*/
private void syncTagsWithMasterList(Task task) {
final UniqueTagList taskTags = task.getTags();
tags.mergeFrom(taskTags);
// Create map with values = tag object references in the master list
final Map<Tag, Tag> masterTagObjects = new HashMap<>();
for (Tag tag : tags) {
masterTagObjects.put(tag, tag);
}
// Rebuild the list of person tags using references from the master list
final Set<Tag> commonTagReferences = new HashSet<>();
for (Tag tag : taskTags) {
commonTagReferences.add(masterTagObjects.get(tag));
}
task.setTags(new UniqueTagList(commonTagReferences));
}
public boolean removeTask(ReadOnlyTask key) throws UniqueTaskList.TaskNotFoundException {
if (tasks.remove(key)) {
Counter();
return true;
} else {
throw new UniqueTaskList.TaskNotFoundException();
}
}
//@@author A0139714B
public boolean editTask(ReadOnlyTask key, Task toEdit)
throws UniqueTaskList.TaskNotFoundException, IllegalValueException{
if (tasks.edit(key, toEdit)){
Counter();
return true;
}
else {
throw new UniqueTaskList.TaskNotFoundException();
}
}
//@@author A0143095H
public void doneTask(ReadOnlyTask key, boolean isDone){
tasks.done(key,isDone);
Counter();
}
//@@Gauri Joshi
//@@author A0143095H
public void undoneTask(ReadOnlyTask key, boolean isDone){
tasks.done(key,isDone);
Counter();
}
//// tag-level operations
public void addTag(Tag t) throws UniqueTagList.DuplicateTagException {
tags.add(t);
Counter();
}
//// util methods
@Override
public String toString() {
return tasks.getInternalList().size() + " Tasks, " + tags.getInternalList().size() + " tags";
// TODO: refine later
}
@Override
public List<ReadOnlyTask> getTaskList() {
return Collections.unmodifiableList(tasks.getInternalList());
}
@Override
public List<Tag> getTagList() {
return Collections.unmodifiableList(tags.getInternalList());
}
@Override
public UniqueTaskList getUniqueTaskList() {
return this.tasks;
}
@Override
public UniqueTagList getUniqueTagList() {
return this.tags;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof ListOfTask // instanceof handles nulls
&& this.tasks.equals(((ListOfTask) other).tasks)
&& this.tags.equals(((ListOfTask) other).tags));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(tasks, tags);
}
//@@author A0143095H
//Method counts the number of each type of tasks
public void Counter(){
int today = 0;
int tomorrow = 0;
int overdue = 0;
int done = 0;
int undone = 0;
calendar_tmr.setTime(calendar.getTime());
calendar_tmr.add(Calendar.DAY_OF_YEAR, 1);
// calendar_nextWeek.setTime(calendar.getTime());
// calendar_nextWeek.add(Calendar.WEEK_OF_YEAR, 1);
for(int i=0; i<tasks.getInternalList().size(); i++) {
if(tasks.getInternalList().get(i).getDone()){
done++;
}
if(!tasks.getInternalList().get(i).getDone()){
undone++;
}
//Checks if date of task matches the date "today" and ensures that task is still undone
if(tasks.getInternalList().get(i).getDate().getFullDate().equals(DATEFORMATTER.format(calendar.getTime())) && (tasks.getInternalList().get(i).getDone() == false)){
today++;
}
//Checks if date of task matches the date "tomorrow" and ensures that task is still undone
else if(tasks.getInternalList().get(i).getDate().getFullDate().equals(DATEFORMATTER.format(calendar_tmr.getTime())) && (tasks.getInternalList().get(i).getDone() == false)){
tomorrow++;
}
//Checks if date of task matches the date "next week" and ensures that task is still undone
// else if(tasks.getInternalList().get(i).getDate().getFullDate().equals(DATEFORMATTER.format(calendar_nextWeek.getTime())) && (tasks.getInternalList().get(i).getDone() == false)){
// nextWeek++;
else if(tasks.getInternalList().get(i).getOverdue()){
overdue++;
}
}
todayCounter = today;
tomorrowCounter = tomorrow;
overdueCounter = overdue;
doneCounter = done;
undoneCounter = undone;
}
}
|
package uk.ac.horizon.artcodes;
import android.accounts.AccountManager;
import android.app.Application;
import android.util.Log;
import com.google.android.gms.auth.GoogleAuthUtil;
import uk.ac.horizon.artcodes.account.Account;
import uk.ac.horizon.artcodes.account.AccountInfo;
import uk.ac.horizon.artcodes.account.AppEngineAccount;
import uk.ac.horizon.artcodes.account.LocalAccount;
import uk.ac.horizon.artcodes.source.ContentSource;
import uk.ac.horizon.artcodes.source.FileSource;
import uk.ac.horizon.artcodes.source.HTTPSource;
import java.util.ArrayList;
import java.util.List;
public final class Artcodes extends Application
{
private Account account;
@Override
public void onCreate()
{
super.onCreate();
GoogleAnalytics.initialize(this);
// TODO SharedPreferences
final List<AccountInfo> infos = getAccounts();
setAccount(infos.get(0).create());
}
public Account getAccount()
{
return account;
}
public List<AccountInfo> getAccounts()
{
final List<AccountInfo> result = new ArrayList<>();
final AccountManager manager = AccountManager.get(this);
final android.accounts.Account[] accounts = manager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
for(android.accounts.Account account: accounts)
{
result.add(new AppEngineAccount.Info(this, account.name));
}
result.add(new LocalAccount.Info(this));
return result;
}
public void setAccount(Account account)
{
this.account = account;
account.add(new ContentSource.Factory());
account.add(new HTTPSource.Factory());
account.add(new FileSource.Factory());
Log.i("", "Set account " + account.getInfo().getId());
}
//public List<Ac>
// public static File createImageLogFile()
// if(LOG_MARKER_IMAGE)
// final String title = "IMG_" + System.currentTimeMillis();
// final File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
// final File directory = new File(picturesDir, "Artcodes");
// if (!directory.exists())
// boolean success = directory.mkdir();
// return new File(directory, title + ".jpg");
// return null;
}
|
package util.driver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.util.Map;
import static environment.EnvironmentFactory.*;
public class CapabilitiesFactory {
private static DesiredCapabilities capabilities = new DesiredCapabilities();
public static DesiredCapabilities getCapabilities() {
if (isAndroid()) {
capabilities = getAndroidCapabilities();
} else if (isIOS()) {
capabilities = getIOSCapabilities();
} else if (isRemote()) {
capabilities = getRemoteDriverCapabilities();
}
return capabilities;
}
public static DesiredCapabilities updateCapabilities(DesiredCapabilities desiredCapabilities, Map<String, Object> mapCapabilities) {
if (mapCapabilities.size() > 0) {
for (Map.Entry<String, Object> capability : mapCapabilities.entrySet()) {
desiredCapabilities.setCapability(capability.getKey(), capability.getValue());
}
}
return desiredCapabilities;
}
private static DesiredCapabilities getCommonMobileCapabilities() {
capabilities.setCapability("automationName", getAutomationName());
capabilities.setCapability("platformVersion", getPlatformVersion());
capabilities.setCapability("deviceName", getDevice());
capabilities.setCapability("deviceOrientation", "portrait");
capabilities.setCapability("app", getApp());
capabilities.setCapability("browserName", getMobileBrowser());
capabilities.setCapability("appiumVersion", getAppiumVersion());
capabilities.setCapability("name", getName());
capabilities.setCapability("newCommandTimeout", getNewCommandTimeout());
return capabilities;
}
private static DesiredCapabilities getAndroidCapabilities() {
capabilities = getCommonMobileCapabilities();
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("appActivity", getAppActivity());
capabilities.setCapability("appPackage", getAppPackage());
return capabilities;
}
private static DesiredCapabilities getIOSCapabilities() {
capabilities = getCommonMobileCapabilities();
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("udid", getUDIDDevice());
capabilities.setCapability("waitForAppScript", true);
return capabilities;
}
private static DesiredCapabilities getRemoteDriverCapabilities() {
if (isFirefox()) {
capabilities = DesiredCapabilities.firefox();
} else if (isChrome()) {
capabilities = DesiredCapabilities.chrome();
} else if (isSafari()) {
capabilities = DesiredCapabilities.safari();
} else if (isInternetExplorer()) {
capabilities = DesiredCapabilities.internetExplorer();
}
if (getSlDesktopPlatform() != null) {
capabilities.setCapability("platform", getSlDesktopPlatform());
capabilities.setCapability("version", getSlBrowserVersion());
capabilities.setCapability("screenResolution", getSlDesktopResolution());
}
return capabilities;
}
}
|
package wong.spance.sparePool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* <br/>
* free<br/>
* StatementResultSetConnectionfree()<br/>
* -Connection,Statement,ResultSet.<br/>
* SparePool.shutdown()
*
* @author Spance Wong
* @version 0.1
* @since 2013/10/1
*/
public class SparePool {
private static SparePool INSTANCE;
private static Logger log = LoggerFactory.getLogger("SparePool.main");
private ConcurrentLinkedQueue<Connection> freePool;
private ConcurrentLinkedQueue<Connection> activePool;
private ConcurrentLinkedQueue<Thread> activeThread;
private Map<Connection, ConnectionDetail> detailMap;
private ThreadLocal<Connection> localConn;
private ReentrantLock lock;
private Condition isLack;
private volatile boolean isReady;
private AtomicInteger activeCount;
private AtomicInteger freeCount;
private AtomicInteger waitingCount;
private String url;
private String user;
private String password;
private int maxWait;
private int maxSize;
private int initSize;
private SparePool(Properties config) {
this.url = config.getProperty("url");
this.user = config.getProperty("username");
this.password = config.getProperty("password");
this.maxWait = toInt(config.getProperty("maxWait"), 30000) / 1000;
this.maxSize = 20;
this.initSize = 6;
this.freePool = new ConcurrentLinkedQueue<Connection>();
this.activePool = new ConcurrentLinkedQueue<Connection>();
this.activeThread = new ConcurrentLinkedQueue<Thread>();
this.detailMap = Collections.synchronizedMap(new HashMap<Connection, ConnectionDetail>());
this.localConn = new ThreadLocal<Connection>();
this.activeCount = new AtomicInteger(0);
this.freeCount = new AtomicInteger(0);
this.waitingCount = new AtomicInteger(0);
this.lock = new ReentrantLock();
this.isLack = this.lock.newCondition();
this.isReady = true;
}
public static synchronized void init(Properties config) {
if (INSTANCE != null) {
throw new IllegalStateException("already init");
}
INSTANCE = new SparePool(config);
try {
for (int i = 0; i < INSTANCE.initSize; i++) {
SparePool.getInstance().createConnection();
}
log.info("SparePool size={}", INSTANCE.initSize);
} catch (Exception e) {
log.error("SparePool ", e);
}
}
public static synchronized void shutdown() {
INSTANCE.isReady = false;
log.info(" SparePool{}", INSTANCE.statistics());
while (!INSTANCE.freePool.isEmpty()) {
Connection _conn = INSTANCE.freePool.poll();
INSTANCE.release(_conn);
}
while (!INSTANCE.activeThread.isEmpty()) {
Thread thread = INSTANCE.activeThread.poll();
thread.interrupt();
}
while (!INSTANCE.activePool.isEmpty()) {
Connection _conn = INSTANCE.activePool.poll();
INSTANCE.release(_conn);
}
INSTANCE = null;
log.debug("OK. Shutdown!");
/** System.gc(); */
}
/**
*
*
* @return
*/
public static SparePool getInstance() {
if (INSTANCE == null || !INSTANCE.isReady)
throw new IllegalStateException("pool is shutdown.");
return INSTANCE;
}
/**
*
*
* @return
*/
public Connection getConnection() throws SQLException {
if (!isReady)
throw new IllegalStateException("pool is shutdown.");
activeThread.offer(Thread.currentThread());
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
throw new DBException(e);
}
try {
Connection conn = localConn.get();
if (conn == null || conn.isClosed()) {
conn = getConnectionDirectly();
localConn.set(conn);
}
return conn;
} finally {
lock.unlock();
}
}
private Connection getConnectionDirectly() throws SQLException {
for (; ; ) {
if (activeCount.get() < maxSize || freeCount.get() > 0) {
Connection conn;
byte i = 1;
for (; ((conn = freePool.poll()) == null || conn.isClosed()) && i > 0; --i) {
this.createConnection();
}
if (conn != null) {
freeCount.decrementAndGet();
activePool.offer(conn);
activeCount.incrementAndGet();
ConnectionDetail cd = detailMap.get(conn);
assert cd != null;
cd.setInPool(false);
cd.setLastGetTime();
if (log.isDebugEnabled())
log.debug("(-) {}{}", i == 0 ? "reuse-old" : "create-new", statistics());
return conn;
}
throw new DBException("Can't create new Connection !!!");
} else {
waitingCount.incrementAndGet();
if (log.isDebugEnabled())
log.debug("before-await {}{}", Thread.currentThread(), statistics());
boolean await = false;
try {
await = isLack.await(maxWait, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new DBException(e);
}
if (await) {
waitingCount.decrementAndGet();
} else
throw new DBException("%d%ds!%s", maxSize, maxWait, statistics());
}
}
}
private void createConnection() throws SQLException {
Connection conn = DriverManager.getConnection(url, user, password);
if (conn != null) {
ConnectionDetail cd = new ConnectionDetail();
freePool.offer(new ConnectionWrapper(conn, cd).wrapper());
freeCount.incrementAndGet();
detailMap.put(conn, cd);
}
}
public static void freeLocal() {
INSTANCE.free();
}
public void free() {
Connection _conn = localConn.get();
if (_conn != null) {
localConn.remove();
release(_conn);
activeThread.remove(Thread.currentThread());
}
}
/**
*
*
* @param conn
*/
public void release(Connection conn) {
if (null == conn) return;
boolean available = isReady;
if (available) {
ConnectionDetail detail = detailMap.get(conn);
detail.closeAllStatement();
detail.setLastFreeTime();
detail.setInPool(true);
try {
if (!conn.isClosed())
conn.setAutoCommit(true);
else {
available = false;
detailMap.remove(conn);
log.warn("the connection closed in the external");
}
} catch (SQLException e) {
log.error("", e);
}
if (activePool.remove(conn))
activeCount.decrementAndGet();
if (available && freePool.offer(conn))
freeCount.incrementAndGet();
if (log.isDebugEnabled())
log.debug("(+) release into freePool{}", statistics());
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
throw new DBException(e);
}
try {
isLack.signal();
} finally {
lock.unlock();
}
} else { // kill connection
try {
detailMap.remove(conn);
conn.close();
} catch (SQLException e) {
log.warn("", e);
}
}
}
private String statistics() {
return String.format("; Stat{A/F/W=%d/%d/%d}",
activeCount.get(), /** permits.availablePermits(), */freeCount.get(), waitingCount.get());
}
/**
* Connection close Statement
*/
static class ConnectionWrapper implements InvocationHandler {
private final Connection conn;
private final ConnectionDetail connectionDetail;
private ConnectionWrapper(Connection conn, ConnectionDetail connectionDetail) {
this.conn = conn;
this.connectionDetail = connectionDetail;
}
private Connection wrapper() {
return (Connection) Proxy.newProxyInstance(
conn.getClass().getClassLoader(),
new Class[]{Connection.class},/** conn.getClass().getInterfaces(), */
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
if (methodName.equals("close") && INSTANCE.isReady) {
INSTANCE.release(conn);
return null;
}
if (methodName.equals("equals")) {
Object arg = args[0];
return Proxy.isProxyClass(arg.getClass()) ? proxy == arg : conn == arg || conn.equals(arg);
}
if (connectionDetail.isInPool() && !methodName.matches("(?:isClosed|close|hashCode|setAutoCommit)"))
throw new DBException("Can't call method[%s] when the Connection has been recovered!", methodName);
Class<?> returnType = method.getReturnType();
Object obj = null;
try {
obj = method.invoke(conn, args);
if (returnType != null && Statement.class.isAssignableFrom(returnType) && obj != null) {
connectionDetail.markStatement((Statement) obj);
return new StatementWrapper((Statement) obj, connectionDetail).wrapper();
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
/**
* Statement close ResultSet
*/
static class StatementWrapper implements InvocationHandler {
private final ConnectionDetail connectionDetail;
private final Statement statement;
private StatementWrapper(Statement statement, ConnectionDetail connectionDetail) {
this.statement = statement;
this.connectionDetail = connectionDetail;
}
private Statement wrapper() {
return (Statement) Proxy.newProxyInstance(
statement.getClass().getClassLoader(),
statement.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
if (methodName.equals("close")) {
connectionDetail.closeStatement(statement);
return null;
}
Class<?> returnType = method.getReturnType();
Object obj = null;
try {
obj = method.invoke(statement, args);
if (returnType != null && ResultSet.class.isAssignableFrom(returnType) && obj != null) {
connectionDetail.markResultSet(statement, (ResultSet) obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
public static int toInt(String property, int defaultValue) {
try {
if (property != null)
defaultValue = Integer.parseInt(property);
} catch (Exception ignored) {
}
return defaultValue;
}
}
|
package org.eclipse.birt.report.engine.adapter;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.script.JavascriptEvalUtil;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IDataQueryDefinition;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.olap.api.query.IBaseCubeQueryDefinition;
import org.eclipse.birt.report.data.adapter.api.DataAdapterUtil;
import org.eclipse.birt.report.data.adapter.api.DataRequestSession;
import org.eclipse.birt.report.data.adapter.api.DataSessionContext;
import org.eclipse.birt.report.data.adapter.api.IModelAdapter;
import org.eclipse.birt.report.data.adapter.impl.DataRequestSessionImpl;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.ir.Expression;
/**
* This class help to manipulate expressions.
*
*/
public final class ExpressionUtil
{
private static final String TOTAL_PREFIX = "TOTAL_COLUMN_";
private int totalColumnSuffix = 0;
private IModelAdapter adapter = null;
public ITotalExprBindings prepareTotalExpressions( List<Expression> exprs, IDataQueryDefinition queryDefn ) throws EngineException
{
return prepareTotalExpressions( exprs, null, queryDefn );
}
/**
*
* @param exprs
* @return
* @throws EngineException
*/
public ITotalExprBindings prepareTotalExpressions( List<Expression> exprs,
String groupName, IDataQueryDefinition queryDefn )
throws EngineException
{
TotalExprBinding result = new TotalExprBinding( );
List l = new ArrayList( );
boolean isCube = false;
if ( queryDefn instanceof IBaseCubeQueryDefinition )
{
isCube = true;
}
for ( int i = 0; i < exprs.size( ); i++ )
{
Expression expr = exprs.get( i );
result.addColumnBindings( l );
if ( expr == null )
{
result.addNewExpression( null );
}
else
{
switch ( expr.getType( ) )
{
case Expression.CONSTANT :
result.addNewExpression( expr );
break;
case Expression.SCRIPT :
String newExpr = prepareTotalExpression( expr
.getScriptText( ), l, groupName, isCube );
result.addColumnBindings( l );
expr.setScriptText( newExpr );
result.addNewExpression( expr );
break;
case Expression.CONDITIONAL :
addConditionalExprBindings( result,
(Expression.Conditional) expr, l, groupName,
isCube );
break;
default :
throw new IllegalStateException(
"invalid expression type:" + expr.getType( ) );
}
}
}
return result;
}
/**
* When a TopN/TopPercent/BottomN/BottomPercent ConditionalExpression is
* set, transform it to
* Total.TopN/Total.TopPercent/Total.BottomN/Total.BottomPercent
* aggregations with "isTrue" operator.
*
* @param ce
* @return
*/
public static IConditionalExpression transformConditionalExpression(
IConditionalExpression ce )
{
boolean needTransform = false;
switch ( ce.getOperator( ) )
{
case IConditionalExpression.OP_TOP_N :
case IConditionalExpression.OP_BOTTOM_N :
case IConditionalExpression.OP_TOP_PERCENT :
case IConditionalExpression.OP_BOTTOM_PERCENT :
needTransform = true;
break;
default:
needTransform = false;
break;
}
if( needTransform )
{
ce = new ToBeTransformTopBottomConditionalExpression( ce.getExpression( ),
ce.getOperator( ),
ce.getOperand1( ),
ce.getOperand2( ) );
}
return ce;
}
/**
* @param result
* @param key
* @throws EngineException
*/
private void addConditionalExprBindings( TotalExprBinding result,
Expression.Conditional key, List bindings, String groupName, boolean isCube ) throws EngineException
{
try
{
IConditionalExpression ce = key.getConditionalExpression( );
if ( !hasAggregationInFilter( ce ) && !(ce instanceof ToBeTransformTopBottomConditionalExpression) )
{
result.addNewExpression( key );
return;
}
if ( groupName != null )
ce.setGroupName( groupName );
String bindingName = TOTAL_PREFIX + totalColumnSuffix;
totalColumnSuffix++;
if( ce instanceof ToBeTransformTopBottomConditionalExpression)
{
List allColumnBindings = new ArrayList( );
allColumnBindings.add( ((ToBeTransformTopBottomConditionalExpression)ce).transform( bindingName, groupName ) );
result.addColumnBindings( allColumnBindings );
result.addNewExpression(Expression.newScript( org.eclipse.birt.core.data.ExpressionUtil
.createJSRowExpression( bindingName ) ));
return;
}
Binding columnBinding = new Binding( bindingName, ce );
if ( groupName != null )
{
columnBinding.addAggregateOn( groupName );
}
List allColumnBindings = new ArrayList( );
allColumnBindings.add( columnBinding );
result.addColumnBindings( allColumnBindings );
if ( !isCube )
{
String script = org.eclipse.birt.core.data.ExpressionUtil
.createJSRowExpression( bindingName );
result.addNewExpression( Expression.newScript( script ) );
}
else
{
String script = org.eclipse.birt.core.data.ExpressionUtil
.createJSDataExpression( bindingName );
result.addNewExpression( Expression.newScript( script ) );
}
}
catch ( DataException e )
{
throw new EngineException( e );
}
}
/**
*
* @param expr
* @return
*/
private boolean hasAggregationInFilter( IBaseExpression expr )
{
if ( expr == null )
return false;
if ( expr instanceof IScriptExpression )
{
return org.eclipse.birt.core.data.ExpressionUtil.hasAggregation( ( (ScriptExpression) expr ).getText( ) );
}
else if ( expr instanceof IConditionalExpression )
{
IConditionalExpression ce = (IConditionalExpression) expr;
if ( hasAggregationInFilter( ce.getExpression( ) ) )
{
return true;
}
if ( hasAggregationInFilter( ce.getOperand1( ) ) )
{
return true;
}
if ( hasAggregationInFilter( ce.getOperand2( ) ) )
{
return true;
}
}
return false;
}
/**
* Translate the old expression with "row" as indicator to new expression
* using "dataSetRow" as indicator.
*
* @param oldExpression
* @return
* @throws DataException
*/
private String prepareTotalExpression( String oldExpression,
List columnBindings, String groupName, boolean isCube ) throws EngineException
{
try
{
if ( oldExpression == null )
return null;
char[] chars = oldExpression.toCharArray( );
// 5 is the minium length of expression that can cantain a row
// expression
if ( chars.length < 8 )
return oldExpression;
else
{
ParseIndicator indicator = new ParseIndicator( 0,
0,
false,
false,
true,
true );
for ( int i = 0; i < chars.length; i++ )
{
indicator = getParseIndicator( chars,
i,
indicator.omitNextQuote( ),
indicator.getCandidateKey1( ),
indicator.getCandidateKey2( ) );
i = indicator.getNewIndex( );
if ( i >= indicator.getRetrieveSize( ) + 6 )
{
if ( indicator.isCandidateKey( )
&& chars[i - indicator.getRetrieveSize( ) - 6] == 'T'
&& chars[i - indicator.getRetrieveSize( ) - 5] == 'o'
&& chars[i - indicator.getRetrieveSize( ) - 4] == 't'
&& chars[i - indicator.getRetrieveSize( ) - 3] == 'a'
&& chars[i - indicator.getRetrieveSize( ) - 2] == 'l'
&& chars[i - indicator.getRetrieveSize( ) - 1] == '.' )
{
if ( i - indicator.getRetrieveSize( ) - 7 <= 0
|| isValidProceeding( chars[i
- indicator.getRetrieveSize( ) - 7] ) )
{
String firstPart = oldExpression.substring( 0,
i - indicator.getRetrieveSize( ) - 6 );
int startIndex = i
- indicator.getRetrieveSize( ) - 6;
i = advanceToNextValidEncloser( chars, i );
String secondPart = "";
String name = "";
String expr = "";
if ( i < chars.length )
{
int endIndex = i + 1;
expr = oldExpression.substring( startIndex,
endIndex );
secondPart = prepareTotalExpression( oldExpression.substring( i
+ 1 - indicator.getRetrieveSize( ) ),
columnBindings,
groupName, isCube );
}
else
{
expr = oldExpression.substring( startIndex );
}
boolean shouldAddToList = true;
for ( int j = 0; j < columnBindings.size( ); j++ )
{
IBaseExpression expression = ( (IBinding) columnBindings.get( j ) ).getExpression( );
if ( expression instanceof IScriptExpression )
{
if ( oldExpression.equals( ( (IScriptExpression) expression ).getText( ) ) )
{
shouldAddToList = false;
name = ( (IBinding) columnBindings.get( j ) ).getBindingName( );
break;
}
}
}
if ( shouldAddToList )
{
name = TOTAL_PREFIX + totalColumnSuffix;
totalColumnSuffix++;
ScriptExpression se = new ScriptExpression( expr );
se.setGroupName( groupName );
Binding columnBinding = new Binding( name, se );
columnBindings.add( columnBinding );
}
String newExpression = null;
if ( !isCube )
{
newExpression = firstPart
+ org.eclipse.birt.core.data.ExpressionUtil.createJSRowExpression( name )
+ secondPart;
}
else
{
newExpression = firstPart
+ org.eclipse.birt.core.data.ExpressionUtil.createJSDataExpression( name )
+ secondPart;
}
return newExpression;
}
}
}
}
}
return oldExpression;
}
catch ( DataException e )
{
throw new EngineException( e );
}
}
/**
*
* @param chars
* @param i
* @return
*/
private static int advanceToNextValidEncloser( char[] chars, int i )
{
boolean isTotalConstants = true;
int numberOfOpenBracket = 0;
while ( i < chars.length )
{
ParseIndicator pid = getParseIndicator( chars, i, false, true,true);
i = pid.getNewIndex( );
if( pid.isCandidateKey( ))
if ( chars[i] == '(' )
{
isTotalConstants = false;
numberOfOpenBracket ++;
}
if ( isTotalConstants )
{
if ( !isValidProceeding( chars[i] ) )
i++;
else
break;
}
else
{
if ( chars[i] != ')' )
i++;
else
{
if( chars[i] == ')')
{
numberOfOpenBracket
}
if( numberOfOpenBracket == 0)
{
break;
}else
{
i++;
}
}
}
}
if ( isTotalConstants )
i
return i;
}
/**
* This method is used to provide information necessary for next step parsing.
*
* @param chars
* @param i
* @param omitNextQuote
* @param candidateKey1
* @param candidateKey2
* @return
*/
private static ParseIndicator getParseIndicator( char[] chars, int i,
boolean omitNextQuote, boolean candidateKey1, boolean candidateKey2 )
{
int retrieveSize = 0;
if ( chars[i] == '/' )
{
if ( i > 0 && chars[i - 1] == '/' )
{
retrieveSize++;
while ( i < chars.length - 2 )
{
i++;
retrieveSize++;
if ( chars[i] == '\n' )
{
break;
}
}
retrieveSize++;
i++;
}
}
else if ( chars[i] == '*' )
{
if ( i > 0 && chars[i - 1] == '/' )
{
i++;
retrieveSize = retrieveSize + 2;
while ( i < chars.length - 2 )
{
i++;
retrieveSize++;
if ( chars[i - 1] == '*' && chars[i] == '/' )
{
break;
}
}
retrieveSize++;
i++;
}
}
if ( ( !omitNextQuote ) && chars[i] == '"' )
{
candidateKey1 = !candidateKey1;
if ( candidateKey1 )
candidateKey2 = true;
}
if ( ( !omitNextQuote ) && chars[i] == '\'' )
{
candidateKey2 = !candidateKey2;
if ( candidateKey2 )
candidateKey1 = true;
}
if ( chars[i] == '\\' )
omitNextQuote = true;
else
omitNextQuote = false;
return new ParseIndicator( retrieveSize,
i,
candidateKey1,
omitNextQuote,
candidateKey1,
candidateKey2 );
}
/**
* Test whether the char immediately before the candidate "row" key is
* valid.
*
* @param operator
* @return
*/
private static boolean isValidProceeding( char operator )
{
if ( ( operator >= 'A' && operator <= 'Z' )
|| ( operator >= 'a' && operator <= 'z' ) || operator == '_' )
return false;
return true;
}
private IScriptExpression adapterExpression(Expression expr)
{
if ( expr instanceof Expression.Script
&& "bre".equals( ( (Expression.Script) expr ).getLanguage( ) ) )
{
ScriptExpression scriptExpr = null;
try
{
scriptExpr = getModelAdapter( ).adaptJSExpression(
expr.getScriptText( ),
( (Expression.Script) expr ).getLanguage( ) );
}
catch ( Exception ex )
{
}
return new ScriptExpression( scriptExpr.getText( ) );
}
else
{
if ( expr.getType( ) == Expression.CONSTANT )
{
ScriptExpression jsExpr = new ScriptExpression(
JavascriptEvalUtil.transformToJsExpression( expr
.getScriptText( ) ) );
jsExpr.setConstant( true );
return jsExpr;
}
else
{
return new ScriptExpression( expr.getScriptText( ) );
}
}
}
public IConditionalExpression createConditionalExpression(
Expression testExpression, String operator, Expression value1,
Expression value2 )
{
IScriptExpression expr = null, tempV1 = null, tempV2 = null;
if ( testExpression != null )
{
expr = adapterExpression( testExpression );
}
if ( value1 != null )
{
tempV1 = adapterExpression( value1 );
}
if ( value2 != null )
{
tempV2 = adapterExpression( value2 );
}
ConditionalExpression expression = new ConditionalExpression( expr,
DataAdapterUtil.adaptModelFilterOperator( operator ), tempV1,
tempV2 );
return ExpressionUtil.transformConditionalExpression( expression );
}
public IConditionalExpression createConditionExpression(
Expression testExpression, String operator,
List<Expression> valueList )
{
ArrayList<IScriptExpression> values = new ArrayList<IScriptExpression>( valueList.size( ) );
for ( Expression expr : valueList )
{
values.add( adapterExpression( expr ) );
}
IScriptExpression expr = null;
if ( testExpression != null )
{
expr = adapterExpression( testExpression );
}
ConditionalExpression expression = new ConditionalExpression( expr,
DataAdapterUtil.adaptModelFilterOperator( operator ), values );
return ExpressionUtil.transformConditionalExpression( expression );
}
private IModelAdapter getModelAdapter( ) throws BirtException
{
if ( adapter == null )
{
DataRequestSession session = new DataRequestSessionImpl( new DataSessionContext( DataSessionContext.MODE_DIRECT_PRESENTATION ) );
adapter = session.getModelAdaptor( );
}
return adapter;
}
}
class TotalExprBinding implements ITotalExprBindings
{
private List newExprs;
private List columnBindings;
TotalExprBinding()
{
this.newExprs = new ArrayList();
this.columnBindings = new ArrayList();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.core.data.ITotalExprBindings#getNewExpression()
*/
public List getNewExpression( )
{
return this.newExprs;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.core.data.ITotalExprBindings#getColumnBindings()
*/
public IBinding[] getColumnBindings( )
{
IBinding[] result = new IBinding[columnBindings.size()];
for ( int i = 0; i < result.length; i++ )
{
result[i] = (IBinding) columnBindings.get( i );
}
return result;
}
public void addNewExpression( Object expr )
{
this.newExprs.add( expr );
}
public void addColumnBindings( List columnBindingList )
{
for( int i = 0; i < columnBindingList.size( ); i++ )
{
if( !this.columnBindings.contains( columnBindingList.get( i ) ))
{
this.columnBindings.add( columnBindingList.get( i ) );
}
}
}
}
/**
* A utility class for internal use only.
*
*/
class ParseIndicator
{
private int retrieveSize;
private int newIndex;
private boolean isCandidateKey;
private boolean omitNextQuote;
private boolean candidateKey1;
private boolean candidateKey2;
ParseIndicator( int retrieveSize, int newIndex, boolean isCandidateKey,
boolean omitNextQuote, boolean candidateKey1, boolean candidateKey2 )
{
this.retrieveSize = retrieveSize;
this.newIndex = newIndex;
this.isCandidateKey = isCandidateKey;
this.omitNextQuote = omitNextQuote;
this.candidateKey1 = candidateKey1;
this.candidateKey2 = candidateKey2;
}
public int getRetrieveSize( )
{
return this.retrieveSize;
}
public int getNewIndex( )
{
return this.newIndex;
}
public boolean isCandidateKey( )
{
return this.isCandidateKey;
}
public boolean omitNextQuote( )
{
return this.omitNextQuote;
}
public boolean getCandidateKey1( )
{
return this.candidateKey1;
}
public boolean getCandidateKey2( )
{
return this.candidateKey2;
}
}
|
package com.ibm.streamsx.topology.spl;
import static com.ibm.streamsx.topology.internal.core.InternalProperties.TK_DIRS;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.ibm.json.java.JSONObject;
import com.ibm.streams.operator.StreamSchema;
import com.ibm.streams.operator.Type.MetaType;
import com.ibm.streamsx.topology.TSink;
import com.ibm.streamsx.topology.Topology;
import com.ibm.streamsx.topology.TopologyElement;
import com.ibm.streamsx.topology.builder.BInputPort;
import com.ibm.streamsx.topology.builder.BOperatorInvocation;
import com.ibm.streamsx.topology.builder.BOutputPort;
import com.ibm.streamsx.topology.function.Supplier;
import com.ibm.streamsx.topology.internal.core.SourceInfo;
import com.ibm.streamsx.topology.internal.core.SubmissionParameter;
import com.ibm.streamsx.topology.internal.core.TSinkImpl;
/**
* Integration between Java topologies and SPL operator invocations. If the SPL
* operator to be invoked is an SPL Java primitive operator then the methods of
* {@link JavaPrimitive} should be used.
* <p>
* When necessary use {@code createValue(T, MetaType)}
* to create parameter values for SPL types.
* For example:
* <pre>{@code
* Map<String,Object> params = ...
* params.put("aInt32", 13);
* params.put("aUInt32", SPL.createValue(13, MetaType.UINT32));
* params.put("aRString", "some string value");
* params.put("aUString", SPL.createValue("some ustring value", MetaType.USTRING));
* ... = SPLPrimitive.invokeOperator(..., params);
* }</pre>
* <p>
* In addition to the usual Java types used for operator parameter values,
* a {@code Supplier<T>} parameter value may be specified.
* Submission time parameters are passed in this manner.
* See {@link #createSubmissionParameter(Topology, String, Object, boolean)}.
* For example:
* <pre>{@code
* Map<String,Object> params = ...
* params.put("aInt32", topology.createSubmissionParameter("int32Param", 13);
* params.put("aUInt32", SPL.createSubmissionParameter(topology, "uint32Param", SPL.createValue(13, MetaType.UINT32), true);
* params.put("aRString", topology.createSubmissionParameter("rstrParam", "some string value");
* params.put("aUString", SPL.createSubmissionParameter(topology, "ustrParam", SPL.createValue("some ustring value", MetaType.USTRING), true);
* params.put("aUInt8", SPL.createSubmissionParameter(topology, "uint8Param", SPL.createValue((byte)13, MetaType.UINT8), true);
* ... = SPLPrimitive.invokeOperator(..., params);
* }</pre>
*/
public class SPL {
public static <T> Object createValue(T value, MetaType metaType) {
return new SPLValue<T>(value, metaType).toJSON();
}
private static SPLValue<?> createSPLValue(Object paramValue) {
if (paramValue instanceof JSONObject) {
SPLValue<?> splValue = SPLValue.fromJSON((JSONObject) paramValue);
return splValue;
}
throw new IllegalArgumentException("param is not from createValue()");
}
public static <T> Supplier<T> createSubmissionParameter(Topology top,
String name, Object paramValue, boolean withDefault) {
SPLValue<?> splValue = createSPLValue(paramValue);
SubmissionParameter<T> sp = new SubmissionParameter<T>(name, splValue.toJSON(), withDefault);
top.builder().createSubmissionParameter(name, sp.toJSON());
return sp;
}
/**
* Create an SPLStream from the invocation of an SPL operator
* that consumes a stream.
*
* @param kind
* SPL kind of the operator to be invoked.
* @param input
* Stream that will be connected to the only input port of the
* operator
* @param outputSchema
* SPL schema of the operator's only output port.
* @param params
* Parameters for the SPL operator, ignored if it is null.
* @return SPLStream the represents the output of the operator.
*/
public static SPLStream invokeOperator(String kind, SPLInput input,
StreamSchema outputSchema, Map<String, ? extends Object> params) {
return invokeOperator(opNameFromKind(kind), kind, input,
outputSchema, params);
}
/**
* Create an SPLStream from the invocation of an SPL operator
* that consumes a stream.
*
* @param name Name for the operator invocation.
* @param kind
* SPL kind of the operator to be invoked.
* @param input
* Stream that will be connected to the only input port of the
* operator
* @param outputSchema
* SPL schema of the operator's only output port.
* @param params
* Parameters for the SPL operator, ignored if it is null.
* @return SPLStream the represents the output of the operator.
*/
public static SPLStream invokeOperator(String name, String kind,
SPLInput input,
StreamSchema outputSchema, Map<String, ? extends Object> params) {
BOperatorInvocation op = input.builder().addSPLOperator(name, kind, params);
SourceInfo.setSourceInfo(op, SPL.class);
SPL.connectInputToOperator(input, op);
BOutputPort stream = op.addOutput(outputSchema);
return new SPLStreamImpl(input, stream);
}
/**
* Connect an input to an operator invocation, including making the input
* windowed if it is an instance of SPLWindow.
*/
static BInputPort connectInputToOperator(SPLInput input,
BOperatorInvocation op) {
BInputPort inputPort = input.getStream().connectTo(op, false, null);
if (input instanceof SPLWindow) {
((SPLWindowImpl) input).windowInput(inputPort);
}
return inputPort;
}
/**
* Invocation an SPL operator that consumes a Stream.
*
* @param kind
* SPL kind of the operator to be invoked.
* @param input
* Stream that will be connected to the only input port of the
* operator
* @param params
* Parameters for the SPL operator, ignored if it is null.
* @return the sink element
*/
public static TSink invokeSink(String kind, SPLInput input,
Map<String, ? extends Object> params) {
return invokeSink(opNameFromKind(kind), kind, input, params);
}
/**
* Invocation an SPL operator that consumes a Stream.
*
* @param name
* Name of the operator
* @param kind
* SPL kind of the operator to be invoked.
* @param input
* Stream that will be connected to the only input port of the
* operator
* @param params
* Parameters for the SPL operator, ignored if it is null.
* @return the sink element
*/
public static TSink invokeSink(String name, String kind, SPLInput input,
Map<String, ? extends Object> params) {
BOperatorInvocation op = input.builder().addSPLOperator(name, kind,
params);
SourceInfo.setSourceInfo(op, SPL.class);
SPL.connectInputToOperator(input, op);
return new TSinkImpl(input.topology(), op);
}
private static String opNameFromKind(String kind) {
String opName;
if (kind.contains("::"))
opName = kind.substring(kind.lastIndexOf(':') + 1);
else
opName = kind;
return opName;
}
/**
* Invocation an SPL source operator to produce a Stream.
*
* @param te
* Reference to Topology the operator will be in.
* @param kind
* SPL kind of the operator to be invoked.
* @param params
* Parameters for the SPL operator.
* @param schema
* Schema of the output port.
* @return SPLStream the represents the output of the operator.
*/
public static SPLStream invokeSource(TopologyElement te, String kind,
Map<String, Object> params, StreamSchema schema) {
BOperatorInvocation splSource = te.builder().addSPLOperator(
opNameFromKind(kind), kind, params);
SourceInfo.setSourceInfo(splSource, SPL.class);
BOutputPort stream = splSource.addOutput(schema);
return new SPLStreamImpl(te, stream);
}
/**
* Add a dependency on an SPL toolkit.
* @param te Element within the topology.
* @param toolkitRoot Root directory of the toolkit.
* @throws IOException {@code toolkitRoot} is not a valid path.
*/
public static void addToolkit(TopologyElement te, File toolkitRoot) throws IOException {
@SuppressWarnings("unchecked")
Set<String> tks = (Set<String>) te.topology().getConfig().get(TK_DIRS);
if (tks == null) {
tks = new HashSet<>();
te.topology().getConfig().put(TK_DIRS, tks);
}
tks.add(toolkitRoot.getCanonicalPath());
}
}
|
package io.quarkus.rest.runtime.jaxrs;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Link;
import javax.ws.rs.core.Link.Builder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import io.quarkus.rest.runtime.client.QuarkusRestClientResponse;
import io.quarkus.rest.runtime.headers.HeaderUtil;
import io.quarkus.rest.runtime.headers.LinkHeaders;
import io.quarkus.rest.runtime.util.CaseInsensitiveMap;
/**
* This is the Response class for user-created responses. The client response
* object has more deserialising powers in @{link {@link QuarkusRestClientResponse}.
*/
public class QuarkusRestResponse extends Response {
int status;
String reasonPhrase;
protected Object entity;
MultivaluedMap<String, Object> headers;
InputStream entityStream;
private QuarkusRestStatusType statusType;
private MultivaluedMap<String, String> stringHeaders;
Annotation[] entityAnnotations;
protected boolean consumed;
protected boolean closed;
protected boolean buffered;
@Override
public int getStatus() {
return status;
}
/**
* Internal: this is just cheaper than duplicating the response just to change the status
*/
public void setStatus(int status) {
this.status = status;
statusType = null;
}
@Override
public StatusType getStatusInfo() {
if (statusType == null) {
statusType = new QuarkusRestStatusType(status, reasonPhrase);
}
return statusType;
}
/**
* Internal: this is just cheaper than duplicating the response just to change the status
*/
public void setStatusInfo(StatusType statusType) {
this.statusType = QuarkusRestStatusType.valueOf(statusType);
status = statusType.getStatusCode();
}
@Override
public Object getEntity() {
// The spec says that getEntity() can be called after readEntity() to obtain the same entity,
// but it also sort-of implies that readEntity() calls Response.close(), and the TCK does check
// that we throw if closed and non-buffered
checkClosed();
// this check seems very ugly, but it seems to be needed by the TCK
// this will likely require a better solution
if (entity instanceof GenericEntity) {
GenericEntity<?> genericEntity = (GenericEntity<?>) entity;
if (genericEntity.getRawType().equals(genericEntity.getType())) {
return ((GenericEntity<?>) entity).getEntity();
}
}
return entity;
}
protected void setEntity(Object entity) {
this.entity = entity;
if (entity instanceof InputStream) {
this.entityStream = (InputStream) entity;
}
}
public InputStream getEntityStream() {
return entityStream;
}
public void setEntityStream(InputStream entityStream) {
this.entityStream = entityStream;
}
protected <T> T readEntity(Class<T> entityType, Type genericType, Annotation[] annotations) {
// TODO: we probably need better state handling
if (entity != null && entityType.isInstance(entity)) {
// Note that this works if entityType is InputStream where we return it without closing it, as per spec
return (T) entity;
}
checkClosed();
// Spec says to throw this
throw new ProcessingException(
"Request could not be mapped to type " + (genericType != null ? genericType : entityType));
}
@Override
public <T> T readEntity(Class<T> entityType) {
return readEntity(entityType, entityType, null);
}
@SuppressWarnings("unchecked")
@Override
public <T> T readEntity(GenericType<T> entityType) {
return (T) readEntity(entityType.getRawType(), entityType.getType(), null);
}
@Override
public <T> T readEntity(Class<T> entityType, Annotation[] annotations) {
return readEntity(entityType, entityType, annotations);
}
@SuppressWarnings("unchecked")
@Override
public <T> T readEntity(GenericType<T> entityType, Annotation[] annotations) {
return (T) readEntity(entityType.getRawType(), entityType.getType(), annotations);
}
@Override
public boolean hasEntity() {
// The TCK checks that
checkClosed();
// we have an entity already read, or still to be read
return entity != null || entityStream != null;
}
@Override
public boolean bufferEntity() {
checkClosed();
// must be idempotent
if (buffered) {
return true;
}
if (entityStream != null && !consumed) {
// let's not try this again, even if it fails
consumed = true;
// we're supposed to read the entire stream, but if we can rewind it there's no point so let's keep it
if (!entityStream.markSupported()) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int read;
try {
while ((read = entityStream.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
entityStream.close();
} catch (IOException x) {
throw new UncheckedIOException(x);
}
entityStream = new ByteArrayInputStream(os.toByteArray());
}
buffered = true;
return true;
}
return false;
}
protected void checkClosed() {
// apparently the TCK says that buffered responses don't care about being closed
if (closed && !buffered)
throw new IllegalStateException("Response has been closed");
}
@Override
public void close() {
if (!closed) {
closed = true;
if (entityStream != null) {
try {
entityStream.close();
} catch (IOException e) {
throw new ProcessingException(e);
}
}
}
}
@Override
public MediaType getMediaType() {
return HeaderUtil.getMediaType(headers);
}
@Override
public Locale getLanguage() {
return HeaderUtil.getLanguage(headers);
}
@Override
public int getLength() {
return HeaderUtil.getLength(headers);
}
@Override
public Set<String> getAllowedMethods() {
return HeaderUtil.getAllowedMethods(headers);
}
@Override
public Map<String, NewCookie> getCookies() {
return HeaderUtil.getNewCookies(headers);
}
@Override
public EntityTag getEntityTag() {
return HeaderUtil.getEntityTag(headers);
}
@Override
public Date getDate() {
return HeaderUtil.getDate(headers);
}
@Override
public Date getLastModified() {
return HeaderUtil.getLastModified(headers);
}
@Override
public URI getLocation() {
return HeaderUtil.getLocation(headers);
}
private LinkHeaders getLinkHeaders() {
return new LinkHeaders(headers);
}
@Override
public Set<Link> getLinks() {
return new HashSet<>(getLinkHeaders().getLinks());
}
@Override
public boolean hasLink(String relation) {
return getLinkHeaders().getLinkByRelationship(relation) != null;
}
@Override
public Link getLink(String relation) {
return getLinkHeaders().getLinkByRelationship(relation);
}
@Override
public Builder getLinkBuilder(String relation) {
Link link = getLinkHeaders().getLinkByRelationship(relation);
if (link == null) {
return null;
}
return Link.fromLink(link);
}
@Override
public MultivaluedMap<String, Object> getMetadata() {
return headers;
}
@Override
public MultivaluedMap<String, String> getStringHeaders() {
// FIXME: is this mutable?
if (stringHeaders == null) {
// let's keep this map case-insensitive
stringHeaders = new CaseInsensitiveMap<>();
for (Entry<String, List<Object>> entry : headers.entrySet()) {
List<String> stringValues = new ArrayList<>(entry.getValue().size());
for (Object value : entry.getValue()) {
stringValues.add(HeaderUtil.headerToString(value));
}
stringHeaders.put(entry.getKey(), stringValues);
}
}
return stringHeaders;
}
@Override
public String getHeaderString(String name) {
return HeaderUtil.getHeaderString(getStringHeaders(), name);
}
public Annotation[] getEntityAnnotations() {
return entityAnnotations;
}
}
|
package net.java.sip.communicator.impl.gui.main.presence;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.lookandfeel.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.plugin.desktoputil.presence.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.globalstatus.*;
import net.java.sip.communicator.service.systray.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.account.*;
import org.jitsi.util.*;
/**
* The <tt>GlobalStatusSelectorBox</tt> is a global status selector box, which
* appears in the status panel, when the user has more than one account. It
* allows to the user to change globally its status with only one click, instead
* of going through all accounts and selecting the desired status for every one
* of them.
* <p>
* By default the <tt>GlobalStatusSelectorBox</tt> will show the most connected
* status of all registered accounts.
*
* @author Yana Stamcheva
* @author Lubomir Marinov
* @author Adam Netocny
*/
public class GlobalStatusSelectorBox
extends StatusSelectorMenu
implements ActionListener
{
/**
* Class id key used in UIDefaults.
*/
private static final String uiClassID =
GlobalStatusSelectorBox.class.getName() + "StatusMenuUI";
/**
* Adds the ui class to UIDefaults.
*/
static
{
UIManager.getDefaults().put(uiClassID,
SIPCommStatusMenuUI.class.getName());
}
/**
* The indent of the image.
*/
private static final int IMAGE_INDENT = 10;
/**
* The arrow icon shown on the right of the status and indicating that
* this is a menu.
*/
private Image arrowImage
= ImageLoader.getImage(ImageLoader.DOWN_ARROW_ICON);
/**
* The width of the text.
*/
private int textWidth = 0;
/**
* Indicates if this is the first account added.
*/
private boolean isFirstAccount = true;
/**
* Take care for global status items, that only one is selected.
*/
private ButtonGroup group = new ButtonGroup();
/**
* The global status message menu.
*/
private final GlobalStatusMessageMenu globalStatusMessageMenu;
/**
* The parent panel that creates us.
*/
private final AccountStatusPanel accountStatusPanel;
/**
* The index of the first status, the online one.
*/
private int firstStatusIndex = -1;
/**
* Creates an instance of <tt>SimpleStatusSelectorBox</tt>.
*/
public GlobalStatusSelectorBox(AccountStatusPanel accountStatusPanel)
{
super();
this.accountStatusPanel = accountStatusPanel;
JLabel titleLabel = new JLabel(GuiActivator.getResources()
.getI18NString("service.gui.SET_GLOBAL_STATUS"));
titleLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD));
this.add(titleLabel);
this.addSeparator();
GlobalStatusEnum offlineStatus = GlobalStatusEnum.ONLINE;
group.add(createMenuItem(offlineStatus, -1));
firstStatusIndex = getItemCount();
if(isPresenceOpSetForProvidersAvailable())
addAvailableStatuses();
group.add(createMenuItem(GlobalStatusEnum.OFFLINE, -1));
this.addSeparator();
globalStatusMessageMenu = new GlobalStatusMessageMenu(true);
globalStatusMessageMenu.addPropertyChangeListener(new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if(evt.getPropertyName().equals(
GlobalStatusMessageMenu.STATUS_MESSAGE_UPDATED_PROP))
{
changeTooltip((String)evt.getNewValue());
}
}
});
this.add((JMenu)globalStatusMessageMenu.getMenu());
if(!ConfigurationUtils.isHideAccountStatusSelectorsEnabled())
this.addSeparator();
this.setFont(titleLabel.getFont().deriveFont(Font.PLAIN, 11f));
if(offlineStatus != null)
this.setIcon(new ImageIcon(offlineStatus.getStatusIcon()));
this.setIconTextGap(2);
this.setOpaque(false);
this.setText("Offline");
changeTooltip(null);
fitSizeToText();
}
/**
* Adds the available global statuses. All the statuses except ONLINE and
* OFFLINE, those that will be inserted between them.
* Check first whether the statuses are not already inserted.
*/
private void addAvailableStatuses()
{
if(hasAvailableStatuses())
return;
int index = firstStatusIndex;
// creates menu item entry for every global status
// except ONLINE and OFFLINE
for(GlobalStatusEnum status : GlobalStatusEnum.globalStatusSet)
{
if(status.equals(GlobalStatusEnum.OFFLINE)
|| status.equals(GlobalStatusEnum.ONLINE))
continue;
group.add(createMenuItem(status, index++));
}
}
/**
* Removes the available global statuses (those except ONLINE and OFFLINE)
*/
private void removeAvailableStatuses()
{
// removes menu item entry for every global status
// except ONLINE and OFFLINE
for(GlobalStatusEnum status : GlobalStatusEnum.globalStatusSet)
{
if(status.equals(GlobalStatusEnum.OFFLINE)
|| status.equals(GlobalStatusEnum.ONLINE))
continue;
JCheckBoxMenuItem item = getItemFromStatus(status);
if(item == null)
continue;
group.remove(item);
this.remove(item);
}
}
/**
* Check for available statuses we have in the menu.
* All except ONLINE and OFFLINE one.
* @return
*/
private boolean hasAvailableStatuses()
{
// check menu item entries for every global status
// except ONLINE and OFFLINE
for(GlobalStatusEnum status : GlobalStatusEnum.globalStatusSet)
{
if(status.equals(GlobalStatusEnum.OFFLINE)
|| status.equals(GlobalStatusEnum.ONLINE))
continue;
if(getItemFromStatus(status) != null)
return true;
}
return false;
}
/**
* Changes the tooltip to default or the current set status message.
* @param message
*/
private void changeTooltip(String message)
{
if(StringUtils.isNullOrEmpty(message))
{
globalStatusMessageMenu.clearSelectedItems();
this.setToolTipText("<html><b>" + GuiActivator.getResources()
.getI18NString("service.gui.SET_GLOBAL_STATUS")
+ "</b></html>");
accountStatusPanel.setStatusMessage(null);
}
else
{
this.setToolTipText("<html><b>" + message + "</b></html>");
accountStatusPanel.setStatusMessage(message);
}
}
/**
* Creates a menu item with the given <tt>textKey</tt>, <tt>iconID</tt> and
* <tt>name</tt>.
*
* @param status the global status
* @param index index the position in the container's list at which to
* insert the status, where <code>-1</code> means append to the end
* @return the created <tt>JCheckBoxMenuItem</tt>
*/
private JCheckBoxMenuItem createMenuItem(
GlobalStatusEnum status,
int index)
{
JCheckBoxMenuItem menuItem
= new JCheckBoxMenuItem(
GlobalStatusEnum.getI18NStatusName(status),
new ImageIcon(status.getStatusIcon()));
menuItem.setName(status.getStatusName());
menuItem.addActionListener(this);
if(index == -1)
add(menuItem);
else
add(menuItem, index);
return menuItem;
}
/**
* Adds a status menu for the account given by <tt>protocolProvider</tt>.
* @param protocolProvider the <tt>ProtocolProviderService</tt>, for which
* to add a status menu
*/
public void addAccount(ProtocolProviderService protocolProvider)
{
if (protocolProvider.getAccountID().isHidden())
return;
OperationSetPersistentPresence presenceOpSet
= (OperationSetPersistentPresence)
protocolProvider.getOperationSet(OperationSetPresence.class);
JMenuItem itemToAdd;
if(protocolProvider.getAccountID().isStatusMenuHidden())
{
itemToAdd = new ReadonlyStatusItem(protocolProvider);
}
else
{
itemToAdd = (presenceOpSet != null)
? new PresenceStatusMenu(protocolProvider)
: new SimpleStatusMenu(protocolProvider);
}
if(ConfigurationUtils.isHideAccountStatusSelectorsEnabled())
itemToAdd.setVisible(false);
// If this is the first account in our menu.
if (isFirstAccount)
{
add(itemToAdd);
isFirstAccount = false;
// if we have a provider with opset presence add available statuses
if(presenceOpSet != null)
addAvailableStatuses();
return;
}
boolean isMenuAdded = false;
AccountID accountId = protocolProvider.getAccountID();
// If we already have other accounts.
for (Component c : getPopupMenu().getComponents())
{
if (!(c instanceof StatusEntry))
continue;
StatusEntry menu = (StatusEntry) c;
int menuIndex = getPopupMenu().getComponentIndex(
menu.getEntryComponent());
AccountID menuAccountID = menu.getProtocolProvider().getAccountID();
int protocolCompare = accountId.getProtocolDisplayName().compareTo(
menuAccountID.getProtocolDisplayName());
// If the new account protocol name is before the name of the menu
// we insert the new account before the given menu.
if (protocolCompare < 0)
{
insert(itemToAdd, menuIndex);
isMenuAdded = true;
break;
}
else if (protocolCompare == 0)
{
// If we have the same protocol name, we check the account name.
if (accountId.getDisplayName()
.compareTo(menuAccountID.getDisplayName()) < 0)
{
insert( itemToAdd, menuIndex);
isMenuAdded = true;
break;
}
}
}
if (!isMenuAdded)
add(itemToAdd);
// if we have a provider with opset presence add available statuses
if(presenceOpSet != null)
addAvailableStatuses();
}
/**
* Removes the status menu corresponding to the account given by
* <tt>protocolProvider</tt>.
* @param protocolProvider the <tt>ProtocolProviderService</tt>, which
* menu to remove
*/
public void removeAccount(ProtocolProviderService protocolProvider)
{
StatusEntry menu = getStatusEntry(protocolProvider);
if (menu != null)
{
menu.dispose();
remove(menu.getEntryComponent());
}
// if we do not have provider with presence opset
// remove available statuses
if(!isPresenceOpSetForProvidersAvailable())
removeAvailableStatuses();
}
/**
* Check the available providers for operation set presence.
* @return do we have a provider with opset presence.
*/
private boolean isPresenceOpSetForProvidersAvailable()
{
for (Component c : getPopupMenu().getComponents())
{
if(!(c instanceof StatusEntry))
continue;
StatusEntry menu = (StatusEntry) c;
if(menu.getProtocolProvider()
.getOperationSet(OperationSetPresence.class) != null)
return true;
}
return false;
}
/**
* Checks if a menu for the given <tt>protocolProvider</tt> exists.
* @param protocolProvider the <tt>ProtocolProviderService</tt> to check
* @return <tt>true</tt> to indicate that a status menu for the given
* <tt>protocolProvider</tt> already exists, otherwise returns
* <tt>false</tt>
*/
public boolean containsAccount(ProtocolProviderService protocolProvider)
{
return getStatusEntry(protocolProvider) != null;
}
/**
* Starts connecting user interface for the given <tt>protocolProvider</tt>.
* @param protocolProvider the <tt>ProtocolProviderService</tt> to start
* connecting for
*/
public void startConnecting(ProtocolProviderService protocolProvider)
{
StatusEntry menu = getStatusEntry(protocolProvider);
if (menu != null)
menu.startConnecting();
}
/**
* Stops connecting user interface for the given <tt>protocolProvider</tt>.
* @param protocolProvider the <tt>ProtocolProviderService</tt> to stop
* connecting for
*/
public void stopConnecting(ProtocolProviderService protocolProvider)
{
StatusEntry menu = getStatusEntry(protocolProvider);
if (menu != null)
menu.stopConnecting();
}
/**
* Returns <tt>true</tt> if there are selected status selector boxes,
* otherwise returns <tt>false</tt>.
* @return <tt>true</tt> if there are selected status selector boxes,
* otherwise returns <tt>false</tt>
*/
public boolean hasSelectedMenus()
{
for (Component c : getComponents())
{
if (!(c instanceof StatusEntry))
continue;
StatusEntry menu = (StatusEntry) c;
if (menu.isSelected())
return true;
}
return false;
}
/**
* Handles the <tt>ActionEvent</tt> triggered when one of the items
* in the list is selected.
* @param e the <tt>ActionEvent</tt> that notified us
*/
public void actionPerformed(ActionEvent e)
{
JMenuItem menuItem = (JMenuItem) e.getSource();
String itemName = menuItem.getName();
if(GuiActivator.getGlobalStatusService() != null)
{
GuiActivator.getGlobalStatusService().publishStatus(
GlobalStatusEnum.getStatusByName(itemName));
}
}
/**
* Updates the status of the given <tt>protocolProvider</tt>.
*
* @param protocolProvider the <tt>ProtocolProviderService</tt>
* corresponding to the menu to update
*/
public void updateStatus(ProtocolProviderService protocolProvider)
{
StatusEntry accountMenu = getStatusEntry(protocolProvider);
if (accountMenu == null)
return;
PresenceStatus presenceStatus;
if (!protocolProvider.isRegistered())
presenceStatus = accountMenu.getOfflineStatus();
else
{
presenceStatus
= AccountStatusUtils.getPresenceStatus(protocolProvider);
if (presenceStatus == null)
presenceStatus = accountMenu.getOnlineStatus();
}
accountMenu.updateStatus(presenceStatus);
accountMenu.repaint();
this.updateGlobalStatus();
}
/**
* Updates the status of the given <tt>protocolProvider</tt> with the given
* <tt>presenceStatus</tt>.
* @param protocolProvider the <tt>ProtocolProviderService</tt>
* corresponding to the menu to update
* @param presenceStatus the new status to set
*/
public void updateStatus(ProtocolProviderService protocolProvider,
PresenceStatus presenceStatus)
{
StatusEntry accountMenu = getStatusEntry(protocolProvider);
if (accountMenu == null)
return;
accountMenu.updateStatus(presenceStatus);
this.updateGlobalStatus();
}
/**
* Updates the global status by picking the most connected protocol provider
* status.
*/
private void updateGlobalStatus()
{
if(GuiActivator.getGlobalStatusService() == null)
return;
PresenceStatus globalStatus
= GuiActivator.getGlobalStatusService().getGlobalPresenceStatus();
JCheckBoxMenuItem item = getItemFromStatus(globalStatus);
item.setSelected(true);
setSelected(new SelectedObject(item.getText(), item.getIcon(), item));
fitSizeToText();
this.revalidate();
setSystrayIcon(globalStatus);
if(!globalStatus.isOnline())
{
changeTooltip(null);
}
}
/**
* Sets the systray icon corresponding to the given status.
*
* @param globalStatus the status, for which we're setting the systray icon.
*/
private void setSystrayIcon(PresenceStatus globalStatus)
{
SystrayService trayService = GuiActivator.getSystrayService();
if(trayService == null)
return;
int imgType = SystrayService.SC_IMG_OFFLINE_TYPE;
if (globalStatus.equals(GlobalStatusEnum.OFFLINE))
{
imgType = SystrayService.SC_IMG_OFFLINE_TYPE;
}
else if (globalStatus.equals(GlobalStatusEnum.DO_NOT_DISTURB))
{
imgType = SystrayService.SC_IMG_DND_TYPE;
}
else if (globalStatus.equals(GlobalStatusEnum.AWAY))
{
imgType = SystrayService.SC_IMG_AWAY_TYPE;
}
else if (globalStatus.equals(GlobalStatusEnum.EXTENDED_AWAY))
{
imgType = SystrayService.SC_IMG_EXTENDED_AWAY_TYPE;
}
else if (globalStatus.equals(GlobalStatusEnum.ONLINE))
{
imgType = SystrayService.SC_IMG_TYPE;
}
else if (globalStatus.equals(GlobalStatusEnum.FREE_FOR_CHAT))
{
imgType = SystrayService.SC_IMG_FFC_TYPE;
}
trayService.setSystrayIcon(imgType);
}
/**
* Returns the <tt>JCheckBoxMenuItem</tt> corresponding to the given status.
* For status constants we use here the values defined in the
* <tt>PresenceStatus</tt>, but this is only for convenience.
*
* @param globalStatus the status to which the item should correspond
* @return the <tt>JCheckBoxMenuItem</tt> corresponding to the given status
*/
private JCheckBoxMenuItem getItemFromStatus(PresenceStatus globalStatus)
{
for(Component c : getMenuComponents())
{
if(c instanceof JCheckBoxMenuItem
&& globalStatus.getStatusName().equals(c.getName()))
{
return (JCheckBoxMenuItem) c;
}
}
return null;
}
/**
* Overwrites the <tt>paintComponent(Graphics g)</tt> method in order to
* provide a new look and the mouse moves over this component.
* @param g the <tt>Graphics</tt> object used for painting
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (textWidth != 0)
{
g = g.create();
try
{
AntialiasingManager.activateAntialiasing(g);
g.drawImage(
arrowImage,
textWidth + 2*IMAGE_INDENT + 2,
getX()
+ (this.getHeight() - arrowImage.getHeight(null)) / 2
+ 1,
null);
}
finally
{
g.dispose();
}
}
}
/**
* Computes the width of the text in pixels in order to position the arrow
* during its painting.
*/
private void fitSizeToText()
{
String text = getText();
textWidth
= (text == null)
? 0
: ComponentUtils.getStringWidth(this, text);
this.setPreferredSize(new Dimension(
textWidth + 2*IMAGE_INDENT + arrowImage.getWidth(null) + 5, 20));
}
/**
* Returns the <tt>StatusEntry</tt> corresponding to the given
* <tt>protocolProvider</tt>.
* @param protocolProvider the <tt>ProtocolProviderService</tt>, which
* corresponding menu we're looking for
* @return the <tt>StatusEntry</tt> corresponding to the given
* <tt>protocolProvider</tt>
*/
private StatusEntry getStatusEntry(ProtocolProviderService protocolProvider)
{
for (Component c : getPopupMenu().getComponents())
{
if (!(c instanceof StatusEntry))
continue;
StatusEntry menu = (StatusEntry) c;
if (menu.getProtocolProvider() != null
&& menu.getProtocolProvider().equals(protocolProvider))
return menu;
}
return null;
}
/**
* Loads all icons and updates global status.
*/
@Override
public void loadSkin()
{
super.loadSkin();
arrowImage
= ImageLoader.getImage(ImageLoader.DOWN_ARROW_ICON);
updateGlobalStatus();
}
/**
* Returns the name of the L&F class that renders this component.
*
* @return the string "TreeUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
@Override
public String getUIClassID()
{
return uiClassID;
}
/**
* Not used.
* @param presenceStatus the <tt>PresenceStatus</tt> to be selected in this
*/
@Override
public void updateStatus(PresenceStatus presenceStatus)
{}
}
|
//This code is developed as part of the Java CoG Kit project
//This message may not be removed or altered.
package org.griphyn.vdl.karajan.monitor.monitors.ansi;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import org.apache.log4j.Logger;
import org.globus.cog.abstraction.coaster.service.local.LocalRequestManager;
import org.globus.cog.abstraction.impl.execution.coaster.WorkerShellCommand;
import org.globus.cog.abstraction.interfaces.Service;
import org.globus.cog.abstraction.interfaces.Task;
import org.globus.cog.karajan.workflow.service.ProtocolException;
import org.globus.cog.karajan.workflow.service.channels.ChannelManager;
import org.globus.cog.karajan.workflow.service.channels.KarajanChannel;
import org.griphyn.vdl.karajan.monitor.monitors.ansi.tui.Dialog;
import org.griphyn.vdl.karajan.monitor.monitors.ansi.tui.Terminal;
import org.griphyn.vdl.karajan.monitor.monitors.ansi.tui.Terminal.InputHandler;
import org.ietf.jgss.GSSCredential;
public class WorkerTerminalInputHandler implements InputHandler {
public static final Logger logger = Logger
.getLogger(WorkerTerminalInputHandler.class);
private Dialog dialog;
private Terminal term;
private Task task;
private String workerId, contact;
private GSSCredential cred;
public WorkerTerminalInputHandler(Dialog dialog, Terminal term, Task task,
String workerId) {
this.dialog = dialog;
this.term = term;
this.task = task;
this.workerId = workerId;
Service s = task.getService(0);
this.contact = (String) s.getAttribute("coaster-url");
if (this.contact == null) {
this.contact = task.getService(0).getServiceContact().getContact();
}
this.cred = (GSSCredential) task.getService(0).getSecurityContext()
.getCredentials();
}
public void handleInput(String in) {
if (in.equals("exit")) {
dialog.close();
}
else {
String result = runcmd(in);
if (result != null && !result.equals("")) {
term.append(runcmd(in));
}
}
}
private String runcmd(String cmd) {
try {
KarajanChannel channel = ChannelManager.getManager()
.reserveChannel(contact, cred, LocalRequestManager.INSTANCE);
WorkerShellCommand wsc = new WorkerShellCommand(workerId, cmd);
wsc.execute(channel);
return wsc.getInDataAsString(0);
}
catch (ProtocolException e) {
term.append(e.getMessage());
return null;
}
catch (Exception e) {
logger.warn("Cannot execute worker command", e);
CharArrayWriter caw = new CharArrayWriter();
e.printStackTrace(new PrintWriter(caw));
term.append(caw.toString());
return null;
}
}
public String autoComplete(String in) {
String result = runcmd("mls " + in + "*");
if (result == null) {
return null;
}
String[] r = result.split("\\s+");
if (r.length == 0) {
return null;
}
else if (r.length == 1) {
return r[0];
}
else {
term.append(join(r));
return null;
}
}
private String join(String[] s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length - 1; i++) {
sb.append(s[i]);
sb.append(' ');
}
sb.append(s[s.length - 1]);
return sb.toString();
}
}
|
package edu.asu.diging.gilesecosystem.web.service.impl;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.commons.lang3.text.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import edu.asu.diging.gilesecosystem.web.service.IIdentityProviderRegistry;
@Service
@PropertySource("classpath:/providers.properties")
public class IdentityProviderRegistry implements IIdentityProviderRegistry {
private Map<String, String> providers;
private Map<String, String> providerTokenChecker;
@Autowired
private Environment env;
@PostConstruct
public void init() {
providers = new HashMap<String, String>();
providerTokenChecker = new HashMap<>();
}
/* (non-Javadoc)
* @see edu.asu.giles.service.impl.IIdentityProviderRegistry#addProvider(java.lang.String)
*/
/**
* Method to register a new provider with a given authorization type.
* Internally, this method creates a key of the form providerId_authorizationType
* (e.g. 'mitreidconnect_accessToken'), which should be used in the properties file
* when specifying the label for a provider in the drop down menu when registering new applications.
* Make sure not to have '_' in the passed provider id.
* @param providerId type of provider used for authentication (e.g. 'mitreidconnect')
* @param authorizationType type of authorization used, may be null (e.g. 'accessToken')
*/
@Override
public void addProvider(String providerId, String authorizationType) {
providerId = getProviderIdwithAuthType(providerId, authorizationType);
String providerName = env.getProperty(providerId);
if (providerName == null || providerName.trim().isEmpty()) {
providerName = WordUtils.capitalize(providerId);
}
providers.put(providerId, providerName);
}
@Override
public void addProviderTokenChecker(String providerId, String authorizationType, String checkerId) {
providerTokenChecker.put(getProviderIdwithAuthType(providerId, authorizationType), checkerId);
}
/* (non-Javadoc)
* @see edu.asu.giles.service.impl.IIdentityProviderRegistry#getProviders()
*/
@Override
public Map<String, String> getProviders() {
return Collections.unmodifiableMap(providers);
}
@Override
public String getProviderName(String id) {
return providers.get(id);
}
@Override
public String getCheckerId(String providerId, String authorizationType) {
return providerTokenChecker.get(getProviderIdwithAuthType(providerId, authorizationType));
}
private String getProviderIdwithAuthType(String providerId, String authorizationType) {
if (authorizationType != null && !authorizationType.trim().isEmpty()) {
return providerId + "_" + authorizationType;
}
return providerId;
}
}
|
package org.schors.flibot;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.net.ProxyOptions;
import io.vertx.core.net.ProxyType;
import io.vertx.core.streams.Pump;
import jersey.repackaged.com.google.common.cache.Cache;
import jersey.repackaged.com.google.common.cache.CacheBuilder;
import org.apache.log4j.Logger;
import org.telegram.telegrambots.ApiContext;
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.api.methods.ActionType;
import org.telegram.telegrambots.api.methods.send.SendChatAction;
import org.telegram.telegrambots.api.methods.send.SendDocument;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Message;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardButton;
import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import sun.security.action.GetPropertyAction;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.AccessController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class FliBot extends AbstractVerticle {
private static final String rootOPDStor = "flibustahezeous3.onion";
private static final String rootOPDShttp = "http://flibusta.is";
private static final String authorSearch = "/search?searchType=authors&searchTerm=%s";
private static final String bookSearch = "/search?searchType=books&searchTerm=%s";
private static final File tmpdir = new File(AccessController
.doPrivileged(new GetPropertyAction("java.io.tmpdir")));
private static final Logger log = Logger.getLogger(FliBot.class);
private TelegramBotsApi telegram;
private HttpClient httpclient;
private Storage db;
private Cache<String, String> urlCache;
private Map<String, Search> searches = new ConcurrentHashMap<>();
private String rootOPDS;
private FileNameParser fileNameParser = new FileNameParser();
{
fileNameParser
.add(new FileNameParser.FileType("mobi") {
@Override
public String parse(String url) {
String[] parts = url.split("/");
return parts[parts.length - 2] + "." + parts[parts.length - 1];
}
})
.add(new FileNameParser.FileType("\\w+\\+zip") {
@Override
public String parse(String url) {
String[] parts = url.split("/");
return parts[parts.length - 2] + "." + parts[parts.length - 1] + ".zip";
}
})
.add(new FileNameParser.FileType("djvu") {
@Override
public String parse(String url) {
String[] parts = url.split("/");
return parts[parts.length - 1] + ".djvu";
}
})
.add(new FileNameParser.FileType("pdf") {
@Override
public String parse(String url) {
String[] parts = url.split("/");
return parts[parts.length - 1] + ".pdf";
}
})
.add(new FileNameParser.FileType("doc") {
@Override
public String parse(String url) {
String[] parts = url.split("/");
return parts[parts.length - 1] + ".doc";
}
})
.add(new FileNameParser.FileType("\\w+\\+rar") {
@Override
public String parse(String url) {
String[] parts = url.split("/");
return parts[parts.length - 2] + "." + parts[parts.length - 1] + ".rar";
}
})
.add(new FileNameParser.FileType("fb2") {
@Override
public String parse(String url) {
String[] parts = url.split("/");
return parts[parts.length - 2] + "." + parts[parts.length - 1] + ".zip";
}
})
;
}
@Override
public void start() {
ApiContextInitializer.init();
DefaultBotOptions botOptions = ApiContext.getInstance(DefaultBotOptions.class);
telegram = new TelegramBotsApi();
db = new Storage(vertx, config().getString("admin"));
urlCache = CacheBuilder.newBuilder().maximumSize(1000).build();
boolean usetor = config().getBoolean("usetor");
HttpClientOptions httpOptions = new HttpClientOptions()
.setTrustAll(true)
.setIdleTimeout(50)
.setMaxPoolSize(100)
.setDefaultHost(usetor ? rootOPDStor : rootOPDShttp)
.setDefaultPort(80)
.setLogActivity(true);
if (usetor) {
httpOptions
.setProxyOptions(new ProxyOptions()
.setType(ProxyType.SOCKS4)
.setHost(config().getString("torhost"))
.setPort(Integer.valueOf(config().getString("torport"))));
}
httpclient = vertx.createHttpClient(httpOptions);
try {
telegram.registerBot(new TelegramLongPollingBot() {
private void sendReply(Update update, String res) {
Message result = null;
SendMessage message = new SendMessage()
.setChatId(String.valueOf(update.getMessage().getChatId()))
.setText(res)
.enableHtml(true);
try {
result = sendMessage(message);
} catch (TelegramApiException e) {
log.error(e, e);
}
}
private void sendReply(Update update, SendMessage res) {
Message result = null;
res.setChatId(String.valueOf(update.getMessage().getChatId()));
try {
result = sendMessage(res);
} catch (TelegramApiException e) {
log.error(e, e);
}
// return result;
}
private Message sendReply(Update update, SendMessageList res) {
Message result = null;
for (SendMessage sm : res.getMessages()) {
if (sm.getText() != null && sm.getText().length() > 0) {
sm.setChatId(String.valueOf(update.getMessage().getChatId()));
try {
result = sendMessage(sm);
} catch (TelegramApiException e) {
log.error(e, e);
}
}
}
return result;
}
private Message sendFile(Update update, SendDocument res) {
Message result = null;
res.setChatId(update.getMessage().getChatId().toString());
try {
result = sendDocument(res);
} catch (TelegramApiException e) {
log.error(e, e);
}
return result;
}
private void sendBusy(Update update) {
SendChatAction sca = new SendChatAction();
sca.setChatId(update.getMessage().getChatId().toString());
sca.setAction(ActionType.UPLOADDOCUMENT);
try {
sendChatAction(sca);
} catch (TelegramApiException e) {
log.error(e, e);
}
}
@Override
public String getBotUsername() {
return config().getString("name");
}
@Override
public String getBotToken() {
return config().getString("token");
}
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
sendBusy(update);
String cmd = update.getMessage().getText();
String userName = update.getMessage().getFrom().getUserName();
log.info("onUpdate: " + cmd + ", " + userName);
if (db.isRegisteredUser(userName)) {
if (cmd.startsWith("/author")) {
Search search = searches.get(userName);
log.info("onAuthorSearch: " + search);
if (search != null) {
searches.remove(userName);
getAuthor(search.getToSearch(), event -> {
if (event.succeeded()) {
sendReply(update, (SendMessageList) event.result());
} else {
sendReply(update, "Error happened :(");
log.warn("onError: " + event.cause().getMessage());
}
});
} else {
search = new Search();
search.setSearchType(SearchType.AUTHOR);
searches.put(userName, search);
sendReply(update, "Please enter the author name to search");
}
} else if (cmd.startsWith("/book")) {
Search search = searches.get(userName);
log.info("onBookSearch: " + search);
if (search != null) {
searches.remove(userName);
getBook(search.getToSearch(), event -> {
if (event.succeeded()) {
sendReply(update, (SendMessageList) event.result());
} else {
sendReply(update, "Error happened :(");
log.warn("onError: " + event.cause().getMessage());
}
});
} else {
search = new Search();
search.setSearchType(SearchType.BOOK);
searches.put(userName, search);
sendReply(update, "Please enter the book name to search");
}
} else if (cmd.startsWith("/c")) {
String url = urlCache.getIfPresent(normalizeCmd(cmd));
if (url != null) {
getCmd(url, event -> {
if (event.succeeded()) {
sendReply(update, (SendMessageList) event.result());
} else {
sendReply(update, "Error happened :(");
log.warn("onError: " + event.cause().getMessage());
}
});
} else {
sendReply(update, "Expired command");
}
} else if (cmd.startsWith("/d")) {
String url = urlCache.getIfPresent(normalizeCmd(cmd));
if (url != null) {
download(url, event -> {
if (event.succeeded()) {
sendFile(update, (SendDocument) event.result());
} else {
sendReply(update, "Error happened :(");
log.warn("onError: " + event.cause().getMessage());
}
});
} else {
sendReply(update, "Expired command");
}
} else if (cmd.startsWith("/z")) {
String url = urlCache.getIfPresent(normalizeCmd(cmd));
if (url != null) {
downloadz(url, event -> {
if (event.succeeded()) {
sendFile(update, (SendDocument) event.result());
} else {
sendReply(update, "Error happened :(");
log.warn("onError: " + event.cause().getMessage());
}
});
} else {
sendReply(update, "Expired command");
}
} else if (cmd.startsWith("/k")) {
catalog(event -> {
if (event.succeeded()) {
sendReply(update, (SendMessageList) event.result());
} else {
sendReply(update, "Error happened :(");
log.warn("onError: " + event.cause().getMessage());
}
});
} else if (cmd.startsWith("/r")) {
if (userName.equals(config().getString("admin"))) {
db.registerUser(normalizeCmd(cmd));
}
} else if (cmd.startsWith("/u")) {
if (userName.equals(config().getString("admin"))) {
db.unregisterUser(normalizeCmd(cmd));
}
} else {
Search search = searches.get(userName);
log.info("onSearch: " + search);
if (search != null) {
searches.remove(userName);
switch (search.getSearchType()) {
case AUTHOR: {
getAuthor(cmd.trim().replaceAll(" ", "+"), event -> {
if (event.succeeded()) {
sendReply(update, (SendMessageList) event.result());
} else {
sendReply(update, "Error happened :(");
log.warn("onError: " + event.cause().getMessage());
}
});
break;
}
case BOOK: {
getBook(cmd.trim().replaceAll(" ", "+"), event -> {
if (event.succeeded()) {
sendReply(update, (SendMessageList) event.result());
} else {
sendReply(update, "Error happened :(");
log.warn("onError: " + event.cause().getMessage());
}
});
break;
}
}
} else {
search = new Search();
search.setToSearch(cmd.trim().replaceAll(" ", "+"));
searches.put(userName, search);
KeyboardButton authorButton = new KeyboardButton();
authorButton.setText("/author");
KeyboardButton bookButton = new KeyboardButton();
bookButton.setText("/book");
KeyboardRow keyboardRow = new KeyboardRow();
keyboardRow.add(authorButton);
keyboardRow.add(bookButton);
List<KeyboardRow> keyboardRows = new ArrayList<KeyboardRow>();
keyboardRows.add(keyboardRow);
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
keyboardMarkup.setKeyboard(keyboardRows);
keyboardMarkup.setResizeKeyboard(true);
keyboardMarkup.setSelective(true);
SendMessage sendMessage = new SendMessage();
sendMessage.setChatId(update.getMessage().getChatId().toString());
sendMessage.setReplyMarkup(keyboardMarkup);
sendMessage.setText("What to search, author or book?");
sendReply(update, sendMessage);
}
}
} else {
sendReply(update, "I do not talk to strangers");
}
}
}
});
} catch (Exception e) {
log.error(e, e);
}
}
private void downloadz(String url, Handler<AsyncResult<Object>> handler) {
log.info("Start downloading zip");
httpclient.get(url, res -> {
if (res.statusCode() == 200) {
try {
log.info("Downloaded");
File book = File.createTempFile("flibot_" + Long.toHexString(System.currentTimeMillis()), null);
vertx.fileSystem().open(book.getAbsolutePath(), new OpenOptions().setWrite(true), event -> {
if (event.succeeded()) {
Pump.pump(res
.endHandler(done -> {
Future unzipFuture = Future.future();
Future flushFuture = Future.future();
event.result().flush(flushFuture.completer());
flushFuture.compose(o -> {
Future closeFuture = Future.future();
event.result().close(closeFuture.completer());
return closeFuture;
}).compose(o -> {
vertx.executeBlocking(future -> {
try {
log.info("Start unzip");
ZipInputStream zip = new ZipInputStream(new FileInputStream(book));
ZipEntry entry = zip.getNextEntry();
log.info(String.format("TMP: %s, ENTRY: %s", tmpdir, entry));
// File book2 = File.createTempFile("fbunzip_" + Long.toHexString(System.currentTimeMillis()), null);
File book2 = new File(tmpdir.getAbsolutePath() + "/" + entry.getName());
if (book2.exists()) {
try {
book2.delete();
} catch (Exception e) {
log.warn("Unable to delete: " + book2.getName());
}
}
byte[] buffer = new byte[2048];
FileOutputStream fileOutputStream = new FileOutputStream(book2);
int len = 0;
while ((len = zip.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
zip.close();
final SendDocument sendDocument = new SendDocument();
sendDocument.setNewDocument(book2);
sendDocument.setCaption(book2.getName());
future.complete(sendDocument);
} catch (Exception e) {
log.info("Exception on unzip", e);
future.fail(e);
}
}, unzipFuture.completer());
}, unzipFuture);
handler.handle(unzipFuture);
// unzipFuture.setHandler(handler);
})
.exceptionHandler(e -> {
log.info("Pump eception: ", e);
handler.handle(Future.failedFuture(e));
}),
event.result())
.start();
} else {
log.info("Error on file open: ", event.cause());
handler.handle(Future.failedFuture(event.cause()));
}
});
} catch (Exception e) {
log.info("Exception after download: ", e);
handler.handle(Future.failedFuture(e));
}
}
}).exceptionHandler(event -> {
log.info("Exception on download: ", event.getCause());
handler.handle(Future.failedFuture(event.getCause()));
}).setFollowRedirects(true).end();
}
private void download(String url, Handler<AsyncResult<Object>> handler) {
log.info("Download: " + url);
httpclient.get("https://gist.githubusercontent.com", "/flicus/dc1fe51afff2809a848f0ed8d6d1e558/raw/a63ec2e0bdc626226e0a997b783bd63318369910/TelegramOptions.java", res -> {
// httpclient.get(url, res -> {
log.info(String.format("onDownload: RC=%d, MSG=%s", res.statusCode(), res.statusMessage()));
if (res.statusCode() == 200) {
try {
String fileName = fileNameParser.parse(url);
// File book = File.createTempFile(fileName, null);
File book = new File(tmpdir.getAbsolutePath() + "/" + fileName);
vertx.fileSystem().open(book.getAbsolutePath(), new OpenOptions().setWrite(true), event -> {
if (event.succeeded()) {
Pump.pump(res
.endHandler(done -> {
event.result().close();
// book.renameTo(new File(book.getParent() + "/" + fileName));
handler.handle(Future.succeededFuture(
new SendDocument()
.setNewDocument(book)
.setCaption(fileName)
));
})
.exceptionHandler(e -> handler.handle(Future.failedFuture(e))),
event.result())
.start();
} else {
handler.handle(Future.failedFuture(event.cause()));
}
});
} catch (Exception e) {
handler.handle(Future.failedFuture(e));
}
} else {
log.warn("Unsuccesfull HTTP req: " + res.statusCode());
handler.handle(Future.failedFuture("Error on request: " + res.statusCode()));
}
}).exceptionHandler(e -> {
handler.handle(Future.failedFuture(e));
}).setFollowRedirects(true).end();
}
private void catalog(Handler<AsyncResult<Object>> handler) {
doGenericRequest("/opds", handler);
}
private void getCmd(String url, Handler<AsyncResult<Object>> handler) {
doGenericRequest(url, handler);
}
private void getAuthor(String author, Handler<AsyncResult<Object>> handler) {
doGenericRequest("/opds" + String.format(authorSearch, author), handler);
}
private void getBook(String book, Handler<AsyncResult<Object>> handler) {
doGenericRequest("/opds" + String.format(bookSearch, book), handler);
}
protected void doGenericRequest(String url, Handler<AsyncResult<Object>> handler) {
SendMessageList result = new SendMessageList(4096);
log.info("URL: " + url);
httpclient.get(url, event -> {
log.info(String.format("onGenericReq: RC=%d, MSG=%s", event.statusCode(), event.statusMessage()));
if (event.statusCode() == 200) {
event
.bodyHandler(buffer -> {
log.info("onBodyHandler");
Page page = PageParser.parse(new ByteArrayInputStream(buffer.getBytes()));
log.info("Page: " + page);
if (page.getEntries() != null && page.getEntries().size() > 0) {
if (page.getTitle() != null) {
result.append("<b>").append(page.getTitle()).append("</b>\n");
}
page.getEntries().stream().forEach(entry -> {
result.append("<b>").append(entry.getTitle()).append("</b>");
if (entry.getAuthor() != null) {
result.append(" (").append(entry.getAuthor()).append(")");
}
result.append("\n");
entry.getLinks().stream()
.filter((l) -> l.getType() != null && l.getType().toLowerCase().contains("opds-catalog"))
.forEach(link -> {
if (link.getTitle() != null) {
result.append(link.getTitle());
}
String id = Integer.toHexString(link.getHref().hashCode());
urlCache.put(id, link.getHref());
result.append(" /c").append(id).append("\n");
});
entry.getLinks().stream()
.filter(l -> l.getRel() != null && l.getRel().contains("open-access"))
.forEach(link -> {
String type = link.getType().replace("application/", "");
result.append(type);
String id = Integer.toHexString(link.getHref().hashCode());
urlCache.put(id, link.getHref());
result.append(" : /d").append(id).append("\n");
if ("fb2+zip".equals(type)) {
result.append("fb2").append(" : /z").append(id).append("\n");
}
});
result.append("\n");
});
page.getLinks().stream()
.filter((l) -> l.getRel().equals("next"))
.forEach(lnk -> {
String id = Integer.toHexString(lnk.getHref().hashCode());
urlCache.put(id, lnk.getHref());
result.append("next : /c").append(id).append("\n");
});
} else {
result.append("Nothing found");
}
handler.handle(Future.succeededFuture(result));
})
.exceptionHandler(e -> {
handler.handle(Future.failedFuture(e));
});
} else {
log.warn("Unsuccesfull HTTP req: " + event.statusCode());
handler.handle(Future.failedFuture(event.statusMessage()));
}
}).exceptionHandler(e -> {
handler.handle(Future.failedFuture(e));
}).setFollowRedirects(true).end();
}
private String normalizeCmd(String cmd) {
return cmd.split("@")[0].substring(2).trim().replaceAll(" ", "+");
}
}
|
package uk.ac.ebi.spot.goci.curation.model;
public class StudyFileSummary {
private String fileName;
public StudyFileSummary(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
|
package com.silverpeas.usernotification.builder;
import com.silverpeas.usernotification.builder.helper.UserNotificationHelper;
import com.silverpeas.usernotification.builder.mock.OrganizationControllerMock;
import com.silverpeas.usernotification.model.NotificationResourceData;
import com.silverpeas.ui.DisplayI18NHelper;
import org.silverpeas.util.StringUtil;
import org.silverpeas.util.template.SilverpeasTemplate;
import com.stratelia.silverpeas.notificationManager.NotificationMetaData;
import com.stratelia.silverpeas.notificationManager.constant.NotifAction;
import com.stratelia.silverpeas.notificationManager.constant.NotifMessageType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.inject.Inject;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.reset;
/**
* @author Yohann Chastagnier
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring-user-notification-builder.xml" })
public class UserNotificationBuilderTest {
private static final String TECHNICAL_CONTENT =
"<!--BEFORE_MESSAGE_FOOTER--><!--AFTER_MESSAGE_FOOTER-->";
@Inject
OrganizationControllerMock organizationController;
@Test
public void testBuild_AUNB_1() {
// Build
NotificationMetaData notifTest = UserNotificationHelper.build(new AUNBTest() {
@Override
protected Collection<String> getUserIdsToNotify() {
return null;
}
});
assertThat(notifTest, nullValue());
// Asserts
notifTest = UserNotificationHelper.build(new AUNBTest());
assertThat(notifTest, notNullValue());
assertThat(notifTest.getMessageType(), is(NotifMessageType.NORMAL.getId()));
assertThat(notifTest.getAction(), is(NotifAction.CREATE));
assertThat(notifTest.getComponentId(), is("aComponentInstanceId"));
assertThat(notifTest.getSender(), is("aSenderId"));
assertThat(notifTest.getContent(), is(TECHNICAL_CONTENT));
assertThat(notifTest.getDate(), notNullValue());
assertThat(notifTest.getFileName(), nullValue());
assertThat(notifTest.getLanguages().size(), is(0));
assertThat(notifTest.getLink(), is(""));
assertThat(notifTest.getSource(), is(""));
assertThat(notifTest.getTitle(), nullValue());
assertThat(notifTest.getTemplates().size(), is(0));
assertThat(notifTest.isSendImmediately(), is(false));
assertThat(notifTest.isAnswerAllowed(), is(false));
assertThat(notifTest.getUserRecipients().size(), is(1));
}
@Test
public void testBuild_AUNB_1Bis() {
// Build
final NotificationMetaData notifTest =
UserNotificationHelper.build(new AUNBTest() {
@Override
protected NotifMessageType getMessageType() {
return NotifMessageType.URGENT;
}
@Override
protected boolean isSendImmediatly() {
return true;
}
@Override
protected NotifAction getAction() {
return NotifAction.REPORT;
}
@Override
protected void performBuild() {
super.performBuild();
getNotificationMetaData().setTitle("Title_ANB_1Bis");
getNotificationMetaData().setContent("Content_ANB_1Bis");
}
});
// Asserts
assertThat(notifTest, notNullValue());
assertThat(notifTest.getMessageType(), is(NotifMessageType.URGENT.getId()));
assertThat(notifTest.getAction(), is(NotifAction.REPORT));
assertThat(notifTest.getComponentId(), is("aComponentInstanceId"));
assertThat(notifTest.getSender(), is("aSenderId"));
assertThat(notifTest.getContent(), is("Content_ANB_1Bis" + TECHNICAL_CONTENT));
assertThat(notifTest.getDate(), notNullValue());
assertThat(notifTest.getFileName(), nullValue());
assertThat(notifTest.getLanguages().size(), is(1));
assertThat(notifTest.getLink(), is(""));
assertThat(notifTest.getSource(), is(""));
assertThat(notifTest.getTitle(), is("Title_ANB_1Bis"));
assertThat(notifTest.getTemplates().size(), is(0));
assertThat(notifTest.isSendImmediately(), is(true));
assertThat(notifTest.isAnswerAllowed(), is(false));
assertThat(notifTest.getNotificationResourceData(), nullValue());
assertThat(notifTest.getUserRecipients().size(), is(1));
}
@Test
public void testBuild_AUNB_2() {
// Build
final NotificationMetaData notifTest =
UserNotificationHelper.build(new AUNBTest(null, null) {
@Override
protected String getSender() {
return "aSenderId";
}
@Override
protected String getComponentInstanceId() {
return "aComponentInstanceId";
}
@Override
protected NotifAction getAction() {
return NotifAction.CREATE;
}
});
// Asserts
assertThat(notifTest, notNullValue());
assertThat(notifTest.getMessageType(), is(NotifMessageType.NORMAL.getId()));
assertThat(notifTest.getAction(), is(NotifAction.CREATE));
assertThat(notifTest.getComponentId(), is("aComponentInstanceId"));
assertThat(notifTest.getSender(), is("aSenderId"));
assertThat(notifTest.getContent(), is(TECHNICAL_CONTENT));
assertThat(notifTest.getDate(), notNullValue());
assertThat(notifTest.getFileName(), nullValue());
assertThat(notifTest.getLanguages().size(), is(0));
assertThat(notifTest.getLink(), is(""));
assertThat(notifTest.getSource(), is(""));
assertThat(notifTest.getTitle(), nullValue());
assertThat(notifTest.getTemplates().size(), is(0));
assertThat(notifTest.isSendImmediately(), is(false));
assertThat(notifTest.isAnswerAllowed(), is(false));
assertThat(notifTest.getNotificationResourceData(), nullValue());
assertThat(notifTest.getUserRecipients().size(), is(1));
}
@Test
public void testBuild_AUNB_2Bis() {
// Build
final NotificationMetaData notifTest =
UserNotificationHelper.build(new AUNBTest("aTitle", "aContent"));
// Asserts
assertThat(notifTest, notNullValue());
assertThat(notifTest.getMessageType(), is(NotifMessageType.NORMAL.getId()));
assertThat(notifTest.getAction(), is(NotifAction.CREATE));
assertThat(notifTest.getComponentId(), is("aComponentInstanceId"));
assertThat(notifTest.getSender(), is("aSenderId"));
assertThat(notifTest.getContent(), is("aContent" + TECHNICAL_CONTENT));
assertThat(notifTest.getDate(), notNullValue());
assertThat(notifTest.getFileName(), nullValue());
assertThat(notifTest.getLanguages().size(), is(1));
assertThat(notifTest.getLink(), is(""));
assertThat(notifTest.getSource(), is(""));
assertThat(notifTest.getTitle(), is("aTitle"));
assertThat(notifTest.getTemplates().size(), is(0));
assertThat(notifTest.isSendImmediately(), is(false));
assertThat(notifTest.isAnswerAllowed(), is(false));
assertThat(notifTest.getNotificationResourceData(), nullValue());
assertThat(notifTest.getUserRecipients().size(), is(1));
}
@Test
public void testBuild_ARUNB_1() {
// Build
NotificationMetaData notifTest = UserNotificationHelper.build(new ARUNBTest(null));
assertBuild_ARUNB_1(notifTest, "", false);
notifTest = UserNotificationHelper.build(new ARUNBTest(new String("testBuild_ARUNB_1")) {
@Override
protected void performBuild(final Object resource) {
getNotificationMetaData().setSource(resource.toString());
}
});
assertBuild_ARUNB_1(notifTest, "testBuild_ARUNB_1", false);
notifTest = UserNotificationHelper.build(new ARUNBTest(new ResourceDataTest()));
assertBuild_ARUNB_1(notifTest, "", true);
notifTest = UserNotificationHelper.build(new ARUNBTest(new ResourceDataTest()) {
@Override
protected void performBuild(final Object resource) {
super.performBuild(resource);
stop();
}
});
assertThat(notifTest, nullValue());
}
private void assertBuild_ARUNB_1(final NotificationMetaData notifTest, final String aSource,
final boolean isSilverpeasContent) {
assertThat(notifTest, notNullValue());
assertThat(notifTest.getMessageType(), is(NotifMessageType.NORMAL.getId()));
assertThat(notifTest.getAction(), is(NotifAction.UPDATE));
assertThat(notifTest.getComponentId(), is("aComponentInstanceId"));
assertThat(notifTest.getSender(), is("aSenderId"));
assertThat(notifTest.getContent(), is(TECHNICAL_CONTENT));
assertThat(notifTest.getDate(), notNullValue());
assertThat(notifTest.getFileName(), nullValue());
assertThat(notifTest.getLanguages().size(), is(0));
assertThat(StringUtil.isDefined(notifTest.getLink()), is(isSilverpeasContent));
assertThat(notifTest.getSource(), is(aSource));
assertThat(notifTest.getTitle(), nullValue());
assertThat(notifTest.getTemplates().size(), is(0));
assertThat(notifTest.isSendImmediately(), is(false));
assertThat(notifTest.isAnswerAllowed(), is(false));
final NotificationResourceData nrdTest = notifTest.getNotificationResourceData();
assertThat(nrdTest, notNullValue());
assertThat(nrdTest.getComponentInstanceId(), is("aComponentInstanceId"));
assertThat(nrdTest.getResourceDescription(), nullValue());
if (isSilverpeasContent) {
assertThat(nrdTest.getResourceId(), is("aIdFromResource"));
} else {
assertThat(nrdTest.getResourceId(), nullValue());
}
assertThat(nrdTest.getResourceLocation(), nullValue());
assertThat(nrdTest.getResourceName(), nullValue());
if (isSilverpeasContent) {
assertThat(nrdTest.getResourceType(), is("aContributionTypeFromResource"));
} else {
assertThat(nrdTest.getResourceType(), nullValue());
}
assertThat(StringUtil.isDefined(nrdTest.getResourceUrl()), is(isSilverpeasContent));
assertThat(notifTest.getUserRecipients().size(), is(2));
}
@Test
public void testBuild_ARUNB_2() {
// Build
final NotificationMetaData notifTest =
UserNotificationHelper.build(new ARUNBTest(new ResourceDataTest()) {
@Override
protected void performNotificationResource(final Object resource,
final NotificationResourceData notificationResourceData) {
final ResourceDataTest resourceTest = (ResourceDataTest) resource;
notificationResourceData.setResourceDescription("aResourceDescription");
notificationResourceData.setResourceName(resourceTest.getTitle());
notificationResourceData.setResourceLocation(resourceTest.getComponentInstanceId());
}
});
// Asserts
assertThat(notifTest, notNullValue());
assertThat(notifTest.getMessageType(), is(NotifMessageType.NORMAL.getId()));
assertThat(notifTest.getAction(), is(NotifAction.UPDATE));
assertThat(notifTest.getComponentId(), is("aComponentInstanceId"));
assertThat(notifTest.getSender(), is("aSenderId"));
assertThat(notifTest.getContent(), is(TECHNICAL_CONTENT));
assertThat(notifTest.getDate(), notNullValue());
assertThat(notifTest.getFileName(), nullValue());
assertThat(notifTest.getLanguages().size(), is(0));
assertThat(StringUtil.isDefined(notifTest.getLink()), is(true));
assertThat(notifTest.getSource(), is(""));
assertThat(notifTest.getTitle(), nullValue());
assertThat(notifTest.getTemplates().size(), is(0));
assertThat(notifTest.isSendImmediately(), is(false));
assertThat(notifTest.isAnswerAllowed(), is(false));
final NotificationResourceData nrdTest = notifTest.getNotificationResourceData();
assertThat(nrdTest, notNullValue());
assertThat(nrdTest.getComponentInstanceId(), is("aComponentInstanceId"));
assertThat(nrdTest.getResourceDescription(), is("aResourceDescription"));
assertThat(nrdTest.getResourceId(), is("aIdFromResource"));
assertThat(nrdTest.getResourceLocation(), is("aComponentInstanceIdFromResource"));
assertThat(nrdTest.getResourceName(), is("aTitleFromResource"));
assertThat(nrdTest.getResourceType(), is("aContributionTypeFromResource"));
assertThat(StringUtil.isDefined(nrdTest.getResourceUrl()), is(true));
assertThat(notifTest.getUserRecipients().size(), is(2));
}
@Test
public void testBuild_ARUNB_2Bis() {
// Build
final NotificationMetaData notifTest =
UserNotificationHelper.build(new ARUNBTest(new ResourceDataTest(), "aTitle", "aContent"));
// Asserts
assertThat(notifTest, notNullValue());
assertThat(notifTest.getMessageType(), is(NotifMessageType.NORMAL.getId()));
assertThat(notifTest.getAction(), is(NotifAction.UPDATE));
assertThat(notifTest.getComponentId(), is("aComponentInstanceId"));
assertThat(notifTest.getSender(), is("aSenderId"));
assertThat(notifTest.getContent(), is("aContent" + TECHNICAL_CONTENT));
assertThat(notifTest.getDate(), notNullValue());
assertThat(notifTest.getFileName(), nullValue());
assertThat(notifTest.getLanguages().size(), is(1));
assertThat(StringUtil.isDefined(notifTest.getLink()), is(true));
assertThat(notifTest.getSource(), is(""));
assertThat(notifTest.getTitle(), is("aTitle"));
assertThat(notifTest.getTemplates().size(), is(0));
assertThat(notifTest.isSendImmediately(), is(false));
assertThat(notifTest.isAnswerAllowed(), is(false));
final NotificationResourceData nrdTest = notifTest.getNotificationResourceData();
assertThat(nrdTest, notNullValue());
assertThat(nrdTest.getComponentInstanceId(), is("aComponentInstanceId"));
assertThat(nrdTest.getResourceDescription(), nullValue());
assertThat(nrdTest.getResourceId(), is("aIdFromResource"));
assertThat(nrdTest.getResourceLocation(), nullValue());
assertThat(nrdTest.getResourceName(), nullValue());
assertThat(nrdTest.getResourceType(), is("aContributionTypeFromResource"));
assertThat(StringUtil.isDefined(nrdTest.getResourceUrl()), is(true));
assertThat(notifTest.getUserRecipients().size(), is(2));
}
@Test
public void testBuild_ATUNB_1() {
mockOrganizationController_isComponentExist();
NotificationMetaData notifTest =
UserNotificationHelper.build(new ATUNBTest(new ResourceDataTest(), "aTitle", "notificationHelperTemplateFile"));
assertBuild_ATUNB_1(notifTest, "");
notifTest =
UserNotificationHelper.build(new ATUNBTest(new ResourceDataTest(), "aTitle", "notificationHelperTemplateFile") {
@Override
protected String getMultilangPropertyFile() {
return "com.silverpeas.notification.helper.multilang.notificationHelperBundle";
}
});
assertBuild_ATUNB_1(notifTest, "bundleValue");
}
private void assertBuild_ATUNB_1(final NotificationMetaData notifTest, final String contentValue) {
assertThat(notifTest, notNullValue());
assertThat(notifTest.getMessageType(), is(NotifMessageType.ERROR.getId()));
assertThat(notifTest.getAction(), is(NotifAction.DELETE));
assertThat(notifTest.getComponentId(), is("aComponentInstanceId"));
assertThat(notifTest.getSender(), is("aSenderId"));
assertThat(notifTest.getDate(), notNullValue());
assertThat(notifTest.getFileName(), is("notificationHelperTemplateFile"));
assertThat(notifTest.getLanguages().size(), is(3));
assertThat(StringUtil.isDefined(notifTest.getLink()), is(true));
assertThat(notifTest.getSource(), is("aSource"));
assertThat(notifTest.getTitle(), is("aTitle"));
assertThat(notifTest.getTemplates().size(), is(3));
assertThat(notifTest.isSendImmediately(), is(false));
assertThat(notifTest.isAnswerAllowed(), is(false));
final NotificationResourceData nrdTest = notifTest.getNotificationResourceData();
assertThat(nrdTest, notNullValue());
assertThat(nrdTest.getComponentInstanceId(), is("aComponentInstanceId"));
assertThat(nrdTest.getResourceDescription(), nullValue());
assertThat(nrdTest.getResourceId(), is("aIdFromResource"));
assertThat(nrdTest.getResourceLocation(), nullValue());
assertThat(nrdTest.getResourceName(), is("aTitleFromResource"));
assertThat(nrdTest.getResourceType(), is("aContributionTypeFromResource"));
assertThat(StringUtil.isDefined(nrdTest.getResourceUrl()), is(true));
assertThat(notifTest.getUserRecipients().size(), is(3));
for (final String curLanguage : DisplayI18NHelper.getLanguages()) {
assertThat(notifTest.getContent(curLanguage),
is(curLanguage + "-" + contentValue + " :-)" + TECHNICAL_CONTENT));
}
}
@Test
public void testBuild_ATUNB_2() {
mockOrganizationController_isComponentExist();
// Builds
final NotificationMetaData notifTest =
UserNotificationHelper.build(new ATUNBTest(new ResourceDataTest(), "aTitle", "notificationHelperTemplateFile") {
@Override
protected String getMultilangPropertyFile() {
return "com.silverpeas.notification.helper.multilang.notificationHelperBundle";
}
@Override
protected String getComponentInstanceId() {
return "<componentInstanceId>";
}
});
// Asserts
assertThat(notifTest, notNullValue());
assertThat(notifTest.getMessageType(), is(NotifMessageType.ERROR.getId()));
assertThat(notifTest.getAction(), is(NotifAction.DELETE));
assertThat(notifTest.getComponentId(), is("<componentInstanceId>"));
assertThat(notifTest.getSender(), is("aSenderId"));
assertThat(notifTest.getDate(), notNullValue());
assertThat(notifTest.getFileName(), is("notificationHelperTemplateFile"));
assertThat(notifTest.getLanguages().size(), is(3));
assertThat(StringUtil.isDefined(notifTest.getLink()), is(true));
assertThat(notifTest.getSource(), is("aSource"));
assertThat(notifTest.getTitle(), is("aTitle"));
assertThat(notifTest.getTemplates().size(), is(3));
assertThat(notifTest.isSendImmediately(), is(false));
assertThat(notifTest.isAnswerAllowed(), is(false));
final NotificationResourceData nrdTest = notifTest.getNotificationResourceData();
assertThat(nrdTest, notNullValue());
assertThat(nrdTest.getComponentInstanceId(), is("<componentInstanceId>"));
assertThat(nrdTest.getResourceDescription(), nullValue());
assertThat(nrdTest.getResourceId(), is("aIdFromResource"));
assertThat(nrdTest.getResourceLocation(), nullValue());
assertThat(nrdTest.getResourceName(), is("aTitleFromResource"));
assertThat(nrdTest.getResourceType(), is("aContributionTypeFromResource"));
assertThat(StringUtil.isDefined(nrdTest.getResourceUrl()), is(true));
assertThat(notifTest.getUserRecipients().size(), is(3));
for (final String curLanguage : DisplayI18NHelper.getLanguages()) {
assertThat(notifTest.getContent(curLanguage),
is(curLanguage + "-bundleValue :-) - components" + TECHNICAL_CONTENT));
}
}
protected void mockOrganizationController_isComponentExist() {
reset(organizationController.getMock());
doAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(final InvocationOnMock invocation) throws Throwable {
final String componentInstanceId = (String) invocation.getArguments()[0];
if ("<componentInstanceId>".equals(componentInstanceId)) {
return true;
}
return false;
}
}).when(organizationController.getMock()).isComponentExist(anyString());
}
protected class ATUNBTest extends AbstractTemplateUserNotificationBuilder<ResourceDataTest> {
public ATUNBTest(final ResourceDataTest resource, final String title, final String fileName) {
super(resource, title, fileName);
}
@Override
protected String getBundleSubjectKey() {
return null;
}
@Override
protected Collection<String> getUserIdsToNotify() {
return Arrays.asList("123", "124", "125");
}
@Override
protected void perform(final ResourceDataTest resource) {
getNotificationMetaData().setSource("aSource");
}
@Override
protected String getTemplatePath() {
return "//notification////helper//////";
}
@Override
protected void performTemplateData(final String language, final ResourceDataTest resource,
final SilverpeasTemplate template) {
if (getBundle(language) != null) {
template.setAttribute("testAttribute", getBundle(language).getString("testAttributeKey", ""));
}
}
@Override
protected void performNotificationResource(final String language,
final ResourceDataTest resource,
final NotificationResourceData notificationResourceData) {
notificationResourceData.setResourceName(resource.getTitle());
}
@Override
protected String getSender() {
return "aSenderId";
}
@Override
protected String getComponentInstanceId() {
return "aComponentInstanceId";
}
@Override
protected NotifAction getAction() {
return NotifAction.DELETE;
}
@Override
protected NotifMessageType getMessageType() {
return NotifMessageType.ERROR;
}
}
protected class ARUNBTest extends AbstractResourceUserNotificationBuilder<Object> {
public ARUNBTest(final Object resource, final String title, final String content) {
super(resource, title, content);
}
public ARUNBTest(final Object resource) {
super(resource);
}
@Override
protected Collection<String> getUserIdsToNotify() {
return Arrays.asList("123", "124");
}
@Override
protected void performBuild(final Object resource) {
// Nothing to do
}
@Override
protected void performNotificationResource(final Object resource,
final NotificationResourceData notificationResourceData) {
// Nothing to do
}
@Override
protected String getSender() {
return "aSenderId";
}
@Override
protected String getComponentInstanceId() {
return "aComponentInstanceId";
}
@Override
protected NotifAction getAction() {
return NotifAction.UPDATE;
}
}
/**
* @author Yohann Chastagnier
*/
protected class AUNBTest extends AbstractUserNotificationBuilder {
public AUNBTest() {
super();
}
public AUNBTest(final String title, final String content) {
super(title, content);
}
@Override
protected Collection<String> getUserIdsToNotify() {
return Collections.singletonList("123");
}
@Override
protected void performBuild() {
// Nothing to do
}
@Override
protected String getSender() {
return "aSenderId";
}
@Override
protected String getComponentInstanceId() {
return "aComponentInstanceId";
}
@Override
protected NotifAction getAction() {
return NotifAction.CREATE;
}
}
}
|
package backtype.storm.task;
import backtype.storm.generated.ShellComponent;
import backtype.storm.tuple.Tuple;
import backtype.storm.utils.ShellProcess;
import backtype.storm.multilang.BoltMsg;
import backtype.storm.multilang.ShellMsg;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.Map;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A bolt that shells out to another process to process tuples. ShellBolt
* communicates with that process over stdio using a special protocol. An ~100
* line library is required to implement that protocol, and adapter libraries
* currently exist for Ruby and Python.
*
* <p>To run a ShellBolt on a cluster, the scripts that are shelled out to must be
* in the resources directory within the jar submitted to the master.
* During development/testing on a local machine, that resources directory just
* needs to be on the classpath.</p>
*
* <p>When creating topologies using the Java API, subclass this bolt and implement
* the IRichBolt interface to create components for the topology that use other languages. For example:
* </p>
*
* <pre>
* public class MyBolt extends ShellBolt implements IRichBolt {
* public MyBolt() {
* super("python", "mybolt.py");
* }
*
* public void declareOutputFields(OutputFieldsDeclarer declarer) {
* declarer.declare(new Fields("field1", "field2"));
* }
* }
* </pre>
*/
public class ShellBolt implements IBolt {
public static Logger LOG = LoggerFactory.getLogger(ShellBolt.class);
Process _subprocess;
OutputCollector _collector;
Map<String, Tuple> _inputs = new ConcurrentHashMap<String, Tuple>();
private String[] _command;
private ShellProcess _process;
private volatile boolean _running = true;
private volatile Throwable _exception;
private LinkedBlockingQueue _pendingWrites = new LinkedBlockingQueue();
private Random _rand;
private Thread _readerThread;
private Thread _writerThread;
public ShellBolt(ShellComponent component) {
this(component.get_execution_command(), component.get_script());
}
public ShellBolt(String... command) {
_command = command;
}
public void prepare(Map stormConf, TopologyContext context,
final OutputCollector collector) {
_rand = new Random();
_collector = collector;
_process = new ShellProcess(_command);
//subprocesses must send their pid first thing
Number subpid = _process.launch(stormConf, context);
LOG.info("Launched subprocess with pid " + subpid);
// reader
_readerThread = new Thread(new Runnable() {
public void run() {
while (_running) {
try {
ShellMsg shellMsg = _process.readShellMsg();
String command = shellMsg.getCommand();
if(command.equals("ack")) {
handleAck(shellMsg.getId());
} else if (command.equals("fail")) {
handleFail(shellMsg.getId());
} else if (command.equals("error")) {
handleError(shellMsg.getMsg());
} else if (command.equals("log")) {
String msg = shellMsg.getMsg();
LOG.info("Shell msg: " + msg);
} else if (command.equals("emit")) {
handleEmit(shellMsg);
}
} catch (InterruptedException e) {
} catch (Throwable t) {
die(t);
}
}
}
});
_readerThread.start();
_writerThread = new Thread(new Runnable() {
public void run() {
while (_running) {
try {
Object write = _pendingWrites.poll(1, SECONDS);
if (write instanceof BoltMsg) {
_process.writeBoltMsg((BoltMsg)write);
} else if (write instanceof List<?>) {
_process.writeTaskIds((List<Integer>)write);
} else if (write != null) {
throw new RuntimeException("Unknown class type to write: " + write.getClass().getName());
}
} catch (InterruptedException e) {
} catch (Throwable t) {
die(t);
}
}
}
});
_writerThread.start();
}
public void execute(Tuple input) {
if (_exception != null) {
throw new RuntimeException(_exception);
}
//just need an id
String genId = Long.toString(_rand.nextLong());
_inputs.put(genId, input);
try {
BoltMsg boltMsg = new BoltMsg();
boltMsg.setId(genId);
boltMsg.setComp(input.getSourceComponent());
boltMsg.setStream(input.getSourceStreamId());
boltMsg.setTask(input.getSourceTask());
boltMsg.setTuple(input.getValues());
_pendingWrites.put(boltMsg);
} catch(InterruptedException e) {
throw new RuntimeException("Error during multilang processing", e);
}
}
public void cleanup() {
_running = false;
_process.destroy();
_inputs.clear();
}
private void handleAck(String id) {
Tuple acked = _inputs.remove(id);
if(acked==null) {
throw new RuntimeException("Acked a non-existent or already acked/failed id: " + id);
}
_collector.ack(acked);
}
private void handleFail(String id) {
Tuple failed = _inputs.remove(id);
if(failed==null) {
throw new RuntimeException("Failed a non-existent or already acked/failed id: " + id);
}
_collector.fail(failed);
}
private void handleError(String msg) {
_collector.reportError(new Exception("Shell Process Exception: " + msg));
}
private void handleEmit(ShellMsg shellMsg) throws InterruptedException {
List<Tuple> anchors = new ArrayList<Tuple>();
for (String anchor : shellMsg.getAnchors()) {
Tuple t = _inputs.get(anchor);
if (t == null) {
throw new RuntimeException("Anchored onto " + anchor + " after ack/fail");
}
anchors.add(t);
}
if(shellMsg.getTask() == 0) {
List<Integer> outtasks = _collector.emit(shellMsg.getStream(), anchors, shellMsg.getTuple());
if (shellMsg.areTaskIdsNeeded()) {
_pendingWrites.put(outtasks);
}
} else {
_collector.emitDirect((int) shellMsg.getTask(),
shellMsg.getStream(), anchors, shellMsg.getTuple());
}
}
private void die(Throwable exception) {
_exception = exception;
}
}
|
package com.appspot.movevote.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilter;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
public class MovieEvent {
private String eventId;
private String userId;
private String tmdbId;
private String eventAction;
private int rating;
public MovieEvent() {
}
public MovieEvent(String userId, String eventAction) {
this.userId = userId;
this.eventAction = eventAction;
}
public MovieEvent(String userId, String tmdbId, String eventAction) {
this.userId = userId;
this.tmdbId = tmdbId;
this.eventAction = eventAction;
}
public MovieEvent(String userId, String tmdbId, String eventAction, int rating) {
this(userId, tmdbId, eventAction);
this.rating = rating;
}
public void storeEventRecord() {
DatastoreService dataStore = DatastoreServiceFactory.getDatastoreService();
Entity eventEntity = getSpecificEventRecord();
if (eventEntity == null) {
eventEntity = new Entity(Constant.DS_TABLE_MOVIE_EVENT);
eventEntity.setProperty("userId", userId);
eventEntity.setProperty("tmdbId", tmdbId);
}
switch (eventAction) {
case Constant.MOVIE_EVENT_ACTION_CLICK:
eventEntity.setProperty("action", eventAction);
eventEntity.setProperty("last_update", new Date());
break;
case Constant.MOVIE_EVENT_ACTION_RATE:
eventEntity.setProperty("rating", rating);
eventEntity.setProperty("action", eventAction);
eventEntity.setProperty("last_update", new Date());
break;
case Constant.MOVIE_EVENT_ACTION_WANT_TO_WATCH:
eventEntity.setProperty("action", eventAction);
eventEntity.setProperty("last_update", new Date());
break;
case Constant.MOVIE_EVENT_ACTION_WATCH:
eventEntity.setProperty("action", eventAction);
eventEntity.setProperty("last_update", new Date());
break;
}
dataStore.put(eventEntity);
}
public Entity getSpecificEventRecord() {
DatastoreService dataStore = DatastoreServiceFactory.getDatastoreService();
Filter tmdbIdFilter = new FilterPredicate("tmdbId", FilterOperator.EQUAL, tmdbId);
Filter userIdFilter = new FilterPredicate("userId", FilterOperator.EQUAL, userId);
Filter actionFilter = new FilterPredicate("action", FilterOperator.EQUAL, eventAction);
CompositeFilter movieEventCompFilter = CompositeFilterOperator.and(tmdbIdFilter,
userIdFilter, actionFilter);
Query query = new Query(Constant.DS_TABLE_MOVIE_EVENT).setFilter(movieEventCompFilter);
PreparedQuery pq = dataStore.prepare(query);
Entity eventEntity = pq.asSingleEntity();
return eventEntity;
}
public List<Entity> getSpecificEventRecords() {
List<Entity> entityList = new ArrayList<Entity>();
DatastoreService dataStore = DatastoreServiceFactory.getDatastoreService();
Filter userIdFilter = new FilterPredicate("userId", FilterOperator.EQUAL, userId);
Filter actionFilter = new FilterPredicate("action", FilterOperator.EQUAL, eventAction);
CompositeFilter movieEventCompFilter = CompositeFilterOperator.and(userIdFilter,
actionFilter);
Query query = new Query(Constant.DS_TABLE_MOVIE_EVENT).setFilter(movieEventCompFilter);
PreparedQuery pq = dataStore.prepare(query);
for (Entity entity : pq.asIterable()) {
entityList.add(entity);
}
return entityList;
}
public int getSpecificEventRecordCount() {
DatastoreService dataStore = DatastoreServiceFactory.getDatastoreService();
Filter userIdFilter = new FilterPredicate("userId", FilterOperator.EQUAL, userId);
Filter actionFilter = new FilterPredicate("action", FilterOperator.EQUAL, eventAction);
CompositeFilter movieEventCompFilter = CompositeFilterOperator.and(userIdFilter,
actionFilter);
Query query = new Query(Constant.DS_TABLE_MOVIE_EVENT).setFilter(movieEventCompFilter);
PreparedQuery pq = dataStore.prepare(query);
return pq.countEntities(FetchOptions.Builder.withDefaults());
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTmdbId() {
return tmdbId;
}
public void setTmdbId(String tmdbId) {
this.tmdbId = tmdbId;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public String getEventAction() {
return eventAction;
}
public void setEventAction(String eventAction) {
this.eventAction = eventAction;
}
}
|
package com.azabani.java.rover;
import java.util.Stack;
import java.util.Iterator;
public class RoverController {
RoverListList program;
private Stack<Iterator<RoverCommand>> stack;
private ConcreteComm comm;
private ConcreteDriver driver;
private ConcreteSoilAnalyser soilAnalyser;
private ConcreteCamera camera;
private CommObserver commObserver;
private DriverObserver driverObserver;
private SoilAnalyserObserver soilAnalyserObserver;
private CameraObserver cameraObserver;
public RoverController(
ConcreteComm comm,
ConcreteDriver driver,
ConcreteSoilAnalyser soilAnalyser,
ConcreteCamera camera
) {
program = new RoverListList();
stack = new Stack<Iterator<RoverCommand>>();
this.comm = comm;
this.driver = driver;
this.soilAnalyser = soilAnalyser;
this.camera = camera;
commObserver = new CommObserver(
comm, this
);
driverObserver = new DriverObserver(
driver, this
);
soilAnalyserObserver = new SoilAnalyserObserver(
soilAnalyser, this
);
cameraObserver = new CameraObserver(
camera, this
);
}
public void start() {
// TODO: write algorithm here
}
public void messageReceived(String message) {
RoverCommandCodec c = new RoverCommandCodec();
program.add(c.decode(message));
}
public void drivingAttempted(boolean success) {
// TODO: write algorithm here
}
public void analysisReceived(String soilAnalysis) {
// TODO: write algorithm here
}
public void photographReceived(char[] photoData) {
// TODO: write algorithm here
}
}
|
package com.ecyrd.jspwiki.plugin;
import org.apache.oro.text.regex.*;
import org.apache.log4j.Logger;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Map;
import java.util.Vector;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.HashMap;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.FileUtil;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.InternalWikiException;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Manages plugin classes. There exists a single instance of PluginManager
* per each instance of WikiEngine, that is, each JSPWiki instance.
* <P>
* A plugin is defined to have three parts:
* <OL>
* <li>The plugin class
* <li>The plugin parameters
* <li>The plugin body
* </ol>
*
* For example, in the following line of code:
* <pre>
* [{INSERT com.ecyrd.jspwiki.plugin.FunnyPlugin foo='bar'
* blob='goo'
*
* abcdefghijklmnopqrstuvw
* 01234567890}]
* </pre>
*
* The plugin class is "com.ecyrd.jspwiki.plugin.FunnyPlugin", the
* parameters are "foo" and "blob" (having values "bar" and "goo",
* respectively), and the plugin body is then
* "abcdefghijklmnopqrstuvw\n01234567890". The plugin body is
* accessible via a special parameter called "_body".
* <p>
* If the parameter "debug" is set to "true" for the plugin,
* JSPWiki will output debugging information directly to the page if there
* is an exception.
* <P>
* The class name can be shortened, and marked without the package.
* For example, "FunnyPlugin" would be expanded to
* "com.ecyrd.jspwiki.plugin.FunnyPlugin" automatically. It is also
* possible to defined other packages, by setting the
* "jspwiki.plugin.searchPath" property. See the included
* jspwiki.properties file for examples.
* <P>
* Even though the nominal way of writing the plugin is
* <pre>
* [{INSERT pluginclass WHERE param1=value1...}],
* </pre>
* it is possible to shorten this quite a lot, by skipping the
* INSERT, and WHERE words, and dropping the package name. For
* example:
*
* <pre>
* [{INSERT com.ecyrd.jspwiki.plugin.Counter WHERE name='foo'}]
* </pre>
*
* is the same as
* <pre>
* [{Counter name='foo'}]
* </pre>
*
* @author Janne Jalkanen
* @since 1.6.1
*/
public class PluginManager
{
private static Logger log = Logger.getLogger( PluginManager.class );
/**
* This is the default package to try in case the instantiation
* fails.
*/
public static final String DEFAULT_PACKAGE = "com.ecyrd.jspwiki.plugin";
/**
* The property name defining which packages will be searched for properties.
*/
public static final String PROP_SEARCHPATH = "jspwiki.plugin.searchPath";
/**
* The name of the body content. Current value is "_body".
*/
public static final String PARAM_BODY = "_body";
/**
* A special name to be used in case you want to see debug output
*/
public static final String PARAM_DEBUG = "debug";
Vector m_searchPath = new Vector();
Pattern m_pluginPattern;
private boolean m_pluginsEnabled = true;
/**
* Create a new PluginManager.
*
* @param props Contents of a "jspwiki.properties" file.
*/
public PluginManager( Properties props )
{
String packageNames = props.getProperty( PROP_SEARCHPATH );
if( packageNames != null )
{
StringTokenizer tok = new StringTokenizer( packageNames, "," );
while( tok.hasMoreTokens() )
{
m_searchPath.add( tok.nextToken() );
}
}
// The default package is always added.
m_searchPath.add( DEFAULT_PACKAGE );
PatternCompiler compiler = new Perl5Compiler();
try
{
m_pluginPattern = compiler.compile( "\\{?(INSERT)?\\s*([\\w\\._]+)[ \\t]*(WHERE)?[ \\t]*" );
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: someone messed with pluginmanager patterns.", e );
throw new InternalWikiException( "PluginManager patterns are broken" );
}
}
/**
* Enables or disables plugin execution.
*/
public void enablePlugins( boolean enabled )
{
m_pluginsEnabled = enabled;
}
/**
* Returns plugin execution status. If false, plugins are not
* executed when they are encountered on a WikiPage, and an
* empty string is returned in their place.
*/
public boolean pluginsEnabled()
{
return( m_pluginsEnabled );
}
/**
* Returns true if the link is really command to insert
* a plugin.
* <P>
* Currently we just check if the link starts with "{INSERT",
* or just plain "{" but not "{$".
*
* @param link Link text, i.e. the contents of text between [].
* @return True, if this link seems to be a command to insert a plugin here.
*/
public static boolean isPluginLink( String link )
{
return link.startsWith("{INSERT") ||
(link.startsWith("{") && !link.startsWith("{$"));
}
/**
* Attempts to locate a plugin class from the class path
* set in the property file.
*
* @param classname Either a fully fledged class name, or just
* the name of the file (that is,
* "com.ecyrd.jspwiki.plugin.Counter" or just plain "Counter").
*
* @return A found class.
*
* @throws ClassNotFoundException if no such class exists.
*/
private Class findPluginClass( String classname )
throws ClassNotFoundException
{
return ClassUtil.findClass( m_searchPath, classname );
}
/**
* Outputs a HTML-formatted version of a stack trace.
*/
private String stackTrace( Map params, Throwable t )
{
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter( sw );
out.println("<div class=\"debug\">");
out.println("Plugin execution failed, stack trace follows:");
out.println("<pre>");
t.printStackTrace( out );
out.println("</pre>");
out.println("<b>Parameters to the plugin</b>");
out.println("<ul>");
for( Iterator i = params.keySet().iterator(); i.hasNext(); )
{
String key = (String) i.next();
out.println(" <li>'"+key+"'='"+params.get(key)+"'</li>");
}
out.println("</ul>");
out.println("</div>");
out.flush();
return sw.toString();
}
/**
* Executes a plugin class in the given context.
* <P>Used to be private, but is public since 1.9.21.
*
* @param context The current WikiContext.
* @param classname The name of the class. Can also be a
* shortened version without the package name, since the class name is searched from the
* package search path.
*
* @param params A parsed map of key-value pairs.
*
* @return Whatever the plugin returns.
*
* @throws PluginException If the plugin execution failed for
* some reason.
*
* @since 2.0
*/
public String execute( WikiContext context,
String classname,
Map params )
throws PluginException
{
if( !m_pluginsEnabled )
return( "" );
try
{
Class pluginClass;
WikiPlugin plugin;
boolean debug = TextUtil.isPositive( (String) params.get( PARAM_DEBUG ) );
pluginClass = findPluginClass( classname );
// Create...
try
{
plugin = (WikiPlugin) pluginClass.newInstance();
}
catch( InstantiationException e )
{
throw new PluginException( "Cannot instantiate plugin "+classname, e );
}
catch( IllegalAccessException e )
{
throw new PluginException( "Not allowed to access plugin "+classname, e );
}
catch( Exception e )
{
throw new PluginException( "Instantiation of plugin "+classname+" failed.", e );
}
// ...and launch.
try
{
return plugin.execute( context, params );
}
catch( PluginException e )
{
if( debug )
{
return stackTrace( params, e );
}
// Just pass this exception onward.
throw (PluginException) e.fillInStackTrace();
}
catch( Throwable t )
{
// But all others get captured here.
log.info( "Plugin failed while executing:", t );
if( debug )
{
return stackTrace( params, t );
}
throw new PluginException( "Plugin failed", t );
}
}
catch( ClassNotFoundException e )
{
throw new PluginException( "Could not find plugin "+classname, e );
}
catch( ClassCastException e )
{
throw new PluginException( "Class "+classname+" is not a Wiki plugin.", e );
}
}
/**
* Parses plugin arguments. Handles quotes and all other kewl
* stuff.
*
* @param argstring The argument string to the plugin. This is
* typically a list of key-value pairs, using "'" to escape
* spaces in strings, followed by an empty line and then the
* plugin body.
*
* @return A parsed list of parameters. The plugin body is put
* into a special parameter defined by PluginManager.PARAM_BODY.
*
* @throws IOException If the parsing fails.
*/
public Map parseArgs( String argstring )
throws IOException
{
HashMap arglist = new HashMap();
StringReader in = new StringReader(argstring);
StreamTokenizer tok = new StreamTokenizer(in);
int type;
String param = null, value = null;
tok.eolIsSignificant( true );
boolean potentialEmptyLine = false;
boolean quit = false;
while( !quit )
{
String s;
type = tok.nextToken();
switch( type )
{
case StreamTokenizer.TT_EOF:
quit = true;
s = null;
break;
case StreamTokenizer.TT_WORD:
s = tok.sval;
potentialEmptyLine = false;
break;
case StreamTokenizer.TT_EOL:
quit = potentialEmptyLine;
potentialEmptyLine = true;
s = null;
break;
case StreamTokenizer.TT_NUMBER:
s = Integer.toString( new Double(tok.nval).intValue() );
potentialEmptyLine = false;
break;
case '\'':
s = tok.sval;
break;
default:
s = null;
}
// Assume that alternate words on the line are
// parameter and value, respectively.
if( s != null )
{
if( param == null )
{
param = s;
}
else
{
value = s;
arglist.put( param, value );
// log.debug("ARG: "+param+"="+value);
param = null;
}
}
}
// Now, we'll check the body.
if( potentialEmptyLine )
{
StringWriter out = new StringWriter();
FileUtil.copyContents( in, out );
String bodyContent = out.toString();
if( bodyContent != null )
{
arglist.put( PARAM_BODY, bodyContent );
}
}
return arglist;
}
/**
* Parses a plugin. Plugin commands are of the form:
* [{INSERT myplugin WHERE param1=value1, param2=value2}]
* myplugin may either be a class name or a plugin alias.
* <P>
* This is the main entry point that is used.
*
* @param context The current WikiContext.
* @param commandline The full command line, including plugin
* name, parameters and body.
*
* @return HTML as returned by the plugin, or possibly an error
* message.
*/
public String execute( WikiContext context,
String commandline )
throws PluginException
{
if( !m_pluginsEnabled )
return( "" );
PatternMatcher matcher = new Perl5Matcher();
try
{
if( matcher.contains( commandline, m_pluginPattern ) )
{
MatchResult res = matcher.getMatch();
String plugin = res.group(2);
String args = commandline.substring(res.endOffset(0),
commandline.length() -
(commandline.charAt(commandline.length()-1) == '}' ? 1 : 0 ) );
Map arglist = parseArgs( args );
return execute( context, plugin, arglist );
}
}
catch( NoSuchElementException e )
{
String msg = "Missing parameter in plugin definition: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
catch( IOException e )
{
String msg = "Zyrf. Problems with parsing arguments: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
// FIXME: We could either return an empty string "", or
// the original line. If we want unsuccessful requests
// to be invisible, then we should return an empty string.
return commandline;
}
/*
// FIXME: Not functioning, needs to create or fetch PageContext from somewhere.
public class TagPlugin implements WikiPlugin
{
private Class m_tagClass;
public TagPlugin( Class tagClass )
{
m_tagClass = tagClass;
}
public String execute( WikiContext context, Map params )
throws PluginException
{
WikiPluginTag plugin = m_tagClass.newInstance();
}
}
*/
}
|
package com.ecyrd.jspwiki.plugin;
import java.io.*;
import java.net.URL;
import java.util.*;
import org.apache.commons.lang.ClassUtils;
import org.apache.ecs.xhtml.*;
import org.apache.log4j.Logger;
import org.apache.oro.text.regex.*;
import org.jdom.Content;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import com.ecyrd.jspwiki.FileUtil;
import com.ecyrd.jspwiki.InternalWikiException;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.modules.ModuleManager;
import com.ecyrd.jspwiki.modules.WikiModuleInfo;
import com.ecyrd.jspwiki.parser.PluginContent;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Manages plugin classes. There exists a single instance of PluginManager
* per each instance of WikiEngine, that is, each JSPWiki instance.
* <P>
* A plugin is defined to have three parts:
* <OL>
* <li>The plugin class
* <li>The plugin parameters
* <li>The plugin body
* </ol>
*
* For example, in the following line of code:
* <pre>
* [{INSERT com.ecyrd.jspwiki.plugin.FunnyPlugin foo='bar'
* blob='goo'
*
* abcdefghijklmnopqrstuvw
* 01234567890}]
* </pre>
*
* The plugin class is "com.ecyrd.jspwiki.plugin.FunnyPlugin", the
* parameters are "foo" and "blob" (having values "bar" and "goo",
* respectively), and the plugin body is then
* "abcdefghijklmnopqrstuvw\n01234567890". The plugin body is
* accessible via a special parameter called "_body".
* <p>
* If the parameter "debug" is set to "true" for the plugin,
* JSPWiki will output debugging information directly to the page if there
* is an exception.
* <P>
* The class name can be shortened, and marked without the package.
* For example, "FunnyPlugin" would be expanded to
* "com.ecyrd.jspwiki.plugin.FunnyPlugin" automatically. It is also
* possible to defined other packages, by setting the
* "jspwiki.plugin.searchPath" property. See the included
* jspwiki.properties file for examples.
* <P>
* Even though the nominal way of writing the plugin is
* <pre>
* [{INSERT pluginclass WHERE param1=value1...}],
* </pre>
* it is possible to shorten this quite a lot, by skipping the
* INSERT, and WHERE words, and dropping the package name. For
* example:
*
* <pre>
* [{INSERT com.ecyrd.jspwiki.plugin.Counter WHERE name='foo'}]
* </pre>
*
* is the same as
* <pre>
* [{Counter name='foo'}]
* </pre>
* <p>
* Since 2.3.25 you can also define a generic plugin XML properties file per
* each JAR file.
* <pre>
* <modules>
* <plugin class="com.ecyrd.jspwiki.foo.TestPlugin">
* <author>Janne Jalkanen</author>
* <script>foo.js</script>
* <stylesheet>foo.css</stylesheet>
* <alias>code</alias>
* </plugin>
* <plugin class="com.ecyrd.jspwiki.foo.TestPlugin2">
* <author>Janne Jalkanen</author>
* </plugin>
* </modules>
* </pre>
*
* @author Janne Jalkanen
* @since 1.6.1
*/
public class PluginManager extends ModuleManager
{
private static final String PLUGIN_INSERT_PATTERN = "\\{?(INSERT)?\\s*([\\w\\._]+)[ \\t]*(WHERE)?[ \\t]*";
private static Logger log = Logger.getLogger( PluginManager.class );
/**
* This is the default package to try in case the instantiation
* fails.
*/
public static final String DEFAULT_PACKAGE = "com.ecyrd.jspwiki.plugin";
public static final String DEFAULT_FORMS_PACKAGE = "com.ecyrd.jspwiki.forms";
/**
* The property name defining which packages will be searched for properties.
*/
public static final String PROP_SEARCHPATH = "jspwiki.plugin.searchPath";
/**
* The name of the body content. Current value is "_body".
*/
public static final String PARAM_BODY = "_body";
/**
* The name of the command line content parameter. The value is "_cmdline".
*/
public static final String PARAM_CMDLINE = "_cmdline";
/**
* A special name to be used in case you want to see debug output
*/
public static final String PARAM_DEBUG = "debug";
Vector m_searchPath = new Vector();
Pattern m_pluginPattern;
private boolean m_pluginsEnabled = true;
private boolean m_initStage = false;
/**
* Keeps a list of all known plugin classes.
*/
private Map m_pluginClassMap = new HashMap();
/**
* Create a new PluginManager.
*
* @param props Contents of a "jspwiki.properties" file.
*/
public PluginManager( Properties props )
{
String packageNames = props.getProperty( PROP_SEARCHPATH );
if( packageNames != null )
{
StringTokenizer tok = new StringTokenizer( packageNames, "," );
while( tok.hasMoreTokens() )
{
m_searchPath.add( tok.nextToken() );
}
}
registerPlugins();
// The default packages are always added.
m_searchPath.add( DEFAULT_PACKAGE );
m_searchPath.add( DEFAULT_FORMS_PACKAGE );
PatternCompiler compiler = new Perl5Compiler();
try
{
m_pluginPattern = compiler.compile( PLUGIN_INSERT_PATTERN );
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: someone messed with pluginmanager patterns.", e );
throw new InternalWikiException( "PluginManager patterns are broken" );
}
}
/**
* Enables or disables plugin execution.
*/
public void enablePlugins( boolean enabled )
{
m_pluginsEnabled = enabled;
}
/**
* Sets the initialization stage for the initial page scan.
*/
public void setInitStage( boolean value )
{
m_initStage = value;
}
/**
* Returns plugin execution status. If false, plugins are not
* executed when they are encountered on a WikiPage, and an
* empty string is returned in their place.
*/
public boolean pluginsEnabled()
{
return( m_pluginsEnabled );
}
/**
* Returns true if the link is really command to insert
* a plugin.
* <P>
* Currently we just check if the link starts with "{INSERT",
* or just plain "{" but not "{$".
*
* @param link Link text, i.e. the contents of text between [].
* @return True, if this link seems to be a command to insert a plugin here.
*/
public static boolean isPluginLink( String link )
{
return link.startsWith("{INSERT") ||
(link.startsWith("{") && !link.startsWith("{$"));
}
/**
* Attempts to locate a plugin class from the class path
* set in the property file.
*
* @param classname Either a fully fledged class name, or just
* the name of the file (that is,
* "com.ecyrd.jspwiki.plugin.Counter" or just plain "Counter").
*
* @return A found class.
*
* @throws ClassNotFoundException if no such class exists.
*/
private Class findPluginClass( String classname )
throws ClassNotFoundException
{
return ClassUtil.findClass( m_searchPath, classname );
}
/**
* Outputs a HTML-formatted version of a stack trace.
*/
private String stackTrace( Map params, Throwable t )
{
div d = new div();
d.setClass("debug");
d.addElement("Plugin execution failed, stack trace follows:");
StringWriter out = new StringWriter();
t.printStackTrace( new PrintWriter(out) );
d.addElement( new pre( out.toString() ) );
d.addElement( new b( "Parameters to the plugin" ) );
ul list = new ul();
for( Iterator i = params.entrySet().iterator(); i.hasNext(); )
{
Map.Entry e = (Map.Entry) i.next();
String key = (String)e.getKey();
list.addElement(new li( key+"'='"+e.getValue() ) );
}
d.addElement( list );
return d.toString();
}
/**
* Executes a plugin class in the given context.
* <P>Used to be private, but is public since 1.9.21.
*
* @param context The current WikiContext.
* @param classname The name of the class. Can also be a
* shortened version without the package name, since the class name is searched from the
* package search path.
*
* @param params A parsed map of key-value pairs.
*
* @return Whatever the plugin returns.
*
* @throws PluginException If the plugin execution failed for
* some reason.
*
* @since 2.0
*/
public String execute( WikiContext context,
String classname,
Map params )
throws PluginException
{
if( !m_pluginsEnabled )
return( "" );
try
{
WikiPlugin plugin;
boolean debug = TextUtil.isPositive( (String) params.get( PARAM_DEBUG ) );
WikiPluginInfo pluginInfo = (WikiPluginInfo) m_pluginClassMap.get(classname);
if(pluginInfo == null)
{
pluginInfo = WikiPluginInfo.newInstance(findPluginClass( classname ));
registerPlugin(pluginInfo);
}
// Create...
try
{
plugin = (WikiPlugin) pluginInfo.newPluginInstance();
}
catch( InstantiationException e )
{
throw new PluginException( "Cannot instantiate plugin "+classname, e );
}
catch( IllegalAccessException e )
{
throw new PluginException( "Not allowed to access plugin "+classname, e );
}
catch( Exception e )
{
throw new PluginException( "Instantiation of plugin "+classname+" failed.", e );
}
// ...and launch.
try
{
if( m_initStage )
{
if( plugin instanceof InitializablePlugin )
{
((InitializablePlugin)plugin).initialize( context, params );
}
return "";
}
return plugin.execute( context, params );
}
catch( PluginException e )
{
if( debug )
{
return stackTrace( params, e );
}
// Just pass this exception onward.
throw (PluginException) e.fillInStackTrace();
}
catch( Throwable t )
{
// But all others get captured here.
log.info( "Plugin failed while executing:", t );
if( debug )
{
return stackTrace( params, t );
}
throw new PluginException( "Plugin failed", t );
}
}
catch( ClassNotFoundException e )
{
throw new PluginException( "Could not find plugin "+classname, e );
}
catch( ClassCastException e )
{
throw new PluginException( "Class "+classname+" is not a Wiki plugin.", e );
}
}
/**
* Parses plugin arguments. Handles quotes and all other kewl
* stuff.
*
* @param argstring The argument string to the plugin. This is
* typically a list of key-value pairs, using "'" to escape
* spaces in strings, followed by an empty line and then the
* plugin body. In case the parameter is null, will return an
* empty parameter list.
*
* @return A parsed list of parameters. The plugin body is put
* into a special parameter defined by PluginManager.PARAM_BODY.
*
* @throws IOException If the parsing fails.
*/
public Map parseArgs( String argstring )
throws IOException
{
HashMap arglist = new HashMap();
// Protection against funny users.
if( argstring == null ) return arglist;
arglist.put( PARAM_CMDLINE, argstring );
StringReader in = new StringReader(argstring);
StreamTokenizer tok = new StreamTokenizer(in);
int type;
String param = null, value = null;
tok.eolIsSignificant( true );
boolean potentialEmptyLine = false;
boolean quit = false;
while( !quit )
{
String s;
type = tok.nextToken();
switch( type )
{
case StreamTokenizer.TT_EOF:
quit = true;
s = null;
break;
case StreamTokenizer.TT_WORD:
s = tok.sval;
potentialEmptyLine = false;
break;
case StreamTokenizer.TT_EOL:
quit = potentialEmptyLine;
potentialEmptyLine = true;
s = null;
break;
case StreamTokenizer.TT_NUMBER:
s = Integer.toString( new Double(tok.nval).intValue() );
potentialEmptyLine = false;
break;
case '\'':
s = tok.sval;
break;
default:
s = null;
}
// Assume that alternate words on the line are
// parameter and value, respectively.
if( s != null )
{
if( param == null )
{
param = s;
}
else
{
value = s;
arglist.put( param, value );
// log.debug("ARG: "+param+"="+value);
param = null;
}
}
}
// Now, we'll check the body.
if( potentialEmptyLine )
{
StringWriter out = new StringWriter();
FileUtil.copyContents( in, out );
String bodyContent = out.toString();
if( bodyContent != null )
{
arglist.put( PARAM_BODY, bodyContent );
}
}
return arglist;
}
/**
* Parses a plugin. Plugin commands are of the form:
* [{INSERT myplugin WHERE param1=value1, param2=value2}]
* myplugin may either be a class name or a plugin alias.
* <P>
* This is the main entry point that is used.
*
* @param context The current WikiContext.
* @param commandline The full command line, including plugin
* name, parameters and body.
*
* @return HTML as returned by the plugin, or possibly an error
* message.
*/
public String execute( WikiContext context,
String commandline )
throws PluginException
{
if( !m_pluginsEnabled )
return( "" );
PatternMatcher matcher = new Perl5Matcher();
try
{
if( matcher.contains( commandline, m_pluginPattern ) )
{
MatchResult res = matcher.getMatch();
String plugin = res.group(2);
String args = commandline.substring(res.endOffset(0),
commandline.length() -
(commandline.charAt(commandline.length()-1) == '}' ? 1 : 0 ) );
Map arglist = parseArgs( args );
return execute( context, plugin, arglist );
}
}
catch( NoSuchElementException e )
{
String msg = "Missing parameter in plugin definition: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
catch( IOException e )
{
String msg = "Zyrf. Problems with parsing arguments: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
// FIXME: We could either return an empty string "", or
// the original line. If we want unsuccessful requests
// to be invisible, then we should return an empty string.
return commandline;
}
public Content parsePluginLine( WikiContext context, String commandline )
throws PluginException
{
PatternMatcher matcher = new Perl5Matcher();
try
{
if( matcher.contains( commandline, m_pluginPattern ) )
{
MatchResult res = matcher.getMatch();
String plugin = res.group(2);
String args = commandline.substring(res.endOffset(0),
commandline.length() -
(commandline.charAt(commandline.length()-1) == '}' ? 1 : 0 ) );
Map arglist = parseArgs( args );
PluginContent result = new PluginContent( plugin, arglist );
return result;
}
}
catch( ClassCastException e )
{
log.error( "Invalid type offered in parsing plugin arguments.", e );
throw new InternalWikiException("Oops, someone offered !String!");
}
catch( NoSuchElementException e )
{
String msg = "Missing parameter in plugin definition: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
catch( IOException e )
{
String msg = "Zyrf. Problems with parsing arguments: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
return null;
}
/** Registrar a plugin.
*/
private void registerPlugin(WikiPluginInfo pluginClass)
{
String name;
// Registrar the plugin with the className without the package-part
name = pluginClass.getName();
if(name != null)
{
log.debug("Registering plugin [name]: " + name);
m_pluginClassMap.put(name, pluginClass);
}
// Registrar the plugin with a short convenient name.
name = pluginClass.getAlias();
if(name != null)
{
log.debug("Registering plugin [shortName]: " + name);
m_pluginClassMap.put(name, pluginClass);
}
// Registrar the plugin with the className with the package-part
name = pluginClass.getClassName();
if(name != null)
{
log.debug("Registering plugin [className]: " + name);
m_pluginClassMap.put(name, pluginClass);
}
}
private void registerPlugins()
{
log.info( "Registering plugins" );
SAXBuilder builder = new SAXBuilder();
try
{
// Register all plugins which have created a resource containing its properties.
// Get all resources of all plugins.
Enumeration resources = getClass().getClassLoader().getResources( PLUGIN_RESOURCE_LOCATION );
while( resources.hasMoreElements() )
{
URL resource = (URL) resources.nextElement();
try
{
log.debug( "Processing XML: " + resource );
Document doc = builder.build( resource );
List plugins = XPath.selectNodes( doc, "/modules/plugin");
for( Iterator i = plugins.iterator(); i.hasNext(); )
{
Element pluginEl = (Element) i.next();
String className = pluginEl.getAttributeValue("class");
WikiPluginInfo pluginInfo = WikiPluginInfo.newInstance( className, pluginEl );
if( pluginInfo != null )
{
registerPlugin( pluginInfo );
}
}
}
catch( java.io.IOException e )
{
log.error( "Couldn't load " + PLUGIN_RESOURCE_LOCATION + " resources: " + resource, e );
}
catch( JDOMException e )
{
log.error( "Error parsing XML for plugin: "+PLUGIN_RESOURCE_LOCATION );
}
}
}
catch( java.io.IOException e )
{
log.error( "Couldn't load all " + PLUGIN_RESOURCE_LOCATION + " resources", e );
}
}
/**
* Contains information about a bunch of plugins.
*
* @author Kees Kuip
* @author Janne Jalkanen
*
* @since
*/
// FIXME: This class needs a better interface to return all sorts of possible
// information from the plugin XML. In fact, it probably should have
// some sort of a superclass system.
protected static class WikiPluginInfo
extends WikiModuleInfo
{
private String m_className;
private String m_alias;
private Class m_clazz;
protected static WikiPluginInfo newInstance( String className, Element el )
{
if( className == null || className.length() == 0 ) return null;
WikiPluginInfo info = new WikiPluginInfo( className );
info.initializeFromXML( el );
return info;
}
protected void initializeFromXML( Element el )
{
super.initializeFromXML( el );
m_alias = el.getChildText("alias");
}
protected static WikiPluginInfo newInstance( Class clazz )
{
WikiPluginInfo info = new WikiPluginInfo( clazz.getName() );
return info;
}
private WikiPluginInfo(String className)
{
setClassName(className);
}
private void setClassName(String fullClassName)
{
m_name = ClassUtils.getShortClassName( fullClassName );
m_className = fullClassName;
}
public String getClassName()
{
return m_className;
}
public String getAlias()
{
return m_alias;
}
public WikiPlugin newPluginInstance()
throws ClassNotFoundException,
InstantiationException,
IllegalAccessException
{
if( m_clazz == null )
{
m_clazz = Class.forName(m_className);
}
return (WikiPlugin) m_clazz.newInstance();
}
public String getIncludeText(String type)
{
try
{
if( type.equals("script") )
{
return getScriptText();
}
else if( type.equals("stylesheet") )
{
return getStylesheetText();
}
}
catch(Exception ex)
{
return ex.getMessage();
}
return null;
}
private String getScriptText()
throws IOException
{
if (m_scriptText != null)
{
return m_scriptText;
}
if (m_scriptLocation == null)
{
return "";
}
try
{
m_scriptText = getTextResource(m_scriptLocation);
}
catch(IOException ex)
{
// Only throw this exception once!
m_scriptText = "";
throw ex;
}
return m_scriptText;
}
private String getStylesheetText()
throws IOException
{
if (m_stylesheetText != null)
{
return m_stylesheetText;
}
if (m_stylesheetLocation == null)
{
return "";
}
try
{
m_stylesheetText = getTextResource(m_stylesheetLocation);
}
catch(IOException ex)
{
// Only throw this exception once!
m_stylesheetText = "";
throw ex;
}
return m_stylesheetText;
}
public String toString()
{
return "Plugin :[name=" + m_name + "][className=" + m_className + "]";
}
} // WikiPluginClass
}
|
package com.ecyrd.jspwiki.plugin;
import org.apache.oro.text.regex.*;
import org.apache.log4j.Logger;
import org.apache.ecs.xhtml.*;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Map;
import java.util.Vector;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.HashMap;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.FileUtil;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.InternalWikiException;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Manages plugin classes. There exists a single instance of PluginManager
* per each instance of WikiEngine, that is, each JSPWiki instance.
* <P>
* A plugin is defined to have three parts:
* <OL>
* <li>The plugin class
* <li>The plugin parameters
* <li>The plugin body
* </ol>
*
* For example, in the following line of code:
* <pre>
* [{INSERT com.ecyrd.jspwiki.plugin.FunnyPlugin foo='bar'
* blob='goo'
*
* abcdefghijklmnopqrstuvw
* 01234567890}]
* </pre>
*
* The plugin class is "com.ecyrd.jspwiki.plugin.FunnyPlugin", the
* parameters are "foo" and "blob" (having values "bar" and "goo",
* respectively), and the plugin body is then
* "abcdefghijklmnopqrstuvw\n01234567890". The plugin body is
* accessible via a special parameter called "_body".
* <p>
* If the parameter "debug" is set to "true" for the plugin,
* JSPWiki will output debugging information directly to the page if there
* is an exception.
* <P>
* The class name can be shortened, and marked without the package.
* For example, "FunnyPlugin" would be expanded to
* "com.ecyrd.jspwiki.plugin.FunnyPlugin" automatically. It is also
* possible to defined other packages, by setting the
* "jspwiki.plugin.searchPath" property. See the included
* jspwiki.properties file for examples.
* <P>
* Even though the nominal way of writing the plugin is
* <pre>
* [{INSERT pluginclass WHERE param1=value1...}],
* </pre>
* it is possible to shorten this quite a lot, by skipping the
* INSERT, and WHERE words, and dropping the package name. For
* example:
*
* <pre>
* [{INSERT com.ecyrd.jspwiki.plugin.Counter WHERE name='foo'}]
* </pre>
*
* is the same as
* <pre>
* [{Counter name='foo'}]
* </pre>
*
* @author Janne Jalkanen
* @since 1.6.1
*/
public class PluginManager
{
private static Logger log = Logger.getLogger( PluginManager.class );
/**
* This is the default package to try in case the instantiation
* fails.
*/
public static final String DEFAULT_PACKAGE = "com.ecyrd.jspwiki.plugin";
public static final String DEFAULT_FORMS_PACKAGE = "com.ecyrd.jspwiki.forms";
/**
* The property name defining which packages will be searched for properties.
*/
public static final String PROP_SEARCHPATH = "jspwiki.plugin.searchPath";
/**
* The name of the body content. Current value is "_body".
*/
public static final String PARAM_BODY = "_body";
/**
* A special name to be used in case you want to see debug output
*/
public static final String PARAM_DEBUG = "debug";
Vector m_searchPath = new Vector();
Pattern m_pluginPattern;
private boolean m_pluginsEnabled = true;
private boolean m_initStage = false;
/**
* Create a new PluginManager.
*
* @param props Contents of a "jspwiki.properties" file.
*/
public PluginManager( Properties props )
{
String packageNames = props.getProperty( PROP_SEARCHPATH );
if( packageNames != null )
{
StringTokenizer tok = new StringTokenizer( packageNames, "," );
while( tok.hasMoreTokens() )
{
m_searchPath.add( tok.nextToken() );
}
}
// The default packages are always added.
m_searchPath.add( DEFAULT_PACKAGE );
m_searchPath.add( DEFAULT_FORMS_PACKAGE );
PatternCompiler compiler = new Perl5Compiler();
try
{
m_pluginPattern = compiler.compile( "\\{?(INSERT)?\\s*([\\w\\._]+)[ \\t]*(WHERE)?[ \\t]*" );
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: someone messed with pluginmanager patterns.", e );
throw new InternalWikiException( "PluginManager patterns are broken" );
}
}
/**
* Enables or disables plugin execution.
*/
public void enablePlugins( boolean enabled )
{
m_pluginsEnabled = enabled;
}
/**
* Sets the initialization stage for the initial page scan.
*/
public void setInitStage( boolean value )
{
m_initStage = value;
}
/**
* Returns plugin execution status. If false, plugins are not
* executed when they are encountered on a WikiPage, and an
* empty string is returned in their place.
*/
public boolean pluginsEnabled()
{
return( m_pluginsEnabled );
}
/**
* Returns true if the link is really command to insert
* a plugin.
* <P>
* Currently we just check if the link starts with "{INSERT",
* or just plain "{" but not "{$".
*
* @param link Link text, i.e. the contents of text between [].
* @return True, if this link seems to be a command to insert a plugin here.
*/
public static boolean isPluginLink( String link )
{
return link.startsWith("{INSERT") ||
(link.startsWith("{") && !link.startsWith("{$"));
}
/**
* Attempts to locate a plugin class from the class path
* set in the property file.
*
* @param classname Either a fully fledged class name, or just
* the name of the file (that is,
* "com.ecyrd.jspwiki.plugin.Counter" or just plain "Counter").
*
* @return A found class.
*
* @throws ClassNotFoundException if no such class exists.
*/
private Class findPluginClass( String classname )
throws ClassNotFoundException
{
return ClassUtil.findClass( m_searchPath, classname );
}
/**
* Outputs a HTML-formatted version of a stack trace.
*/
private String stackTrace( Map params, Throwable t )
{
div d = new div();
d.setClass("debug");
d.addElement("Plugin execution failed, stack trace follows:");
StringWriter out = new StringWriter();
t.printStackTrace( new PrintWriter(out) );
d.addElement( new pre( out.toString() ) );
d.addElement( new b( "Parameters to the plugin" ) );
ul list = new ul();
for( Iterator i = params.keySet().iterator(); i.hasNext(); )
{
String key = (String) i.next();
list.addElement(new li( key+"'='"+params.get(key) ) );
}
d.addElement( list );
return d.toString();
}
/**
* Executes a plugin class in the given context.
* <P>Used to be private, but is public since 1.9.21.
*
* @param context The current WikiContext.
* @param classname The name of the class. Can also be a
* shortened version without the package name, since the class name is searched from the
* package search path.
*
* @param params A parsed map of key-value pairs.
*
* @return Whatever the plugin returns.
*
* @throws PluginException If the plugin execution failed for
* some reason.
*
* @since 2.0
*/
public String execute( WikiContext context,
String classname,
Map params )
throws PluginException
{
if( !m_pluginsEnabled )
return( "" );
try
{
Class pluginClass;
WikiPlugin plugin;
boolean debug = TextUtil.isPositive( (String) params.get( PARAM_DEBUG ) );
pluginClass = findPluginClass( classname );
// Create...
try
{
plugin = (WikiPlugin) pluginClass.newInstance();
}
catch( InstantiationException e )
{
throw new PluginException( "Cannot instantiate plugin "+classname, e );
}
catch( IllegalAccessException e )
{
throw new PluginException( "Not allowed to access plugin "+classname, e );
}
catch( Exception e )
{
throw new PluginException( "Instantiation of plugin "+classname+" failed.", e );
}
// ...and launch.
try
{
if( m_initStage )
{
if( plugin instanceof InitializablePlugin )
{
((InitializablePlugin)plugin).initialize( context, params );
}
return "";
}
else
{
return plugin.execute( context, params );
}
}
catch( PluginException e )
{
if( debug )
{
return stackTrace( params, e );
}
// Just pass this exception onward.
throw (PluginException) e.fillInStackTrace();
}
catch( Throwable t )
{
// But all others get captured here.
log.info( "Plugin failed while executing:", t );
if( debug )
{
return stackTrace( params, t );
}
throw new PluginException( "Plugin failed", t );
}
}
catch( ClassNotFoundException e )
{
throw new PluginException( "Could not find plugin "+classname, e );
}
catch( ClassCastException e )
{
throw new PluginException( "Class "+classname+" is not a Wiki plugin.", e );
}
}
/**
* Parses plugin arguments. Handles quotes and all other kewl
* stuff.
*
* @param argstring The argument string to the plugin. This is
* typically a list of key-value pairs, using "'" to escape
* spaces in strings, followed by an empty line and then the
* plugin body. In case the parameter is null, will return an
* empty parameter list.
*
* @return A parsed list of parameters. The plugin body is put
* into a special parameter defined by PluginManager.PARAM_BODY.
*
* @throws IOException If the parsing fails.
*/
public Map parseArgs( String argstring )
throws IOException
{
HashMap arglist = new HashMap();
// Protection against funny users.
if( argstring == null ) return arglist;
StringReader in = new StringReader(argstring);
StreamTokenizer tok = new StreamTokenizer(in);
int type;
String param = null, value = null;
tok.eolIsSignificant( true );
boolean potentialEmptyLine = false;
boolean quit = false;
while( !quit )
{
String s;
type = tok.nextToken();
switch( type )
{
case StreamTokenizer.TT_EOF:
quit = true;
s = null;
break;
case StreamTokenizer.TT_WORD:
s = tok.sval;
potentialEmptyLine = false;
break;
case StreamTokenizer.TT_EOL:
quit = potentialEmptyLine;
potentialEmptyLine = true;
s = null;
break;
case StreamTokenizer.TT_NUMBER:
s = Integer.toString( new Double(tok.nval).intValue() );
potentialEmptyLine = false;
break;
case '\'':
s = tok.sval;
break;
default:
s = null;
}
// Assume that alternate words on the line are
// parameter and value, respectively.
if( s != null )
{
if( param == null )
{
param = s;
}
else
{
value = s;
arglist.put( param, value );
// log.debug("ARG: "+param+"="+value);
param = null;
}
}
}
// Now, we'll check the body.
if( potentialEmptyLine )
{
StringWriter out = new StringWriter();
FileUtil.copyContents( in, out );
String bodyContent = out.toString();
if( bodyContent != null )
{
arglist.put( PARAM_BODY, bodyContent );
}
}
return arglist;
}
/**
* Parses a plugin. Plugin commands are of the form:
* [{INSERT myplugin WHERE param1=value1, param2=value2}]
* myplugin may either be a class name or a plugin alias.
* <P>
* This is the main entry point that is used.
*
* @param context The current WikiContext.
* @param commandline The full command line, including plugin
* name, parameters and body.
*
* @return HTML as returned by the plugin, or possibly an error
* message.
*/
public String execute( WikiContext context,
String commandline )
throws PluginException
{
if( !m_pluginsEnabled )
return( "" );
PatternMatcher matcher = new Perl5Matcher();
try
{
if( matcher.contains( commandline, m_pluginPattern ) )
{
MatchResult res = matcher.getMatch();
String plugin = res.group(2);
String args = commandline.substring(res.endOffset(0),
commandline.length() -
(commandline.charAt(commandline.length()-1) == '}' ? 1 : 0 ) );
Map arglist = parseArgs( args );
return execute( context, plugin, arglist );
}
}
catch( NoSuchElementException e )
{
String msg = "Missing parameter in plugin definition: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
catch( IOException e )
{
String msg = "Zyrf. Problems with parsing arguments: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
// FIXME: We could either return an empty string "", or
// the original line. If we want unsuccessful requests
// to be invisible, then we should return an empty string.
return commandline;
}
/*
// FIXME: Not functioning, needs to create or fetch PageContext from somewhere.
public class TagPlugin implements WikiPlugin
{
private Class m_tagClass;
public TagPlugin( Class tagClass )
{
m_tagClass = tagClass;
}
public String execute( WikiContext context, Map params )
throws PluginException
{
WikiPluginTag plugin = m_tagClass.newInstance();
}
}
*/
}
|
package com.esotericsoftware.kryo;
import static com.esotericsoftware.minlog.Log.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
/**
* Serializes objects to and from byte arrays and streams.<br>
* <br>
* This class uses a buffer internally and is not thread safe.
* @author Nathan Sweet <misc@n4te.com>
*/
public class ObjectBuffer {
private Kryo kryo;
private final int maxCapacity;
private ByteBuffer buffer;
private byte[] bytes;
/**
* Creates an ObjectStream with an initial buffer size of 2KB and a maximum size of 16KB.
*/
public ObjectBuffer (Kryo kryo) {
this(kryo, 2 * 1024, 16 * 1024);
}
/**
* @param maxCapacity The initial and maximum size in bytes of an object that can be read or written.
* @see #ObjectBuffer(Kryo, int, int)
*/
public ObjectBuffer (Kryo kryo, int maxCapacity) {
this(kryo, maxCapacity, maxCapacity);
}
/**
* @param initialCapacity The initial maximum size in bytes of an object that can be read or written.
* @param maxCapacity The maximum size in bytes of an object that can be read or written. The capacity is doubled until the
* maxCapacity is exceeded, then SerializationException is thrown by the read and write methods.
*/
public ObjectBuffer (Kryo kryo, int initialCapacity, int maxCapacity) {
this.kryo = kryo;
buffer = ByteBuffer.allocate(initialCapacity);
bytes = buffer.array();
this.maxCapacity = maxCapacity;
}
public void setKryo (Kryo kryo) {
this.kryo = kryo;
}
/**
* Reads the specified number of bytes from the stream into the buffer.
* @param contentLength The number of bytes to read, or -1 to read to the end of the stream.
*/
private void readToBuffer (InputStream input, int contentLength) {
if (contentLength == -1) contentLength = Integer.MAX_VALUE;
try {
int position = 0;
while (position < contentLength) {
int count = input.read(bytes, position, contentLength - position);
if (count == -1) break;
position += count;
if (position == bytes.length && !resizeBuffer(true))
throw new SerializationException("Buffer limit exceeded: " + maxCapacity);
}
buffer.position(0);
buffer.limit(position);
} catch (IOException ex) {
throw new SerializationException("Error reading object bytes.", ex);
}
}
/**
* Reads to the end of the stream and returns the deserialized object.
* @see Kryo#readClassAndObject(ByteBuffer)
*/
public Object readClassAndObject (InputStream input) {
readToBuffer(input, -1);
return kryo.readClassAndObject(buffer);
}
/**
* Reads the specified number of bytes and returns the deserialized object.
* @see Kryo#readClassAndObject(ByteBuffer)
*/
public Object readClassAndObject (InputStream input, int contentLength) {
readToBuffer(input, contentLength);
return kryo.readClassAndObject(buffer);
}
/**
* Reads to the end of the stream and returns the deserialized object.
* @see Kryo#readObject(ByteBuffer, Class)
*/
public <T> T readObject (InputStream input, Class<T> type) {
readToBuffer(input, -1);
return kryo.readObject(buffer, type);
}
/**
* Reads the specified number of bytes and returns the deserialized object.
* @see Kryo#readObject(ByteBuffer, Class)
*/
public <T> T readObject (InputStream input, int contentLength, Class<T> type) {
readToBuffer(input, contentLength);
return kryo.readObject(buffer, type);
}
/**
* Reads to the end of the stream and returns the deserialized object.
* @see Kryo#readObjectData(ByteBuffer, Class)
*/
public <T> T readObjectData (InputStream input, Class<T> type) {
readToBuffer(input, -1);
return kryo.readObjectData(buffer, type);
}
/**
* Reads the specified number of bytes and returns the deserialized object.
* @see Kryo#readObjectData(ByteBuffer, Class)
*/
public <T> T readObjectData (InputStream input, int contentLength, Class<T> type) {
readToBuffer(input, contentLength);
return kryo.readObjectData(buffer, type);
}
/**
* @see Kryo#writeClassAndObject(ByteBuffer, Object)
*/
public void writeClassAndObject (OutputStream output, Object object) {
buffer.clear();
while (true) {
try {
kryo.writeClassAndObject(buffer, object);
break;
} catch (SerializationException ex) {
if (!ex.causedBy(BufferOverflowException.class)) throw ex;
if (!resizeBuffer(false)) {
throw new SerializationException("Buffer limit exceeded serializing object of type: "
+ object.getClass().getName(), ex);
}
Kryo.getContext().reset();
}
}
writeToStream(output);
}
/**
* @see Kryo#writeObject(ByteBuffer, Object)
*/
public void writeObject (OutputStream output, Object object) {
buffer.clear();
while (true) {
try {
kryo.writeObject(buffer, object);
break;
} catch (SerializationException ex) {
if (!ex.causedBy(BufferOverflowException.class)) throw ex;
if (!resizeBuffer(false)) {
throw new SerializationException("Buffer limit exceeded serializing object of type: "
+ object.getClass().getName(), ex);
}
Kryo.getContext().reset();
}
}
writeToStream(output);
}
/**
* @see Kryo#writeObjectData(ByteBuffer, Object)
*/
public void writeObjectData (OutputStream output, Object object) {
buffer.clear();
while (true) {
try {
kryo.writeObjectData(buffer, object);
break;
} catch (SerializationException ex) {
if (!ex.causedBy(BufferOverflowException.class)) throw ex;
if (!resizeBuffer(false)) {
throw new SerializationException("Buffer limit exceeded serializing object of type: "
+ object.getClass().getName(), ex);
}
Kryo.getContext().reset();
}
}
writeToStream(output);
}
private void writeToStream (OutputStream output) {
try {
output.write(bytes, 0, buffer.position());
} catch (IOException ex) {
throw new SerializationException("Error writing object bytes.", ex);
}
}
/**
* @see Kryo#readClassAndObject(ByteBuffer)
*/
public Object readClassAndObject (byte[] objectBytes) {
return kryo.readClassAndObject(ByteBuffer.wrap(objectBytes));
}
/**
* @see Kryo#readObject(ByteBuffer, Class)
*/
public <T> T readObject (byte[] objectBytes, Class<T> type) {
return kryo.readObject(ByteBuffer.wrap(objectBytes), type);
}
/**
* @see Kryo#readObjectData(ByteBuffer, Class)
*/
public <T> T readObjectData (byte[] objectBytes, Class<T> type) {
return kryo.readObjectData(ByteBuffer.wrap(objectBytes), type);
}
/**
* @see Kryo#writeClassAndObject(ByteBuffer, Object)
*/
public byte[] writeClassAndObject (Object object) {
buffer.clear();
while (true) {
try {
kryo.writeClassAndObject(buffer, object);
break;
} catch (SerializationException ex) {
if (!ex.causedBy(BufferOverflowException.class)) throw ex;
if (!resizeBuffer(false)) {
throw new SerializationException("Buffer limit exceeded serializing object of type: "
+ object.getClass().getName(), ex);
}
Kryo.getContext().reset();
}
}
return writeToBytes();
}
/**
* @see Kryo#writeObject(ByteBuffer, Object)
*/
public byte[] writeObject (Object object) {
buffer.clear();
while (true) {
try {
kryo.writeObject(buffer, object);
break;
} catch (SerializationException ex) {
if (!ex.causedBy(BufferOverflowException.class)) throw ex;
if (!resizeBuffer(false)) {
throw new SerializationException("Buffer limit exceeded serializing object of type: "
+ object.getClass().getName(), ex);
}
Kryo.getContext().reset();
}
}
return writeToBytes();
}
/**
* @see Kryo#writeObjectData(ByteBuffer, Object)
*/
public byte[] writeObjectData (Object object) {
buffer.clear();
while (true) {
try {
kryo.writeObjectData(buffer, object);
break;
} catch (SerializationException ex) {
if (!ex.causedBy(BufferOverflowException.class)) throw ex;
if (!resizeBuffer(false)) {
throw new SerializationException("Buffer limit exceeded serializing object of type: "
+ object.getClass().getName(), ex);
}
Kryo.getContext().reset();
}
}
return writeToBytes();
}
private byte[] writeToBytes () {
byte[] objectBytes = new byte[buffer.position()];
System.arraycopy(bytes, 0, objectBytes, 0, objectBytes.length);
return objectBytes;
}
private boolean resizeBuffer (boolean preserveContents) {
int capacity = buffer.capacity();
if (capacity == maxCapacity) return false;
int newCapacity = Math.min(maxCapacity, capacity * 2);
ByteBuffer newBuffer = ByteBuffer.allocate(newCapacity);
byte[] newArray = newBuffer.array();
if (preserveContents) System.arraycopy(bytes, 0, newArray, 0, bytes.length);
buffer = newBuffer;
bytes = newArray;
if (DEBUG) debug("kryo", "Resized ObjectBuffer to: " + newCapacity);
return true;
}
}
|
package com.harryjamesuk.ribbit;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class SignUpActivity extends Activity {
protected EditText mUsername;
protected EditText mPassword;
protected EditText mEmail;
protected Button mSignUpButton;
protected Button mCancelButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_sign_up);
ActionBar actionBar = getActionBar();
actionBar.hide();
mUsername = (EditText)findViewById(R.id.usernameField);
mPassword = (EditText)findViewById(R.id.passwordField);
mEmail = (EditText)findViewById(R.id.emailField);
mCancelButton = (Button)findViewById(R.id.cancelButton);
mCancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mSignUpButton = (Button)findViewById(R.id.signupButton);
mSignUpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
username = username.trim();
password = password.trim();
email = email.trim();
if (username.isEmpty() || password.isEmpty() || email.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// Create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser newUser = new ParseUser();
newUser.setUsername(username);
newUser.setPassword(password);
newUser.setEmail(email);
newUser.signUpInBackground(new SignUpCallback() {
@Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
};
}
|
package com.jme3.ai.agents.util;
import com.jme3.scene.Spatial;
public abstract class AbstractBullet extends PhysicalObject {
/**
* Weapon from which bullet was fired.
*/
protected AbstractWeapon weapon;
/**
* Constructor for AbstractBullet.
*
* @param weapon weapon from which bullet was fired
* @param spatial spatial for bullet
*/
public AbstractBullet(AbstractWeapon weapon, Spatial spatial) {
this.weapon = weapon;
this.spatial = spatial;
}
/**
* Get weapon.
*
* @return weapon from which bullet was fired
*/
public AbstractWeapon getWeapon() {
return weapon;
}
/**
* Setting weapon.
*
* @param weapon weapon from which bullet was fired
*/
public void setWeapon(AbstractWeapon weapon) {
this.weapon = weapon;
}
}
|
package com.jme3.ai.agents.util;
import com.jme3.ai.agents.Agent;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
public abstract class AbstractWeapon {
/**
* Name of weapon.
*/
protected String name;
/**
* Name of agent to whom weapon is added.
*/
protected Agent agent;
/**
* Maximum range of weapon.
*/
protected float maxAttackRange;
/**
* Minimum range of weapon.
*/
protected float minAttackRange = 0;
/**
* Attack damage of weapon.
*/
protected float attackDamage;
/**
* Number of bullet that this weapon have left.
*/
protected int numberOfBullets;
/**
* Spatial for weapon.
*/
protected Spatial spatial;
/**
* One weapon have one type of bullet. Each fired bullet can be in it's own
* update().
*/
protected Bullet bullet;
/**
* Check if enemy agent is in range of weapon.
* @param target
* @return
*/
public boolean isInRange(Agent target) {
if (agent.getLocalTranslation().distance(target.getLocalTranslation()) > maxAttackRange) {
return false;
}
if (agent.getLocalTranslation().distance(target.getLocalTranslation()) < minAttackRange) {
return false;
}
return true;
}
/**
* Check if there is any bullets in weapon.
* @return true - has, false - no, it doesn't
*/
public boolean hasBullets(){
if (numberOfBullets == 0) {
return false;
}
return true;
}
/**
* Method for creating bullets and setting them to move.
* @param target agent that should be shoot at
* @param tpf time per frame
* @throws Exception when there is no more bullets left
*/
public void shootAt(Agent target, float tpf) throws Exception{
if (numberOfBullets == 0) {
throw new Exception("No more bullets");
}
Bullet firedBullet = controlShootAt(target, tpf);
Game.getInstance().addBullet(firedBullet);
if (numberOfBullets != -1) {
numberOfBullets
}
}
protected abstract Bullet controlShootAt(Agent target, float tpf);
/**
* Method for creating bullets and setting them to move.
* @param direction direction of bullets to go
* @param tpf time per frame
* @throws Exception when hasBullets()== false
*/
public void shootAt(Vector3f direction, float tpf) throws Exception{
if (numberOfBullets == 0) {
throw new Exception("No more bullets");
}
Bullet firedBullet = controlShootAt(direction, tpf);
//((Node) Game.getInstance().getRootNode()).attachChild(firedBullet.getSpatial());
Game.getInstance().addBullet(firedBullet);
if (numberOfBullets != -1) {
numberOfBullets
}
}
protected abstract Bullet controlShootAt(Vector3f direction, float tpf);
public String getName() {
return name;
}
public Agent getAgent() {
return agent;
}
public float getAttackDamage() {
return attackDamage;
}
public int getNumberOfBullets() {
return numberOfBullets;
}
public Spatial getSpatial() {
return spatial;
}
public void setAgent(Agent agent) {
this.agent = agent;
}
public void setAttackDamage(float attackDamage) {
this.attackDamage = attackDamage;
}
public void setNumberOfBullets(int numberOfBullets) {
this.numberOfBullets = numberOfBullets;
}
public void addNumberOfBullets(int numberOfBullets) {
this.numberOfBullets += numberOfBullets;
}
public void setSpatial(Spatial spatial) {
this.spatial = spatial;
}
public Bullet getBullet() {
return bullet;
}
public void setBullet(Bullet bullet) {
this.bullet = bullet;
}
public float getMaxAttackRange() {
return maxAttackRange;
}
public void setMaxAttackRange(float maxAttackRange) {
this.maxAttackRange = maxAttackRange;
}
public float getMinAttackRange() {
return minAttackRange;
}
public void setMinAttackRange(float minAttackRange) {
this.minAttackRange = minAttackRange;
}
}
|
package com.celements.rights.access;
import static junit.framework.Assert.*;
import static org.easymock.EasyMock.*;
import org.easymock.Capture;
import org.junit.Before;
import org.junit.Test;
import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.model.reference.WikiReference;
import com.celements.common.test.AbstractBridgedComponentTestCase;
import com.celements.rights.access.internal.EntityReferenceRandomCompleter;
import com.celements.rights.access.internal.IEntityReferenceRandomCompleterRole;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.web.Utils;
public class EntityReferenceRandomCompleterTest extends AbstractBridgedComponentTestCase {
private EntityReferenceRandomCompleter randomCompleter;
private XWikiContext context;
private DocumentAccessBridge docAccessBridgeMock;
@Before
public void setUp_EntityReferenceRandomCompleterTest() throws Exception {
docAccessBridgeMock = registerComponentMock(DocumentAccessBridge.class);
context = getContext();
randomCompleter = (EntityReferenceRandomCompleter) Utils.getComponent(
IEntityReferenceRandomCompleterRole.class);
}
@Test
public void testRandomCompleteSpaceRef_entityType_Document() {
DocumentReference entityRef = new DocumentReference(context.getDatabase(), "mySpace",
"myTestDoc");
replayDefault();
assertSame(entityRef, randomCompleter.randomCompleteSpaceRef(entityRef));
verifyDefault();
}
@Test
public void testRandomCompleteSpaceRef_entityType_Wiki() {
WikiReference entityRef = new WikiReference(context.getDatabase());
replayDefault();
assertSame(entityRef, randomCompleter.randomCompleteSpaceRef(entityRef));
verifyDefault();
}
@Test
public void testRandomCompleteSpaceRef_entityType_Space() {
WikiReference wikiRef = new WikiReference(context.getDatabase());
SpaceReference entityRef = new SpaceReference("mySpace", wikiRef);
Capture<DocumentReference> randomDocRefCapture = new Capture<>();
expect(docAccessBridgeMock.exists(capture(randomDocRefCapture))).andReturn(false
).once();
replayDefault();
DocumentReference randomDocRef =
(DocumentReference) randomCompleter.randomCompleteSpaceRef(entityRef);
assertEquals(entityRef, randomDocRef.getLastSpaceReference());
assertEquals(randomDocRefCapture.getValue(), randomDocRef);
verifyDefault();
}
@Test
public void testRandomCompleteSpaceRef_entityType_Space_twoLookups() {
WikiReference wikiRef = new WikiReference(context.getDatabase());
SpaceReference entityRef = new SpaceReference("mySpace", wikiRef);
Capture<DocumentReference> randomDocRefCapture = new Capture<>();
expect(docAccessBridgeMock.exists(capture(randomDocRefCapture))).andReturn(true
).once();
Capture<DocumentReference> randomDocRefCapture2 = new Capture<>();
expect(docAccessBridgeMock.exists(capture(randomDocRefCapture2))).andReturn(false
).once();
replayDefault();
EntityReference randomDocRef = randomCompleter.randomCompleteSpaceRef(entityRef);
verifyDefault();
DocumentReference docRefFirst = randomDocRefCapture.getValue();
DocumentReference docRefSecond = randomDocRefCapture2.getValue();
assertNotNull(docRefFirst);
assertNotNull(docRefSecond);
assertEquals(entityRef, docRefFirst.getLastSpaceReference());
assertFalse("first and second capture may not be equal", docRefFirst.equals(
randomDocRef));
assertEquals(entityRef, docRefSecond.getLastSpaceReference());
assertEquals(docRefSecond, randomDocRef);
}
}
|
package com.justjournal.ctl;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.log4j.Category;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
public class UploadAvatarSubmit extends Protected {
private static Category log = Category.getInstance(UploadAvatarSubmit.class.getName());
public String getMyLogin() {
return currentLoginName();
}
protected String insidePerform() throws Exception {
log.debug("Begin inside perform");
int RowsAffected = 0;
HttpServletRequest req = this.getCtx().getRequest();
boolean isMultipart = FileUpload.isMultipartContent(req);
if (isMultipart) {
log.debug("we have a multipart file upload");
DiskFileUpload upload = new DiskFileUpload();
// set limits
upload.setSizeMax(15 * 1024);
upload.setSizeThreshold(15 * 1024);
upload.setRepositoryPath("/tmp"); // should be changed.
// process request
List /*FileItem*/ items = upload.parseRequest(req);
for (Object item1 : items) {
FileItem item = (FileItem) item1;
if (item.isFormField()) {
// do stuff here... ignore for now
} else { // we're a file
//String fieldName = item.getFieldName();
//String fileName = item.getName();
String contentType = item.getContentType();
//boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
// must be large enough
if (sizeInBytes > 500) {
byte[] data = item.get();
Context ctx;
DataSource ds = null;
Connection conn = null;
PreparedStatement stmt = null; // insert statement
PreparedStatement stmtOn = null; // turn on avatar preference.
PreparedStatement stmtRemove = null; // delete old ones
try {
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/jjDB");
} catch (Exception e) {
log.debug(e.getMessage());
this.addError("Database", "Could not retrieve database resources.");
}
try {
conn = ds.getConnection();
stmtRemove = conn.prepareStatement("DELETE FROM user_pic WHERE id=? LIMIT 1");
stmtRemove.setInt(1, this.currentLoginId());
stmtRemove.execute();
// do the insert of the image
stmt = conn.prepareStatement("INSERT INTO user_pic (id,mimetype,image) VALUES(?,?,?)");
stmt.setInt(1, this.currentLoginId());
stmt.setString(2, contentType);
stmt.setBytes(3, data);
stmt.execute();
RowsAffected = stmt.getUpdateCount();
stmt.close();
// turn on avatars.
stmtOn = conn.prepareStatement("UPDATE user_pref set show_avatar=? WHERE id=? LIMIT 1");
stmtOn.setString(1, "Y");
stmtOn.setInt(2, this.currentLoginId());
stmtOn.execute();
if (stmtOn.getUpdateCount() != 1)
log.debug("error turning on avatar.");
stmtOn.close();
conn.close();
} catch (Exception e) {
log.debug(e.getMessage());
throw new Exception("Error getting connect or executing it", e);
} finally {
/*
* Close any JDBC instances here that weren't
* explicitly closed during normal code path, so
* that we don't 'leak' resources...
*/
try {
stmt.close();
} catch (SQLException sqlEx) {
// ignore -- as we can't do anything about it here
log.debug(sqlEx.getMessage());
}
try {
stmtOn.close();
} catch (SQLException sqlEx) {
// ignore -- as we can't do anything about it here
log.debug(sqlEx.getMessage());
}
try {
stmtRemove.close();
} catch (SQLException sqlEx) {
// ignore -- as we can't do anything about it here
log.debug(sqlEx.getMessage());
}
try {
conn.close();
} catch (SQLException sqlEx) {
// ignore -- as we can't do anything about it here
log.debug(sqlEx.getMessage());
}
}
} else {
log.debug("File size is too small");
addError("File", "File size is too small.");
}
}
}
}
if (hasErrors() || RowsAffected != 1)
return ERROR;
else
return SUCCESS;
}
}
|
package com.opengamma.engine.security;
import com.opengamma.id.IdentifierBundle;
import com.opengamma.id.UniqueIdentifiable;
import com.opengamma.id.UniqueIdentifier;
/**
* A security that it may be possible to hold a position in.
* <p>
* A security generically defined as anything that a position can be held in.
*/
public interface Security extends UniqueIdentifiable {
/**
* Gets the unique identifier of the security.
* @return the identifier, not null
*/
UniqueIdentifier getUniqueIdentifier();
/**
* Gets the name of the security intended for display purposes.
* @return the name, not null
*/
String getName();
/**
* Gets the bundle of identifiers that define the security.
* @return the identifiers defining the security, not null
*/
IdentifierBundle getIdentifiers();
/**
* Gets the text-based type of this security.
* @return the text-based type of this security
*/
String getSecurityType();
}
|
package com.ra4king.jdoodlejump.gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.event.MouseEvent;
import java.util.prefs.Preferences;
import javax.swing.JOptionPane;
import netscape.javascript.JSObject;
import com.ra4king.gameutils.InputAdapter;
import com.ra4king.gameutils.MenuPage;
import com.ra4king.gameutils.Screen;
import com.ra4king.gameutils.gui.Button;
import com.ra4king.gameutils.gui.Label;
import com.ra4king.gameutils.gui.Widget;
import com.ra4king.gameutils.networking.Packet;
import com.ra4king.gameutils.networking.SocketPacketIO;
public class HighScores extends Widget {
private volatile String highScores[][][] = new String[4][][];
private volatile boolean networkActive;
private Button iButtons[] = new Button[4];
private Polygon nextPage;
private Polygon prevPage;
private boolean nextPageHL;
private boolean prevPageHL;
private final String SERVER = "ra4king.is-a-geek.net";
private final int PORT = 5050;
private int iNum;
private int pageNum[] = new int[4];
private String name;
private final double version;
private boolean hasShownUpdate = false;
public HighScores(double version) {
this.version = version;
{
int x[] = {50,80,80};
int y[] = {450,435,465};
prevPage = new Polygon(x,y,3);
}
{
int x[] = {370,370,400};
int y[] = {435,465,450};
nextPage = new Polygon(x,y,3);
}
highScores[0] = new String[100][2];
highScores[1] = new String[500][2];
highScores[2] = new String[1000][2];
highScores[3] = new String[2000][2];
Button.Action action = new Button.Action() {
public void doAction(Button button) {
String d = button.getText();
iButtons[iNum].setBorder(Color.black);
iButtons[iNum].setTextPaint(Color.black);
if(d.equals("TODAY"))
iNum = 0;
else if(d.equals("WEEK"))
iNum = 1;
else if(d.equals("MONTH"))
iNum = 2;
else if(d.equals("ALL TIME"))
iNum = 3;
iButtons[iNum].setBorder(Color.blue);
iButtons[iNum].setTextPaint(Color.red);
}
};
iButtons[0] = new Button("TODAY",20,22,175,5,5,false,action);
iButtons[1] = new Button("WEEK",20,iButtons[0].getIntX()+iButtons[0].getIntWidth()+1,175,5,5,false,action);
iButtons[2] = new Button("MONTH",20,iButtons[1].getIntX()+iButtons[1].getIntWidth()+1,175,5,5,false,action);
iButtons[3] = new Button("ALL TIME",20,iButtons[2].getIntX()+iButtons[2].getIntWidth()+1,175,5,5,false,action);
for(Button b : iButtons) {
b.setBackground(Color.white);
b.setBorderHighlight(Color.red);
}
iButtons[iNum].setBorder(Color.blue);
iButtons[iNum].setTextPaint(Color.red);
clearHighScores();
}
@Override
public void init(Screen parent) {
super.init(parent);
final MenuPage page = (MenuPage)parent;
for(Button b : iButtons)
page.add(b);
page.add(new Label("High Scores",Color.green,30,parent.getGame().getWidth()/2,145,true));
page.getGame().addInputListener("Highscores Menu", new InputAdapter() {
public void mouseMoved(MouseEvent me, Screen screen) {
nextPageHL = prevPageHL = false;
if(nextPage.contains(me.getPoint()))
nextPageHL = true;
else if(prevPage.contains(me.getPoint()))
prevPageHL = true;
}
public void mousePressed(MouseEvent me, Screen screen) {
if(page.getMenus().getMenuPageShown() != getParent())
return;
if(nextPage.contains(me.getPoint())) {
pageNum[iNum]++;
if(pageNum[iNum] > highScores[iNum].length/10-1) pageNum[iNum] = 0;
}
else if(prevPage.contains(me.getPoint())) {
pageNum[iNum]
if(pageNum[iNum] < 0) pageNum[iNum] = highScores[iNum].length/10-1;
}
}
});
}
@Override
public void show() {
super.show();
updateHighScores();
}
private void clearHighScores() {
for(int a = 0; a < highScores.length; a++) {
for(int b = 0; b < highScores[a].length; b++)
for(int c = 0; c < highScores[a][b].length; c++)
highScores[a][b][c] = "";
highScores[a][0][0] = "Fetching . . . . ";
}
}
public void updateHighScores() {
(new Thread() {
@Override
public void run() {
networkActive = true;
SocketPacketIO io = null;
try{
io = new SocketPacketIO(SERVER,PORT,128*1024);
Packet p = new Packet();
p.writeString("DoodleJump game");
io.write(p);
p = new Packet();
p.writeInt(0);
io.write(p);
try{
double serverVer = io.read().readDouble();
if(version < serverVer) System.out.println("NEW UPDATE!");
}
catch(Exception exc) {
exc.printStackTrace();
}
p = new Packet();
p.writeInt(2);
io.write(p);
try{
for(int iNum = 0; iNum < 4; iNum++) {
Packet packet = io.read();
for(int a = 0; a < highScores[iNum].length; a++) {
String sections[] = packet.readString().split("<:>");
highScores[iNum][a][0] = sections[0].trim();
highScores[iNum][a][1] = sections[1].trim();
if(highScores[iNum][a][1].length() == 7)
highScores[iNum][a][1] = " " + highScores[iNum][a][1];
else if(highScores[iNum][a][1].length() == 6)
highScores[iNum][a][1] = " " + highScores[iNum][a][1];
else if(highScores[iNum][a][1].length() == 5)
highScores[iNum][a][1] = " " + highScores[iNum][a][1];
else if(highScores[iNum][a][1].length() == 4)
highScores[iNum][a][1] = " " + highScores[iNum][a][1];
else if(highScores[iNum][a][1].length() == 3)
highScores[iNum][a][1] = " " + highScores[iNum][a][1];
else if(highScores[iNum][a][1].length() == 2)
highScores[iNum][a][1] = " " + highScores[iNum][a][1];
}
}
}
catch(Exception exc) {
exc.printStackTrace();
}
p = new Packet();
p.writeInt(-1);
io.write(p);
}
catch(Exception exc) {
exc.printStackTrace();
for(int a = 0; a < 4; a++)
highScores[a][0][0] = "Connection Error";
}
finally {
try{
io.close();
}
catch(Exception exc) {}
networkActive = false;
}
}
}).start();
}
public void submitScore(final int points, final long duration, boolean isNewHighscore) {
if(points > 0) {
while(name == null || name.equals("")) {
name = JOptionPane.showInputDialog(getParent().getGame().getRootParent(),"Type your name:");
if(name == null)
return;
else if(name.length() > 25) {
JOptionPane.showMessageDialog(getParent().getGame().getRootParent(),"Names longer than 25 character are not allowed.");
name = "";
}
else
name = name.trim();
}
if(isNewHighscore)
saveToCookie(points);
(new Thread() {
@Override
public void run() {
networkActive = true;
SocketPacketIO io = null;
try{
io = new SocketPacketIO(SERVER,PORT);
Packet p = new Packet();
p.writeString("DoodleJump game");
io.write(p);
p = new Packet();
p.writeInt(0);
io.write(p);
try{
double serverVer = io.read().readDouble();
if(version < serverVer && !hasShownUpdate) {
if(getParent().getGame().isApplet())
JOptionPane.showMessageDialog(getParent().getGame(),"<html>New Update! New version: " + serverVer + "<br><br>Please refresh the page...");
else {
JOptionPane.showMessageDialog(getParent().getGame().getRootParent(),"<html>New Update! New version: " + serverVer + "<br><br>Please restart this game...");
System.exit(0);
}
hasShownUpdate = true;
}
}
catch(Exception exc) {
exc.printStackTrace();
}
p = new Packet();
p.writeInt(1);
p.writeString(name);
p.writeInt(points);
p.writeLong(duration);
p.writeBoolean(getParent().getGame().isApplet());
io.write(p);
p = new Packet();
p.writeInt(-1);
io.write(p);
}
catch(Exception exc) {}
finally {
try{
io.close();
}
catch(Exception exc) {}
networkActive = false;
}
}
}).start();
}
}
public boolean isNetworkActive() {
return networkActive;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void draw(Graphics2D g) {
g.setColor(Color.black);
g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,20));
for(int a = pageNum[iNum]*10; a < pageNum[iNum]*10+10; a++) {
g.drawString(""+(a+1),30,235+((a%10)*20));
g.drawString(highScores[iNum][a][0],80,235+((a%10)*20));
g.drawString(highScores[iNum][a][1],380,235+((a%10)*20));
}
g.setColor(Color.red);
g.fill(prevPage);
if(prevPageHL) {
g.setColor(Color.blue);
g.draw(prevPage);
}
g.setColor(Color.red);
g.fill(nextPage);
if(nextPageHL) {
g.setColor(Color.blue);
g.draw(nextPage);
}
}
private void saveToCookie(int highscore) {
if(getParent().getGame().isApplet()) {
try {
JSObject object = JSObject.getWindow(getParent().getGame());
object.eval("document.cookie='name="+name+";expires=Thurs, 31 Dec 2999 23:59:59 GMT';");
object.eval("document.cookie='score="+highscore+";expires=Thurs, 31 Dec 2999 23:59:59 GMT';");
}
catch(Exception exc) {
exc.printStackTrace();
}
}
else {
try {
Preferences prefs = Preferences.userRoot();
prefs = prefs.node("JDoodleJump");
prefs.put("name", name);
prefs.putInt("highscore", highscore);
}
catch(Exception exc) {}
}
}
public int readFromCookie() {
if(getParent().getGame().isApplet()) {
try {
String c = (String)JSObject.getWindow(getParent().getGame()).eval("document.cookie");
String[] cookies = c.split(";");
int score = 0;
for(String s : cookies) {
s = s.trim();
if(s.startsWith("score"))
score = Integer.parseInt(s.split("=")[1]);
else if(s.startsWith("name"))
name = s.split("=")[1];
}
return score;
}
catch(Exception exc) {
exc.printStackTrace();
return 0;
}
}
else {
try {
Preferences prefs = Preferences.userRoot();
prefs = prefs.node("JDoodleJump");
prefs.flush();
name = prefs.get("name", null);
return prefs.getInt("highscore", 0);
}
catch(Throwable exc) {
return 0;
}
}
}
}
|
package org.tap4j.parser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.tap4j.model.BailOut;
import org.tap4j.model.Comment;
import org.tap4j.model.Footer;
import org.tap4j.model.Header;
import org.tap4j.model.Plan;
import org.tap4j.model.TapElement;
import org.tap4j.model.TapElementFactory;
import org.tap4j.model.TestResult;
import org.tap4j.model.TestSet;
import org.tap4j.model.Text;
import org.yaml.snakeyaml.Yaml;
/**
* TAP 13 parser.
*
* @since 1.0
*/
public class Tap13Parser implements Parser {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(Tap13Parser.class
.getCanonicalName());
/**
* UTF-8 encoding constant.
*/
private static final String UTF8_ENCODING = "UTF-8";
/**
* Stack of stream status information bags. Every bag stores state of the parser
* related to certain indentation level. This is to support subtest feature.
*/
private Stack<StreamStatus> states = new Stack<StreamStatus>();
/**
* The current state.
*/
private StreamStatus state = null;
private int baseIndentation;
/**
* Decoder used. This is only used when trying to parse something that is
* encoded (like a raw file or byte stream) and the encoding isn't otherwise
* known.
*/
private CharsetDecoder decoder;
/**
* Require a TAP plan.
*/
private boolean planRequired = true;
/**
* Enable subtests.
*/
private boolean enableSubtests = true;
/**
* Parser Constructor.
*
* A parser constructed this way will enforce that any input should include
* a plan.
*
* @param encoding Encoding. This will not matter when parsing sources that
* are already decoded (e.g. {@link String} or {@link Readable}), but it
* will be used in the {@link #parseFile} method (whether or not it is the
* right encoding for the File being parsed).
* @param enableSubtests Whether subtests are enabled or not
*/
public Tap13Parser(String encoding, boolean enableSubtests) {
this(encoding, enableSubtests, true);
}
/**
* Parser Constructor.
*
* @param encoding Encoding. This will not matter when parsing sources that
* are already decoded (e.g. {@link String} or {@link Readable}), but it
* will be used in the {@link #parseFile} method (whether or not it is the
* right encoding for the File being parsed).
* @param enableSubtests Whether subtests are enabled or not
* @param planRequired flag that defines whether a plan is required or not
*/
public Tap13Parser(String encoding, boolean enableSubtests, boolean planRequired) {
super();
/*
* Resolving the encoding name to a CharsetDecoder here has two
* benefits. First, if it isn't known or supported, the caller finds out
* as early as possible. Second, a decoder obtained this way will check
* the validity of its input and throw exceptions if it doesn't match
* the encoding. All the other ways to specify an encoding result in a
* default behavior to silently drop or change data ... not great in a
* testing tool.
*/
try {
if (null != encoding) {
this.decoder = Charset.forName(encoding).newDecoder();
}
} catch (UnsupportedCharsetException uce) {
throw new ParserException(String.format("Invalid encoding: %s", encoding), uce);
}
this.enableSubtests = enableSubtests;
this.planRequired = planRequired;
}
/**
* Parser Constructor.
*
* A parser created with this constructor will assume that any input to the
* {@link #parseFile} method is encoded in {@code UTF-8}.
*
* @param enableSubtests Whether subtests are enabled or not
*/
public Tap13Parser(boolean enableSubtests) {
this(UTF8_ENCODING, enableSubtests);
}
/**
* Parser Constructor.
*
* A parser created with this constructor will assume that any input to the
* {@link #parseFile} method is encoded in {@code UTF-8}, and will not
* recognize subtests.
*/
public Tap13Parser() {
this(UTF8_ENCODING, false);
}
/**
* Saves the current state in the stack.
* @param indentation state indentation
*/
private void pushState(int indentation) {
states.push(state);
state = new StreamStatus();
state.setIndentationLevel(indentation);
}
/**
* {@inheritDoc}
*/
@Override
public TestSet parseTapStream(String tapStream) {
return parseTapStream(CharBuffer.wrap(tapStream));
}
/**
* {@inheritDoc}
*/
@Override
public TestSet parseFile(File tapFile) {
if (null == decoder) {
throw new ParserException(
"Must have encoding specified if using parseFile");
}
try (
FileInputStream fis = new FileInputStream(tapFile);
InputStreamReader isr = new InputStreamReader(fis, decoder);
) {
return parseTapStream(isr);
} catch (FileNotFoundException e) {
throw new ParserException("TAP file not found: " + tapFile, e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, String.format("Failed to close file stream: %s", e.getMessage()), e);
throw new ParserException(String.format("Failed to close file stream for file %s: %s: ",
tapFile, e.getMessage()), e);
}
}
/**
* {@inheritDoc}
*/
@Override
public TestSet parseTapStream(Readable tapStream) {
state = new StreamStatus();
baseIndentation = Integer.MAX_VALUE;
try (Scanner scanner = new Scanner(tapStream)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line != null && line.length() > 0) {
parseLine(line);
}
}
onFinish();
} catch (Exception e) {
throw new ParserException(String.format("Error parsing TAP Stream: %s", e.getMessage()), e);
}
return state.getTestSet();
}
/**
* Parse a TAP line.
*
* @param tapLine TAP line
*/
public void parseLine(String tapLine) {
TapElement tapElement = TapElementFactory.createTapElement(tapLine);
if (tapElement == null || state.isInYaml()) {
String trimmedLine = tapLine.trim();
Text text = TapElementFactory.createTextElement(tapLine);
if (state.isInYaml()) {
boolean yamlEndMarkReached = trimmedLine.equals("...") && (
tapLine.equals(state.getYamlIndentation() + "...")
|| text.getIndentation() < state.getYamlIndentation().length());
if (yamlEndMarkReached) {
state.setInYaml(false);
parseDiagnostics();
} else {
state.getDiagnosticBuffer().append(tapLine);
state.getDiagnosticBuffer().append('\n');
}
} else {
if (trimmedLine.equals("
if (text.getIndentation() < baseIndentation) {
throw new ParserException(String.format("Invalid indentation. Check your TAP Stream. Line: %s",
tapLine));
}
state.setInYaml(true);
state.setYamlIndentation(text.getIndentationString());
} else {
state.getTestSet().getTapLines().add(text);
state.setLastParsedElement(text);
}
}
return;
}
int indentation = tapElement.getIndentation();
if (indentation < baseIndentation) {
baseIndentation = indentation;
}
if (indentation != state.getIndentationLevel()) { // indentation changed
if (indentation > state.getIndentationLevel()) {
StreamStatus parentState = state;
pushState(indentation); // make room for children
TapElement lastParentElement = parentState.getLastParsedElement();
if (lastParentElement instanceof TestResult) {
final TestResult lastTestResult = (TestResult) lastParentElement;
// whatever test set comes should be attached to parent
if (lastTestResult.getSubtest() == null && this.enableSubtests) {
lastTestResult.setSubtest(state.getTestSet());
state.attachedToParent = true;
}
}
} else {
// going down
do {
StreamStatus prevState = state;
state = states.pop();
if (!prevState.attachedToParent && this.enableSubtests) {
state.looseSubtests = prevState.getTestSet();
}
// there could be more than one level diff
} while (indentation < state.getIndentationLevel());
}
}
if (tapElement instanceof Header) {
if (state.getTestSet().getHeader() != null) {
throw new ParserException("Duplicated TAP Header found.");
}
if (!state.isFirstLine()) {
throw new ParserException(
"Invalid position of TAP Header. It must be the first "
+ "element (apart of Comments) in the TAP Stream.");
}
state.getTestSet().setHeader((Header) tapElement);
} else if (tapElement instanceof Plan) {
Plan currentPlan = (Plan) tapElement;
if (state.getTestSet().getPlan() != null) {
if (currentPlan.getInitialTestNumber() != 1 || currentPlan.getLastTestNumber() != 0) {
throw new ParserException("Duplicated TAP Plan found.");
}
} else {
state.getTestSet().setPlan(currentPlan);
}
if (state.getTestSet().getTestResults().size() <= 0
&& state.getTestSet().getBailOuts().size() <= 0) {
state.setPlanBeforeTestResult(true);
}
} else if (tapElement instanceof TestResult) {
parseDiagnostics();
final TestResult testResult = (TestResult) tapElement;
if (testResult.getTestNumber() == 0) {
if (state.getTestSet().getPlan() != null && !state.isPlanBeforeTestResult()) {
return; // done testing mark
}
if (state.getTestSet().getPlan() != null &&
state.getTestSet().getPlan().getLastTestNumber() == state.getTestSet().getTestResults().size()) {
return; // done testing mark but plan before test result
}
testResult.setTestNumber(state.getTestSet().getNextTestNumber());
}
state.getTestSet().addTestResult(testResult);
if (state.looseSubtests != null && this.enableSubtests) {
testResult.setSubtest(state.looseSubtests);
state.looseSubtests = null;
}
} else if (tapElement instanceof Footer) {
state.getTestSet().setFooter((Footer) tapElement);
} else if (tapElement instanceof BailOut) {
state.getTestSet().addBailOut((BailOut) tapElement);
} else if (tapElement instanceof Comment) {
final Comment comment = (Comment) tapElement;
state.getTestSet().addComment(comment);
if (state.getLastParsedElement() instanceof TestResult) {
((TestResult) state.getLastParsedElement()).addComment(comment);
}
}
state.setFirstLine(false);
if (!(tapElement instanceof Comment)) {
state.setLastParsedElement(tapElement);
}
}
/**
* Called after the rest of the stream has been processed.
*/
private void onFinish() {
if (planRequired && state.getTestSet().getPlan() == null) {
throw new ParserException("Missing TAP Plan.");
}
parseDiagnostics();
while (!states.isEmpty() && state.getIndentationLevel() > baseIndentation) {
state = states.pop();
}
}
/* -- Utility methods --*/
/**
* <p>
* Checks if there is any diagnostic information on the diagnostic buffer.
* </p>
* <p>
* If so, tries to parse it using snakeyaml.
* </p>
*/
private void parseDiagnostics() {
// If we found any meta, then process it with SnakeYAML
if (state.getDiagnosticBuffer().length() > 0) {
if (state.getLastParsedElement() == null) {
throw new ParserException("Found diagnostic information without a previous TAP element.");
}
try {
@SuppressWarnings("unchecked")
Map<String, Object> metaIterable = (Map<String, Object>) new Yaml()
.load(state.getDiagnosticBuffer().toString());
state.getLastParsedElement().setDiagnostic(metaIterable);
} catch (Exception ex) {
throw new ParserException(String.format("Error parsing YAML [%s]: %s",
state.getDiagnosticBuffer().toString(), ex.getMessage()), ex);
}
this.state.getDiagnosticBuffer().setLength(0);
}
}
}
|
package org.jboss.xnio;
import java.io.Serializable;
import java.io.ObjectStreamException;
import java.io.InvalidObjectException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
/**
* A strongly-typed option to configure an aspect of a service or connection. Options are immutable and use identity comparisons
* and hash codes. Options should always be declared as <code>public static final</code> members in order to support serialization.
*
* @param <T> the option value type
*/
public abstract class Option<T> implements Serializable {
private static final long serialVersionUID = -1564427329140182760L;
private final Class<?> declClass;
private final String name;
Option(final Class<?> declClass, final String name) {
this.declClass = declClass;
if (name == null) {
throw new NullPointerException("name is null");
}
this.name = name;
}
/**
* Create an option with a simple type. The class object given <b>must</b> represent some immutable type, otherwise
* unexpected behavior may result.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param type the class of the value associated with this option
* @return the option instance
*/
public static <T> Option<T> simple(final Class<?> declClass, final String name, final Class<T> type) {
return new SingleOption<T>(declClass, name, type);
}
/**
* Create an option with a sequence type. The class object given <b>must</b> represent some immutable type, otherwise
* unexpected behavior may result.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param elementType the class of the sequence element value associated with this option
* @return the option instance
*/
public static <T> Option<Sequence<T>> sequence(final Class<?> declClass, final String name, final Class<T> elementType) {
return new SequenceOption<T>(declClass, name, elementType);
}
/**
* Create an option with a flag set type. The class object given <b>must</b> represent some immutable type, otherwise
* unexpected behavior may result.
*
* @param declClass the declaring class of the option
* @param name the (field) name of this option
* @param elementType the class of the flag values associated with this option
* @param <T> the type of the flag values associated with this option
* @return the option instance
*/
public static <T extends Enum<T>> Option<FlagSet<T>> flags(final Class<?> declClass, final String name, final Class<T> elementType) {
return new FlagsOption<T>(declClass, name, elementType);
}
/**
* Get the name of this option.
*
* @return the option name
*/
public String getName() {
return name;
}
/**
* Get a human-readible string representation of this object.
*
* @return the string representation
*/
public String toString() {
return super.toString() + " (" + declClass.getName() + "#" + name + ")";
}
/**
* Return the given object as the type of this option. If the cast could not be completed, an exception is thrown.
*
* @param o the object to cast
* @return the cast object
* @throws ClassCastException if the object is not of a compatible type
*/
public abstract T cast(Object o) throws ClassCastException;
/**
* Resolve this instance for serialization.
*
* @return the resolved object
* @throws java.io.ObjectStreamException if the object could not be resolved
*/
protected final Object readResolve() throws ObjectStreamException {
try {
final Field field = declClass.getField(name);
final int modifiers = field.getModifiers();
if (! Modifier.isProtected(modifiers)) {
throw new InvalidObjectException("Invalid Option instance (the field is not public)");
}
if (! Modifier.isStatic(modifiers)) {
throw new InvalidObjectException("Invalid Option instance (the field is not static)");
}
return field.get(null);
} catch (NoSuchFieldException e) {
throw new InvalidObjectException("Invalid Option instance (no matching field)");
} catch (IllegalAccessException e) {
throw new InvalidObjectException("Invalid Option instance (Illegal access on field get)");
}
}
/**
* Create a builder for an immutable option set.
*
* @return the builder
*/
public static SetBuilder setBuilder() {
return new SetBuilder();
}
/**
* A builder for an immutable option set.
*/
public static class SetBuilder {
private List<Option> optionSet = new ArrayList<Option>();
SetBuilder() {
}
/**
* Add an option to this set.
*
* @param option the option to add
* @return this builder
*/
public SetBuilder add(Option option) {
if (option == null) {
throw new NullPointerException("option is null");
}
optionSet.add(option);
return this;
}
/**
* Create the immutable option set instance.
*
* @return the option set
*/
public Set<Option> create() {
return Collections.unmodifiableSet(new LinkedHashSet<Option>(optionSet));
}
}
}
final class SingleOption<T> extends Option<T> {
private static final long serialVersionUID = 2449094406108952764L;
private transient final Class<T> type;
SingleOption(final Class<?> declClass, final String name, final Class<T> type) {
super(declClass, name);
this.type = type;
}
public T cast(final Object o) {
return type.cast(o);
}
}
final class FlagsOption<T extends Enum<T>> extends Option<FlagSet<T>> {
private static final long serialVersionUID = -5487268452958691541L;
private transient final Class<T> elementType;
FlagsOption(final Class<?> declClass, final String name, final Class<T> elementType) {
super(declClass, name);
this.elementType = elementType;
}
public FlagSet<T> cast(final Object o) throws ClassCastException {
final FlagSet<?> flagSet = (FlagSet<?>) o;
return flagSet.cast(elementType);
}
}
final class SequenceOption<T> extends Option<Sequence<T>> {
private static final long serialVersionUID = -4328676629293125136L;
private transient final Class<T> elementType;
SequenceOption(final Class<?> declClass, final String name, final Class<T> elementType) {
super(declClass, name);
this.elementType = elementType;
}
public Sequence<T> cast(final Object o) {
if (o instanceof Sequence) {
return ((Sequence<?>)o).cast(elementType);
} else if (o instanceof Object[]){
return Sequence.of((Object[])o).cast(elementType);
} else if (o instanceof Collection) {
return Sequence.of((Collection<?>)o).cast(elementType);
} else {
throw new ClassCastException("Not a sequence");
}
}
}
|
package org.carlspring.strongbox;
import org.carlspring.strongbox.config.IntegrationTest;
import javax.inject.Inject;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.module.mockmvc.response.MockMvcResponse;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.junit.jupiter.api.Assertions.*;
/**
* Test cases which check if UI assets are accessible.
*
* @author Pablo Tirado
*/
@IntegrationTest
public class AssetsManifestTest
{
private static final String FILE_RESOURCE = "assets-manifest.json";
private static final String ROOT_PATH = "/";
private static final Pattern STYLES_REGEX = Pattern.compile("\\/static\\/assets\\/styles(.+).css");
private static final Pattern RUNTIME_REGEX = Pattern.compile("\\/static\\/assets\\/runtime(.+).js");
private static final Pattern POLYFILLS_REGEX = Pattern.compile("\\/static\\/assets\\/polyfills(.+).js");
private static final Pattern MAIN_REGEX = Pattern.compile("\\/static\\/assets\\/main(.+).js");
private static List<Pattern> indexResourcePatterns;
@Inject
private ObjectMapper mapper;
@BeforeAll
static void init()
{
indexResourcePatterns = Lists.newArrayList();
indexResourcePatterns.add(STYLES_REGEX);
indexResourcePatterns.add(RUNTIME_REGEX);
indexResourcePatterns.add(POLYFILLS_REGEX);
indexResourcePatterns.add(MAIN_REGEX);
}
@Test
void testCheckAccessibleUIAssets()
throws IOException, URISyntaxException
{
// Read file path and check if exists.
Path manifestPath = checkFilePath();
// Read file content and check if empty.
String manifestJsonStr = checkFileContent(manifestPath);
// Convert JSON to Map.
Map<String, String> manifestMap = mapper.readValue(manifestJsonStr,
new TypeReference<Map<String, String>>()
{
});
// Iterate map, and check every value (asset path).
for (Map.Entry<String, String> entry : manifestMap.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
checkAccessibleUIAsset(key, value);
}
}
private Path checkFilePath()
throws URISyntaxException
{
URI manifestUri = ClassLoader.getSystemResource(FILE_RESOURCE).toURI();
Path manifestPath = Paths.get(manifestUri);
String notExistsMessage = String.format("The file \"%s\" does not exist!", FILE_RESOURCE);
assertTrue(Files.exists(manifestPath), notExistsMessage);
return manifestPath;
}
private String checkFileContent(Path manifestPath)
throws IOException
{
byte[] manifestContent = Files.readAllBytes(manifestPath);
String manifestJsonStr = new String(manifestContent);
String isEmptyMessage = String.format("The file \"%s\" is empty!", FILE_RESOURCE);
assertFalse(StringUtils.isEmpty(manifestJsonStr), isEmptyMessage);
return manifestJsonStr;
}
private void checkAccessibleUIAsset(String assetFileName,
String assetPath)
{
boolean isIndexFile = StringUtils.equals(ROOT_PATH, assetPath);
// Add filename for root path.
if (isIndexFile)
{
assetPath += assetFileName;
}
MockMvcResponse response = given().get(assetPath);
String errorMessage = String.format("The resource \"%s\" is not accessible.", assetPath);
assertEquals(response.getStatusCode(), HttpStatus.OK.value(), errorMessage);
// Additional check for index.html
if (isIndexFile)
{
checkIndexHtmlResources(response.getBody().print());
}
}
private void checkIndexHtmlResources(String indexHtml)
{
for (Pattern pattern : indexResourcePatterns)
{
Matcher matcher = pattern.matcher(indexHtml);
// Check that the resources exists in index.html.
assertTrue(matcher.find(), String.format("The resource \"%s\" is not found in index.html.", pattern.toString()));
}
}
}
|
package foam.core;
import foam.dao.pg.IndexedPreparedStatement;
import foam.nanos.logger.Logger;
import java.lang.UnsupportedOperationException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public abstract class AbstractArrayPropertyInfo
extends AbstractPropertyInfo
{
@Override
public void setFromString(Object obj, String value) {
// TODO
}
public abstract String of();
// NESTED ARRAY
@Override
public Object fromXML(X x, XMLStreamReader reader) {
List objList = new ArrayList();
String startTag = reader.getLocalName();
try {
int eventType;
while ( reader.hasNext() ) {
eventType = reader.next();
switch ( eventType ) {
case XMLStreamConstants.START_ELEMENT:
if ( reader.getLocalName().equals("value") ) {
// TODO: TYPE CASTING FOR PROPER CONVERSION. NEED FURTHER SUPPORT FOR PRIMITIVE TYPES
throw new UnsupportedOperationException("Primitive typed array XML reading is not supported yet");
}
break;
case XMLStreamConstants.END_ELEMENT:
if ( reader.getLocalName() == startTag ) { return objList.toArray(); }
}
}
} catch (XMLStreamException ex) {
Logger logger = (Logger) x.get("logger");
logger.error("Premature end of XML file");
}
return objList.toArray();
}
@Override
public void toXML (FObject obj, Document doc, Element objElement) {
if ( this.f(obj) == null ) return;
Element prop = doc.createElement(this.getName());
objElement.appendChild(prop);
Object[] nestObj = (Object[]) this.f(obj);
for ( int k = 0; k < nestObj.length; k++ ) {
Element nestedProp = doc.createElement("value");
nestedProp.appendChild(doc.createTextNode(nestObj[k].toString()));
prop.appendChild(nestedProp);
}
}
@Override
public void setStatementValue(IndexedPreparedStatement stmt, FObject o) throws java.sql.SQLException {
Object obj = this.get(o);
if ( obj == null ) {
stmt.setObject(null);
return;
}
Object[] os = (Object[]) obj;
java.lang.StringBuilder sb = new java.lang.StringBuilder();
int length = os.length;
for ( int i=0; i < length; i++) {
if( os[i] == null )
sb.append("");
else
sb.append(os[i]);
if ( i < length - 1 ) {
sb.append(",");
}
}
stmt.setObject(sb.toString());
}
}
|
package org.mifosng.platform.api.infrastructure;
import org.mifosng.platform.api.commands.AdjustLoanTransactionCommand;
import org.mifosng.platform.api.commands.BranchMoneyTransferCommand;
import org.mifosng.platform.api.commands.ChargeCommand;
import org.mifosng.platform.api.commands.ClientCommand;
import org.mifosng.platform.api.commands.DepositAccountCommand;
import org.mifosng.platform.api.commands.DepositProductCommand;
import org.mifosng.platform.api.commands.DepositStateTransitionApprovalCommand;
import org.mifosng.platform.api.commands.DepositStateTransitionCommand;
import org.mifosng.platform.api.commands.FundCommand;
import org.mifosng.platform.api.commands.GroupCommand;
import org.mifosng.platform.api.commands.LoanProductCommand;
import org.mifosng.platform.api.commands.LoanStateTransitionCommand;
import org.mifosng.platform.api.commands.LoanTransactionCommand;
import org.mifosng.platform.api.commands.NoteCommand;
import org.mifosng.platform.api.commands.OfficeCommand;
import org.mifosng.platform.api.commands.OrganisationCurrencyCommand;
import org.mifosng.platform.api.commands.RoleCommand;
import org.mifosng.platform.api.commands.SavingProductCommand;
import org.mifosng.platform.api.commands.StaffCommand;
import org.mifosng.platform.api.commands.LoanApplicationCommand;
import org.mifosng.platform.api.commands.UserCommand;
public interface ApiDataConversionService {
ChargeCommand convertJsonToChargeCommand(Long resourceIdentifier, String json);
FundCommand convertJsonToFundCommand(Long resourceIdentifier, String json);
OfficeCommand convertJsonToOfficeCommand(Long resourceIdentifier, String json);
RoleCommand convertJsonToRoleCommand(Long resourceIdentifier, String json);
UserCommand convertJsonToUserCommand(Long resourceIdentifier, String json);
BranchMoneyTransferCommand convertJsonToBranchMoneyTransferCommand(String jsonRequestBody);
LoanProductCommand convertJsonToLoanProductCommand(Long resourceIdentifier, String json);
SavingProductCommand convertJsonToSavingProductCommand(Long resourceIdentifier, String json);
DepositProductCommand convertJsonToDepositProductCommand(Long resourceIdentifier, String json);
ClientCommand convertJsonToClientCommand(Long resourceIdentifier, String jsonRequestBody);
GroupCommand convertJsonToGroupCommand(Long resourceIdentifier, String jsonRequestBody);
LoanApplicationCommand convertJsonToLoanApplicationCommand(Long resourceIdentifier, String jsonRequestBody);
LoanStateTransitionCommand convertJsonToLoanStateTransitionCommand(Long resourceIdentifier, String jsonRequestBody);
LoanTransactionCommand convertJsonToLoanTransactionCommand(Long resourceIdentifier, String jsonRequestBody);
AdjustLoanTransactionCommand convertJsonToAdjustLoanTransactionCommand(
Long loanId, Long transactionId, String jsonRequestBody);
OrganisationCurrencyCommand convertJsonToOrganisationCurrencyCommand(String jsonRequestBody);
NoteCommand convertJsonToNoteCommand(Long resourceIdentifier, Long clientId, String jsonRequestBody);
DepositAccountCommand convertJsonToDepositAccountCommand(Long resourceIdentifier, String jsonRequestBody);
DepositStateTransitionCommand convertJsonToDepositStateTransitionCommand(Long resourceIdentifier, String jsonRequestBody);
DepositStateTransitionApprovalCommand convertJsonToDepositStateTransitionApprovalCommand(Long resourceIdentifier, String jsonRequestBody);
StaffCommand convertJsonToStaffCommand(Long resourceIdentifier, String json);
}
|
package com.jivesoftware.os.miru.plugin.backfill;
import com.google.common.base.Optional;
import com.jivesoftware.os.filer.io.api.StackBuffer;
import com.jivesoftware.os.miru.api.MiruHost;
import com.jivesoftware.os.miru.api.activity.MiruPartitionId;
import com.jivesoftware.os.miru.api.base.MiruIBA;
import com.jivesoftware.os.miru.api.base.MiruStreamId;
import com.jivesoftware.os.miru.api.base.MiruTenantId;
import com.jivesoftware.os.miru.api.query.filter.MiruFilter;
import com.jivesoftware.os.miru.plugin.bitmap.MiruBitmaps;
import com.jivesoftware.os.miru.plugin.bitmap.MiruIntIterator;
import com.jivesoftware.os.miru.plugin.context.MiruRequestContext;
import com.jivesoftware.os.miru.plugin.index.BitmapAndLastId;
import com.jivesoftware.os.miru.plugin.index.MiruInvertedIndexAppender;
import com.jivesoftware.os.miru.plugin.index.TimeVersionRealtime;
import com.jivesoftware.os.miru.plugin.solution.MiruAggregateUtil;
import com.jivesoftware.os.miru.plugin.solution.MiruSolutionLog;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class MiruJustInTimeBackfillerizer {
private static final MetricLogger log = MetricLoggerFactory.getLogger();
private final MiruInboxReadTracker inboxReadTracker;
private final MiruHost localHost;
private final Optional<String> readStreamIdsPropName;
private final ExecutorService backfillExecutor;
private final MiruAggregateUtil aggregateUtil = new MiruAggregateUtil();
public MiruJustInTimeBackfillerizer(MiruInboxReadTracker inboxReadTracker,
MiruHost localHost,
Optional<String> readStreamIdsPropName,
ExecutorService backfillExecutor) {
this.inboxReadTracker = inboxReadTracker;
this.localHost = localHost;
this.readStreamIdsPropName = readStreamIdsPropName;
this.backfillExecutor = backfillExecutor;
}
public <BM extends IBM, IBM> void backfillUnread(MiruBitmaps<BM, IBM> bitmaps,
MiruRequestContext<BM, IBM, ?> requestContext,
MiruSolutionLog solutionLog,
MiruTenantId tenantId,
MiruPartitionId partitionId,
MiruStreamId streamId,
MiruFilter suppressUnreadFilter)
throws Exception {
// backfill in another thread to guard WAL interface from solver cancellation/interruption
Future<?> future = backfillExecutor.submit(() -> {
try {
StackBuffer stackBuffer = new StackBuffer();
synchronized (requestContext.getStreamLocks().lock(streamId, 0)) {
int lastActivityIndex = requestContext.getUnreadTrackingIndex().getLastActivityIndex(streamId, stackBuffer);
int lastId = requestContext.getActivityIndex().lastId(stackBuffer);
if (log.isDebugEnabled()) {
BitmapAndLastId<BM> container = new BitmapAndLastId<>();
requestContext.getUnreadTrackingIndex().getUnread(streamId).getIndex(container, stackBuffer);
log.debug("before:\n host={}\n streamId={}\n unread={}\n last={}",
localHost,
streamId.getBytes(),
container,
lastActivityIndex);
}
long oldestBackfilledTimestamp = Long.MAX_VALUE;
TIntList unreadIds = new TIntArrayList();
for (int i = lastActivityIndex + 1; i <= lastId; i++) {
unreadIds.add(i);
if (oldestBackfilledTimestamp == Long.MAX_VALUE) {
TimeVersionRealtime tvr = requestContext.getActivityIndex().getTimeVersionRealtime("backfillUnread", i, stackBuffer);
if (tvr != null) {
oldestBackfilledTimestamp = tvr.monoTimestamp;
}
}
}
BM unreadMask = bitmaps.createWithBits(unreadIds.toArray());
if (!MiruFilter.NO_FILTER.equals(suppressUnreadFilter)) {
BM suppressUnreadBitmap = aggregateUtil.filter("backfillUnread",
bitmaps,
requestContext,
suppressUnreadFilter,
solutionLog,
null,
lastId,
lastActivityIndex,
-1,
stackBuffer);
bitmaps.inPlaceAndNot(unreadMask, suppressUnreadBitmap);
}
requestContext.getUnreadTrackingIndex().applyUnread(streamId, unreadMask, stackBuffer);
if (log.isDebugEnabled()) {
BitmapAndLastId<BM> container = new BitmapAndLastId<>();
requestContext.getUnreadTrackingIndex().getUnread(streamId).getIndex(container, stackBuffer);
log.debug("after:\n host={}\n streamId={}\n unread={}\n last={}",
localHost,
streamId.getBytes(),
container,
lastActivityIndex);
}
inboxReadTracker.sipAndApplyReadTracking(bitmaps,
requestContext,
tenantId,
partitionId,
streamId,
solutionLog,
lastId,
oldestBackfilledTimestamp,
stackBuffer);
}
} catch (Exception e) {
log.error("Backfillerizer failed", e);
throw new RuntimeException("Backfillerizer failed");
}
return null;
});
// if this is interrupted, the backfill will still complete
future.get();
}
public <BM extends IBM, IBM> void backfill(final MiruBitmaps<BM, IBM> bitmaps,
final MiruRequestContext<BM, IBM, ?> requestContext,
final MiruFilter streamFilter,
final MiruSolutionLog solutionLog,
final MiruTenantId tenantId,
final MiruPartitionId partitionId,
final MiruStreamId streamId,
MiruFilter suppressUnreadFilter)
throws Exception {
// backfill in another thread to guard WAL interface from solver cancellation/interruption
Future<?> future = backfillExecutor.submit(() -> {
try {
StackBuffer stackBuffer = new StackBuffer();
synchronized (requestContext.getStreamLocks().lock(streamId, 0)) {
int lastActivityIndex = requestContext.getInboxIndex().getLastActivityIndex(streamId, stackBuffer);
int lastId = requestContext.getActivityIndex().lastId(stackBuffer);
BM answer = aggregateUtil.filter("justInTimeBackfillerizer",
bitmaps,
requestContext,
streamFilter,
solutionLog,
null,
lastId,
lastActivityIndex,
-1,
stackBuffer);
MiruInvertedIndexAppender inbox = requestContext.getInboxIndex().getAppender(streamId);
if (log.isDebugEnabled()) {
BitmapAndLastId<BM> inboxContainer = new BitmapAndLastId<>();
requestContext.getInboxIndex().getInbox(streamId).getIndex(inboxContainer, stackBuffer);
BitmapAndLastId<BM> unreadContainer = new BitmapAndLastId<>();
requestContext.getUnreadTrackingIndex().getUnread(streamId).getIndex(inboxContainer, stackBuffer);
log.debug("before:\n host={}\n streamId={}\n inbox={}\n unread={}\n last={}",
localHost,
streamId.getBytes(),
inboxContainer,
unreadContainer,
lastActivityIndex);
}
MiruIBA streamIdAsIBA = new MiruIBA(streamId.getBytes());
long oldestBackfilledEventId = Long.MAX_VALUE;
int propId = readStreamIdsPropName.isPresent() ? requestContext.getSchema().getPropertyId(readStreamIdsPropName.get()) : -1;
//TODO more efficient way to merge answer into inbox and unread
MiruIntIterator intIterator = bitmaps.intIterator(answer);
TIntList inboxIds = new TIntArrayList();
TIntList unreadIds = new TIntArrayList();
while (intIterator.hasNext()) {
int i = intIterator.next();
if (i > lastActivityIndex && i <= lastId) {
TimeVersionRealtime tvr = requestContext.getActivityIndex().getTimeVersionRealtime("justInTimeBackfillerizer", i, stackBuffer);
if (tvr == null) {
log.warn("Missing activity at index {}, timeIndex={}, activityIndex={}",
i, requestContext.getTimeIndex().lastId(), lastId);
continue;
}
oldestBackfilledEventId = Math.min(oldestBackfilledEventId, tvr.timestamp);
inboxIds.add(i);
MiruIBA[] readStreamIds = propId < 0 ? null
: requestContext.getActivityIndex().getProp("justInTimeBackfillerizer", i, propId, stackBuffer);
if (readStreamIds == null || !Arrays.asList(readStreamIds).contains(streamIdAsIBA)) {
unreadIds.add(i);
}
}
}
inbox.set(stackBuffer, inboxIds.toArray());
BM unreadMask = bitmaps.createWithBits(unreadIds.toArray());
if (!MiruFilter.NO_FILTER.equals(suppressUnreadFilter)) {
BM suppressUnreadBitmap = aggregateUtil.filter("backfillUnread",
bitmaps,
requestContext,
suppressUnreadFilter,
solutionLog,
null,
lastId,
lastActivityIndex,
-1,
stackBuffer);
bitmaps.inPlaceAndNot(unreadMask, suppressUnreadBitmap);
}
requestContext.getUnreadTrackingIndex().applyUnread(streamId, unreadMask, stackBuffer);
if (log.isDebugEnabled()) {
BitmapAndLastId<BM> inboxContainer = new BitmapAndLastId<>();
requestContext.getInboxIndex().getInbox(streamId).getIndex(inboxContainer, stackBuffer);
BitmapAndLastId<BM> unreadContainer = new BitmapAndLastId<>();
requestContext.getUnreadTrackingIndex().getUnread(streamId).getIndex(inboxContainer, stackBuffer);
log.debug("after:\n host={}\n streamId={}\n inbox={}\n unread={}\n last={}",
localHost,
streamId.getBytes(),
inboxContainer,
unreadContainer,
lastActivityIndex);
}
inboxReadTracker.sipAndApplyReadTracking(bitmaps,
requestContext,
tenantId,
partitionId,
streamId,
solutionLog,
lastId,
oldestBackfilledEventId,
stackBuffer);
}
} catch (Exception e) {
log.error("Backfillerizer failed", e);
throw new RuntimeException("Backfillerizer failed");
}
return null;
});
// if this is interrupted, the backfill will still complete
future.get();
}
}
|
package org.eclipse.birt.report.model.metadata;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.birt.report.model.api.metadata.PropertyValueException;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.birt.report.model.core.Module;
/**
* Element name property type. Represents the name of an element.
*
*/
public class NamePropertyType extends TextualPropertyType
{
/**
* Display name key.
*/
private static final String DISPLAY_NAME_KEY = "Property.name"; //$NON-NLS-1$
/**
* Compiled regular expression for allowed values.
* <ul>
* <li>abc_.abc allowed
* <li>abc abc allowed
* <li>_abc allowed
* <li>9abc allowed
* <li>.abc not allowed
* </ul>
*/
private static final Pattern pattern = Pattern
.compile( "[\\w][\\w. ]*" ); //$NON-NLS-1$
/**
* Constructor.
*/
public NamePropertyType( )
{
super( DISPLAY_NAME_KEY );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.design.metadata.PropertyType#getTypeCode()
*/
public int getTypeCode( )
{
return NAME_TYPE;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.design.metadata.PropertyType#getXmlName()
*/
public String getName( )
{
return NAME_TYPE_NAME;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.metadata.PropertyType#validateValue(org.eclipse.birt.report.model.elements.ReportDesign,
* org.eclipse.birt.report.model.metadata.PropertyDefn,
* java.lang.Object)
*/
public Object validateValue( Module module, PropertyDefn defn, Object value )
throws PropertyValueException
{
assert defn != null;
if ( value == null )
{
if ( defn.isStructureMember( ) )
throw new PropertyValueException( value,
PropertyValueException.DESIGN_EXCEPTION_VALUE_REQUIRED,
NAME_TYPE );
return null;
}
if ( value instanceof String )
{
String stringValue = StringUtil.trimString( (String) value ) ;
if ( stringValue == null )
{
if ( defn.isStructureMember( ) )
throw new PropertyValueException(
value,
PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE,
NAME_TYPE );
return null;
}
Matcher matcher = pattern.matcher( stringValue );
if ( !matcher.matches( ) )
throw new PropertyValueException( stringValue,
PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE,
NAME_TYPE );
return stringValue;
}
throw new PropertyValueException( value,
PropertyValueException.DESIGN_EXCEPTION_INVALID_VALUE,
NAME_TYPE );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.metadata.PropertyType#validateXml(org.eclipse.birt.report.model.elements.ReportDesign,
* org.eclipse.birt.report.model.metadata.PropertyDefn,
* java.lang.String)
*/
public Object validateXml( Module module, PropertyDefn defn, String value )
throws PropertyValueException
{
if ( value == null )
return null;
return StringUtil.trimString( value );
}
}
|
package net.devrieze.chatterbox.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.Principal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AuthFilter implements Filter {
// private static final String DARWIN_AUTH_COOKIE = "DWNID";
@SuppressWarnings("unused")
private FilterConfig filterConfig;
private Logger logger;
@Override
public void destroy() {
// Don't do anything yet.
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
doFilter((HttpServletRequest)req, (HttpServletResponse) resp, filterChain);
}
private Logger getLogger() {
if (logger==null) {
logger = Logger.getLogger(getClass().getName());
}
return logger;
}
public void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
// System.err.println("dofilter called for "+req.getRequestURI());
getLogger().log(Level.FINE, "Calling filter for: "+req.getRequestURI());
Principal principal = getPrincipal(req);
if (req.getRequestURI().startsWith("/accounts/login")) {
getLogger().log(Level.FINER, "Calling not filtering authentication: "+req.getRequestURI());
filterChain.doFilter(req, resp);
return;
}
// Allow access to messages without authentication
if ("/messages".equals(req.getServletPath()) && req.getMethod().equals("GET")) {
filterChain.doFilter(req, resp);
return;
}
if (principal!=null) {
if (isAllowed(principal, req)) {
filterChain.doFilter(req, resp);
return;
} else {
String extramsg="";
if ("POST".equals(req.getMethod())){
String token = req.getParameter("key");
if (token!=null && token.length()>0) {
if (ChatboxManager.isValidToken(token, req)) {
addAllowedUser(principal, req);
resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURI()));
return;
} else {
extramsg="The token is not right, you will not be authorized to use this app.";
}
} else {
extramsg="No token received, you will not be authorized to use this app.";
}
}
resp.setContentType("text/html; charset=utf8");
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE html>\n<html><head><title>Provide access token</title></head><body>");
out.print("<div style='margin:5em; border: 1px solid black; padding: 2em;'><div style='margin-bottom:2em;'>");
out.print(extramsg);
out.print("</div><div><form method='POST' action='"+req.getRequestURI()+"'>");
out.println("Please provide your access token</div><div><input type='text' name='key' /><button type='submit'>Submit</button></form></div>");
out.println("<div style='margin-top: 1em;'>You are logged in as "+principal.getName()+"</div></div>");
out.println("</body></html>");
resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
} else {
//resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE html>\n<html><head><title>Please login</title></head><body>");
out.print("<div style='margin:5em; border: 1px solid black; padding: 2em;'><div style='margin-bottom:2em;'>");
out.print("Please <a href=\"");
if (req.getRequestURI().endsWith("logout")) {
out.print(getLoginURL("/"));
} else {
out.print(getLoginURL(req.getRequestURI()));
}
out.print("\">login</a></div>");
out.println("</body></html>");
// resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
private Principal getPrincipal(HttpServletRequest req) {
Principal result = req.getUserPrincipal();
if (result!=null) { return result; }
// Cookie cookie = getCookie(req, DARWIN_AUTH_COOKIE);
return req.getUserPrincipal();
}
private Cookie getCookie(HttpServletRequest pReq, String pCookieName) {
for (Cookie cookie: pReq.getCookies()) {
if (cookie.getName()==pCookieName) {
return cookie;
}
}
return null;
}
/**
* Get the login url that will forward the user to the requested page.
* @param pRequestURI The url to forward to.
*/
private String getLoginURL(String pRequestURI) {
return "";
}
private static void addAllowedUser(Principal principal, ServletRequest pKey) {
UserManager.addAllowedUser(principal, pKey);
}
private static boolean isAllowed(Principal principal, ServletRequest pKey) {
return UserManager.isAllowedUser(principal, pKey);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
this.filterConfig = arg0;
// Object dbKey = new Object();
// ChatboxManager.ensureTables(dbKey);
// try {
// DBHelper.dbHelper(UserManager.RESOURCE_REF, dbKey).close();
// } catch (SQLException e) {
// throw new ServletException(e);
}
}
|
package org.navalplanner.web.planner.tabs;
import static org.navalplanner.web.I18nHelper._;
import static org.navalplanner.web.planner.tabs.MultipleTabsPlannerController.BREADCRUMBS_SEPARATOR;
import static org.navalplanner.web.planner.tabs.MultipleTabsPlannerController.PLANNIFICATION;
import java.util.HashMap;
import java.util.Map;
import org.navalplanner.business.orders.entities.Order;
import org.navalplanner.web.limitingresources.LimitingResourcesController;
import org.navalplanner.web.planner.tabs.CreatedOnDemandTab.IComponentCreator;
import org.zkoss.ganttz.extensions.ITab;
import org.zkoss.ganttz.resourceload.ResourcesLoadPanel.IToolbarCommand;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zul.Image;
import org.zkoss.zul.Label;
public class LimitingResourcesTabCreator {
/* Unnecesary */
private static String ORDER_LIMITING_RESOURCES_VIEW = _("Limiting resources (order)");
public static ITab create(Mode mode,
LimitingResourcesController LimitingResourcesController,
IToolbarCommand upCommand,
LimitingResourcesController LimitingResourcesControllerGlobal,
Component breadcrumbs) {
return new LimitingResourcesTabCreator(mode,
LimitingResourcesController, LimitingResourcesControllerGlobal,
breadcrumbs)
.build();
}
private final Mode mode;
private final LimitingResourcesController limitingResourcesController;
private final LimitingResourcesController limitingResourcesControllerGlobal;
private final Component breadcrumbs;
private LimitingResourcesTabCreator(Mode mode,
LimitingResourcesController LimitingResourcesController,
LimitingResourcesController LimitingResourcesControllerGlobal,
Component breadcrumbs) {
this.mode = mode;
this.limitingResourcesController = LimitingResourcesController;
this.limitingResourcesControllerGlobal = LimitingResourcesControllerGlobal;
this.breadcrumbs = breadcrumbs;
}
private ITab build() {
return TabOnModeType.forMode(mode)
.forType(ModeType.GLOBAL,
createGlobalLimitingResourcesTab()).forType(ModeType.ORDER,
createOrderLimitingResourcesTab())
.create();
}
private ITab createOrderLimitingResourcesTab() {
IComponentCreator componentCreator = new IComponentCreator() {
@Override
/* Should never be called */
public org.zkoss.zk.ui.Component create(
org.zkoss.zk.ui.Component parent) {
Map<String, Object> arguments = new HashMap<String, Object>();
// LimitingResourcesController.add(upCommand);
arguments.put("LimitingResourcesController",
limitingResourcesController);
return Executions.createComponents(
"/limitingresources/_limitingresources.zul", parent,
arguments);
}
};
return new CreatedOnDemandTab(ORDER_LIMITING_RESOURCES_VIEW,
"order-limiting-resources",
componentCreator) {
@Override
protected void afterShowAction() {
breadcrumbs.getChildren().clear();
breadcrumbs.appendChild(new Image(BREADCRUMBS_SEPARATOR));
breadcrumbs.appendChild(new Label(PLANNIFICATION));
breadcrumbs.appendChild(new Image(BREADCRUMBS_SEPARATOR));
breadcrumbs
.appendChild(new Label(ORDER_LIMITING_RESOURCES_VIEW));
breadcrumbs.appendChild(new Image(BREADCRUMBS_SEPARATOR));
Order currentOrder = mode.getOrder();
limitingResourcesController.filterBy(currentOrder);
limitingResourcesController.reload();
breadcrumbs.appendChild(new Label(currentOrder.getName()));
}
};
}
private ITab createGlobalLimitingResourcesTab() {
final IComponentCreator componentCreator = new IComponentCreator() {
@Override
public org.zkoss.zk.ui.Component create(
org.zkoss.zk.ui.Component parent) {
Map<String, Object> arguments = new HashMap<String, Object>();
arguments.put("LimitingResourcesController",
limitingResourcesControllerGlobal);
return Executions.createComponents(
"/limitingresources/_limitingresources.zul", parent,
arguments);
}
};
return new CreatedOnDemandTab(_("Limiting Resources Planning"),
"limiting-resources",
componentCreator) {
@Override
protected void afterShowAction() {
limitingResourcesControllerGlobal.filterBy(null);
limitingResourcesControllerGlobal.reload();
if (breadcrumbs.getChildren() != null) {
breadcrumbs.getChildren().clear();
}
breadcrumbs.appendChild(new Image(BREADCRUMBS_SEPARATOR));
breadcrumbs.appendChild(new Label(PLANNIFICATION));
breadcrumbs.appendChild(new Image(BREADCRUMBS_SEPARATOR));
breadcrumbs.appendChild(new Label(
_("Limiting Resources Planning")));
}
};
}
}
|
package com.yahoo.vespa.hosted.node.admin.task.util.process;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* @author hakonhall
*/
public class TestProcessFactory implements ProcessFactory {
private static class SpawnCall {
private final String commandDescription;
private final Function<CommandLine, ChildProcess2> callback;
private SpawnCall(String commandDescription,
Function<CommandLine, ChildProcess2> callback) {
this.commandDescription = commandDescription;
this.callback = callback;
}
}
private final List<SpawnCall> expectedSpawnCalls = new ArrayList<>();
private final List<CommandLine> spawnCommandLines = new ArrayList<>();
private boolean muteVerifyAllCommandsExecuted = false;
/** Forward call to spawn() to callback. */
public TestProcessFactory interceptSpawn(String commandDescription,
Function<CommandLine, ChildProcess2> callback) {
expectedSpawnCalls.add(new SpawnCall(commandDescription, callback));
return this;
}
// Convenience method for the caller to avoid having to create a TestChildProcess2 instance.
public TestProcessFactory expectSpawn(String commandLineString, TestChildProcess2 toReturn) {
int commandIndex = expectedSpawnCalls.size();
return interceptSpawn(
commandLineString,
commandLine -> defaultSpawn(commandLine, commandLineString, toReturn, commandIndex));
}
// Convenience method for the caller to avoid having to create a TestChildProcess2 instance.
public TestProcessFactory expectSpawn(String commandLine, int exitCode, String output) {
return expectSpawn(commandLine, new TestChildProcess2(exitCode, output));
}
/** Ignore the CommandLine passed to spawn(), just return successfully with the given output. */
public TestProcessFactory ignoreSpawn(String output) {
return interceptSpawn(
"[call index " + expectedSpawnCalls.size() + "]",
commandLine -> new TestChildProcess2(0, output));
}
public TestProcessFactory ignoreSpawn() {
return ignoreSpawn("");
}
public void verifyAllCommandsExecuted() {
if (muteVerifyAllCommandsExecuted) return;
if (spawnCommandLines.size() < expectedSpawnCalls.size()) {
int missingCommandIndex = spawnCommandLines.size();
throw new IllegalStateException("Command #" + missingCommandIndex +
" never executed: " +
expectedSpawnCalls.get(missingCommandIndex).commandDescription);
}
}
/**
* WARNING: CommandLine is mutable, and e.g. reusing a CommandLine for the next call
* would make the CommandLine in this list no longer reflect the original CommandLine.
*/
public List<CommandLine> getMutableCommandLines() {
return spawnCommandLines;
}
@Override
public ChildProcess2 spawn(CommandLine commandLine) {
String commandLineString = commandLine.toString();
if (spawnCommandLines.size() + 1 > expectedSpawnCalls.size()) {
throw new IllegalStateException("Too many invocations: " + commandLineString);
}
spawnCommandLines.add(commandLine);
return expectedSpawnCalls.get(spawnCommandLines.size() - 1).callback.apply(commandLine);
}
private ChildProcess2 defaultSpawn(CommandLine commandLine,
String expectedCommandLineString,
ChildProcess2 toReturn,
int commandSequenceNumber) {
String actualCommandLineString = commandLine.toString();
if (!Objects.equals(actualCommandLineString, expectedCommandLineString)) {
muteVerifyAllCommandsExecuted = true;
throw new IllegalArgumentException("Expected command #" + commandSequenceNumber + " to be '" +
expectedCommandLineString + "' but got '" + actualCommandLineString + "'");
}
return toReturn;
}
}
|
package com.kickstarter;
import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import com.facebook.FacebookSdk;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import net.danlew.android.joda.JodaTimeAndroid;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.CrashManagerListener;
import java.net.CookieHandler;
import java.net.CookieManager;
import javax.inject.Inject;
import timber.log.Timber;
public class KSApplication extends Application {
private ApplicationComponent component;
private RefWatcher refWatcher;
@Inject CookieManager cookieManager;
@Override
public void onCreate() {
super.onCreate();
// Only log for internal builds
if (BuildConfig.FLAVOR.equals("internal")) {
Timber.plant(new Timber.DebugTree());
}
// Send crash reports in release builds
if (!BuildConfig.DEBUG && !isInUnitTests()) {
checkForCrashes();
}
if (!isInUnitTests()) {
refWatcher = LeakCanary.install(this);
}
JodaTimeAndroid.init(this);
component = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
component().inject(this);
CookieHandler.setDefault(cookieManager);
FacebookSdk.sdkInitialize(this);
}
public ApplicationComponent component() {
return component;
}
public static RefWatcher getRefWatcher(@NonNull final Context context) {
final KSApplication application = (KSApplication) context.getApplicationContext();
return application.refWatcher;
}
protected boolean isInUnitTests() {
return false;
}
private void checkForCrashes() {
CrashManager.register(this, getString(R.string.hockey_app_id), new CrashManagerListener() {
public boolean shouldAutoUploadCrashes() {
return true;
}
});
}
}
|
package org.ai4fm.proofprocess.zeves.impl;
import net.sourceforge.czt.base.ast.Term;
import org.ai4fm.proofprocess.parse.StringCompression;
import org.ai4fm.proofprocess.zeves.*;
import org.ai4fm.proofprocess.zeves.parse.ZmlTermParser;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class ZEvesProofProcessFactoryImpl extends EFactoryImpl implements ZEvesProofProcessFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static ZEvesProofProcessFactory init() {
try {
ZEvesProofProcessFactory theZEvesProofProcessFactory = (ZEvesProofProcessFactory)EPackage.Registry.INSTANCE.getEFactory("http://org/ai4fm/proofprocess/zeves/v1.0.0");
if (theZEvesProofProcessFactory != null) {
return theZEvesProofProcessFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new ZEvesProofProcessFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ZEvesProofProcessFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case ZEvesProofProcessPackage.UNPARSED_TERM: return (EObject)createUnparsedTerm();
case ZEvesProofProcessPackage.CZT_TERM: return (EObject)createCztTerm();
case ZEvesProofProcessPackage.ZEVES_TRACE: return (EObject)createZEvesTrace();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case ZEvesProofProcessPackage.ZML_TERM:
return createZmlTermFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case ZEvesProofProcessPackage.ZML_TERM:
return convertZmlTermToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public UnparsedTerm createUnparsedTerm() {
UnparsedTermImpl unparsedTerm = new UnparsedTermImpl();
return unparsedTerm;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public CztTerm createCztTerm() {
CztTermImpl cztTerm = new CztTermImpl();
return cztTerm;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ZEvesTrace createZEvesTrace() {
ZEvesTraceImpl zEvesTrace = new ZEvesTraceImpl();
return zEvesTrace;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public Term createZmlTermFromString(EDataType eDataType, String initialValue) {
// check if uncompressed ZML value (backwards compatibility) or a compressed one
String zml;
if (initialValue.startsWith("<?xml")) {
zml = initialValue;
} else {
// compressed
zml = StringCompression.decompress(initialValue);
}
return ZmlTermParser.parseZml(zml);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public String convertZmlTermToString(EDataType eDataType, Object instanceValue) {
String zml = ZmlTermParser.convertToZml((Term) instanceValue);
// compress the ZML string, since it tends to occupy the majority of storage space
// the compression can be up to 95% efficient on large Strings
return StringCompression.compress(zml);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ZEvesProofProcessPackage getZEvesProofProcessPackage() {
return (ZEvesProofProcessPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static ZEvesProofProcessPackage getPackage() {
return ZEvesProofProcessPackage.eINSTANCE;
}
} //ZEvesProofProcessFactoryImpl
|
package com.mk.places.utilities;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.annotation.DrawableRes;
import android.support.customtabs.CustomTabsClient;
import android.support.customtabs.CustomTabsIntent;
import android.support.customtabs.CustomTabsServiceConnection;
import android.support.customtabs.CustomTabsSession;
import android.support.design.widget.Snackbar;
import android.support.v7.graphics.Palette;
import android.text.Html;
import android.view.View;
import com.mk.places.R;
public class Utils extends Activity {
public static String convertEntitiesCharsHTML(String string) {
return Html.fromHtml((String) string).toString().replace("\\n ", "\n");
}
public static boolean compareStrings(String string_1, String string_2) {
return string_1.toLowerCase().replace(" ", "").replace(",", "")
.equals(string_2.toLowerCase().replace(" ", "").replace(",", ""));
}
public static boolean stringIsContained(String string_1, String string_2) {
return string_1.toLowerCase().replace(" ", "").replace(",", "")
.contains(string_2.toLowerCase().replace(" ", "").replace(",", ""));
}
public static Typeface customTypeface(Context context, int index) {
Typeface typeface = null;
if (index == 1) typeface = Typeface.createFromAsset(context.getAssets(), "fonts/BreeSerif-Regular.ttf");
if (index == 2) typeface = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
if (index == 3) typeface = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Bold.ttf");
return typeface;
}
public static void customChromeTab(Context context, String link, int color) {
final CustomTabsClient[] mClient = new CustomTabsClient[1];
final CustomTabsSession[] mCustomTabsSession = new CustomTabsSession[1];
CustomTabsServiceConnection mCustomTabsServiceConnection = new CustomTabsServiceConnection() {
@Override
public void onCustomTabsServiceConnected(ComponentName componentName, CustomTabsClient customTabsClient) {
mClient[0] = customTabsClient;
mClient[0].warmup(0L);
mCustomTabsSession[0] = mClient[0].newSession(null);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mClient[0] = null;
}
};
if (color == 0) color = context.getResources().getColor(R.color.cardBackground);
CustomTabsClient.bindCustomTabsService(context, "com.android.chrome", mCustomTabsServiceConnection);
CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder(mCustomTabsSession[0])
.setToolbarColor(color)
.setShowTitle(true)
.addDefaultShareMenuItem()
.build();
customTabsIntent.launchUrl((Activity) context, Uri.parse(link));
context.unbindService(mCustomTabsServiceConnection);
}
public static boolean hasNetwork(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public static int colorVariant(int color, float intensity) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= intensity;
color = Color.HSVToColor(hsv);
return color;
}
public static int colorFromPalette(Context context, Palette palette) {
final int defaultColor = context.getResources().getColor(R.color.colorPrimary);
int mutedLight = palette.getLightMutedColor(defaultColor);
int vibrantLight = palette.getLightVibrantColor(mutedLight);
int mutedDark = palette.getDarkMutedColor(vibrantLight);
int muted = palette.getMutedColor(mutedDark);
int vibrantDark = palette.getDarkVibrantColor(muted);
return palette.getVibrantColor(vibrantDark);
}
public static void simpleSnackBar(Activity activity, int color, int view, int text, int length) {
View layout = activity.findViewById(view);
Snackbar snackbar = Snackbar.make(layout, text, length)
.setActionTextColor(activity.getResources().getColor(R.color.white));
View snackBarView = snackbar.getView();
if (color == 0) color = activity.getResources().getColor(R.color.colorPrimary);
snackBarView.setBackgroundColor(color);
snackbar.show();
}
}
|
package org.archive.wayback.util.htmllex;
import java.net.URI;
import java.net.URL;
import junit.framework.TestCase;
/**
* @author brad
*
*/
public class ParseContextTest extends TestCase {
/**
* Test method for {@link org.archive.wayback.util.htmllex.ParseContext#contextualizeUrl(java.lang.String)}.
*/
public void testContextualizeUrl() {
ParseContext pc = new ParseContext();
try {
URI tmp = new URI("http://base.com/foo.html#REF");
String ref = tmp.getFragment();
assertEquals("REF",ref);
tmp = new URI("http://base.com/foo.html");
assertNull(tmp.getFragment());
pc.setBaseUrl(new URL("http://base.com/"));
assertEquals("http://base.com/images.gif",
pc.contextualizeUrl("/images.gif"));
assertEquals("http://base.com/images.gif",
pc.contextualizeUrl("../images.gif"));
assertEquals("http://base.com/images.gif",
pc.contextualizeUrl("../../images.gif"));
assertEquals("http://base.com/image/1s.gif",
pc.contextualizeUrl("/image/1s.gif"));
assertEquals("http://base.com/image/1s.gif",
pc.contextualizeUrl("../../image/1s.gif"));
assertEquals("http://base.com/image/1s.gif",
pc.contextualizeUrl("/../../image/1s.gif"));
assertEquals("http://base.com/image/1.html#REF",
pc.contextualizeUrl("/../../image/1.html#REF"));
assertEquals("http://base.com/image/1.html#REF FOO",
pc.contextualizeUrl("/../../image/1.html#REF FOO"));
assertEquals("http://base.com/image/foo?boo=baz",
pc.contextualizeUrl("/image/foo?boo=baz"));
assertEquals("http://base.com/image/foo?boo=baz%253A&gar=war",
pc.contextualizeUrl("/image/foo?boo=baz%3A&gar=war"));
// TODO: we need to escape again, right?
// pc.contextualizeUrl("/image/foo?boo=baz%3A&gar=war"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
fail(e.getLocalizedMessage());
}
}
}
|
package Interface;
public class Sword {
}
|
package me.anuraag.grader;
import java.text.DecimalFormat;
public class SingleGrade {
private double percentage;
private double pointsRight;
private String name;
private double totalPoints;
public SingleGrade(){
}
public double getPercentage(){
return Math.floor((this.pointsRight/this.totalPoints)*10000)/100;
}
public double getPointsRight(){
return this.pointsRight;
}
public double getTotalPoints(){
return this.totalPoints;
}
public void setPercentage(double percentage){
this.percentage = percentage;
}
public void setPointsRight(int pointsRight){
this.pointsRight = pointsRight;
}
public void setName(String name){
this.name = name;
}
public void setTotalPoints(int totalPoints){
this.totalPoints = totalPoints;
}
public String toString(){
return this.percentage + " " + this.pointsRight + " " + this.totalPoints;
}
public String getName(){
return this.name;
}
}
|
package org.opens.tgol.presentation.data;
import java.util.Date;
/**
* The interface handles displayable contractInfo data
*
* @author jkowalczyk
*/
public interface ContractInfo {
/**
*
* @return
* the id of the contract
*/
int getId();
/**
* Sets the id of the contract
* @param id
*/
void setId(int id);
/**
*
* @return
* the label of the contract
*/
String getLabel();
/**
* Sets the label of the contract
*
* @param label
*/
void setLabel(String label);
/**
*
* @return
* the Url associated with the contract
*/
String getUrl();
/**
* Sets the Url associated with the contract (can be empty)
*
* @param url
*/
void setUrl(String url);
/**
*
* @return
* the last actInfo associated with the contract
*/
ActInfo getLastActInfo();
/**
* Sets the last actInfo associated with the contract
*
* @param lastActInfo
*/
void setLastActInfo(ActInfo lastActInfo);
// /**
// *
// * @return
// * whether the pages function is enabled for the contract
// */
// boolean isIsPagesForbidden();
// /**
// * Disable/Enable the pages function for the contract
// *
// * @param isPagesForbidden
// */
// void setIsPagesForbidden(boolean isPagesForbidden);
// /**
// *
// * @return
// * whether the site function is enabled for the contract
// */
// boolean isIsFullSiteForbidden();
// /**
// * Disable/Enable the site function for the contract
// *
// * @param isFullSiteForbidden
// */
// void setIsFullSiteForbidden(boolean isFullSiteForbidden);
/**
*
* @return
* whether the contract is expired
*/
boolean getIsContractExpired();
/**
* Sets whether a contract is expired or not.
* @param isContractExpired
*/
void setContractExpired(boolean isContractExpired);
/**
*
* @return
* the expiration date of the contract
*/
Date getExpirationDate();
/**
* Sets the expiration date of the contract
*
* @param expirationDate
*/
void setExpirationDate(Date expirationDate);
/**
*
* @return
* the site audit result progression of the contract
*/
String getSiteAuditProgression();
/**
* Sets the site audit result progression of the contract
* @param siteAuditProgression
*/
void setSiteAuditProgression(AuditProgressionEnum siteAuditProgression);
/**
*
* @return
* whether an act is currently running on this contract
*/
boolean getIsActRunning();
/**
* @param isActRunning
*/
void setIsActRunning(boolean isActRunning);
}
|
package LeetCode;
public class Devide
{
public static int divide1(int dividend, int divisor)
{
if (divisor == 1) // Trival case 1
return dividend;
// Use negative integers to avoid integer overflow
if (dividend > 0)
return -divide(-dividend, divisor);
if (divisor > 0)
return -divide(dividend, -divisor);
if (dividend > divisor) // Trivial case 2
return 0;
if ((dividend == Integer.MIN_VALUE) && (divisor == -1)) // Overflow case
return Integer.MAX_VALUE;
// Find the highest mult = (divisor * 2^shifts) which is <= dividend
// by shifting mult to the left without causing an overflow.
// At most (log2(|dividend|) - log2(|divisor|) + 1) iterations.
int min_divisor = Integer.MIN_VALUE >> 1;
int mult = divisor; // = divisor * 2^shifts
int shifts = 0;
while ((mult >= min_divisor) && (mult > dividend)) {
mult <<= 1;
++shifts;
}
// Compute the result by shifting mult to the right.
// At most (log2(|dividend|) - log2(|divisor|) + 1) iterations for the outer loop.
// At most (log2(|dividend|) - log2(|divisor|) + 1) iterations for the inner loop
// (in total, not per outer iteration).
int result = 0;
int power = 1 << shifts; // = 2^shifts
while (dividend <= divisor) {
shifts = 0;
while (mult < dividend) {
mult >>= 1;
++shifts;
}
dividend -= mult;
power >>= shifts;
result |= power; // Adds power to result
}
return result;
}
// slow
// pass both
public static int divide(int dividend, int divisor)
{
if (dividend == 0 || divisor == 1) return dividend;
if (dividend == divisor) return 1;
int code;
if (dividend < 0 && divisor > 0 || dividend > 0 && divisor < 0)
code = 0;// negative
else
code = 1;
if (dividend == Integer.MAX_VALUE && divisor == Integer.MIN_VALUE)
return 0;
else if (dividend == Integer.MIN_VALUE && divisor == Integer.MAX_VALUE)
return code == 0
? -1
: 1;
long div = dividend, div2 = divisor;
div = Math.abs(div);
div2 = Math.abs(div2);
// System.out.println(div + " " + div2 + " " + code);
double ret = Math.pow(10, Math.log10((div)) - Math.log10(((div2))));
int result = (int) Math.floor(ret + 0.0000001);
return code == 0
? -result
: result;
}
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println(divide1(123456, 7));
}
}
|
package automaticResumeParser.utilities;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
public class Utilities {
public static List<Long> sortedNumbersList(List<String> paragraphs) {
List<Long> final_list = new ArrayList<Long>();
for (int i = 0; i < paragraphs.size(); i++) {
List<Long> list = returnNumberList((String) paragraphs.get(i));
Iterator<Long> iterator = list.iterator();
while (iterator.hasNext()) {
Long insert = iterator.next();
if (final_list.contains(insert)) {
} else {
final_list.add(insert);
}
}
}
Collections.sort(final_list);
return final_list;
}
public static List<Long> returnNumberList(String value) {
List<Long> list = new ArrayList<Long>();
Pattern intsOnly = Pattern.compile("\\d+");
Matcher makeMatch = intsOnly.matcher(value);
while (makeMatch.find()) {
String inputInt = makeMatch.group();
if ((list.contains(inputInt))) {
} else {
list.add(Long.parseLong(inputInt));
}
}
return list;
}
public static boolean stringContainsInteger(String value) {
if (Pattern.matches("[\\D]+", value)) {
return false;
}
return true;
}
public static boolean emaildId(String value) {
if (value.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$") == true) {
return true;
}
return false;
}
public static List<Integer> getyears(List<Long> numberList) {
List<Integer> returnList = new ArrayList<Integer>();
Calendar cal = new GregorianCalendar();
int year = cal.get(Calendar.YEAR);
int size = numberList.size();
for (int i = 0; i < size; i++) {
Long number = (Long) numberList.get(i);
if ((number > 1980) && (number <= year)) {
returnList.add(Integer.parseInt(numberList.get(i).toString()));
}
}
Collections.sort(returnList);
return returnList;
}
public static List<Integer> getPercentage(List<Long> numberList) {
List<Integer> returnList = new ArrayList<Integer>();
;
int size = numberList.size();
for (int i = 0; i < size; i++) {
Long number = (Long) numberList.get(i);
if ((number > 30) && (number <= 100)) {
returnList.add(Integer.parseInt(numberList.get(i).toString()));
}
}
Collections.sort(returnList);
return returnList;
}
public static String properCase(String value) {
value = value.replaceAll("\\s+", " ");
char[] charArray = value.toCharArray();
for (int i = 0; i < charArray.length - 1; i++) {
if (i == 0) {
charArray[i] = Character.toUpperCase(charArray[i]);
}
if (charArray[i] == ' ') {
charArray[i + 1] = Character.toUpperCase(charArray[i + 1]);
}
}
String result = new String(charArray);
return result;
}
public static String writeToLog(Exception exception, String Info) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.print(" [ ");
pw.print(exception.getClass().getName());
pw.print(" ] ");
pw.print(exception.getMessage());
exception.printStackTrace(pw);
File file = new File("E:\\" + "Log.txt");
String date = getSysDate();
try {
if (file.exists()) {
file.createNewFile();
String old_Data = FileUtils.readFileToString(file);
String new_data = old_Data + "\n" + "Resume :" + Info + " "
+ date + " " + sw.toString();
FileUtils.writeStringToFile(file, new_data);
} else {
FileUtils.writeStringToFile(file, "Resume :" + Info + " "
+ date + " " + sw.toString());
}
} catch (Exception e) {
return "FatalException";
}
return "success";
}
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)(\\.[A-Za-z]{2,})$";
public static boolean validateEmailId(final String hex) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(hex);
return matcher.matches();
}
public static String getSysDate() {
String date;
Calendar cal = new GregorianCalendar();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int Min = cal.get(Calendar.MINUTE);
date = "" + year + ":" + (month + 1) + ":" + day + ":" + hour + ":"
+ Min;
return date;
}
public static String FindExtension(String resumeName) {
String extension = "";
int length = resumeName.length();
int p = 0;
for (int j = 0; j < length; j++) {
if (resumeName.charAt(j) == '.') {
p = j;
}
}
if (p != 0) {
extension = resumeName.substring(p + 1, length);
}
return extension;
}
public static Set<String> pastForm(String word) {
String past = "";
String presentContinuous = "";
Set<String> pastSet = new HashSet<String>();
String lastChar = Character.toString(word.charAt(word.length() - 1));
String secondlastChar = Character
.toString(word.charAt(word.length() - 1));
if ((lastChar.equalsIgnoreCase("e") || lastChar.equalsIgnoreCase("y") || lastChar
.equalsIgnoreCase("o")) && secondlastChar.equalsIgnoreCase("e")) {
presentContinuous = word + "ing";
past = word + "d";
} else if ((!isVowel(lastChar)) && isVowel(secondlastChar)) {
past = word + lastChar + "ed";
presentContinuous = word + lastChar + "ing";
} else if (lastChar.equalsIgnoreCase("e")) {
presentContinuous = word.subSequence(0, word.length() - 2) + "ing";
past = word.subSequence(0, word.length() - 1) + "d";
}
pastSet.add(past);
pastSet.add(presentContinuous);
return pastSet;
}
private static boolean isVowel(String val) {
return val.equalsIgnoreCase("a") || val.equalsIgnoreCase("e")
|| val.equalsIgnoreCase("i") || val.equalsIgnoreCase("o")
|| val.equalsIgnoreCase("u");
}
}
|
package org.incode.eurocommercial.ecpcrm.restapi;
import java.io.InputStream;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.assertj.core.util.Strings;
import org.joda.time.LocalDate;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.applib.services.clock.ClockService;
import org.apache.isis.viewer.restfulobjects.applib.RepresentationType;
import org.apache.isis.viewer.restfulobjects.applib.RestfulMediaType;
import org.apache.isis.viewer.restfulobjects.rendering.service.RepresentationService;
import org.apache.isis.viewer.restfulobjects.rendering.service.conneg.PrettyPrinting;
import org.apache.isis.viewer.restfulobjects.server.resources.ResourceAbstract;
import org.incode.eurocommercial.ecpcrm.dom.CardStatus;
import org.incode.eurocommercial.ecpcrm.dom.Title;
import org.incode.eurocommercial.ecpcrm.dom.card.Card;
import org.incode.eurocommercial.ecpcrm.dom.card.CardRepository;
import org.incode.eurocommercial.ecpcrm.dom.center.CenterRepository;
import org.incode.eurocommercial.ecpcrm.dom.user.User;
import org.incode.eurocommercial.ecpcrm.dom.user.UserRepository;
@Path("/crm/api/6.0")
public class EcpCrmResource extends ResourceAbstract {
@Override
protected void init(
final RepresentationType representationType,
final Where where,
final RepresentationService.Intent intent) {
super.init(representationType, where, intent);
this.getServicesInjector().injectServicesInto(this);
}
@POST
@Path("/card-check")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.WILDCARD })
@Produces({
MediaType.APPLICATION_JSON, RestfulMediaType.APPLICATION_JSON_OBJECT, RestfulMediaType.APPLICATION_JSON_ERROR,
MediaType.APPLICATION_XML, RestfulMediaType.APPLICATION_XML_OBJECT, RestfulMediaType.APPLICATION_XML_ERROR
})
@PrettyPrinting
//public Response cardCheck(@HeaderParam("card") String cardNumber, @HeaderParam("origin") String origin) {
public Response cardCheck(@FormParam("request") String request) {
JsonParser jsonParser = new JsonParser();
JsonElement cardNumberJson = jsonParser.parse(request).getAsJsonObject().get("card");
String cardNumber = cardNumberJson == null ? null : cardNumberJson.getAsString();
JsonElement originJson = jsonParser.parse(request).getAsJsonObject().get("origin");
String origin = originJson == null ? null : originJson.getAsString();
init(RepresentationType.DOMAIN_OBJECT, Where.OBJECT_FORMS, RepresentationService.Intent.ALREADY_PERSISTENT);
if(Strings.isNullOrEmpty(cardNumber) || Strings.isNullOrEmpty(origin)) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 302)
.add("message", "Invalid parameter")
.toJsonString())
.build();
}
if(!cardRepository.cardNumberIsValid(cardNumber)) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 312)
.add("message", "Invalid card number")
.toJsonString())
.build();
}
Card card = cardRepository.findByExactNumber(cardNumber);
if(card == null || card.getStatus() != CardStatus.ENABLED) {
if(card != null && card.getStatus() == CardStatus.TOCHANGE) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 319)
.add("message", "Outdated card")
.toJsonString())
.build();
}
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 303)
.add("message", "Invalid card")
.toJsonString())
.build();
}
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 314)
.add("message", "Failed to bind user to card")
.toJsonString())
.build();
}
@POST
@Path("/card-game")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.WILDCARD })
@Produces({
MediaType.APPLICATION_JSON, RestfulMediaType.APPLICATION_JSON_OBJECT, RestfulMediaType.APPLICATION_JSON_ERROR,
MediaType.APPLICATION_XML, RestfulMediaType.APPLICATION_XML_OBJECT, RestfulMediaType.APPLICATION_XML_ERROR
})
@PrettyPrinting
//public Response cardGame(@HeaderParam("card") String cardNumber, @HeaderParam("win") String win, @HeaderParam("desc") String desc) {
public Response cardGame(@FormParam("request") String request) {
init(RepresentationType.DOMAIN_OBJECT, Where.OBJECT_FORMS, RepresentationService.Intent.ALREADY_PERSISTENT);
JsonParser jsonParser = new JsonParser();
JsonElement cardNumberJson = jsonParser.parse(request).getAsJsonObject().get("card");
String cardNumber = cardNumberJson == null ? null : cardNumberJson.getAsString();
/*not sure about these*/
JsonElement winJson = jsonParser.parse(request).getAsJsonObject().get("win");
String win = winJson == null ? null : winJson.getAsString();
JsonElement descJson = jsonParser.parse(request).getAsJsonObject().get("desc");
String desc = descJson == null ? null : descJson.getAsString();
if(Strings.isNullOrEmpty(cardNumber)) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 302)
.add("message", "Invalid parameter")
.toJsonString())
.build();
}
Card card = cardRepository.findByExactNumber(cardNumber);
if(card == null || card.getOwner() == null || card.getStatus() != CardStatus.ENABLED) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 303)
.add("message", "Invalid card")
.toJsonString())
.build();
}
if(!card.getOwner().isEnabled()) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 304)
.add("message", "Invalid user")
.toJsonString())
.build();
}
if(!card.canPlay()) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 315)
.add("message", "Card has already played")
.toJsonString())
.build();
}
card.play();
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 200)
.toJsonString())
.build();
}
@POST
@Path("/card-request")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.WILDCARD })
@Produces({
MediaType.APPLICATION_JSON, RestfulMediaType.APPLICATION_JSON_OBJECT, RestfulMediaType.APPLICATION_JSON_ERROR,
MediaType.APPLICATION_XML, RestfulMediaType.APPLICATION_XML_OBJECT, RestfulMediaType.APPLICATION_XML_ERROR
})
@PrettyPrinting
public Response cardRequest(InputStream body) {
init(RepresentationType.DOMAIN_OBJECT, Where.OBJECT_FORMS, RepresentationService.Intent.ALREADY_PERSISTENT);
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(String.format("{ \"status\": 200, \"message\": \"test\"}"))
.build();
}
@POST
@Path("/user-create")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.WILDCARD, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({
MediaType.APPLICATION_JSON, RestfulMediaType.APPLICATION_JSON_OBJECT, RestfulMediaType.APPLICATION_JSON_ERROR,
MediaType.APPLICATION_XML, RestfulMediaType.APPLICATION_XML_OBJECT, RestfulMediaType.APPLICATION_XML_ERROR
})
@PrettyPrinting
public Response userCreate(@FormParam("request") String request) {
init(RepresentationType.DOMAIN_OBJECT, Where.OBJECT_FORMS, RepresentationService.Intent.ALREADY_PERSISTENT);
JsonParser jsonParser = new JsonParser();
JsonElement cardNumberJson = jsonParser.parse(request).getAsJsonObject().get("card");
JsonElement titleJson = jsonParser.parse(request).getAsJsonObject().get("title");
JsonElement firstNameJson = jsonParser.parse(request).getAsJsonObject().get("first_name");
JsonElement lastNameJson = jsonParser.parse(request).getAsJsonObject().get("last_name");
JsonElement addressJson = jsonParser.parse(request).getAsJsonObject().get("address");
JsonElement zipcodeJson = jsonParser.parse(request).getAsJsonObject().get("zipcode");
JsonElement cityJson = jsonParser.parse(request).getAsJsonObject().get("city");
JsonElement emailJson = jsonParser.parse(request).getAsJsonObject().get("email");
JsonElement promotionalEmailsJson = jsonParser.parse(request).getAsJsonObject().get("optin");
String cardNumber = cardNumberJson == null ? null : cardNumberJson.getAsString();
String title = titleJson == null ? null : titleJson.getAsString();
String firstName = firstNameJson == null ? null : firstNameJson.getAsString();
String lastName = lastNameJson == null ? null : lastNameJson.getAsString();
String address = addressJson == null ? null : addressJson.getAsString();
String zipcode = zipcodeJson == null ? null : zipcodeJson.getAsString();
String city = cityJson == null ? null : cityJson.getAsString();
String email = emailJson == null ? null : emailJson.getAsString();
int promotionalEmails = promotionalEmailsJson == null ? 0 : promotionalEmailsJson.getAsInt();
if(title == null || Strings.isNullOrEmpty(firstName) || Strings.isNullOrEmpty(lastName)) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 302)
.add("message", "Invalid parameter")
.toJsonString())
.build();
}
if(!cardRepository.cardNumberIsValid(cardNumber)) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 312)
.add("message", "Invalid card number")
.toJsonString())
.build();
}
Card card = cardRepository.findByExactNumber(cardNumber);
if(card != null) {
if(card.getStatus() != CardStatus.ENABLED) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 303)
.add("message", "Invalid card")
.toJsonString())
.build();
}
//TODO: Check against center of hostess
if(card.getOwner() != null) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 308)
.add("message", "Card is already bound to another user")
.toJsonString())
.build();
}
}
User user = userRepository.findByExactEmail(email);
if(user != null) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 309)
.add("message", "Email already exists in our system")
.toJsonString())
.build();
}
//TODO: Extract center of request
user = userRepository.findOrCreate(true, Title.valueOf(title), firstName, lastName, email,
address, zipcode, city, null, null, cardNumber,
asBoolean(promotionalEmails), null, null);
if(user == null) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 316)
.add("message", "Failed to create or update user")
.toJsonString())
.build();
}
card = cardRepository.findByExactNumber(cardNumber);
if(card != null && card.getOwner() != user) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 314)
.add("message", "Failed to bind user to card")
.toJsonString())
.build();
}
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 200)
.toJsonString())
.build();
}
@POST
@Path("/user-update")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.WILDCARD, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({
MediaType.APPLICATION_JSON, RestfulMediaType.APPLICATION_JSON_OBJECT, RestfulMediaType.APPLICATION_JSON_ERROR,
MediaType.APPLICATION_XML, RestfulMediaType.APPLICATION_XML_OBJECT, RestfulMediaType.APPLICATION_XML_ERROR
})
@PrettyPrinting
public Response userUpdate(@FormParam("request") String request) {
init(RepresentationType.DOMAIN_OBJECT, Where.OBJECT_FORMS, RepresentationService.Intent.ALREADY_PERSISTENT);
JsonParser jsonParser = new JsonParser();
JsonElement cardNumberJson = jsonParser.parse(request).getAsJsonObject().get("card");
JsonElement titleJson = jsonParser.parse(request).getAsJsonObject().get("title");
JsonElement firstNameJson = jsonParser.parse(request).getAsJsonObject().get("first_name");
JsonElement lastNameJson = jsonParser.parse(request).getAsJsonObject().get("last_name");
JsonElement addressJson = jsonParser.parse(request).getAsJsonObject().get("address");
JsonElement zipcodeJson = jsonParser.parse(request).getAsJsonObject().get("zipcode");
JsonElement cityJson = jsonParser.parse(request).getAsJsonObject().get("city");
JsonElement emailJson = jsonParser.parse(request).getAsJsonObject().get("email");
JsonElement promotionalEmailsJson = jsonParser.parse(request).getAsJsonObject().get("optin");
String cardNumber = cardNumberJson == null ? null : cardNumberJson.getAsString();
String title = titleJson == null ? null : titleJson.getAsString();
String firstName = firstNameJson == null ? null : firstNameJson.getAsString();
String lastName = lastNameJson == null ? null : lastNameJson.getAsString();
String address = addressJson == null ? null : addressJson.getAsString();
String zipcode = zipcodeJson == null ? null : zipcodeJson.getAsString();
String city = cityJson == null ? null : cityJson.getAsString();
String email = emailJson == null ? null : emailJson.getAsString();
int promotionalEmails = promotionalEmailsJson == null ? 0 : promotionalEmailsJson.getAsInt();
if(Strings.isNullOrEmpty(title) || Strings.isNullOrEmpty(firstName) || Strings.isNullOrEmpty(lastName)
|| Strings.isNullOrEmpty(cardNumber) || Strings.isNullOrEmpty(email)) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 302)
.add("message", "Invalid parameter")
.toJsonString())
.build();
}
if(!cardRepository.cardNumberIsValid(cardNumber)) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 312)
.add("message", "Invalid card number")
.toJsonString())
.build();
}
Card card = cardRepository.findByExactNumber(cardNumber);
if(card != null) {
if(card.getStatus() != CardStatus.ENABLED) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 303)
.add("message", "Invalid card")
.toJsonString())
.build();
}
//TODO: Check against center of hostess
if(card.getOwner() != null) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 308)
.add("message", "Card is already bound to another user")
.toJsonString())
.build();
}
}
User user = userRepository.findByExactEmail(email);
if(user != null && !(firstName.equals(user.getFirstName()) && lastName.equals(user.getLastName()))) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 309)
.add("message", "Email already exists in our system")
.toJsonString())
.build();
}
//TODO: Extract center of request
user = userRepository.findOrCreate(true, Title.valueOf(title), firstName, lastName, email,
address, zipcode, city, null, null, cardNumber,
asBoolean(promotionalEmails), null, null);
if(user == null) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 316)
.add("message", "Failed to create or update user")
.toJsonString())
.build();
}
user.setTitle(Title.valueOf(title));
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setAddress(address);
user.setZipcode(zipcode);
user.setCity(city);
user.setPromotionalEmails(asBoolean(promotionalEmails));
user.newCard(cardNumber);
card = cardRepository.findByExactNumber(cardNumber);
if(card != null && card.getOwner() != user) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 314)
.add("message", "Failed to bind user to card")
.toJsonString())
.build();
}
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 200)
.toJsonString())
.build();
}
@POST
@Path("/user-detail")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.WILDCARD, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({
MediaType.APPLICATION_JSON, RestfulMediaType.APPLICATION_JSON_OBJECT, RestfulMediaType.APPLICATION_JSON_ERROR
})
@PrettyPrinting
public Response userDetail(@FormParam("request") String request) {
init(RepresentationType.DOMAIN_OBJECT, Where.OBJECT_FORMS, RepresentationService.Intent.ALREADY_PERSISTENT);
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
String reference = jsonParser.parse(request).getAsJsonObject().get("id").getAsString();
//TODO: Not sure how to implement 302 and 310
if(reference == null) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 302)
.add("message", "Invalid parameter")
.toJsonString())
.build();
}
User user = userRepository.findByReference(reference);
if(user == null) {
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 304)
.add("message", "Invalid user")
.toJsonString())
.build();
}
JsonObject userJson = gson.toJsonTree(UserViewModel.fromUser(user)).getAsJsonObject();
return Response
.ok()
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(new JsonBuilder()
.add("status", 200)
.add("response", userJson)
.toJsonString())
.build();
}
public static boolean asBoolean(final int i) {
return i > 0;
}
public static String asString(final int i) {
return "" + i;
}
public static String asString(final boolean bool) {
return bool ? "true" : "false";
}
public static String asString(final LocalDate localDate) {
return localDate == null ? null : localDate.toString();
}
public class JsonBuilder {
private final JsonObject json = new JsonObject();
public String toJsonString() {
return json.toString();
}
public JsonObject toJsonObject() {
return json;
}
public JsonBuilder add(String key, String value) {
json.addProperty(key, value);
return this;
}
public JsonBuilder add(String key, Number value) {
json.addProperty(key, value);
return this;
}
public JsonBuilder add(String key, Boolean value) {
json.addProperty(key, value);
return this;
}
public JsonBuilder add(String key, JsonBuilder value) {
json.add(key, value.toJsonObject());
return this;
}
public JsonBuilder add(String key, JsonObject value) {
json.add(key, value);
return this;
}
}
@Inject UserRepository userRepository;
@Inject CardRepository cardRepository;
@Inject CenterRepository centerRepository;
@Inject ClockService clockService;
}
|
package automaticResumeParser.utilities;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
public class Utilities {
public static List<Long> sortedNumbersList(List<String> paragraphs) {
List<Long> final_list = new ArrayList<Long>();
for (int i = 0; i < paragraphs.size(); i++) {
List<Long> list = returnNumberList((String) paragraphs.get(i));
Iterator<Long> iterator = list.iterator();
while (iterator.hasNext()) {
Long insert = iterator.next();
if (final_list.contains(insert)) {
} else {
final_list.add(insert);
}
}
}
Collections.sort(final_list);
return final_list;
}
public static List<Long> returnNumberList(String value) {
List<Long> list = new ArrayList<Long>();
Pattern intsOnly = Pattern.compile("\\d+");
Matcher makeMatch = intsOnly.matcher(value);
while (makeMatch.find()) {
String inputInt = makeMatch.group();
if ((list.contains(inputInt))) {
} else {
list.add(Long.parseLong(inputInt));
}
}
return list;
}
public static boolean stringContainsInteger(String value) {
if (Pattern.matches("[\\D]+", value)) {
return false;
}
return true;
}
public static boolean emaildId(String value) {
if (value.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$") == true) {
return true;
}
return false;
}
public static List<Integer> getyears(List<Long> numberList) {
List<Integer> returnList = new ArrayList<Integer>();
Calendar cal = new GregorianCalendar();
int year = cal.get(Calendar.YEAR);
int size = numberList.size();
for (int i = 0; i < size; i++) {
Long number = (Long) numberList.get(i);
if ((number > 1980) && (number <= year)) {
returnList.add(Integer.parseInt(numberList.get(i).toString()));
}
}
Collections.sort(returnList);
return returnList;
}
public static List<Integer> getPercentage(List<Long> numberList) {
List<Integer> returnList = new ArrayList<Integer>();
;
int size = numberList.size();
for (int i = 0; i < size; i++) {
Long number = (Long) numberList.get(i);
if ((number > 30) && (number <= 100)) {
returnList.add(Integer.parseInt(numberList.get(i).toString()));
}
}
Collections.sort(returnList);
return returnList;
}
public static String properCase(String value) {
value = value.replaceAll("\\s+", " ");
char[] charArray = value.toCharArray();
for (int i = 0; i < charArray.length - 1; i++) {
if (i == 0) {
charArray[i] = Character.toUpperCase(charArray[i]);
}
if (charArray[i] == ' ') {
charArray[i + 1] = Character.toUpperCase(charArray[i + 1]);
}
}
String result = new String(charArray);
return result;
}
public static String writeToLog(Exception exception, String Info) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.print(" [ ");
pw.print(exception.getClass().getName());
pw.print(" ] ");
pw.print(exception.getMessage());
exception.printStackTrace(pw);
File file = new File("E:\\" + "Log.txt");
String date = getSysDate();
try {
if (file.exists()) {
file.createNewFile();
String old_Data = FileUtils.readFileToString(file);
String new_data = old_Data + "\n" + "Resume :" + Info + " "
+ date + " " + sw.toString();
FileUtils.writeStringToFile(file, new_data);
} else {
FileUtils.writeStringToFile(file, "Resume :" + Info + " "
+ date + " " + sw.toString());
}
} catch (Exception e) {
return "FatalException";
}
return "success";
}
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)(\\.[A-Za-z]{2,})$";
public static boolean validateEmailId(final String hex) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(hex);
return matcher.matches();
}
public static String getSysDate() {
String date;
Calendar cal = new GregorianCalendar();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int Min = cal.get(Calendar.MINUTE);
date = "" + year + ":" + (month + 1) + ":" + day + ":" + hour + ":"
+ Min;
return date;
}
public static String FindExtension(String resumeName) {
String extension = "";
int length = resumeName.length();
int p = 0;
for (int j = 0; j < length; j++) {
if (resumeName.charAt(j) == '.') {
p = j;
}
}
if (p != 0) {
extension = resumeName.substring(p + 1, length);
}
return extension;
}
public static Set<String> englishWords() throws IOException {
Set<String> wordsSet = new HashSet<String>();
BufferedReader bf = new BufferedReader(new FileReader(new File(
"E:\\ResumeParser_2014\\property files\\words.txt")));
String line = bf.readLine();
while (line != null) {
if (line.trim().length() != 0) {
wordsSet.add(line);
}
line = bf.readLine();
}
return wordsSet;
}
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import mpi.*;
public class MPIPointCluster {
private int rank;
private int procs;
// each number represents the cluster it belongs to.
private int[] clusters;
private int[] capacity;
private double[] xPoint;
private double[] yPoint;
private double[] seedX;
private double[] seedY;
private int clusterNumber;
private int number;
public static void main(String args[]) throws MPIException {
if (args.length != 3) {
System.out
.println("Usage: MPIPointCluster <DataFileName> <ClusterNumber> <PointNumber>");
System.exit(-1);
}
MPI.Init(args);
MPIPointCluster cluster = new MPIPointCluster(
Integer.parseInt(args[1]), Integer.parseInt(args[2]));
if (cluster.rank == 0) {
cluster.readData(args[0]);
cluster.initSeed();
}
// start to calculate time data
long start = System.currentTimeMillis();
cluster.init();
cluster.iteration();
// time ends here.
System.out.println("Rank " + cluster.rank + ": "
+ (System.currentTimeMillis() - start));
MPI.Finalize();
cluster.printCluster();
}
public MPIPointCluster(int k, int number) throws MPIException {
this.rank = MPI.COMM_WORLD.Rank();
this.procs = MPI.COMM_WORLD.Size();
this.clusterNumber = k;
this.number = number;
this.xPoint = new double[number];
this.yPoint = new double[number];
this.seedX = new double[this.clusterNumber];
this.seedY = new double[this.clusterNumber];
}
private void readData(String filename) {
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line = null;
int count = 0;
while ((line = br.readLine()) != null && count < this.number) {
String[] coordinate = line.split(",");
double x = Double.parseDouble(coordinate[0]);
double y = Double.parseDouble(coordinate[1]);
xPoint[count] = x;
yPoint[count] = y;
count++;
}
br.close();
} catch (FileNotFoundException e) {
System.out.println(filename + " does not exist!");
System.exit(-1);
} catch (IOException e) {
System.out.println("I/O Exception while reading the data");
System.exit(-1);
}
}
private void initSeed() {
Random rand = new Random();
for (int i = 0; i < this.clusterNumber; i++) {
int index = rand.nextInt(this.xPoint.length);
this.seedX[i] = this.xPoint[index];
this.seedY[i] = this.yPoint[index];
}
}
/**
* Send data to each process
*/
public void init() throws MPIException {
this.capacity = new int[this.procs];
for (int i = 1; i < this.procs; i++) {
this.capacity[i] = xPoint.length / (this.procs - 1)
+ (i <= xPoint.length % (this.procs - 1) ? 1 : 0);
}
try {
System.out.println(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
this.clusters = new int[xPoint.length];
Arrays.fill(clusters, -1);
if (rank == 0) {// master
int offset = 0;
for (int i = 1; i < this.procs; i++) {
MPI.COMM_WORLD.Send(xPoint, offset, this.capacity[i],
MPI.DOUBLE, i, i);
MPI.COMM_WORLD.Send(yPoint, offset, this.capacity[i],
MPI.DOUBLE, i, i);
MPI.COMM_WORLD.Send(clusters, offset, this.capacity[i],
MPI.INT, i, i);
offset += this.capacity[i];
}
} else {
MPI.COMM_WORLD.Recv(xPoint, 0, this.capacity[rank], MPI.DOUBLE, 0,
rank);
MPI.COMM_WORLD.Recv(yPoint, 0, this.capacity[rank], MPI.DOUBLE, 0,
rank);
MPI.COMM_WORLD.Recv(clusters, 0, this.capacity[rank], MPI.INT, 0,
rank);
}
}
public void iteration() throws MPIException {
boolean[] changed = new boolean[1];
changed[0] = true;
int count = 0;
while (changed[0]) {
System.out.println("Iteration #" + count + " rank #" + this.rank);
count++;
MPI.COMM_WORLD.Bcast(seedX, 0, this.clusterNumber, MPI.DOUBLE, 0);
MPI.COMM_WORLD.Bcast(seedY, 0, this.clusterNumber, MPI.DOUBLE, 0);
// System.out.println("SeedX length " + seedX.length +" for rank "+
// this.rank);
// System.out.println("SeedX: " + Arrays.toString(this.seedX));
for (int i = 0; i < this.capacity[rank]; i++) {
double dis = Double.MAX_VALUE;
for (int j = 0; j < seedX.length; j++) {
double mydis = distance(xPoint[i], yPoint[i], seedX[j],
seedY[j]);
if (mydis < dis) {
dis = mydis;
this.clusters[i] = j;
}
}
// System.out.println("The cluster it belongs to"+
// this.clusters[i]);
}
// calculate distance
if (this.rank != 0) { // wait for all the participants to send
// System.out.println("Send back cluster!");
MPI.COMM_WORLD.Send(clusters, 0, this.capacity[rank], MPI.INT,
0, 0);
} else {
int[] newCluster = new int[this.clusters.length];
int offset = 0;
for (int i = 1; i < this.procs; i++) {
// System.out.println("Offset is " + offset);
MPI.COMM_WORLD.Recv(newCluster, offset, this.capacity[i],
MPI.INT, i, 0);
offset += this.capacity[i];
}
// System.out.println(Arrays.toString(newCluster));
// System.out.println(Arrays.toString(this.clusters));
// compare the two
int i = 0;
for (i = 0; i < newCluster.length; i++) {
if (this.clusters[i] == newCluster[i]) {
changed[0] = false;
} else {
this.clusters = newCluster;
this.recalculateSeed();
changed[0] = true;
break;
}
}
// //System.out.println("now status: "+changed[0]);
}
if (rank == 0) {
for (int i = 1; i < procs; i++) {
MPI.COMM_WORLD.Send(changed, 0, 1, MPI.BOOLEAN, i, i);
}
} else {
MPI.COMM_WORLD.Recv(changed, 0, 1, MPI.BOOLEAN, 0, rank);
}
}
}
private void recalculateSeed() {
// System.out.println("Data To Calculate Now:"+
// Arrays.toString(this.xPoint));
double[] seedX = new double[this.clusterNumber];
double[] seedY = new double[this.clusterNumber];
int[] count = new int[this.clusterNumber];
for (int i = 0; i < this.clusters.length; i++) {
seedX[clusters[i]] += this.xPoint[i];
seedY[clusters[i]] += this.yPoint[i];
count[clusters[i]]++;
}
for (int i = 0; i < this.clusterNumber; i++) {
seedX[i] /= count[i];
seedY[i] /= count[i];
}
this.seedX = seedX;
this.seedY = seedY;
}
public void printCluster() {
if (this.rank == 0) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(new File("mpioutput.csv"))));
for (int i = 0; i < xPoint.length; i++) {
bw.write(xPoint[i] + "," + yPoint[i] + "," + clusters[i]
+ "\n");
}
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println("I/O Exception!");
} catch (IOException e) {
e.printStackTrace();
System.err.println("I/O Exception!");
}
}
}
private double distance(double x, double y, double xCenter, double yCenter) {
return Math.sqrt((x - xCenter) * (x - xCenter) + (y - yCenter)
* (y - yCenter));
}
}
|
package com.exedio.cope;
import java.util.Iterator;
import bak.pcj.map.IntKeyOpenHashMap;
import bak.pcj.set.IntSet;
import com.exedio.cope.util.CacheInfo;
final class Cache
{
private final IntKeyOpenHashMap[] stateMaps;
private final int[] hits, misses;
Cache( int numberOfTypes )
{
stateMaps = new IntKeyOpenHashMap[numberOfTypes];
for ( int i=0; i<numberOfTypes; i++ )
{
stateMaps[i] = new IntKeyOpenHashMap();
}
hits = new int[numberOfTypes];
misses = new int[numberOfTypes];
}
private IntKeyOpenHashMap getStateMap( Type type )
{
return getStateMap( type.transientNumber );
}
private IntKeyOpenHashMap getStateMap( int transientTypeNumber )
{
return stateMaps[ transientTypeNumber ];
}
PersistentState getPersistentState( final Transaction connectionSource, final Item item )
{
PersistentState state;
final IntKeyOpenHashMap stateMap = getStateMap( item.type );
synchronized (stateMap)
{
state = (PersistentState)stateMap.get( item.pk );
}
if(state!=null)
state.notifyUsed();
boolean hit = true;
if ( state==null )
{
state = new PersistentState( connectionSource.getConnection(), item );
final Object oldValue;
final int mapSize, newMapSize;
synchronized (stateMap)
{
oldValue = stateMap.put( item.pk, state );
mapSize = stateMap.size();
final int mapSizeLimit = 2000;
if(mapSize>=mapSizeLimit)
{
final long now = System.currentTimeMillis();
long ageSum = 0;
for(Iterator i = stateMap.values().iterator(); i.hasNext(); )
{
final PersistentState currentState = (PersistentState)i.next();
final long currentLastUsage = currentState.getLastUsageMillis();
ageSum+=(now-currentLastUsage);
}
final long age = ageSum / mapSize;
final long ageLimit = (mapSizeLimit * age) / mapSize;
final long timeLimit = now-ageLimit;
for(Iterator i = stateMap.values().iterator(); i.hasNext(); )
{
final PersistentState currentState = (PersistentState)i.next();
final long currentLastUsage = currentState.getLastUsageMillis();
if(timeLimit>currentLastUsage)
i.remove();
}
newMapSize = stateMap.size();
}
else
newMapSize = -1;
}
// logging must be outside synchronized block
if(newMapSize>=0)
System.out.println("cleanup "+item.type.getID()+": "+mapSize+"->"+newMapSize);
if ( oldValue!=null )
{
System.out.println("warning: duplicate computation of state "+item.getCopeID());
}
hit = false;
}
(hit ? hits : misses)[item.type.transientNumber]++;
return state;
}
void invalidate( int transientTypeNumber, IntSet invalidatedPKs )
{
final IntKeyOpenHashMap stateMap = getStateMap( transientTypeNumber );
synchronized ( stateMap )
{
stateMap.keySet().removeAll( invalidatedPKs );
}
}
void clear()
{
for ( int i=0; i<stateMaps.length; i++ )
{
final IntKeyOpenHashMap stateMap = getStateMap( i );
synchronized ( stateMap )
{
stateMap.clear();
}
}
}
CacheInfo[] getInfo(final Type[] types)
{
final CacheInfo[] result = new CacheInfo[stateMaps.length];
for(int i=0; i<stateMaps.length; i++ )
{
final IntKeyOpenHashMap stateMap = getStateMap(i);
final int numberOfItemsInCache;
synchronized(stateMap)
{
numberOfItemsInCache = stateMap.size();
}
result[i] = new CacheInfo(types[i], numberOfItemsInCache, hits[i], misses[i]);
}
return result;
}
}
|
package com.intellij.ide.structureView.impl;
import com.intellij.ide.structureView.StructureView;
import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.ide.structureView.TreeBasedStructureViewBuilder;
import com.intellij.ide.util.StructureViewCompositeModel;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageStructureViewBuilder;
import com.intellij.lang.LanguageUtil;
import com.intellij.lang.PsiStructureViewFactory;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.templateLanguages.TemplateLanguageFileViewProvider;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PairFunction;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author peter
*/
public abstract class TemplateLanguageStructureViewBuilder extends TreeBasedStructureViewBuilder {
@NotNull
public static TemplateLanguageStructureViewBuilder create(@NotNull PsiFile psiFile,
@Nullable PairFunction<? super PsiFile, ? super Editor, ? extends StructureViewModel> modelFactory) {
return new TemplateLanguageStructureViewBuilder(psiFile) {
@Override
protected TreeBasedStructureViewBuilder createMainBuilder(@NotNull PsiFile psi) {
return modelFactory == null ? null : new TreeBasedStructureViewBuilder() {
@Override
public boolean isRootNodeShown() {
return false;
}
@NotNull
@Override
public StructureViewModel createStructureViewModel(@Nullable Editor editor) {
return modelFactory.fun(psi, editor);
}
};
}
};
}
private final VirtualFile myVirtualFile;
private final Project myProject;
protected TemplateLanguageStructureViewBuilder(PsiElement psiElement) {
myProject = psiElement.getProject();
myVirtualFile = psiElement.getContainingFile().getVirtualFile();
}
@Override
public boolean isRootNodeShown() {
return false;
}
@Override
@NotNull
public StructureView createStructureView(FileEditor fileEditor, @NotNull Project project) {
List<StructureViewComposite.StructureViewDescriptor> viewDescriptors = new ArrayList<>();
VirtualFile file = fileEditor == null ? null : fileEditor.getFile();
PsiFile psiFile = file == null || !file.isValid()? null : PsiManager.getInstance(project).findFile(file);
List<Language> languages = getLanguages(psiFile).toList();
for (Language language : languages) {
StructureViewBuilder builder = getBuilder(Objects.requireNonNull(psiFile), language);
if (builder == null) continue;
StructureView structureView = builder.createStructureView(fileEditor, project);
String title = language.getDisplayName();
Icon icon = ObjectUtils.notNull(LanguageUtil.getLanguageFileType(language), FileTypes.UNKNOWN).getIcon();
viewDescriptors.add(new StructureViewComposite.StructureViewDescriptor(title, structureView, icon));
}
StructureViewComposite.StructureViewDescriptor[] array = viewDescriptors.toArray(new StructureViewComposite.StructureViewDescriptor[0]);
return new StructureViewComposite(array) {
@Override
public boolean isOutdated() {
VirtualFile file = fileEditor == null ? null : fileEditor.getFile();
PsiFile psiFile = file == null || !file.isValid() ? null : PsiManager.getInstance(project).findFile(file);
List<Language> newLanguages = getLanguages(psiFile).toList();
// think views count depends only on acceptable languages
return !Comparing.equal(languages, newLanguages);
}
};
}
@Override
@NotNull
public StructureViewModel createStructureViewModel(@Nullable Editor editor) {
List<StructureViewComposite.StructureViewDescriptor> viewDescriptors = new ArrayList<>();
PsiFile psiFile = Objects.requireNonNull(PsiManager.getInstance(myProject).findFile(myVirtualFile));
for (Language language : getLanguages(psiFile)) {
StructureViewBuilder builder = getBuilder(psiFile, language);
if (!(builder instanceof TreeBasedStructureViewBuilder)) continue;
StructureViewModel model = ((TreeBasedStructureViewBuilder)builder).createStructureViewModel(editor);
String title = language.getDisplayName();
Icon icon = ObjectUtils.notNull(LanguageUtil.getLanguageFileType(language), FileTypes.UNKNOWN).getIcon();
viewDescriptors.add(new StructureViewComposite.StructureViewDescriptor(title, model, icon));
}
return new StructureViewCompositeModel(psiFile, editor, viewDescriptors);
}
@NotNull
protected JBIterable<Language> getLanguagesUnfiltered(@NotNull PsiFile psiFile) {
FileViewProvider viewProvider = psiFile.getViewProvider();
Language baseLanguage = viewProvider.getBaseLanguage();
Language dataLanguage = viewProvider instanceof TemplateLanguageFileViewProvider
? ((TemplateLanguageFileViewProvider)viewProvider).getTemplateDataLanguage() : null;
return JBIterable.of(baseLanguage)
.append(dataLanguage)
.append(viewProvider.getLanguages())
.unique();
}
@NotNull
private JBIterable<Language> getLanguages(@Nullable PsiFile psiFile) {
if (psiFile == null) return JBIterable.empty();
return getLanguagesUnfiltered(psiFile)
.filter(language -> {
PsiFile psi = psiFile.getViewProvider().getPsi(language);
return psi != null && (language == psiFile.getViewProvider().getBaseLanguage() || isAcceptableBaseLanguageFile(psi));
});
}
@Nullable
private StructureViewBuilder getBuilder(@NotNull PsiFile psiFile, @NotNull Language language) {
FileViewProvider viewProvider = psiFile.getViewProvider();
Language baseLanguage = viewProvider.getBaseLanguage();
PsiFile psi = viewProvider.getPsi(language);
if (psi == null) return null;
if (language == baseLanguage) return createMainBuilder(psi);
PsiStructureViewFactory factory = LanguageStructureViewBuilder.INSTANCE.forLanguage(language);
return factory == null ? null : factory.getStructureViewBuilder(psi);
}
protected boolean isAcceptableBaseLanguageFile(PsiFile dataFile) {
return true;
}
@Nullable
protected abstract TreeBasedStructureViewBuilder createMainBuilder(@NotNull PsiFile psi);
}
|
package com.intellij.internal.statistic.editor;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.CodeInsightWorkspaceSettings;
import com.intellij.internal.statistic.beans.UsageDescriptor;
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector;
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces;
import com.intellij.openapi.editor.richcopy.settings.RichCopySettings;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.BooleanFunction;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
class EditorSettingsStatisticsCollector extends ApplicationUsagesCollector {
@NotNull
@Override
public String getGroupId() {
return "statistics.editor.settings.ide";
}
@NotNull
@Override
public Set<UsageDescriptor> getUsages() {
Set<UsageDescriptor> set = new HashSet<>();
EditorSettingsExternalizable es = EditorSettingsExternalizable.getInstance();
EditorSettingsExternalizable esDefault = new EditorSettingsExternalizable();
addBoolIfDiffers(set, es, esDefault, s -> s.isVirtualSpace(), "caretAfterLineEnd");
addBoolIfDiffers(set, es, esDefault, s -> s.isCaretInsideTabs(), "caretInsideTabs");
addBoolIfDiffers(set, es, esDefault, s -> s.isAdditionalPageAtBottom(), "virtualSpaceAtFileBottom");
addBoolIfDiffers(set, es, esDefault, s -> s.isUseSoftWraps(SoftWrapAppliancePlaces.MAIN_EDITOR), "softWraps");
addBoolIfDiffers(set, es, esDefault, s -> s.isUseSoftWraps(SoftWrapAppliancePlaces.CONSOLE), "softWraps.console");
addBoolIfDiffers(set, es, esDefault, s -> s.isUseSoftWraps(SoftWrapAppliancePlaces.PREVIEW), "softWraps.preview");
addBoolIfDiffers(set, es, esDefault, s -> s.isUseCustomSoftWrapIndent(), "softWraps.relativeIndent");
addBoolIfDiffers(set, es, esDefault, s -> s.isAllSoftWrapsShown(), "softWraps.showAll");
addIfDiffers(set, es, esDefault, s -> s.getStripTrailingSpaces(), "stripTrailingSpaces");
addBoolIfDiffers(set, es, esDefault, s -> s.isEnsureNewLineAtEOF(), "ensureNewlineAtEOF");
addBoolIfDiffers(set, es, esDefault, s -> s.isShowQuickDocOnMouseOverElement(), "quickDocOnMouseHover");
addBoolIfDiffers(set, es, esDefault, s -> s.isBlinkCaret(), "blinkingCaret");
addBoolIfDiffers(set, es, esDefault, s -> s.isBlockCursor(), "blockCaret");
addBoolIfDiffers(set, es, esDefault, s -> s.isRightMarginShown(), "rightMargin");
addBoolIfDiffers(set, es, esDefault, s -> s.isLineNumbersShown(), "lineNumbers");
addBoolIfDiffers(set, es, esDefault, s -> s.areGutterIconsShown(), "gutterIcons");
addBoolIfDiffers(set, es, esDefault, s -> s.isFoldingOutlineShown(), "foldingOutline");
addBoolIfDiffers(set, es, esDefault, s -> s.isWhitespacesShown() && s.isLeadingWhitespacesShown(), "showLeadingWhitespace");
addBoolIfDiffers(set, es, esDefault, s -> s.isWhitespacesShown() && s.isInnerWhitespacesShown(), "showInnerWhitespace");
addBoolIfDiffers(set, es, esDefault, s -> s.isWhitespacesShown() && s.isTrailingWhitespacesShown(), "showTrailingWhitespace");
addBoolIfDiffers(set, es, esDefault, s -> s.isIndentGuidesShown(), "indentGuides");
addBoolIfDiffers(set, es, esDefault, s -> s.isSmoothScrolling(), "animatedScroll");
addBoolIfDiffers(set, es, esDefault, s -> s.isDndEnabled(), "dragNDrop");
addBoolIfDiffers(set, es, esDefault, s -> s.isWheelFontChangeEnabled(), "wheelZoom");
addBoolIfDiffers(set, es, esDefault, s -> s.isMouseClickSelectionHonorsCamelWords(), "mouseCamel");
addBoolIfDiffers(set, es, esDefault, s -> s.isVariableInplaceRenameEnabled(), "inplaceRename");
addBoolIfDiffers(set, es, esDefault, s -> s.isPreselectRename(), "preselectOnRename");
addBoolIfDiffers(set, es, esDefault, s -> s.isShowInlineLocalDialog(), "inlineDialog");
addBoolIfDiffers(set, es, esDefault, s -> s.isRefrainFromScrolling(), "minimizeScrolling");
addBoolIfDiffers(set, es, esDefault, s -> s.getOptions().SHOW_NOTIFICATION_AFTER_REFORMAT_CODE_ACTION, "afterReformatNotification");
addBoolIfDiffers(set, es, esDefault, s -> s.getOptions().SHOW_NOTIFICATION_AFTER_OPTIMIZE_IMPORTS_ACTION, "afterOptimizeNotification");
addBoolIfDiffers(set, es, esDefault, s -> s.isSmartHome(), "smartHome");
addBoolIfDiffers(set, es, esDefault, s -> s.isCamelWords(), "camelWords");
addBoolIfDiffers(set, es, esDefault, s -> s.isShowParameterNameHints(), "editor.inlay.parameter.hints");
addBoolIfDiffers(set, es, esDefault, s -> s.isBreadcrumbsAbove(), "noBreadcrumbsBelow");
addBoolIfDiffers(set, es, esDefault, s -> s.isBreadcrumbsShown(), "breadcrumbs");
addBoolIfDiffers(set, es, esDefault, s -> s.isShowIntentionBulb(), "intentionBulb");
for (String language : es.getOptions().getLanguageBreadcrumbsMap().keySet()) {
addBoolIfDiffers(set, es, esDefault, s -> s.isBreadcrumbsShownFor(language), "breadcrumbsFor" + language);
}
RichCopySettings rcs = RichCopySettings.getInstance();
RichCopySettings rcsDefault = new RichCopySettings();
addBoolIfDiffers(set, rcs, rcsDefault, s -> s.isEnabled(), "richCopy");
CodeInsightSettings cis = CodeInsightSettings.getInstance();
CodeInsightSettings cisDefault = new CodeInsightSettings();
addBoolIfDiffers(set, cis, cisDefault, s -> s.AUTO_POPUP_PARAMETER_INFO, "parameterAutoPopup");
addBoolIfDiffers(set, cis, cisDefault, s -> s.AUTO_POPUP_JAVADOC_INFO, "javadocAutoPopup");
addBoolIfDiffers(set, cis, cisDefault, s -> s.AUTO_POPUP_COMPLETION_LOOKUP, "completionAutoPopup");
addIfDiffers(set, cis, cisDefault, s -> s.COMPLETION_CASE_SENSITIVE, "completionCaseSensitivity");
addBoolIfDiffers(set, cis, cisDefault, s -> s.SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS, "autoPopupCharComplete");
addBoolIfDiffers(set, cis, cisDefault, s -> s.AUTOCOMPLETE_ON_CODE_COMPLETION, "autoCompleteBasic");
addBoolIfDiffers(set, cis, cisDefault, s -> s.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION, "autoCompleteSmart");
addBoolIfDiffers(set, cis, cisDefault, s -> s.SHOW_FULL_SIGNATURES_IN_PARAMETER_INFO, "parameterInfoFullSignature");
addIfDiffers(set, cis, cisDefault, s -> s.getBackspaceMode(), "smartBackspace");
addBoolIfDiffers(set, cis, cisDefault, s -> s.SMART_INDENT_ON_ENTER, "indentOnEnter");
addBoolIfDiffers(set, cis, cisDefault, s -> s.INSERT_BRACE_ON_ENTER, "braceOnEnter");
addBoolIfDiffers(set, cis, cisDefault, s -> s.JAVADOC_STUB_ON_ENTER, "javadocOnEnter");
addBoolIfDiffers(set, cis, cisDefault, s -> s.SMART_END_ACTION, "smartEnd");
addBoolIfDiffers(set, cis, cisDefault, s -> s.JAVADOC_GENERATE_CLOSING_TAG, "autoCloseJavadocTags");
addBoolIfDiffers(set, cis, cisDefault, s -> s.SURROUND_SELECTION_ON_QUOTE_TYPED, "surroundByQuoteOrBrace");
addBoolIfDiffers(set, cis, cisDefault, s -> s.AUTOINSERT_PAIR_BRACKET, "pairBracketAutoInsert");
addBoolIfDiffers(set, cis, cisDefault, s -> s.AUTOINSERT_PAIR_QUOTE, "pairQuoteAutoInsert");
addBoolIfDiffers(set, cis, cisDefault, s -> s.REFORMAT_BLOCK_ON_RBRACE, "reformatOnRBrace");
addIfDiffers(set, cis, cisDefault, s -> s.REFORMAT_ON_PASTE, "reformatOnPaste");
addIfDiffers(set, cis, cisDefault, s -> s.ADD_IMPORTS_ON_PASTE, "importsOnPaste");
addBoolIfDiffers(set, cis, cisDefault, s -> s.HIGHLIGHT_BRACES, "bracesHighlight");
addBoolIfDiffers(set, cis, cisDefault, s -> s.HIGHLIGHT_SCOPE, "scopeHighlight");
addBoolIfDiffers(set, cis, cisDefault, s -> s.HIGHLIGHT_IDENTIFIER_UNDER_CARET, "identifierUnderCaretHighlight");
addBoolIfDiffers(set, cis, cisDefault, s -> s.ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY, "autoAddImports");
addBoolIfDiffers(set, cis, cisDefault, s -> s.SHOW_PARAMETER_NAME_HINTS_ON_COMPLETION, "completionHints");
addBoolIfDiffers(set, cis, cisDefault, s -> s.SHOW_EXTERNAL_ANNOTATIONS_INLINE, "externalAnnotationsInline");
addBoolIfDiffers(set, cis, cisDefault, s -> s.SHOW_INFERRED_ANNOTATIONS_INLINE, "inferredAnnotationsInline");
addBoolIfDiffers(set, cis, cisDefault, s -> s.TAB_EXITS_BRACKETS_AND_QUOTES, "tabExitsBracketsAndQuotes");
return set;
}
private static <T> void addBoolIfDiffers(Set<UsageDescriptor> set,
T settingsBean, T defaultSettingsBean, BooleanFunction<T> valueFunction, String featureId) {
boolean value = valueFunction.fun(settingsBean);
boolean defaultValue = valueFunction.fun(defaultSettingsBean);
if (value != defaultValue) {
set.add(new UsageDescriptor(defaultValue ? "no" + StringUtil.capitalize(featureId) : featureId, 1));
}
}
private static <T> void addIfDiffers(Set<UsageDescriptor> set,
T settingsBean, T defaultSettingsBean, Function<T, Object> valueFunction, String featureIdPrefix) {
Object value = valueFunction.apply(settingsBean);
Object defaultValue = valueFunction.apply(defaultSettingsBean);
if (!Comparing.equal(value, defaultValue)) {
set.add(new UsageDescriptor(featureIdPrefix + "." + value, 1));
}
}
public static class ProjectUsages extends ProjectUsagesCollector {
@NotNull
@Override
public String getGroupId() {
return "statistics.editor.settings.project";
}
@NotNull
@Override
public Set<UsageDescriptor> getUsages(@NotNull Project project) {
Set<UsageDescriptor> set = new HashSet<>();
CodeInsightWorkspaceSettings ciws = CodeInsightWorkspaceSettings.getInstance(project);
CodeInsightWorkspaceSettings ciwsDefault = new CodeInsightWorkspaceSettings();
addBoolIfDiffers(set, ciws, ciwsDefault, s -> s.optimizeImportsOnTheFly, "autoOptimizeImports");
return set;
}
}
}
|
package com.intellij.xdebugger.impl.breakpoints.ui;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.util.Disposer;
import com.intellij.xdebugger.impl.breakpoints.XBreakpointUtil;
import org.jetbrains.annotations.Nullable;
public class BreakpointsDialogFactory {
private final Project myProject;
private Balloon myBalloonToHide;
private Object myBreakpoint;
private BreakpointsDialog myDialogShowing;
public BreakpointsDialogFactory(Project project) {
myProject = project;
}
public void setBalloonToHide(final Balloon balloonToHide, Object breakpoint) {
myBalloonToHide = balloonToHide;
myBreakpoint = breakpoint;
Disposer.register(myBalloonToHide, new Disposable() {
@Override
public void dispose() {
if (myBalloonToHide == balloonToHide) {
myBalloonToHide = null;
myBreakpoint = null;
}
}
});
}
public static BreakpointsDialogFactory getInstance(Project project) {
return ServiceManager.getService(project, BreakpointsDialogFactory.class);
}
public boolean popupRequested(Object breakpoint) {
if (myBalloonToHide != null && !myBalloonToHide.isDisposed()) {
return true;
}
if (myDialogShowing != null) {
myDialogShowing.selectBreakpoint(breakpoint);
myDialogShowing.toFront();
return true;
}
return false;
}
public void showDialog(@Nullable Object initialBreakpoint) {
if (myDialogShowing != null && myDialogShowing.getWindow().isDisplayable()) { // workaround for IDEA-197804
myDialogShowing.toFront();
return;
}
final BreakpointsDialog dialog = new BreakpointsDialog(myProject, initialBreakpoint != null ? initialBreakpoint : myBreakpoint, XBreakpointUtil.collectPanelProviders()) {
@Override
protected void dispose() {
myBreakpoint = null;
for (BreakpointPanelProvider provider : XBreakpointUtil.collectPanelProviders()) {
provider.onDialogClosed(myProject);
}
myDialogShowing = null;
super.dispose();
}
};
if (myBalloonToHide != null) {
if (!myBalloonToHide.isDisposed()) {
myBalloonToHide.hide();
}
myBalloonToHide = null;
}
myDialogShowing = dialog;
dialog.show();
}
}
|
package org.knowm.xchange.ftx.service;
import org.apache.commons.lang3.StringUtils;
import org.knowm.xchange.ftx.FtxAdapters;
import org.knowm.xchange.ftx.FtxExchange;
import org.knowm.xchange.ftx.dto.account.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
public class FtxLendingServiceRaw extends FtxBaseService {
public FtxLendingServiceRaw(FtxExchange exchange) {
super(exchange);
}
public FtxLendDataDto stopLending(String subaccount, String coin) {
return lend(subaccount, coin, 0, 0);
}
public List<FtxLendDataDto> stopLending(String subaccount, List<String> coins) {
return coins.stream()
.map(coin -> stopLending(subaccount, coin))
.collect(Collectors.toList());
}
public FtxLendDataDto lend(String subaccount, String coin, double size, double rate) {
Objects.requireNonNull(coin);
if (StringUtils.isNotBlank(coin))
throw new FtxLendingServiceException("Coin are blank or empty");
if (rate < 0)
throw new FtxLendingServiceException("Rate must to be >= 0, subaccount: " + subaccount + ", coin: " + coin);
if (size < 0)
throw new FtxLendingServiceException("Size must to be >= 0, subaccount: " + subaccount + ", coin: " + coin + ", rate: " + rate);
try {
FtxLendingInfoDto info = info(subaccount, coin);
double sizeToLend = FtxAdapters.lendingRounding(new BigDecimal(size)).doubleValue();
if (Double.compare(sizeToLend, info.getLendable()) == 1) {
throw new FtxLendingServiceException("Can't lend sizeToLend > to lendable, subaccount: " + subaccount + ", coin: " + coin + ", size: " + size + ", sizeToLend: " + sizeToLend + ", rate: " + rate);
}
ftx.submitLendingOffer(
exchange.getExchangeSpecification().getApiKey(),
exchange.getNonceFactory().createValue(),
signatureCreator,
subaccount,
new FtxSubmitLendingOfferParams(coin, FtxAdapters.lendingRounding(new BigDecimal(sizeToLend)).doubleValue(), rate)
);
return new FtxLendDataDto(coin, info.getLocked(), info.getOffered(), sizeToLend, rate);
} catch (IOException e) {
throw new FtxLendingServiceException("Can't lend subaccount: " + subaccount + ", coin: " + coin + ", size: " + size + ", rate: " + rate, e);
}
}
public List<FtxLendingHistoryDto> histories(String subaccount) {
try {
return ftx.getlendingHistories(
exchange.getExchangeSpecification().getApiKey(),
exchange.getNonceFactory().createValue(),
signatureCreator,
subaccount
).getResult();
} catch (IOException e) {
throw new FtxLendingServiceException("Can't get lending infos subAccount: " + subaccount, e);
}
}
public List<FtxLendingHistoryDto> histories(String subaccount, List<String> coins) {
Objects.requireNonNull(coins);
return histories(subaccount).stream()
.filter(lendingHistory -> coins.contains(lendingHistory.getCoin()))
.collect(Collectors.toList());
}
public FtxLendingHistoryDto history(String subaccount, String coin) {
Objects.requireNonNull(coin);
if (StringUtils.isNotBlank(coin))
throw new FtxLendingServiceException("Coin are blank or empty");
return histories(subaccount).stream()
.filter(lendingHistory -> lendingHistory.getCoin().equalsIgnoreCase(coin))
.findFirst()
.orElse(null);
}
public List<FtxLendingInfoDto> infos(String subaccount) {
try {
return ftx.getLendingInfos(
exchange.getExchangeSpecification().getApiKey(),
exchange.getNonceFactory().createValue(),
signatureCreator,
subaccount
).getResult();
} catch (IOException e) {
throw new FtxLendingServiceException("Can't get lending infos subAccount: " + subaccount, e);
}
}
public List<FtxLendingInfoDto> infos(String subaccount, List<String> coins) {
Objects.requireNonNull(coins);
return infos(subaccount).stream()
.filter(lendingInfo -> coins.contains(lendingInfo.getCoin()))
.collect(Collectors.toList());
}
public FtxLendingInfoDto info(String subaccount, String coin) {
Objects.requireNonNull(coin);
if (StringUtils.isNotBlank(coin))
throw new FtxLendingServiceException("Coin are blank or empty");
return infos(subaccount).stream()
.filter(lendingInfo -> lendingInfo.getCoin().equalsIgnoreCase(coin))
.findFirst()
.orElse(null);
}
public List<FtxLendingRatesDto> rates() {
try {
return ftx.getLendingRates(
exchange.getExchangeSpecification().getApiKey(),
exchange.getNonceFactory().createValue(),
signatureCreator
).getResult();
} catch (IOException e) {
throw new FtxLendingServiceException("Can't get lending rates", e);
}
}
public List<FtxLendingRatesDto> rates(List<String> coins) {
Objects.requireNonNull(coins);
return rates().stream()
.filter(lendingRates -> coins.contains(lendingRates.getCoin()))
.collect(Collectors.toList());
}
public FtxLendingRatesDto rate(String coin) {
Objects.requireNonNull(coin);
if (StringUtils.isNotBlank(coin))
throw new FtxLendingServiceException("Coin are blank or empty");
try {
return ftx.getLendingRates(
exchange.getExchangeSpecification().getApiKey(),
exchange.getNonceFactory().createValue(),
signatureCreator
).getResult().stream()
.filter(lendingRates -> lendingRates.getCoin().equalsIgnoreCase(coin))
.findFirst()
.orElse(null);
} catch (IOException e) {
throw new FtxLendingServiceException("Can't get lending rate coin: " + coin, e);
}
}
public static class FtxLendingServiceException extends RuntimeException {
public FtxLendingServiceException(String message, Throwable cause) {
super(message, cause);
}
public FtxLendingServiceException(String message) {
super(message);
}
}
}
|
package de.plushnikov.intellij.plugin.processor.modifier;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;
import de.plushnikov.intellij.plugin.LombokTestUtil;
import org.jetbrains.annotations.NotNull;
/**
* @author Alexej Kubarev
*/
public class ValueModifierTest extends LightJavaCodeInsightFixtureTestCase {
@Override
protected String getBasePath() {
return "/plugins/lombok/testData/augment/modifier";
}
@Override
protected @NotNull LightProjectDescriptor getProjectDescriptor() {
return LombokTestUtil.LOMBOK_DESCRIPTOR;
}
public void testValueModifiers() {
PsiFile file = myFixture.configureByFile(getTestName(false) + ".java");
PsiField field = PsiTreeUtil.getParentOfType(file.findElementAt(myFixture.getCaretOffset()), PsiField.class);
assertNotNull(field);
assertNotNull(field.getModifierList());
assertTrue("@Value should make variable final", field.getModifierList().hasModifierProperty(PsiModifier.FINAL));
assertTrue("@Value should make variable private", field.getModifierList().hasModifierProperty(PsiModifier.PRIVATE));
PsiClass clazz = PsiTreeUtil.getParentOfType(field, PsiClass.class);
assertNotNull(clazz);
PsiModifierList list = clazz.getModifierList();
assertNotNull(list);
assertTrue("@Value should make class final", list.hasModifierProperty(PsiModifier.FINAL));
assertFalse("@Value should not make class private", list.hasModifierProperty(PsiModifier.PRIVATE));
assertFalse("@Value should not make class static", list.hasModifierProperty(PsiModifier.STATIC));
}
public void testValueModifiersStatic() {
PsiFile file = myFixture.configureByFile(getTestName(false) + ".java");
PsiField field = PsiTreeUtil.getParentOfType(file.findElementAt(myFixture.getCaretOffset()), PsiField.class);
assertNotNull(field);
assertNotNull(field.getModifierList());
assertFalse("@Value should not make static variable final", field.getModifierList().hasModifierProperty(PsiModifier.FINAL));
assertFalse("@Value should not make static variable private", field.getModifierList().hasModifierProperty(PsiModifier.PRIVATE));
}
}
|
package org.eclipse.epp.usagedata.ui.wizards;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
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.epp.usagedata.gathering.events.UsageDataEvent;
import org.eclipse.epp.usagedata.recording.uploading.UsageDataFileReader;
import org.eclipse.epp.usagedata.ui.uploaders.AskUserUploader;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.OwnerDrawLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.deferred.DeferredContentProvider;
import org.eclipse.jface.viewers.deferred.SetModel;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
public class UploadPreviewPage extends WizardPage {
private TableViewer viewer;
private final AskUserUploader uploader;
private Job contentJob;
private SetModel events = new SetModel();
private static final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
private static final Comparator<UsageDataEvent> sortByTimeStampComparator = new Comparator<UsageDataEvent>() {
public int compare(UsageDataEvent event1, UsageDataEvent event2) {
if (event1.when == event2.when) return 0;
return event1.when > event2.when ? 1 : -1;
}
};
private UsageDataTableViewerColumn whatColumn;
private UsageDataTableViewerColumn kindColumn;
private UsageDataTableViewerColumn descriptionColumn;
private UsageDataTableViewerColumn bundleIdColumn;
private UsageDataTableViewerColumn bundleVersionColumn;
private UsageDataTableViewerColumn timestampColumn;
private Color colorGray;
private Color colorBlack;
public UploadPreviewPage(AskUserUploader uploader) {
super("wizardPage");
this.uploader = uploader;
setTitle("Upload Preview");
}
public void createControl(Composite parent) {
colorGray = parent.getDisplay().getSystemColor(SWT.COLOR_GRAY);
colorBlack = parent.getDisplay().getSystemColor(SWT.COLOR_BLACK);
Composite container = new Composite(parent, SWT.NONE);
container.setLayout(new GridLayout());
viewer = new TableViewer(container,SWT.VIRTUAL | SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.getTable().setHeaderVisible(true);
viewer.getTable().setLinesVisible(false);
GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true);
viewer.getTable().setLayoutData(layoutData);
OwnerDrawLabelProvider.setUpOwnerDraw(viewer);
createWhatColumn();
createKindColumn();
createDescriptionColumn();
createBundleIdColumn();
createBundleVersionColumn();
createTimestampColumn();
DeferredContentProvider provider = new DeferredContentProvider(sortByTimeStampComparator);
viewer.setContentProvider(provider);
viewer.setInput(events);
setControl(container);
startContentJob();
}
private void createWhatColumn() {
whatColumn = new UsageDataTableViewerColumn(SWT.LEFT);
whatColumn.setText("What");
whatColumn.setLabelProvider(new UsageDataColumnProvider() {
@Override
public String getText(UsageDataEvent event) {
return event.what;
}
});
}
private void createKindColumn() {
kindColumn = new UsageDataTableViewerColumn(SWT.LEFT);
kindColumn.setText("Kind");
kindColumn.setLabelProvider(new UsageDataColumnProvider() {
@Override
public String getText(UsageDataEvent event) {
return event.kind;
}
});
}
private void createDescriptionColumn() {
descriptionColumn = new UsageDataTableViewerColumn(SWT.LEFT);
descriptionColumn.setText("Description");
descriptionColumn.setLabelProvider(new UsageDataColumnProvider() {
@Override
public String getText(UsageDataEvent event) {
return event.description;
}
});
}
private void createBundleIdColumn() {
bundleIdColumn = new UsageDataTableViewerColumn(SWT.LEFT);
bundleIdColumn.setText("Bundle Id");
bundleIdColumn.setLabelProvider(new UsageDataColumnProvider() {
@Override
public String getText(UsageDataEvent event) {
return event.bundleId;
}
});
}
private void createBundleVersionColumn() {
bundleVersionColumn = new UsageDataTableViewerColumn(SWT.LEFT);
bundleVersionColumn.setText("Version");
bundleVersionColumn.setLabelProvider(new UsageDataColumnProvider() {
@Override
public String getText(UsageDataEvent event) {
return event.bundleVersion;
}
});
}
private void createTimestampColumn() {
timestampColumn = new UsageDataTableViewerColumn(SWT.LEFT);
timestampColumn.setText("When");
timestampColumn.setLabelProvider(new UsageDataColumnProvider() {
@Override
public String getText(UsageDataEvent event) {
return dateFormat.format(new Date(event.when));
}
});
timestampColumn.setSorter(sortByTimeStampComparator);
}
/**
* This method starts the job that populates the list of
* events.
*/
private void startContentJob() {
contentJob = new Job("Generate Usage Data Upload Preview") {
@Override
protected IStatus run(IProgressMonitor monitor) {
// TODO Consider actually using the monitor
File[] files = uploader.getFiles();
for (File file : files) {
if (isDisposed()) break;
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
processFile(file, monitor);
}
return Status.OK_STATUS;
}
};
contentJob.schedule();
}
/**
* This method extracts the events found in a {@link File}
* and adds them to the list of events displayed by the
* receiver. Events are batched into groups to reduce
* the number of times the viewer will have to update.
*
* @param file the {@link File} to process.
* @param monitor the monitor.
*/
void processFile(File file, IProgressMonitor monitor) {
// TODO Add a progress bar to the page?
// TODO Actually use the monitor? May not be worth it.
List<UsageDataEvent> events = new ArrayList<UsageDataEvent>();
UsageDataFileReader reader = null;
try {
reader = new UsageDataFileReader(file);
UsageDataEvent event = null;
while ((event = reader.next()) != null) {
if (isDisposed()) return;
if (monitor.isCanceled()) return;
events.add(event);
if (events.size() > 50) {
addEvents(events);
events.clear();
}
}
addEvents(events);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
boolean isDisposed() {
if (viewer == null) return true;
if (viewer.getTable() == null) return true;
return viewer.getTable().isDisposed();
}
void addEvents(List<UsageDataEvent> events) {
this.events.addAll(events);
resizeColumns();
}
/*
* Oddly enough, this method resizes the columns. In order to figure out how
* wide to make the columns, we need to use a GC (specifically, the
* {@link GC#textExtent(String)} method). To avoid creating too many of
* them, we create one in this method and pass it into the helper method
* {@link #resizeColumn(GC, UsageDataTableViewerColumn)} which does most of
* the heavy lifting.
*/
void resizeColumns() {
viewer.getTable().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
GC gc = new GC(viewer.getTable().getDisplay());
gc.setFont(viewer.getTable().getFont());
resizeColumn(gc, whatColumn);
resizeColumn(gc, kindColumn);
resizeColumn(gc, bundleIdColumn);
resizeColumn(gc, bundleVersionColumn);
resizeColumn(gc, descriptionColumn);
resizeColumn(gc, timestampColumn);
gc.dispose();
}
});
}
void resizeColumn(GC gc, UsageDataTableViewerColumn column) {
column.resize(gc, events.getElements());
}
/**
* The {@link UsageDataTableViewerColumn} provides a level of abstraction
* for building table columns specifically for the table displaying
* instances of {@link UsageDataEvent}. Instances automatically know how to
* sort themselves (ascending only) with help from the label provider. This
* behaviour can be overridden by providing an alternative
* {@link Comparator}.
*/
class UsageDataTableViewerColumn {
private TableViewerColumn column;
private UsageDataColumnProvider usageDataColumnProvider;
private Comparator<UsageDataEvent> comparator = new Comparator<UsageDataEvent>() {
@Override
public int compare(UsageDataEvent event1, UsageDataEvent event2) {
if (usageDataColumnProvider == null) return 0;
String text1 = usageDataColumnProvider.getText(event1);
String text2 = usageDataColumnProvider.getText(event2);
if (text1 == null && text2 == null) return 0;
if (text1 == null) return -1;
if (text2 == null) return 1;
return text1.compareTo(text2);
}
};
private SelectionListener selectionListener = new SelectionAdapter() {
/**
* When the column is selected (clicked on by the
* the user, sort the table based on the value
* presented in that column.
*/
@Override
public void widgetSelected(SelectionEvent e) {
getTable().setSortColumn(getColumn());
getTable().setSortDirection(SWT.DOWN);
getContentProvider().setSortOrder(comparator);
}
};
public UsageDataTableViewerColumn(int style) {
column = new TableViewerColumn(viewer, style);
initialize();
}
private void initialize() {
getColumn().addSelectionListener(selectionListener);
getColumn().setWidth(100);
}
DeferredContentProvider getContentProvider() {
return (DeferredContentProvider)viewer.getContentProvider();
}
TableColumn getColumn() {
return column.getColumn();
}
Table getTable() {
return viewer.getTable();
}
public void setSorter(Comparator<UsageDataEvent> comparator) {
// TODO May need to handle the case when the active comparator is changed.
this.comparator = comparator;
}
public void resize(GC gc, Object[] objects) {
int width = usageDataColumnProvider.getMaximumWidth(gc, objects) + 20;
getColumn().setWidth(width);
}
public void setLabelProvider(UsageDataColumnProvider usageDataColumnProvider) {
this.usageDataColumnProvider = usageDataColumnProvider;
column.setLabelProvider(usageDataColumnProvider);
}
public void setWidth(int width) {
getColumn().setWidth(width);
}
public void setText(String text) {
getColumn().setText(text);
}
}
/**
* The {@link UsageDataColumnProvider} is a column label provider
* that includes some convenience methods.
*/
abstract class UsageDataColumnProvider extends ColumnLabelProvider {
/**
* This convenience method is used to determine an appropriate
* width for the column based on the collection of event objects.
* The returned value is the maximum width (in pixels) of the
* text the receiver associates with each of the events. The
* events are provided as Object[] because converting them to
* UsageDataEvent[] would be an unnecessary expense.
*
* @param gc a {@link GC} loaded with the font used to display the events.
* @param events an array of {@link UsageDataEvent} instances.
* @return the width of the widest event
*/
public int getMaximumWidth(GC gc, Object[] events) {
int width = 0;
for (Object event : events) {
Point extent = gc.textExtent(getText(event));
if (extent.x > width) width = extent.x;
}
return width;
}
/**
* This method provides a foreground colour for the cell.
* The cell will be black if the filter includes the
* includes the provided {@link UsageDataEvent}, or gray if the filter
* excludes it.
*/
@Override
public Color getForeground(Object element) {
if (uploader.getFilter().includes((UsageDataEvent)element)) {
return colorBlack;
} else {
return colorGray;
}
}
@Override
public String getText(Object element) {
return getText((UsageDataEvent)element);
}
public abstract String getText(UsageDataEvent element);
}
}
|
package org.jkiss.dbeaver.ui.controls.resultset;
import org.eclipse.jface.dialogs.ControlEnableState;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.model.data.DBDDataFilter;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.exec.DBCStatistics;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.dialogs.sql.ViewSQLDialog;
import org.jkiss.utils.CommonUtils;
import java.util.List;
/**
* ResultSetFilterPanel
*/
class ResultSetFilterPanel extends Composite
{
private final ResultSetViewer viewer;
private Combo filtersText;
private ToolItem filtersApplyButton;
private ToolItem filtersClearButton;
private ToolItem filtersCustomButton;
private ToolItem historyBackButton;
private ToolItem historyForwardButton;
private ControlEnableState filtersEnableState;
public ResultSetFilterPanel(ResultSetViewer rsv) {
super(rsv.getControl(), SWT.NONE);
this.viewer = rsv;
this.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayout gl = new GridLayout(4, false);
gl.marginHeight = 3;
gl.marginWidth = 3;
this.setLayout(gl);
Button sourceQueryButton = new Button(this, SWT.PUSH | SWT.NO_FOCUS);
sourceQueryButton.setImage(DBeaverIcons.getImage(UIIcon.SQL_TEXT));
sourceQueryButton.setText("SQL");
sourceQueryButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
DBCStatistics statistics = viewer.getModel().getStatistics();
String queryText = statistics == null ? null : statistics.getQueryText();
if (queryText == null || queryText.isEmpty()) {
queryText = "<empty>";
}
ViewSQLDialog dialog = new ViewSQLDialog(viewer.getSite(), viewer.getExecutionContext(), "Query Text", DBeaverIcons.getImage(UIIcon.SQL_TEXT), queryText);
dialog.setEnlargeViewPanel(false);
dialog.setWordWrap(true);
dialog.open();
}
});
/*
Button customizeButton = new Button(this, SWT.PUSH | SWT.NO_FOCUS);
customizeButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER));
customizeButton.setText("Filters");
customizeButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
new FilterSettingsDialog(viewer).open();
}
});
*/
this.filtersText = new Combo(this, SWT.BORDER | SWT.DROP_DOWN);
this.filtersText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
this.filtersText.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
setCustomDataFilter();
}
});
{
// Register filters text in focus service
UIUtils.addFocusTracker(viewer.getSite(), UIUtils.INLINE_WIDGET_EDITOR_ID, this.filtersText);
this.filtersText.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e)
{
// Unregister from focus service
UIUtils.removeFocusTracker(viewer.getSite(), filtersText);
dispose();
}
});
}
// Handle all shortcuts by filters editor, not by host editor
UIUtils.enableHostEditorKeyBindingsSupport(viewer.getSite(), this.filtersText);
ToolBar filterToolbar = new ToolBar(this, SWT.HORIZONTAL | SWT.RIGHT);
filtersApplyButton = new ToolItem(filterToolbar, SWT.PUSH | SWT.NO_FOCUS);
filtersApplyButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER_APPLY));
//filtersApplyButton.setText("Apply");
filtersApplyButton.setToolTipText("Apply filter criteria");
filtersApplyButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setCustomDataFilter();
}
});
filtersApplyButton.setEnabled(false);
filtersClearButton = new ToolItem(filterToolbar, SWT.PUSH | SWT.NO_FOCUS);
filtersClearButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER_RESET));
filtersClearButton.setToolTipText("Remove all filters");
filtersClearButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
viewer.resetDataFilter(true);
}
});
filtersClearButton.setEnabled(false);
filtersCustomButton = new ToolItem(filterToolbar, SWT.PUSH | SWT.NO_FOCUS);
filtersCustomButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER));
filtersCustomButton.setToolTipText("Custom Filters");
filtersCustomButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
new FilterSettingsDialog(viewer).open();
}
});
filtersCustomButton.setEnabled(true);
historyBackButton = new ToolItem(filterToolbar, SWT.DROP_DOWN | SWT.NO_FOCUS);
historyBackButton.setImage(DBeaverIcons.getImage(UIIcon.RS_BACK));
historyBackButton.setEnabled(false);
historyBackButton.addSelectionListener(new HistoryMenuListener(historyBackButton, true));
historyForwardButton = new ToolItem(filterToolbar, SWT.DROP_DOWN | SWT.NO_FOCUS);
historyForwardButton.setImage(DBeaverIcons.getImage(UIIcon.RS_FORWARD));
historyForwardButton.setEnabled(false);
historyForwardButton.addSelectionListener(new HistoryMenuListener(historyForwardButton, false));
this.filtersText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e)
{
if (filtersEnableState == null) {
String filterText = filtersText.getText();
filtersApplyButton.setEnabled(true);
filtersClearButton.setEnabled(!CommonUtils.isEmpty(filterText));
}
}
});
this.addTraverseListener(new TraverseListener() {
@Override
public void keyTraversed(TraverseEvent e)
{
if (e.detail == SWT.TRAVERSE_RETURN) {
setCustomDataFilter();
e.doit = false;
e.detail = SWT.TRAVERSE_NONE;
}
}
});
filtersEnableState = ControlEnableState.disable(this);
}
void enableFilters(boolean enableFilters) {
if (enableFilters) {
if (filtersEnableState != null) {
filtersEnableState.restore();
filtersEnableState = null;
}
int historyPosition = viewer.getHistoryPosition();
List<ResultSetViewer.StateItem> stateHistory = viewer.getStateHistory();
String filterText = filtersText.getText();
filtersApplyButton.setEnabled(true);
filtersClearButton.setEnabled(!CommonUtils.isEmpty(filterText));
// Update history buttons
if (historyPosition > 0) {
historyBackButton.setEnabled(true);
historyBackButton.setToolTipText(stateHistory.get(historyPosition - 1).describeState());
} else {
historyBackButton.setEnabled(false);
}
if (historyPosition < stateHistory.size() - 1) {
historyForwardButton.setEnabled(true);
historyForwardButton.setToolTipText(stateHistory.get(historyPosition + 1).describeState());
} else {
historyForwardButton.setEnabled(false);
}
} else if (filtersEnableState == null) {
filtersEnableState = ControlEnableState.disable(this);
}
}
private void setCustomDataFilter()
{
DBCExecutionContext context = viewer.getExecutionContext();
if (context == null) {
return;
}
String condition = filtersText.getText();
StringBuilder currentCondition = new StringBuilder();
SQLUtils.appendConditionString(viewer.getModel().getDataFilter(), context.getDataSource(), null, currentCondition, true);
if (currentCondition.toString().trim().equals(condition.trim())) {
// The same
return;
}
DBDDataFilter newFilter = viewer.getModel().createDataFilter();
newFilter.setWhere(condition);
viewer.setDataFilter(newFilter, true);
viewer.getControl().setFocus();
}
void addFiltersHistory(String whereCondition)
{
int historyCount = filtersText.getItemCount();
for (int i = 0; i < historyCount; i++) {
if (filtersText.getItem(i).equals(whereCondition)) {
if (i > 0) {
// Move to beginning
filtersText.remove(i);
break;
} else {
return;
}
}
}
filtersText.add(whereCondition, 0);
filtersText.setText(whereCondition);
}
Control getEditControl() {
return filtersText;
}
void setFilterValue(String whereCondition) {
filtersText.setText(whereCondition);
}
private class HistoryMenuListener extends SelectionAdapter {
private final ToolItem dropdown;
private final boolean back;
public HistoryMenuListener(ToolItem item, boolean back) {
this.dropdown = item;
this.back = back;
}
@Override
public void widgetSelected(SelectionEvent e) {
int historyPosition = viewer.getHistoryPosition();
List<ResultSetViewer.StateItem> stateHistory = viewer.getStateHistory();
if (e.detail == SWT.ARROW) {
ToolItem item = (ToolItem) e.widget;
Rectangle rect = item.getBounds();
Point pt = item.getParent().toDisplay(new Point(rect.x, rect.y));
Menu menu = new Menu(dropdown.getParent().getShell());
menu.setLocation(pt.x, pt.y + rect.height);
menu.setVisible(true);
for (int i = historyPosition + (back ? -1 : 1); i >= 0 && i < stateHistory.size(); i += back ? -1 : 1) {
MenuItem mi = new MenuItem(menu, SWT.NONE);
ResultSetViewer.StateItem state = stateHistory.get(i);
mi.setText(state.describeState());
final int statePosition = i;
mi.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
viewer.navigateHistory(statePosition);
}
});
}
} else {
int newPosition = back ? historyPosition - 1 : historyPosition + 1;
viewer.navigateHistory(newPosition);
}
}
}
}
|
package org.jkiss.dbeaver.ui.controls.resultset;
import org.eclipse.jface.dialogs.ControlEnableState;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.jkiss.dbeaver.model.DBIcon;
import org.jkiss.dbeaver.model.data.DBDDataFilter;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.exec.DBCStatistics;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.dialogs.sql.ViewSQLDialog;
import org.jkiss.utils.CommonUtils;
import java.util.List;
/**
* ResultSetFilterPanel
*/
class ResultSetFilterPanel extends Composite
{
private final ResultSetViewer viewer;
private StyledText filtersText;
private ToolItem filtersApplyButton;
private ToolItem filtersClearButton;
private ToolItem historyBackButton;
private ToolItem historyForwardButton;
private ControlEnableState filtersEnableState;
private final Composite filterComposite;
private final Color hoverBgColor;
public ResultSetFilterPanel(ResultSetViewer rsv) {
super(rsv.getControl(), SWT.NONE);
this.viewer = rsv;
this.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayout gl = new GridLayout(4, false);
gl.marginHeight = 3;
gl.marginWidth = 3;
this.setLayout(gl);
hoverBgColor = getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW);
//new Color(getDisplay(), 0xe7, 0xe6, 0xe6);
/*
Button sourceQueryButton = new Button(this, SWT.PUSH | SWT.NO_FOCUS);
sourceQueryButton.setImage(DBeaverIcons.getImage(UIIcon.SQL_TEXT));
sourceQueryButton.setText("SQL");
sourceQueryButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e)
{
showSourceQuery();
}
});
*/
{
filterComposite = new Composite(this, SWT.BORDER);
gl = new GridLayout(4, false);
gl.marginHeight = 0;
gl.marginWidth = 0;
gl.horizontalSpacing = 0;
gl.verticalSpacing = 0;
filterComposite.setLayout(gl);
filterComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
new ActiveObjectPanel(filterComposite);
//new Label(filterComposite, SWT.SEPARATOR | SWT.VERTICAL);
this.filtersText = new StyledText(filterComposite, SWT.SINGLE);
this.filtersText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
/*
this.filtersText.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setCustomDataFilter();
}
});
*/
new RefreshPanel(filterComposite);
//addressBar.setBackgroundMode(filtersText.getBackground());
}
{
// Register filters text in focus service
UIUtils.addFocusTracker(viewer.getSite(), UIUtils.INLINE_WIDGET_EDITOR_ID, this.filtersText);
this.filtersText.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e)
{
// Unregister from focus service
UIUtils.removeFocusTracker(viewer.getSite(), filtersText);
dispose();
}
});
}
// Handle all shortcuts by filters editor, not by host editor
UIUtils.enableHostEditorKeyBindingsSupport(viewer.getSite(), this.filtersText);
ToolBar filterToolbar = new ToolBar(this, SWT.HORIZONTAL | SWT.RIGHT);
filtersApplyButton = new ToolItem(filterToolbar, SWT.PUSH | SWT.NO_FOCUS);
filtersApplyButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER_APPLY));
//filtersApplyButton.setText("Apply");
filtersApplyButton.setToolTipText("Apply filter criteria");
filtersApplyButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setCustomDataFilter();
}
});
filtersApplyButton.setEnabled(false);
filtersClearButton = new ToolItem(filterToolbar, SWT.PUSH | SWT.NO_FOCUS);
filtersClearButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER_RESET));
filtersClearButton.setToolTipText("Remove all filters");
filtersClearButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
viewer.resetDataFilter(true);
}
});
filtersClearButton.setEnabled(false);
ToolItem filtersCustomButton = new ToolItem(filterToolbar, SWT.PUSH | SWT.NO_FOCUS);
filtersCustomButton.setImage(DBeaverIcons.getImage(UIIcon.FILTER));
filtersCustomButton.setToolTipText("Custom Filters");
filtersCustomButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
new FilterSettingsDialog(viewer).open();
}
});
filtersCustomButton.setEnabled(true);
new ToolItem(filterToolbar, SWT.SEPARATOR).setControl(new Label(filterToolbar, SWT.SEPARATOR | SWT.VERTICAL));
historyBackButton = new ToolItem(filterToolbar, SWT.DROP_DOWN | SWT.NO_FOCUS);
historyBackButton.setImage(DBeaverIcons.getImage(UIIcon.RS_BACK));
historyBackButton.setEnabled(false);
historyBackButton.addSelectionListener(new HistoryMenuListener(historyBackButton, true));
historyForwardButton = new ToolItem(filterToolbar, SWT.DROP_DOWN | SWT.NO_FOCUS);
historyForwardButton.setImage(DBeaverIcons.getImage(UIIcon.RS_FORWARD));
historyForwardButton.setEnabled(false);
historyForwardButton.addSelectionListener(new HistoryMenuListener(historyForwardButton, false));
this.filtersText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e)
{
if (filtersEnableState == null) {
String filterText = filtersText.getText();
filtersApplyButton.setEnabled(true);
filtersClearButton.setEnabled(!CommonUtils.isEmpty(filterText));
}
}
});
this.addTraverseListener(new TraverseListener() {
@Override
public void keyTraversed(TraverseEvent e)
{
if (e.detail == SWT.TRAVERSE_RETURN) {
setCustomDataFilter();
e.doit = false;
e.detail = SWT.TRAVERSE_NONE;
}
}
});
filtersEnableState = ControlEnableState.disable(this);
}
private void showSourceQuery() {
DBCStatistics statistics = viewer.getModel().getStatistics();
String queryText = statistics == null ? null : statistics.getQueryText();
if (queryText == null || queryText.isEmpty()) {
queryText = "<empty>";
}
ViewSQLDialog dialog = new ViewSQLDialog(viewer.getSite(), viewer.getExecutionContext(), "Query Text", DBeaverIcons.getImage(UIIcon.SQL_TEXT), queryText);
dialog.setEnlargeViewPanel(false);
dialog.setWordWrap(true);
dialog.open();
}
void enableFilters(boolean enableFilters) {
if (enableFilters) {
if (filtersEnableState != null) {
filtersEnableState.restore();
filtersEnableState = null;
}
int historyPosition = viewer.getHistoryPosition();
List<ResultSetViewer.StateItem> stateHistory = viewer.getStateHistory();
String filterText = filtersText.getText();
filtersApplyButton.setEnabled(true);
filtersClearButton.setEnabled(!CommonUtils.isEmpty(filterText));
// Update history buttons
if (historyPosition > 0) {
historyBackButton.setEnabled(true);
historyBackButton.setToolTipText(stateHistory.get(historyPosition - 1).describeState());
} else {
historyBackButton.setEnabled(false);
}
if (historyPosition < stateHistory.size() - 1) {
historyForwardButton.setEnabled(true);
historyForwardButton.setToolTipText(stateHistory.get(historyPosition + 1).describeState());
} else {
historyForwardButton.setEnabled(false);
}
} else if (filtersEnableState == null) {
filtersEnableState = ControlEnableState.disable(this);
}
filtersText.getParent().setBackground(filtersText.getBackground());
filterComposite.layout();
for (Control child : filterComposite.getChildren()) child.redraw();
}
private void setCustomDataFilter()
{
DBCExecutionContext context = viewer.getExecutionContext();
if (context == null) {
return;
}
String condition = filtersText.getText();
StringBuilder currentCondition = new StringBuilder();
SQLUtils.appendConditionString(viewer.getModel().getDataFilter(), context.getDataSource(), null, currentCondition, true);
if (currentCondition.toString().trim().equals(condition.trim())) {
// The same
return;
}
DBDDataFilter newFilter = viewer.getModel().createDataFilter();
newFilter.setWhere(condition);
viewer.setDataFilter(newFilter, true);
viewer.getControl().setFocus();
}
void addFiltersHistory(String whereCondition)
{
/*
int historyCount = filtersText.getItemCount();
for (int i = 0; i < historyCount; i++) {
if (filtersText.getItem(i).equals(whereCondition)) {
if (i > 0) {
// Move to beginning
filtersText.remove(i);
break;
} else {
return;
}
}
}
filtersText.add(whereCondition, 0);
*/
filtersText.setText(whereCondition);
}
Control getEditControl() {
return filtersText;
}
void setFilterValue(String whereCondition) {
filtersText.setText(whereCondition);
}
private class FilterPanel extends Canvas {
public FilterPanel(Composite parent, int style) {
super(parent, style);
addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
paintPanel(e);
}
});
}
protected void paintPanel(PaintEvent e) {
}
}
private class ActiveObjectPanel extends FilterPanel {
private boolean hover = false;
public ActiveObjectPanel(Composite addressBar) {
super(addressBar, SWT.NONE);
setLayoutData(new GridData(GridData.FILL_VERTICAL));
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
filtersText.setFocus();
}
});
addMouseTrackListener(new MouseTrackAdapter() {
@Override
public void mouseEnter(MouseEvent e) {
hover = true;
redraw();
}
@Override
public void mouseExit(MouseEvent e) {
hover = false;
redraw();
}
});
}
@Override
public Point computeSize(int wHint, int hHint, boolean changed) {
GC sizingGC = new GC(this);
Point textSize = sizingGC.textExtent(viewer.getDataContainer().getName());
Image image = DBeaverIcons.getImage(DBIcon.TREE_TABLE);
if (image != null) {
textSize.x += image.getBounds().width + 4;
}
return new Point(
Math.min(textSize.x + 10, filterComposite.getSize().x / 3),
Math.min(textSize.y + 4, 20));
}
@Override
protected void paintPanel(PaintEvent e) {
e.gc.setForeground(e.gc.getDevice().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
if (hover) {
e.gc.setBackground(hoverBgColor);
e.gc.fillRectangle(e.x, e.y, e.width - 3, e.height);
e.gc.drawLine(
e.x + e.width - 4, e.y,
e.x + e.width - 4, e.y + e.height);
} else {
e.gc.drawLine(
e.x + e.width - 4, e.y + 2,
e.x + e.width - 4, e.y + e.height - 4);
}
//e.gc.setForeground(filtersText.getForeground());
e.gc.setForeground(e.gc.getDevice().getSystemColor(SWT.COLOR_DARK_GREEN));
e.gc.setClipping(e.x, e.y, e.width - 8, e.height);
int textOffset = 2;
Image icon = DBeaverIcons.getImage(DBIcon.TREE_TABLE);
if (icon != null) {
e.gc.drawImage(icon, 2, 3);
textOffset += icon.getBounds().width + 2;
}
e.gc.drawText(viewer.getDataContainer().getName(), textOffset, 3);
e.gc.setClipping((Rectangle) null);
}
}
private class RefreshPanel extends FilterPanel {
public RefreshPanel(Composite addressBar) {
super(addressBar, SWT.NONE);
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.heightHint = 10;
setLayoutData(gd);
}
}
private class HistoryMenuListener extends SelectionAdapter {
private final ToolItem dropdown;
private final boolean back;
public HistoryMenuListener(ToolItem item, boolean back) {
this.dropdown = item;
this.back = back;
}
@Override
public void widgetSelected(SelectionEvent e) {
int historyPosition = viewer.getHistoryPosition();
List<ResultSetViewer.StateItem> stateHistory = viewer.getStateHistory();
if (e.detail == SWT.ARROW) {
ToolItem item = (ToolItem) e.widget;
Rectangle rect = item.getBounds();
Point pt = item.getParent().toDisplay(new Point(rect.x, rect.y));
Menu menu = new Menu(dropdown.getParent().getShell());
menu.setLocation(pt.x, pt.y + rect.height);
menu.setVisible(true);
for (int i = historyPosition + (back ? -1 : 1); i >= 0 && i < stateHistory.size(); i += back ? -1 : 1) {
MenuItem mi = new MenuItem(menu, SWT.NONE);
ResultSetViewer.StateItem state = stateHistory.get(i);
mi.setText(state.describeState());
final int statePosition = i;
mi.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
viewer.navigateHistory(statePosition);
}
});
}
} else {
int newPosition = back ? historyPosition - 1 : historyPosition + 1;
viewer.navigateHistory(newPosition);
}
}
}
}
|
package org.jkiss.dbeaver.ui.editors.sql.syntax;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPKeywordType;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.impl.DBObjectNameCaseTransformer;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.SQLSyntaxManager;
import org.jkiss.dbeaver.model.struct.*;
import org.jkiss.dbeaver.runtime.jobs.DataSourceJob;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.editors.entity.EntityHyperlink;
import org.jkiss.dbeaver.ui.editors.sql.SQLEditorBase;
import org.jkiss.utils.CommonUtils;
import java.util.*;
/**
* SQLHyperlinkDetector
*/
public class SQLHyperlinkDetector extends AbstractHyperlinkDetector
{
static final Log log = Log.getLog(SQLHyperlinkDetector.class);
private final SQLEditorBase editor;
private SQLSyntaxManager syntaxManager;
private static class ObjectLookupCache {
List<DBSObjectReference> references;
boolean loading = true;
}
private Map<String, ObjectLookupCache> linksCache = new HashMap<>();
public SQLHyperlinkDetector(SQLEditorBase editor, SQLSyntaxManager syntaxManager)
{
this.editor = editor;
this.syntaxManager = syntaxManager;
}
@Nullable
@Override
public synchronized IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks)
{
if (region == null || textViewer == null || editor.getExecutionContext() == null) {
return null;
}
IDocument document = textViewer.getDocument();
if (document == null) {
return null;
}
SQLIdentifierDetector wordDetector = new SQLIdentifierDetector(syntaxManager.getStructSeparator(), syntaxManager.getQuoteSymbol());
SQLIdentifierDetector.WordRegion wordRegion = wordDetector.detectIdentifier(document, region);
if (wordRegion.word.length() == 0) {
return null;
}
String fullName = wordRegion.identifier;
String tableName = wordRegion.word;
boolean caseSensitive = false;
if (wordDetector.isQuoted(tableName)) {
tableName = DBUtils.getUnQuotedIdentifier(tableName, syntaxManager.getQuoteSymbol());
caseSensitive = true;
}
String containerName = null;
if (!CommonUtils.equalObjects(fullName, tableName)) {
int divPos = fullName.indexOf(syntaxManager.getStructSeparator());
if (divPos != -1) {
containerName = fullName.substring(0, divPos);
tableName = fullName.substring(divPos + 1);
if (wordDetector.isQuoted(containerName)) {
containerName = DBUtils.getUnQuotedIdentifier(containerName, syntaxManager.getQuoteSymbol());
}
if (wordDetector.isQuoted(tableName)) {
tableName = DBUtils.getUnQuotedIdentifier(tableName, syntaxManager.getQuoteSymbol());
}
}
}
if (syntaxManager.getDialect().getKeywordType(fullName) == DBPKeywordType.KEYWORD) {
// Skip keywords
return null;
}
DBSStructureAssistant structureAssistant = DBUtils.getAdapter(DBSStructureAssistant.class, editor.getDataSource());
if (structureAssistant == null) {
return null;
}
ObjectLookupCache tlc = linksCache.get(fullName);
if (tlc == null) {
// Start new word finder job
tlc = new ObjectLookupCache();
linksCache.put(fullName, tlc);
TablesFinderJob job = new TablesFinderJob(structureAssistant, containerName, tableName, caseSensitive, tlc);
job.schedule();
}
if (tlc.loading) {
// Wait for 1000ms maximum
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// interrupted - just go further
break;
}
if (!tlc.loading) {
break;
}
}
}
if (tlc.loading) {
// Long task - just return no links for now
return null;
} else {
// If no references found for this word - just null result
if (tlc.references.isEmpty()) {
return null;
}
// Create hyperlinks based on references
final IRegion hlRegion = new Region(wordRegion.identStart, wordRegion.identEnd - wordRegion.identStart);
IHyperlink[] links = new IHyperlink[tlc.references.size()];
for (int i = 0, objectsSize = tlc.references.size(); i < objectsSize; i++) {
links[i] = new EntityHyperlink(tlc.references.get(i), hlRegion);
}
return links;
}
}
@Override
public void dispose()
{
super.dispose();
linksCache.clear();
}
private class TablesFinderJob extends DataSourceJob {
private final DBSStructureAssistant structureAssistant;
private final String containerName;
private final String word;
private final ObjectLookupCache cache;
private final boolean caseSensitive;
protected TablesFinderJob(DBSStructureAssistant structureAssistant, String containerName, String word, boolean caseSensitive, ObjectLookupCache cache)
{
super("Find table names for '" + word + "'", DBeaverIcons.getImageDescriptor(UIIcon.SQL_EXECUTE), editor.getExecutionContext());
this.structureAssistant = structureAssistant;
// Transform container name case
this.containerName = containerName == null ?
null : DBObjectNameCaseTransformer.transformName(getExecutionContext().getDataSource(), containerName);
this.word = word;
this.caseSensitive = caseSensitive;
this.cache = cache;
setUser(false);
setSystem(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor)
{
cache.references = new ArrayList<>();
try {
DBSObjectContainer container = null;
if (!CommonUtils.isEmpty(containerName)) {
DBSObjectContainer dsContainer = DBUtils.getAdapter(DBSObjectContainer.class, getExecutionContext().getDataSource());
if (dsContainer != null) {
DBSObject childContainer = dsContainer.getChild(monitor, containerName);
if (childContainer instanceof DBSObjectContainer) {
container = (DBSObjectContainer) childContainer;
} else {
// Bad container - stop search
return Status.CANCEL_STATUS;
}
}
}
DBSObjectType[] objectTypes = structureAssistant.getHyperlinkObjectTypes();
Collection<DBSObjectReference> objects = structureAssistant.findObjectsByMask(monitor, container, objectTypes, word, caseSensitive, 10);
if (!CommonUtils.isEmpty(objects)) {
cache.references.addAll(objects);
}
} catch (DBException e) {
log.warn(e);
}
finally {
cache.loading = false;
}
return Status.OK_STATUS;
}
}
}
|
package se.crisp.codekvast.agent.lib.model.v1;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* The confidence that an invoked could be located in the codebase.
*
* NOTE: Is also defined as an ENUM in the central warehouse's invocations table!
*
* @author olle.hallin@crisp.se
*/
@RequiredArgsConstructor
@Getter
public enum SignatureConfidence {
/**
* The signature has been detected in the codebase, but it has never been invoked.
*/
NOT_INVOKED(1),
/**
* The used signature was found as-is in the scanned code base.
*/
EXACT_MATCH(2),
/**
* The used signature was <em>not</em> found as-is in the scanned code base. It was found however, when searching upwards in the class
* hierarchy. The reason for not finding it in the first place could be that the method was synthesized at runtime by some byte code
* manipulating AOP framework (like Spring or Guice).
*/
FOUND_IN_PARENT_CLASS(3),
/**
* The used signature was <em>not</em> found at all in the scanned code base. This indicates a problem with the code base scanner.
* Access to the source code is required in order to resolve the problem.
*/
NOT_FOUND_IN_CODE_BASE(4);
/*
* The database representation of the value. It is 1-based to make it easy to use with MariaDB's ENUM column type.
* MariaDB reserves 0 for the special value ''.
*/
private final int dbNumber;
public static SignatureConfidence fromOrdinal(int ordinal) {
for (SignatureConfidence confidence : values()) {
if (confidence.ordinal() == ordinal) {
return confidence;
}
}
throw new IllegalArgumentException("Illegal ordinal for a " + SignatureConfidence.class.getSimpleName() + ": " + ordinal);
}
public static SignatureConfidence fromDbNumber(int dbNumber) {
for (SignatureConfidence confidence : values()) {
if (confidence.getDbNumber() == dbNumber) {
return confidence;
}
}
throw new IllegalArgumentException("Illegal dbNumber for a " + SignatureConfidence.class.getSimpleName() + ": " + dbNumber);
}
}
|
package gov.nih.nci.cabig.caaers.service.migrator;
import gov.nih.nci.cabig.caaers.dao.OrganizationDao;
import gov.nih.nci.cabig.caaers.dao.ResearchStaffDao;
import gov.nih.nci.cabig.caaers.dao.SiteInvestigatorDao;
import gov.nih.nci.cabig.caaers.domain.CoordinatingCenter;
import gov.nih.nci.cabig.caaers.domain.FundingSponsor;
import gov.nih.nci.cabig.caaers.domain.Investigator;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.OrganizationAssignedIdentifier;
import gov.nih.nci.cabig.caaers.domain.ResearchStaff;
import gov.nih.nci.cabig.caaers.domain.SiteInvestigator;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.StudyCoordinatingCenter;
import gov.nih.nci.cabig.caaers.domain.StudyFundingSponsor;
import gov.nih.nci.cabig.caaers.domain.StudyInvestigator;
import gov.nih.nci.cabig.caaers.domain.StudyOrganization;
import gov.nih.nci.cabig.caaers.domain.StudyPersonnel;
import gov.nih.nci.cabig.caaers.domain.StudySite;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome;
import gov.nih.nci.cabig.caaers.service.DomainObjectImportOutcome.Severity;
import java.util.List;
import org.springframework.beans.factory.annotation.Required;
public class StudyOrganizationMigrator implements Migrator<Study>{
private OrganizationDao organizationDao;
private SiteInvestigatorDao siteInvestigatorDao;
private ResearchStaffDao researchStaffDao;
/**
* This method will copy the {@link StudyOrganization}s from source to destination
*/
public void migrate(Study source, Study destination,DomainObjectImportOutcome<Study> outcome) {
//migrate funding sponsor
migrateFundingSponsor(source, destination, outcome);
//migrate coordinating center
migrateCoordinatingCenter(source, destination, outcome);
//migrate studyOrganization.
migrateStudySite(source, destination, outcome);
}
private void migrateStudySite(Study source, Study destination,DomainObjectImportOutcome<Study> outcome) {
if(source.getStudyOrganizations() != null && source.getStudyOrganizations().size() > 0){
for (StudyOrganization studyOrganization : source.getStudyOrganizations()) {
String orgName = studyOrganization.getOrganization().getName();
Organization organization = organizationDao.getByName(orgName);
studyOrganization.setOrganization(organization);
// Migrate Study investigators and Study Personnels
migrateStudyInvestigators(studyOrganization, organization, outcome);
migrateStudyPersonnels(studyOrganization, organization, outcome);
destination.addStudySite((StudySite) studyOrganization);
}
}
}
private void migrateFundingSponsor(Study source, Study destination, DomainObjectImportOutcome<Study> outcome ){
FundingSponsor sponsor = source.getFundingSponsor();
if(sponsor == null) return;
StudyFundingSponsor studySponsor = sponsor.getStudyFundingSponsor();
String orgName = studySponsor.getOrganization().getName();
Organization organization = organizationDao.getByName(orgName);
outcome.ifNullObject(organization, DomainObjectImportOutcome.Severity.ERROR,
"The organization specified in fundingSponsor is invalid");
studySponsor.setOrganization(organization);
OrganizationAssignedIdentifier orgIdentifier = sponsor.getOrganizationAssignedIdentifier();
orgIdentifier.setType(OrganizationAssignedIdentifier.SPONSOR_IDENTIFIER_TYPE);
orgIdentifier.setOrganization(organization);
// Migrate Study investigators and Study Personnels
migrateStudyInvestigators(studySponsor, organization, outcome);
migrateStudyPersonnels(studySponsor, organization, outcome);
destination.getIdentifiers().add(orgIdentifier);
destination.addStudyFundingSponsor(studySponsor);
}
private void migrateCoordinatingCenter(Study source, Study destination, DomainObjectImportOutcome<Study> outcome ){
CoordinatingCenter coCenter = source.getCoordinatingCenter();
if(coCenter == null) return;
StudyCoordinatingCenter studyCoordinatingCenter = coCenter.getStudyCoordinatingCenter();
String orgName = studyCoordinatingCenter.getOrganization().getName();
Organization organization = organizationDao.getByName(orgName);
outcome.ifNullObject(organization, DomainObjectImportOutcome.Severity.ERROR, "The organization specified in coordinatingCenter is invalid");
studyCoordinatingCenter.setOrganization(organization);
OrganizationAssignedIdentifier orgIdentifier = coCenter.getOrganizationAssignedIdentifier();
orgIdentifier.setType(OrganizationAssignedIdentifier.COORDINATING_CENTER_IDENTIFIER_TYPE);
orgIdentifier.setOrganization(organization);
// Migrate Study investigators and Study Personnels
migrateStudyInvestigators(studyCoordinatingCenter, organization, outcome);
migrateStudyPersonnels(studyCoordinatingCenter, organization, outcome);
destination.getIdentifiers().add(orgIdentifier);
destination.addStudyOrganization(studyCoordinatingCenter);
}
private void migrateStudyInvestigators(StudyOrganization studyOrganization, Organization organization, DomainObjectImportOutcome studyImportOutcome) {
for (StudyInvestigator studyInvestigator : studyOrganization.getStudyInvestigators()) {
Investigator investigator = studyInvestigator.getSiteInvestigator().getInvestigator();
// TODO : search should be done on something else too
String[] investigatorFirstAndLast = {investigator.getFirstName(), investigator.getLastName()};
List<SiteInvestigator> siteInvestigators = siteInvestigatorDao.getBySubnames(investigatorFirstAndLast, organization.getId());
if (siteInvestigators.size() > 0) {
studyInvestigator.setSiteInvestigator(siteInvestigators.get(0));
studyInvestigator.setStudyOrganization(studyOrganization);
} else {
//studyOrganization.getStudyInvestigators().remove(studyInvestigator);
studyImportOutcome.ifNullObject(null, DomainObjectImportOutcome.Severity.ERROR, "The selected investigator " +
investigator.getFirstName() + " " + investigator.getLastName() + " is not Valid ");
}
}
}
private void migrateStudyPersonnels(StudyOrganization studyOrganization,
Organization organization, DomainObjectImportOutcome<Study> studyImportOutcome) {
for (StudyPersonnel studyPersonnel : studyOrganization.getStudyPersonnels()) {
ResearchStaff researchStaffer = studyPersonnel.getResearchStaff();
// TODO : search should be done on something else too
String[] investigatorFirstAndLast = {researchStaffer.getFirstName(), researchStaffer.getLastName()};
List<ResearchStaff> researchStaffs = researchStaffDao.getBySubnames(investigatorFirstAndLast, organization.getId());
if (researchStaffs.size() > 0) {
ResearchStaff researchStaff = researchStaffs.get(0);
studyPersonnel.setResearchStaff(researchStaff);
studyPersonnel.setStudyOrganization(studyOrganization);
} else {
studyImportOutcome.ifNullObject(null, DomainObjectImportOutcome.Severity.ERROR, "The selected personnel " +
researchStaffer.getFirstName() + " " + researchStaffer.getLastName() + " is not Valid ");
}
}
}
@Required
public void setSiteInvestigatorDao(final SiteInvestigatorDao siteInvestigatorDao) {
this.siteInvestigatorDao = siteInvestigatorDao;
}
@Required
public void setResearchStaffDao(final ResearchStaffDao researchStaffDao) {
this.researchStaffDao = researchStaffDao;
}
@Required
public void setOrganizationDao(OrganizationDao organizationDao) {
this.organizationDao = organizationDao;
}
}
|
package org.keyczar.i18n;
import org.keyczar.annotations.ForTesting;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
private static final String BUNDLE_NAME = "org.keyczar.i18n.messages";
private static ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle(BUNDLE_NAME);
private Messages() {
}
@ForTesting
public static void changeLocale(Locale locale) {
RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME, locale);
}
public static String getString(String key, Object... params) {
try {
return MessageFormat.format(RESOURCE_BUNDLE.getString(key), params);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
|
package kryptografia;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.border.*;
public class Kryptografia extends JFrame {
private static JTextField kluczWejscie;
private static JTextArea textWyjscie, textWejscie, textStat, textKrypto;
private JScrollPane scrollText, scrollText2, scrollTextStat, scrollTextKrypto;
private JButton szyfrujPrzycisk, deszyfrujPrzycisk, kryptoanalizaPrzycisk;
private PrzyciskSzyfruj obslugaSzyfruj;
private PrzyciskDeszyfruj obslugaDeszyfruj;
private PrzyciskKryptoanaliza obslugaKryptoanaliza;
private String kluczKryptoanaliza;
public Kryptografia() {
textWejscie = new JTextArea("", 50, 895);
scrollText2 = new JScrollPane(textWejscie);
scrollText2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textWejscie.setLineWrap(true);
textWejscie.setWrapStyleWord(true);
textStat = new JTextArea("", 800, 50);
scrollTextStat = new JScrollPane(textStat);
scrollTextStat.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textStat.setLineWrap(true);
textStat.setWrapStyleWord(true);
textKrypto = new JTextArea("", 800, 50);
scrollTextKrypto = new JScrollPane(textKrypto);
scrollTextKrypto.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textKrypto.setLineWrap(true);
textKrypto.setWrapStyleWord(true);
kluczWejscie = new JTextField(3);
textWyjscie = new JTextArea("", 50, 895);
textWyjscie.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
textWyjscie = new JTextArea("", 50, 895);
scrollText = new JScrollPane(textWyjscie);
scrollText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textWyjscie.setLineWrap(true);
textWyjscie.setWrapStyleWord(false);
textWyjscie.setEditable(false);
szyfrujPrzycisk = new JButton("Szyfruj");
obslugaSzyfruj = new PrzyciskSzyfruj();
szyfrujPrzycisk.addActionListener(obslugaSzyfruj);
deszyfrujPrzycisk = new JButton("Deszyfruj");
obslugaDeszyfruj = new PrzyciskDeszyfruj();
deszyfrujPrzycisk.addActionListener(obslugaDeszyfruj);
kryptoanalizaPrzycisk = new JButton("Start Kryptoanaliza");
obslugaKryptoanaliza = new PrzyciskKryptoanaliza();
kryptoanalizaPrzycisk.addActionListener(obslugaKryptoanaliza);
setTitle("Kryptografia");
Container okno = getContentPane();
okno.setLayout(null);
deszyfrujPrzycisk.setLocation(550, 452);
szyfrujPrzycisk.setLocation(300, 452);
kryptoanalizaPrzycisk.setLocation(780, 200);
scrollText2.setLocation(5, 52);
kluczWejscie.setLocation(185, 233);
scrollText.setLocation(5, 273);
scrollTextStat.setLocation(410, 52);
scrollTextKrypto.setLocation(595, 52);
deszyfrujPrzycisk.setSize(200, 40);
szyfrujPrzycisk.setSize(200, 40);
kryptoanalizaPrzycisk.setSize(150, 40);
scrollText2.setSize(400, 180);
kluczWejscie.setSize(60, 40);
scrollText.setSize(400, 180);
scrollTextStat.setSize(180, 400);
scrollTextKrypto.setSize(180, 400);
okno.add(deszyfrujPrzycisk);
okno.add(szyfrujPrzycisk);
okno.add(kryptoanalizaPrzycisk);
okno.add(scrollText2);
okno.add(kluczWejscie);
okno.add(scrollText);
okno.add(scrollTextStat);
okno.add(scrollTextKrypto);
setSize(1035, 530);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class PrzyciskSzyfruj implements ActionListener {
public void actionPerformed(ActionEvent e) {
String tresc = textWejscie.getText();
String klucz = kluczWejscie.getText();
klucz = dodajAlfabet(klucz.toUpperCase());
textWyjscie.setText("");
char[] tab_tresc = tresc.toUpperCase().toCharArray();
char[] tab_klucz = klucz.toCharArray();
for (int i = 0; i < tresc.length(); i++) {
int pozycja = sprawdzPozycjeAlfabet(tab_tresc[i]);
char szyfruj;
if(pozycja == -1)
szyfruj = tab_tresc[i];
else
szyfruj = tab_klucz[pozycja];
textWyjscie.append(Character.toString(szyfruj));
}
String charakterystyka = wyznaczCharakterystyke(textWyjscie.getText());
textStat.setText(charakterystyka);
}
}
private class PrzyciskDeszyfruj implements ActionListener {
public void actionPerformed(ActionEvent e) {
String tresc = textWejscie.getText();
String klucz = kluczWejscie.getText();
klucz = dodajAlfabet(klucz.toUpperCase());
textWyjscie.setText("");
String alfabet = pobierzAlfabet();
char[] tab_alfabet = alfabet.toCharArray();
char[] tab_tresc = tresc.toUpperCase().toCharArray();
for (int i = 0; i < tresc.length(); i++) {
int pozycja = sprawdzPozycjeKlucz(tab_tresc[i], klucz);
char deszyfruj;
if(pozycja == -1)
deszyfruj = tab_tresc[i];
else
deszyfruj = tab_alfabet[pozycja];
textWyjscie.append(Character.toString(deszyfruj));
}
String charakterystyka = wyznaczCharakterystyke(textWyjscie.getText());
textStat.setText(charakterystyka);
}
}
private class PrzyciskKryptoanaliza implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = textKrypto.getText();
if(text.isEmpty()) {
String szablon = wygenerujSzablonKryptoanalizy();
textKrypto.setText(szablon);
}
else {
}
}
}
public static String dodajAlfabet(String klucz) {
char[] znaki = klucz.toCharArray();
for (char ch = 'A'; ch <= 'Z'; ++ch) {
boolean poprawnosc = false;
for (int i = 0; i < znaki.length; i++)
if (znaki[i] == ch)
poprawnosc = true;
if (!poprawnosc)
klucz += ch;
}
return klucz;
}
public int sprawdzPozycjeAlfabet(char znak) {
int pozycja=0;
boolean czyZnaleziono = false;
for (char ch = 'A'; ch <= 'Z'; ++ch) {
if(ch == znak) {
czyZnaleziono = true;
break;
}
pozycja++;
}
if(czyZnaleziono)
return pozycja;
else
return -1;
}
public int sprawdzPozycjeKlucz(char znak, String klucz) {
char[] tab_klucz = klucz.toCharArray();
int pozycja=0;
boolean czyZnaleziono = false;
for (int i=0; i<klucz.length(); i++) {
if(znak == tab_klucz[i]) {
czyZnaleziono = true;
break;
}
pozycja++;
}
if(czyZnaleziono)
return pozycja;
else
return -1;
}
/**
* Pobiera alfabet i zapisuje do stringa
* @return
*/
public String pobierzAlfabet() {
String alfabet = "";
for (char ch='A'; ch <= 'Z'; ++ch)
alfabet += ch;
return alfabet;
}
public String wyznaczCharakterystyke(String text) {
String charakterystyka = "";
for(char ch = 'A'; ch <= 'Z'; ++ch) {
charakterystyka += ch;
charakterystyka += " = ";
int ilosc = policzWystapienia(text, ch);
float srednia = (float) ilosc / (float) text.length();
charakterystyka += Integer.toString(ilosc);
charakterystyka += " (";
charakterystyka += Float.toString(srednia);
charakterystyka += ")";
charakterystyka += '\n';
}
return charakterystyka;
}
public int policzWystapienia(String text, char znak) {
int wystapienia = 0;
char[] tab_text = text.toCharArray();
for(int i=0; i<text.length(); i++) {
if(tab_text[i]==znak)
wystapienia++;
}
return wystapienia;
}
public String wygenerujSzablonKryptoanalizy() {
String szablon="";
String alfabet = pobierzAlfabet();
char[] tab_alfabet = alfabet.toCharArray();
if(kluczKryptoanaliza == null)
kluczKryptoanaliza = pobierzAlfabet();
char[] tab_kluczKryptoanaliza = kluczKryptoanaliza.toCharArray();
for(int i=0; i<kluczKryptoanaliza.length(); i++) {
szablon += tab_alfabet[i];
szablon += "\t => ";
szablon += tab_kluczKryptoanaliza[i];
szablon += "\n";
}
return szablon;
}
/**
* Main
* @param args
*/
public static void main(String[] args) {
Kryptografia obiekt = new Kryptografia();
obiekt.setLocationRelativeTo(null);
}
}
|
package lab4_progra2;
import java.util.ArrayList;
import javax.swing.JOptionPane;
/**
*
* @author Franklin Garcia
*/
public class Lab4_progra2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Persona> lista_persona = new ArrayList();
ArrayList<Almacen> lista_almacen = new ArrayList();
ArrayList<Producto> lista_producto = new ArrayList();
String opcion = "";
while (!opcion.equalsIgnoreCase("6")) {
opcion = JOptionPane.showInputDialog("Ingrese opcion \n"
+ "1-Agregar \n"
+ "2-Modificar \n"
+ "3-Eliminar \n "
+ "4-Listar \n"
+ "5-Transferir \n"
+ "6-Salir \n");
switch (opcion) {
case "1": {
String op="";
while(!op.equalsIgnoreCase("4")){
op=JOptionPane.showInputDialog("Ingrese opcion \n"
+ "1-Almacen \n"
+ "2-Persona \n"
+ "3-Producto \n"
+ "4-Salir \n");
switch(op){
case "1":{
}break;
case "2":{
}break;
case "3":{
}break;
}
}
}
break;
case "2": {
}
break;
case "3": {
}
case "4": {
}
break;
case "5": {
}
break;
}
}
}
}
|
package org.apache.xerces.impl.v2;
import org.apache.xerces.impl.v2.datatypes.*;
import org.apache.xerces.impl.v2.identity.*;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.msg.XMLMessageFormatter;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLInputSource;
import java.io.IOException;
import org.apache.xerces.util.NamespaceSupport;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.util.IntStack;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLDTDHandler;
import org.apache.xerces.xni.XMLDTDContentModelHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Vector;
import java.util.StringTokenizer;
public class SchemaValidator
implements XMLComponent, XMLDocumentFilter,
FieldActivator // for identity constraints
{
// Constants
private static final boolean DEBUG = false;
// feature identifiers
/** Feature identifier: validation. */
protected static final String VALIDATION =
Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE;
/** Feature identifier: dynamic validation. */
protected static final String DYNAMIC_VALIDATION =
Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE;
// property identifiers
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: entiry resolver. */
protected static final String ENTITY_RESOLVER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
// REVISIT: this is just a temporary solution for entity resolver
// while we are making a decision
protected static final String ENTITY_MANAGER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY;
// recognized features and properties
/** Recognized features. */
protected static final String[] RECOGNIZED_FEATURES = {
VALIDATION,
DYNAMIC_VALIDATION,
};
/** Recognized properties. */
protected static final String[] RECOGNIZED_PROPERTIES = {
SYMBOL_TABLE,
ERROR_REPORTER,
ENTITY_RESOLVER,
};
// Data
// features
/** Validation. */
protected boolean fValidation = false;
protected boolean fDynamicValidation = false;
protected boolean fDoValidation = false;
// properties
/** Symbol table. */
protected SymbolTable fSymbolTable;
/** Error reporter. */
protected XMLErrorReporter fErrorReporter;
/** Entity resolver */
protected XMLEntityResolver fEntityResolver;
// handlers
/** Document handler. */
protected XMLDocumentHandler fDocumentHandler;
// XMLComponent methods
/*
* Resets the component. The component can query the component manager
* about any features and properties that affect the operation of the
* component.
*
* @param componentManager The component manager.
*
* @throws SAXException Thrown by component on finitialization error.
* For example, if a feature or property is
* required for the operation of the component, the
* component manager may throw a
* SAXNotRecognizedException or a
* SAXNotSupportedException.
*/
public void reset(XMLComponentManager componentManager)
throws XMLConfigurationException {
ownReset(componentManager);
} // reset(XMLComponentManager)
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return RECOGNIZED_FEATURES;
} // getRecognizedFeatures():String[]
/**
* Sets the state of a feature. This method is called by the component
* manager any time after reset when a feature changes state.
* <p>
* <strong>Note:</strong> Components should silently ignore features
* that do not affect the operation of the component.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
if (featureId.equals(VALIDATION))
fValidation = state;
else if (featureId.equals(DYNAMIC_VALIDATION))
fDynamicValidation = state;
} // setFeature(String,boolean)
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return RECOGNIZED_PROPERTIES;
} // getRecognizedProperties():String[]
/**
* Sets the value of a property. This method is called by the component
* manager any time after reset when a property changes value.
* <p>
* <strong>Note:</strong> Components should silently ignore properties
* that do not affect the operation of the component.
*
* @param propertyId The property identifier.
* @param value The value of the property.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
} // setProperty(String,Object)
// XMLDocumentSource methods
/**
* Sets the document handler to receive information about the document.
*
* @param documentHandler The document handler.
*/
public void setDocumentHandler(XMLDocumentHandler documentHandler) {
fDocumentHandler = documentHandler;
} // setDocumentHandler(XMLDocumentHandler)
// XMLDocumentHandler methods
/**
* The start of the document.
*
* @param systemId The system identifier of the entity if the entity
* is external, null otherwise.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal entities or a document entity that is
* parsed from a java.io.Reader).
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startDocument(XMLLocator locator, String encoding)
throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.startDocument(locator, encoding);
}
if(fValidation)
fValueStoreCache.startDocument();
} // startDocument(XMLLocator,String)
/**
* Notifies of the presence of an XMLDecl line in the document. If
* present, this method will be called immediately following the
* startDocument call.
*
* @param version The XML version.
* @param encoding The IANA encoding name of the document, or null if
* not specified.
* @param standalone The standalone value, or null if not specified.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void xmlDecl(String version, String encoding, String standalone)
throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.xmlDecl(version, encoding, standalone);
}
} // xmlDecl(String,String,String)
/**
* Notifies of the presence of the DOCTYPE line in the document.
*
* @param rootElement The name of the root element.
* @param publicId The public identifier if an external DTD or null
* if the external DTD is specified using SYSTEM.
* @param systemId The system identifier if an external DTD, null
* otherwise.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void doctypeDecl(String rootElement, String publicId, String systemId)
throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.doctypeDecl(rootElement, publicId, systemId);
}
} // doctypeDecl(String,String,String)
/**
* The start of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
* @param uri The URI bound to the prefix.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startPrefixMapping(String prefix, String uri)
throws XNIException {
handleStartPrefix(prefix, uri);
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.startPrefixMapping(prefix, uri);
}
} // startPrefixMapping(String,String)
/**
* The start of an element.
*
* @param element The name of the element.
* @param attributes The element attributes.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startElement(QName element, XMLAttributes attributes)
throws XNIException {
handleStartElement(element, attributes);
if (fDocumentHandler != null) {
fDocumentHandler.startElement(element, attributes);
}
} // startElement(QName,XMLAttributes)
/**
* An empty element.
*
* @param element The name of the element.
* @param attributes The element attributes.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void emptyElement(QName element, XMLAttributes attributes)
throws XNIException {
handleStartElement(element, attributes);
handleEndElement(element);
if (fDocumentHandler != null) {
fDocumentHandler.emptyElement(element, attributes);
}
} // emptyElement(QName,XMLAttributes)
/**
* Character content.
*
* @param text The content.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void characters(XMLString text) throws XNIException {
if (fSkipValidationDepth >= 0)
return;
boolean allWhiteSpace = true;
for (int i=text.offset; i< text.offset+text.length; i++) {
if (!XMLChar.isSpace(text.ch[i])) {
allWhiteSpace = false;
break;
}
}
fBuffer.append(text.toString());
if (!allWhiteSpace) {
fSawCharacters = true;
}
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.characters(text);
}
// call all active identity constraints
int count = fMatcherStack.getMatcherCount();
for (int i = 0; i < count; i++) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
matcher.characters(text);
}
} // characters(XMLString)
/**
* Ignorable whitespace. For this method to be called, the document
* source must have some way of determining that the text containing
* only whitespace characters should be considered ignorable. For
* example, the validator can determine if a length of whitespace
* characters in the document are ignorable based on the element
* content model.
*
* @param text The ignorable whitespace.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void ignorableWhitespace(XMLString text) throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.ignorableWhitespace(text);
}
// call all active identity constraints
int count = fMatcherStack.getMatcherCount();
for (int i = 0; i < count; i++) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
matcher.characters(text);
}
} // ignorableWhitespace(XMLString)
/**
* The end of an element.
*
* @param element The name of the element.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endElement(QName element) throws XNIException {
handleEndElement(element);
if (fDocumentHandler != null) {
fDocumentHandler.endElement(element);
}
} // endElement(QName)
/**
* The end of a namespace prefix mapping. This method will only be
* called when namespace processing is enabled.
*
* @param prefix The namespace prefix.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endPrefixMapping(String prefix) throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.endPrefixMapping(prefix);
}
} // endPrefixMapping(String)
/**
* The start of a CDATA section.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startCDATA() throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.startCDATA();
}
} // startCDATA()
/**
* The end of a CDATA section.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endCDATA() throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.endCDATA();
}
} // endCDATA()
/**
* The end of the document.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endDocument() throws XNIException {
// call handlers
if (fDocumentHandler != null) {
fDocumentHandler.endDocument();
}
if(fValidation)
fValueStoreCache.endDocument();
} // endDocument()
// XMLDocumentHandler and XMLDTDHandler methods
/**
* This method notifies of the start of an entity. The DTD has the
* pseudo-name of "[dtd]; parameter entity names start with '%'; and
* general entity names are just the entity name.
* <p>
* <strong>Note:</strong> Since the DTD is an entity, the handler
* will be notified of the start of the DTD entity by calling the
* startEntity method with the entity name "[dtd]" <em>before</em> calling
* the startDTD method.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the entity.
* @param publicId The public identifier of the entity if the entity
* is external, null otherwise.
* @param systemId The system identifier of the entity if the entity
* is external, null otherwise.
* @param baseSystemId The base system identifier of the entity if
* the entity is external, null otherwise.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal parameter entities).
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startEntity(String name,
String publicId, String systemId,
String baseSystemId,
String encoding) throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.startEntity(name, publicId, systemId,
baseSystemId, encoding);
}
} // startEntity(String,String,String,String,String)
/**
* Notifies of the presence of a TextDecl line in an entity. If present,
* this method will be called immediately following the startEntity call.
* <p>
* <strong>Note:</strong> This method will never be called for the
* document entity; it is only called for external general entities
* referenced in document content.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param version The XML version, or null if not specified.
* @param encoding The IANA encoding name of the entity.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void textDecl(String version, String encoding) throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.textDecl(version, encoding);
}
} // textDecl(String,String)
/**
* A comment.
*
* @param text The text in the comment.
*
* @throws XNIException Thrown by application to signal an error.
*/
public void comment(XMLString text) throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.comment(text);
}
} // comment(XMLString)
/**
* A processing instruction. Processing instructions consist of a
* target name and, optionally, text data. The data is only meaningful
* to the application.
* <p>
* Typically, a processing instruction's data will contain a series
* of pseudo-attributes. These pseudo-attributes follow the form of
* element attributes but are <strong>not</strong> parsed or presented
* to the application as anything other than text. The application is
* responsible for parsing the data.
*
* @param target The target.
* @param data The data or null if none specified.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void processingInstruction(String target, XMLString data)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.processingInstruction(target, data);
}
} // processingInstruction(String,XMLString)
/**
* This method notifies the end of an entity. The DTD has the pseudo-name
* of "[dtd]; parameter entity names start with '%'; and general entity
* names are just the entity name.
* <p>
* <strong>Note:</strong> Since the DTD is an entity, the handler
* will be notified of the end of the DTD entity by calling the
* endEntity method with the entity name "[dtd]" <em>after</em> calling
* the endDTD method.
* <p>
* <strong>Note:</strong> This method is not called for entity references
* appearing as part of attribute values.
*
* @param name The name of the entity.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endEntity(String name) throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.endEntity(name);
}
} // endEntity(String)
// constants
static final int INITIAL_STACK_SIZE = 8;
static final int INC_STACK_SIZE = 8;
// some constants that'll be added into the symbol table
String XMLNS;
String URI_XSI;
String XSI_SCHEMALOCATION;
String XSI_NONAMESPACESCHEMALOCATION;
String XSI_TYPE;
String XSI_NIL;
String URI_SCHEMAFORSCHEMA;
// Data
/** Schema grammar resolver. */
final XSGrammarResolver fGrammarResolver;
/** Schema handler */
final XSDHandler fSchemaHandler;
/** Namespace support. */
final NamespaceSupport fNamespaceSupport = new NamespaceSupport();
/** this flag is used to indicate whether the next prefix binding
* should start a new context (.pushContext)
*/
boolean fPushForNextBinding;
/** the DV usd to convert xsi:type to a QName */
// REVISIT: in new simple type design, make things in DVs static,
// so that we can QNameDV.getCompiledForm()
final DatatypeValidator fQNameDV = (DatatypeValidator)SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_QNAME);
/** used to build content models */
// REVISIT: create decl pool, and pass it to each traversers
final CMBuilder fCMBuilder = new CMBuilder(new XSDeclarationPool());
// state
/** Skip validation. */
int fSkipValidationDepth;
/** Element depth. */
int fElementDepth;
/** Child count. */
int fChildCount;
/** Element decl stack. */
int[] fChildCountStack = new int[INITIAL_STACK_SIZE];
/** Current element declaration. */
XSElementDecl fCurrentElemDecl;
/** Element decl stack. */
XSElementDecl[] fElemDeclStack = new XSElementDecl[INITIAL_STACK_SIZE];
/** nil value of the current element */
boolean fNil;
/** nil value stack */
boolean[] fNilStack = new boolean[INITIAL_STACK_SIZE];
/** Current type. */
XSTypeDecl fCurrentType;
/** type stack. */
XSTypeDecl[] fTypeStack = new XSTypeDecl[INITIAL_STACK_SIZE];
/** Current content model. */
XSCMValidator fCurrentCM;
/** Content model stack. */
XSCMValidator[] fCMStack = new XSCMValidator[INITIAL_STACK_SIZE];
/** the current state of the current content model */
int[] fCurrCMState;
/** stack to hold content model states */
int[][] fCMStateStack = new int[INITIAL_STACK_SIZE][];
/** Temporary string buffers. */
final StringBuffer fBuffer = new StringBuffer();
/** Did we see non-whitespace character data? */
boolean fSawCharacters = false;
/** Stack to record if we saw character data outside of element content*/
boolean[] fStringContent = new boolean[INITIAL_STACK_SIZE];
/**
* This table has to be own by instance of XMLValidator and shared
* among ID, IDREF and IDREFS.
* REVISIT: Should replace with a lighter structure.
*/
final Hashtable fTableOfIDs = new Hashtable();
final Hashtable fTableOfIDRefs = new Hashtable();
/**
* temprory qname
*/
final QName fTempQName = new QName();
/**
* temprory empty object, used to fill IDREF table
*/
static final Object fTempObject = new Object();
// identity constraint information
/**
* Stack of active XPath matchers for identity constraints. All
* active XPath matchers are notified of startElement, characters
* and endElement callbacks in order to perform their matches.
* <p>
* For each element with identity constraints, the selector of
* each identity constraint is activated. When the selector matches
* its XPath, then all the fields of the identity constraint are
* activated.
* <p>
* <strong>Note:</strong> Once the activation scope is left, the
* XPath matchers are automatically removed from the stack of
* active matchers and no longer receive callbacks.
*/
protected XPathMatcherStack fMatcherStack = new XPathMatcherStack();
/** Cache of value stores for identity constraint fields. */
protected ValueStoreCache fValueStoreCache = new ValueStoreCache();
// Constructors
/** Default constructor. */
public SchemaValidator() {
fGrammarResolver = new XSGrammarResolver();
fSchemaHandler = new XSDHandler(fGrammarResolver);
} // <init>()
void ownReset(XMLComponentManager componentManager)
throws XMLConfigurationException {
// get error reporter
fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
// get symbol table. if it's a new one, add symbols to it.
SymbolTable symbolTable = (SymbolTable)componentManager.getProperty(SYMBOL_TABLE);
if (symbolTable != fSymbolTable) {
XMLNS = symbolTable.addSymbol(SchemaSymbols.O_XMLNS);
URI_XSI = symbolTable.addSymbol(SchemaSymbols.URI_XSI);
XSI_SCHEMALOCATION = symbolTable.addSymbol(SchemaSymbols.OXSI_SCHEMALOCATION);
XSI_NONAMESPACESCHEMALOCATION = symbolTable.addSymbol(SchemaSymbols.OXSI_NONAMESPACESCHEMALOCATION);
XSI_TYPE = symbolTable.addSymbol(SchemaSymbols.OXSI_TYPE);
XSI_NIL = symbolTable.addSymbol(SchemaSymbols.OXSI_NIL);
URI_SCHEMAFORSCHEMA = symbolTable.addSymbol(SchemaSymbols.OURI_SCHEMAFORSCHEMA);
}
fSymbolTable = symbolTable;
// get entity resolver. if there is no one, create a default
// REVISIT: use default entity resolution from ENTITY MANAGER - temporary solution
fEntityResolver = (XMLEntityResolver)componentManager.getProperty(ENTITY_MANAGER);
// initialize namespace support
fNamespaceSupport.reset(fSymbolTable);
fPushForNextBinding = true;
// clear grammars, and put the one for schema namespace there
fGrammarResolver.reset();
fGrammarResolver.putGrammar(URI_SCHEMAFORSCHEMA, SchemaGrammar.SG_SchemaNS);
// reset schema handler and all traversal objects
fSchemaHandler.reset(fErrorReporter, fEntityResolver, fSymbolTable);
// initialize state
fCurrentElemDecl = null;
fNil = false;
fCurrentType = null;
fCurrentCM = null;
fCurrCMState = null;
fBuffer.setLength(0);
fSawCharacters=false;
fSkipValidationDepth = -1;
fElementDepth = -1;
fChildCount = 0;
// clear values stored in id and idref table
fTableOfIDs.clear();
fTableOfIDRefs.clear();
fMatcherStack.clear();
fValueStoreCache = new ValueStoreCache();
} // reset(XMLComponentManager)
/** ensure element stack capacity */
void ensureStackCapacity() {
if (fElementDepth == fElemDeclStack.length) {
int newSize = fElementDepth + INC_STACK_SIZE;
int[] newArrayI = new int[newSize];
System.arraycopy(fChildCountStack, 0, newArrayI, 0, newSize);
fChildCountStack = newArrayI;
XSElementDecl[] newArrayE = new XSElementDecl[newSize];
System.arraycopy(fElemDeclStack, 0, newArrayE, 0, newSize);
fElemDeclStack = newArrayE;
XSTypeDecl[] newArrayT = new XSTypeDecl[newSize];
System.arraycopy(fTypeStack, 0, newArrayT, 0, newSize);
fTypeStack = newArrayT;
XSCMValidator[] newArrayC = new XSCMValidator[newSize];
System.arraycopy(fCMStack, 0, newArrayC, 0, newSize);
fCMStack = newArrayC;
boolean[] newArrayD = new boolean[newSize];
System.arraycopy(fStringContent, 0, newArrayD, 0, newSize);
fStringContent = newArrayD;
int[][] newArrayIA = new int[newSize][];
System.arraycopy(fCMStateStack, 0, newArrayIA, 0, newSize);
fCMStateStack = newArrayIA;
}
} // ensureStackCapacity
// FieldActivator methods
/**
* Start the value scope for the specified identity constraint. This
* method is called when the selector matches in order to initialize
* the value store.
*
* @param identityConstraint The identity constraint.
*/
public void startValueScopeFor(IdentityConstraint identityConstraint)
throws XNIException {
for(int i=0; i<identityConstraint.getFieldCount(); i++) {
Field field = identityConstraint.getFieldAt(i);
ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(field);
valueStore.startValueScope();
}
} // startValueScopeFor(IdentityConstraint identityConstraint)
/**
* Request to activate the specified field. This method returns the
* matcher for the field.
*
* @param field The field to activate.
*/
public XPathMatcher activateField(Field field) throws XNIException {
ValueStore valueStore = fValueStoreCache.getValueStoreFor(field);
field.setMayMatch(true);
XPathMatcher matcher = field.createMatcher(valueStore);
fMatcherStack.addMatcher(matcher);
matcher.startDocumentFragment(fSymbolTable);
return matcher;
} // activateField(Field):XPathMatcher
/**
* Ends the value scope for the specified identity constraint.
*
* @param identityConstraint The identity constraint.
*/
public void endValueScopeFor(IdentityConstraint identityConstraint)
throws XNIException {
ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint);
valueStore.endValueScope();
} // endValueScopeFor(IdentityConstraint)
// a utility method for Idnetity constraints
private void activateSelectorFor(IdentityConstraint ic) throws XNIException {
Selector selector = ic.getSelector();
FieldActivator activator = this;
if(selector == null)
return;
XPathMatcher matcher = selector.createMatcher(activator);
fMatcherStack.addMatcher(matcher);
matcher.startDocumentFragment(fSymbolTable);
}
// Protected methods
/** Handle element. */
void handleStartElement(QName element, XMLAttributes attributes) {
if (DEBUG) {
System.out.println("handleStartElement: " +element);
}
// we receive prefix binding events before this one,
// so at this point, the prefix bindings for this element is done,
// and we need to push context when we receive another prefix binding.
// but if fPushForNextBinding is still true, that means there has
// been no prefix binding for this element. we still need to push
// context, because the context is always popped in end element.
if (fPushForNextBinding)
fNamespaceSupport.pushContext();
else
fPushForNextBinding = true;
// whether to do validation
// REVISIT: consider DynamicValidation
if (fElementDepth == -1) {
fDoValidation = fValidation;
}
// if we are in the content of "skip", then just skip this element
// REVISIT: is this the correct behaviour for ID constraints? -NG
if (fSkipValidationDepth >= 0) {
fElementDepth++;
return;
}
// if it's not the root element, we push the current states in the stacks
if (fElementDepth != -1) {
ensureStackCapacity();
fChildCountStack[fElementDepth] = fChildCount+1;
fChildCount = 0;
fElemDeclStack[fElementDepth] = fCurrentElemDecl;
fNilStack[fElementDepth] = fNil;
fTypeStack[fElementDepth] = fCurrentType;
fCMStack[fElementDepth] = fCurrentCM;
fStringContent[fElementDepth] = fSawCharacters;
}
// get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes,
// parse them to get the grammars
// REVISIT: we'll defer this operation until there is a reference to
// a component from that namespace
String sLocation = attributes.getValue(URI_XSI, XSI_SCHEMALOCATION);
String nsLocation = attributes.getValue(URI_XSI, XSI_NONAMESPACESCHEMALOCATION);
if (sLocation != null) {
StringTokenizer t = new StringTokenizer(sLocation, " \n\t\r");
String namespace, location;
while (t.hasMoreTokens()) {
namespace = t.nextToken ();
if (!t.hasMoreTokens()) {
// REVISIT: report error for wrong number of uris
break;
}
location = t.nextToken();
if (fGrammarResolver.getGrammar(namespace) == null)
fSchemaHandler.parseSchema(namespace, location);
}
}
if (nsLocation != null) {
if (fGrammarResolver.getGrammar(fSchemaHandler.EMPTY_STRING) == null)
fSchemaHandler.parseSchema(fSchemaHandler.EMPTY_STRING, nsLocation);
}
// get the element decl for this element
fCurrentElemDecl = null;
fNil = false;
XSWildcardDecl wildcard = null;
// if there is a content model, then get the decl from that
if (fCurrentCM != null) {
Object decl = fCurrentCM.oneTransition(element, fCurrCMState);
// it could be an element decl or a wildcard decl
// REVISIT: is there a more efficient way than 'instanceof'
if (decl instanceof XSElementDecl) {
fCurrentElemDecl = (XSElementDecl)decl;
} else if (decl instanceof XSWildcardDecl) {
wildcard = (XSWildcardDecl)decl;
} else if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR &&
fDoValidation) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
//REVISIT: is it the only case we will have particle = null?
if (ctype.fParticle != null) {
reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname, ctype.fParticle.toString()});
} else {
reportSchemaError("cvc-complex-type.2.4.a", new Object[]{element.rawname,"mixed with no element content"});
}
fCurrCMState[0] = XSCMValidator.SUBSEQUENT_ERROR;
} else if (decl instanceof XSElementDecl) {
fCurrentElemDecl = (XSElementDecl)decl;
} else if (decl instanceof XSWildcardDecl) {
wildcard = (XSWildcardDecl)decl;
}
}
// save the current content model state in the stack
if (fElementDepth != -1)
fCMStateStack[fElementDepth] = fCurrCMState;
// increase the element depth after we've saved all states for the
// parent element
fElementDepth++;
// if the wildcard is skip, then return
if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.WILDCARD_SKIP) {
fSkipValidationDepth = fElementDepth;
return;
}
// try again to get the element decl
if (fCurrentElemDecl == null) {
SchemaGrammar sGrammar = fGrammarResolver.getGrammar(element.uri);
if (sGrammar != null)
fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart);
}
// Element Locally Valid (Element)
// 2 Its {abstract} must be false.
if (fCurrentElemDecl != null && fCurrentElemDecl.isAbstract())
reportSchemaError("cvc-elt.2", new Object[]{element.rawname});
// get the type for the current element
fCurrentType = null;
if (fCurrentElemDecl != null) {
// then get the type
fCurrentType = fCurrentElemDecl.fType;
}
// get type from xsi:type
String xsiType = attributes.getValue(URI_XSI, XSI_TYPE);
if (xsiType != null)
getAndCheckXsiType(element, xsiType);
// Element Locally Valid (Type)
// 2 Its {abstract} must be false.
if (fCurrentType != null) {
if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
if (ctype.isAbstractType()) {
reportSchemaError("cvc-type.2", new Object[]{"Element " + element.rawname + " is declared with a type that is abstract. Use xsi:type to specify a non-abstract type"});
}
}
}
// if the element decl is not found
if (fCurrentType == null && fDoValidation) {
// if this is the root element, or wildcard = strict, report error
if (fElementDepth == 0) {
// report error, because it's root element
reportSchemaError("cvc-elt.1", new Object[]{element.rawname});
} else if (wildcard != null &&
wildcard.fProcessContents == XSWildcardDecl.WILDCARD_STRICT) {
// report error, because wilcard = strict
reportSchemaError("cvc-complex-type.2.4.c", new Object[]{element.rawname});
}
// no element decl found, have to skip this element
fSkipValidationDepth = fElementDepth;
return;
}
// then try to get the content model
fCurrentCM = null;
if (fCurrentType != null) {
if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0) {
fCurrentCM = ((XSComplexTypeDecl)fCurrentType).getContentModel(fCMBuilder);
}
}
// and get the initial content model state
fCurrCMState = null;
if (fCurrentCM != null)
fCurrCMState = fCurrentCM.startContentModel();
// and the buffer to hold the value of the element
fBuffer.setLength(0);
fSawCharacters = false;
// get information about xsi:nil
String xsiNil = attributes.getValue(URI_XSI, XSI_NIL);
if (xsiNil != null)
getXsiNil(element, xsiNil);
// now validate everything related with the attributes
// first, get the attribute group
XSAttributeGroupDecl attrGrp = null;
if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
attrGrp = ctype.fAttrGrp;
}
processAttributes(element, attributes, attrGrp);
// activate identity constraints
if (fValidation ) {
fValueStoreCache.startElement();
fMatcherStack.pushContext();
if (fCurrentElemDecl != null) {
fValueStoreCache.initValueStoresFor(fCurrentElemDecl);
int icCount = fCurrentElemDecl.fIDCPos;
int uniqueOrKey = 0;
for (;uniqueOrKey < icCount; uniqueOrKey++) {
if(fCurrentElemDecl.fIDConstraints[uniqueOrKey].getType() != IdentityConstraint.KEYREF ) {
activateSelectorFor(fCurrentElemDecl.fIDConstraints[uniqueOrKey]);
} else
break;
}
for (int keyref = uniqueOrKey; keyref < icCount; keyref++) {
activateSelectorFor((IdentityConstraint)fCurrentElemDecl.fIDConstraints[keyref]);
}
}
// call all active identity constraints
int count = fMatcherStack.getMatcherCount();
for (int i = 0; i < count; i++) {
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
matcher.startElement(element, attributes, fGrammarResolver.getGrammar(element.uri));
}
}
} // handleStartElement(QName,XMLAttributes,boolean)
/** Handle end element. */
void handleEndElement(QName element) {
// need to pop context so that the bindings for this element is
// discarded.
fNamespaceSupport.popContext();
// if we are skipping, return
if (fSkipValidationDepth >= 0) {
// but if this is the top element that we are skipping,
// restore the states.
if (fSkipValidationDepth == fElementDepth &&
fSkipValidationDepth > 0) {
fSkipValidationDepth = -1;
fElementDepth
fChildCount = fChildCountStack[fElementDepth];
fCurrentElemDecl = fElemDeclStack[fElementDepth];
fNil = fNilStack[fElementDepth];
fCurrentType = fTypeStack[fElementDepth];
fCurrentCM = fCMStack[fElementDepth];
fCurrCMState = fCMStateStack[fElementDepth];
fSawCharacters = fStringContent[fElementDepth];
} else {
fElementDepth
}
return;
}
// now validate the content of the element
processElementContent(element);
// Element Locally Valid (Element)
// 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4).
// call matchers and de-activate context
int oldCount = fMatcherStack.getMatcherCount();
for (int i = oldCount - 1; i >= 0; i
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
matcher.endElement(element, fCurrentElemDecl, fGrammarResolver.getGrammar(element.uri));
}
if (fMatcherStack.size() > 0) {
fMatcherStack.popContext();
}
int newCount = fMatcherStack.getMatcherCount();
// handle everything *but* keyref's.
for (int i = oldCount - 1; i >= newCount; i
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
IdentityConstraint id;
if((id = matcher.getIDConstraint()) != null && id.getType() != IdentityConstraint.KEYREF) {
matcher.endDocumentFragment();
fValueStoreCache.transplant(id);
} else if (id == null)
matcher.endDocumentFragment();
}
// now handle keyref's/...
for (int i = oldCount - 1; i >= newCount; i
XPathMatcher matcher = fMatcherStack.getMatcherAt(i);
IdentityConstraint id;
if((id = matcher.getIDConstraint()) != null && id.getType() == IdentityConstraint.KEYREF) {
ValueStoreBase values = fValueStoreCache.getValueStoreFor(id);
if(values != null) // nothing to do if nothing matched!
values.endDocumentFragment();
matcher.endDocumentFragment();
}
}
fValueStoreCache.endElement();
// decrease element depth and restore states
fElementDepth
if (fElementDepth == -1) {
if (fDoValidation) {
try {
// 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4).
// REVISIT: how to do it? new simpletype design?
IDREFDatatypeValidator.checkIdRefs(fTableOfIDs, fTableOfIDRefs);
}
catch (InvalidDatatypeValueException ex) {
// REVISIT: put idref value in ex
reportSchemaError("cvc-id.1", new Object[]{ex.getLocalizedMessage()});
}
}
} else {
// get the states for the parent element.
fChildCount = fChildCountStack[fElementDepth];
fCurrentElemDecl = fElemDeclStack[fElementDepth];
fNil = fNilStack[fElementDepth];
fCurrentType = fTypeStack[fElementDepth];
fCurrentCM = fCMStack[fElementDepth];
fCurrCMState = fCMStateStack[fElementDepth];
fSawCharacters = fStringContent[fElementDepth];
}
} // handleEndElement(QName,boolean)*/
void handleStartPrefix(String prefix, String uri) {
// push namespace context if necessary
if (fPushForNextBinding) {
fNamespaceSupport.pushContext();
fPushForNextBinding = false;
}
// add prefix declaration to the namespace support
// REVISIT: should it be null or ""
fNamespaceSupport.declarePrefix(prefix, uri.length() != 0 ? uri : null);
}
void getAndCheckXsiType(QName element, String xsiType) {
// Element Locally Valid (Element)
// 4.1 The normalized value of that attribute information item must be valid with respect to the built-in QName simple type, as defined by String Valid (3.14.4);
QName typeName = null;
try {
// REVISIT: have QNameDV to return QName
//typeName = fQNameDV.validate(xsiType, fNamespaceSupport);
fQNameDV.validate(xsiType, fNamespaceSupport);
String prefix = fSchemaHandler.EMPTY_STRING;
String localpart = xsiType;
int colonptr = xsiType.indexOf(":");
if (colonptr > 0) {
prefix = fSymbolTable.addSymbol(xsiType.substring(0,colonptr));
localpart = xsiType.substring(colonptr+1);
}
// REVISIT: if we take the null approach (instead of ""),
// we need to chech the retrned value from getURI
// to see whether a binding is found.
String uri = fNamespaceSupport.getURI(prefix);
typeName = new QName(prefix, localpart, xsiType, uri);
} catch (InvalidDatatypeValueException e) {
reportSchemaError("cvc-elt.4.1", new Object[]{element.rawname, URI_XSI+","+XSI_TYPE, xsiType});
return;
}
// 4.2 The local name and namespace name (as defined in QName Interpretation (3.15.3)), of the actual value of that attribute information item must resolve to a type definition, as defined in QName resolution (Instance) (3.15.4)
XSTypeDecl type = null;
SchemaGrammar grammar = fGrammarResolver.getGrammar(typeName.uri);
if (grammar != null)
type = grammar.getGlobalTypeDecl(typeName.localpart);
if (type == null) {
reportSchemaError("cvc-elt.4.2", new Object[]{element.rawname, xsiType});
return;
}
// if there is no current type, set this one as current.
// and we don't need to do extra checking
if (fCurrentType != null) {
// 4.3 The local type definition must be validly derived from the {type definition} given the union of the {disallowed substitutions} and the {type definition}'s {prohibited substitutions}, as defined in Type Derivation OK (Complex) (3.4.6) (if it is a complex type definition), or given {disallowed substitutions} as defined in Type Derivation OK (Simple) (3.14.6) (if it is a simple type definition).
int block = fCurrentElemDecl.fBlock;
if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0)
block |= ((XSComplexTypeDecl)fCurrentType).fBlock;
if (!XSConstraints.checkTypeDerivationOk(type, fCurrentType, block))
reportSchemaError("cvc-elt.4.3", new Object[]{element.rawname, xsiType});
}
fCurrentType = type;
}
void getXsiNil(QName element, String xsiNil) {
// Element Locally Valid (Element)
// 3 The appropriate case among the following must be true:
if (fCurrentElemDecl != null && !fCurrentElemDecl.isNillable())
reportSchemaError("cvc-elt.3.1", new Object[]{element.rawname, URI_XSI+","+XSI_NIL});
// 3.2 If {nillable} is true and there is such an attribute information item and its actual value is true , then all of the following must be true:
// 3.2.2 There must be no fixed {value constraint}.
if (xsiNil.equals(SchemaSymbols.ATTVAL_TRUE) ||
xsiNil.equals(SchemaSymbols.ATTVAL_TRUE_1)) {
fNil = true;
if (fCurrentElemDecl != null &&
fCurrentElemDecl.getConstraintType() == XSElementDecl.FIXED_VALUE) {
reportSchemaError("cvc-elt.3.2.2", new Object[]{element.rawname, URI_XSI+","+XSI_NIL});
}
}
}
void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) {
// add default attributes
if (attrGrp != null) {
addDefaultAttributes(element, attributes, attrGrp);
}
// if we don't do validation, we don't need to validate the attributes
if (!fDoValidation)
return;
// Element Locally Valid (Type)
if (fCurrentType == null ||
(fCurrentType.getXSType()&XSTypeDecl.SIMPLE_TYPE) != 0) {
int attCount = attributes.getLength();
for (int index = 0; index < attCount; index++) {
attributes.getName(index, fTempQName);
if (fTempQName.uri == URI_XSI) {
if (fTempQName.localpart != XSI_SCHEMALOCATION &&
fTempQName.localpart != XSI_NONAMESPACESCHEMALOCATION &&
fTempQName.localpart != XSI_NIL &&
fTempQName.localpart != XSI_TYPE) {
reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname});
}
} else if (fTempQName.rawname != XMLNS && !fTempQName.rawname.startsWith("xmlns:")) {
reportSchemaError("cvc-type.3.1.1", new Object[]{element.rawname});
}
}
return;
}
XSAttributeUse attrUses[] = attrGrp.getAttributeUses();
int useCount = attrUses.length;
XSWildcardDecl attrWildcard = attrGrp.fAttributeWC;
// whether we have seen a Wildcard ID.
String wildcardIDName = null;
// for each present attribute
int attCount = attributes.getLength();
// Element Locally Valid (Complex Type)
// get the corresponding attribute decl
for (int index = 0; index < attCount; index++) {
attributes.getName(index, fTempQName);
// if it's from xsi namespace, it must be one of the four
if (fTempQName.uri == URI_XSI) {
if (fTempQName.localpart == XSI_SCHEMALOCATION ||
fTempQName.localpart == XSI_NONAMESPACESCHEMALOCATION ||
fTempQName.localpart == XSI_NIL ||
fTempQName.localpart == XSI_TYPE) {
continue;
}
} else if (fTempQName.rawname == XMLNS || fTempQName.rawname.startsWith("xmlns:")) {
continue;
}
// it's not xmlns, and not xsi, then we need to find a decl for it
XSAttributeUse currUse = null;
for (int i = 0; i < useCount; i++) {
if (attrUses[i].fAttrDecl.fName == fTempQName.localpart &&
attrUses[i].fAttrDecl.fTargetNamespace == fTempQName.uri) {
currUse = attrUses[i];
break;
}
}
// 3.2 otherwise all of the following must be true:
// 3.2.1 There must be an {attribute wildcard}.
// 3.2.2 The attribute information item must be valid with respect to it as defined in Item Valid (Wildcard) (3.10.4).
// if failed, get it from wildcard
if (currUse == null) {
//if (attrWildcard == null)
// reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname});
if (attrWildcard == null ||
!attrWildcard.allowNamespace(fTempQName.uri)) {
// so this attribute is not allowed
reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname});
continue;
}
}
XSAttributeDecl currDecl = null;
if (currUse != null) {
currDecl = currUse.fAttrDecl;
} else {
// which means it matches a wildcard
// skip it if it's skip
if (attrWildcard.fType == XSWildcardDecl.WILDCARD_SKIP)
continue;
// now get the grammar and attribute decl
SchemaGrammar grammar = fGrammarResolver.getGrammar(fTempQName.uri);
if (grammar != null)
currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart);
// if can't find
if (currDecl == null) {
// if strict, report error
if (attrWildcard.fType == XSWildcardDecl.WILDCARD_STRICT)
reportSchemaError("cvc-complex-type.3.2.2", new Object[]{element.rawname, fTempQName.rawname});
// then continue to the next attribute
continue;
} else {
// 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose validation resulted in a context-determined declaration of mustFind or no context-determined declaration at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true:
// 5.1 There must be no more than one item in wild IDs.
if (currDecl.fType instanceof IDDatatypeValidator) {
if (wildcardIDName != null)
reportSchemaError("cvc-complex-type.5.1", new Object[]{element.rawname, currDecl.fName, wildcardIDName});
else
wildcardIDName = currDecl.fName;
}
}
}
// Attribute Locally Valid
// For an attribute information item to be locally valid with respect to an attribute declaration all of the following must be true:
// 1 The declaration must not be absent (see Missing Sub-components (5.3) for how this can fail to be the case).
// 2 Its {type definition} must not be absent.
// 3 The item's normalized value must be locally valid with respect to that {type definition} as per String Valid (3.14.4).
// get simple type
DatatypeValidator attDV = currDecl.fType;
// get attribute value
String attrValue = attributes.getValue(index);
// normalize it
// REVISIT: or should the normalize() be called within validate()?
attrValue = XSAttributeChecker.normalize(attrValue, attDV.getWSFacet());
Object actualValue = null;
try {
// REVISIT: use XSSimpleTypeDecl.ValidateContext to replace null
// actualValue = attDV.validate(attrValue, null);
attDV.validate(attrValue, null);
} catch (InvalidDatatypeValueException idve) {
reportSchemaError("cvc-attribute.3", new Object[]{element.rawname, fTempQName.rawname, attrValue});
}
// get the value constraint from use or decl
// 4 The item's actual value must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType
if (currDecl.fConstraintType == XSAttributeDecl.FIXED_VALUE) {
// REVISIT: compare should be equal, and takes object, instead of string
// do it in the new datatype design
if (attDV.compare((String)actualValue, (String)currDecl.fDefault) != 0)
reportSchemaError("cvc-attribute.4", new Object[]{element.rawname, fTempQName.rawname, attrValue});
}
// 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an absent {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be valid with respect to that attribute use as per Attribute Locally Valid (Use) (3.5.4). In this case the {attribute declaration} of that attribute use is the context-determined declaration for the attribute information item with respect to Schema-Validity Assessment (Attribute) (3.2.4) and Assessment Outcome (Attribute) (3.2.5).
if (currUse != null && currUse.fConstraintType == XSAttributeDecl.FIXED_VALUE) {
// REVISIT: compare should be equal, and takes object, instead of string
// do it in the new datatype design
if (attDV.compare((String)actualValue, (String)currUse.fDefault) != 0)
reportSchemaError("cvc-complex-type.3.1", new Object[]{element.rawname, fTempQName.rawname, attrValue});
}
} // end of for (all attributes)
// 5.2 If wild IDs is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID.
if (attrGrp.fIDAttrName != null && wildcardIDName != null)
reportSchemaError("cvc-complex-type.5.2", new Object[]{element.rawname, wildcardIDName, attrGrp.fIDAttrName});
} //processAttributes
void addDefaultAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) {
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// REVISIT: should we check prohibited attributes?
// (2) report error for PROHIBITED attrs that are present (V_TAGc)
// (3) add default attrs (FIXED and NOT_FIXED)
if (DEBUG) {
System.out.println("addDefaultAttributes: " + element);
}
XSAttributeUse attrUses[] = attrGrp.getAttributeUses();
int useCount = attrUses.length;
XSAttributeUse currUse;
XSAttributeDecl currDecl;
short constType;
Object defaultValue;
boolean isSpecified;
QName attName;
// for each attribute use
for (int i = 0; i < useCount; i++) {
currUse = attrUses[i];
currDecl = currUse.fAttrDecl;
// get value constraint
constType = currUse.fConstraintType;
defaultValue = currUse.fDefault;
if (constType == XSAttributeDecl.NO_CONSTRAINT) {
constType = currDecl.fConstraintType;
defaultValue = currDecl.fDefault;
}
// whether this attribute is specified
isSpecified = attributes.getValue(currDecl.fTargetNamespace, currDecl.fName) != null;
// Element Locally Valid (Complex Type)
// 4 The {attribute declaration} of each attribute use in the {attribute uses} whose {required} is true matches one of the attribute information items in the element information item's [attributes] as per clause 3.1 above.
if (currUse.fUse == SchemaSymbols.USE_REQUIRED) {
if (!isSpecified)
reportSchemaError("cvc-complex-type.4", new Object[]{element.rawname, currDecl.fName});
}
// if the attribute is not specified, then apply the value constraint
if (!isSpecified && constType != XSAttributeDecl.NO_CONSTRAINT) {
attName = new QName(null, currDecl.fName, currDecl.fName, currDecl.fTargetNamespace);
//REVISIT: what's the proper attrType?
attributes.addAttribute(attName, null, (defaultValue !=null)?defaultValue.toString():"");
}
} // for
} // addDefaultAttributes
void processElementContent(QName element) {
// fCurrentElemDecl: default value; ...
if(fCurrentElemDecl != null) {
if(fCurrentElemDecl.fDefault != null) {
if(fBuffer.toString().trim().length() == 0) {
if(fDocumentHandler != null) {
int bufLen = fCurrentElemDecl.fDefault.toString().length();
char [] chars = new char[bufLen];
fCurrentElemDecl.fDefault.toString().getChars(0, bufLen, chars, 0);
fDocumentHandler.characters(new XMLString(chars, 0, bufLen));
}
}
}
}
// fixed values are handled later, after xsi:type determined.
if (DEBUG) {
System.out.println("processElementContent:" +element);
}
if (fCurrentElemDecl != null &&
fCurrentElemDecl.getConstraintType() == XSElementDecl.DEFAULT_VALUE) {
}
if (fDoValidation) {
String content = fBuffer.toString();
// Element Locally Valid (Element)
// 3.2.1 The element information item must have no character or element information item [children].
if (fNil) {
if (fChildCount != 0 || content.length() != 0)
reportSchemaError("cvc-elt.3.2.1", new Object[]{element.rawname, URI_XSI+","+XSI_NIL});
}
// 5 The appropriate case among the following must be true:
// 5.1 If the declaration has a {value constraint}, the item has neither element nor character [children] and clause 3.2 has not applied, then all of the following must be true:
if (fCurrentElemDecl != null &&
fCurrentElemDecl.getConstraintType() != XSElementDecl.NO_CONSTRAINT &&
fChildCount == 0 && content.length() == 0 && !fNil) {
// 5.1.1 If the actual type definition is a local type definition then the canonical lexical representation of the {value constraint} value must be a valid default for the actual type definition as defined in Element Default Valid (Immediate) (3.3.6).
if (fCurrentType != fCurrentElemDecl.fType) {
if (!XSConstraints.ElementDefaultValidImmediate(fCurrentType, fCurrentElemDecl.fDefault.toString()))
reportSchemaError("cvc-elt.5.1.1", new Object[]{element.rawname, fCurrentType.getXSTypeName(), fCurrentElemDecl.fDefault.toString()});
}
// 5.1.2 The element information item with the canonical lexical representation of the {value constraint} value used as its normalized value must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4).
elementLocallyValidType(element, fCurrentElemDecl.fDefault.toString());
} else {
// 5.2 If the declaration has no {value constraint} or the item has either element or character [children] or clause 3.2 has applied, then all of the following must be true:
// 5.2.1 The element information item must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4).
Object actualValue = elementLocallyValidType(element, content);
// 5.2.2 If there is a fixed {value constraint} and clause 3.2 has not applied, all of the following must be true:
if (fCurrentElemDecl != null &&
fCurrentElemDecl.getConstraintType() == XSElementDecl.FIXED_VALUE &&
!fNil) {
// 5.2.2.1 The element information item must have no element information item [children].
if (fChildCount != 0)
reportSchemaError("cvc-elt.5.2.2.1", new Object[]{element.rawname});
// 5.2.2.2 The appropriate case among the following must be true:
if ((fCurrentType.getXSType() & XSTypeDecl.COMPLEX_TYPE) != 0) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
// 5.2.2.2.1 If the {content type} of the actual type definition is mixed, then the initial value of the item must match the canonical lexical representation of the {value constraint} value.
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) {
// REVISIT: how to get the initial value, does whiteSpace count?
if (!fCurrentElemDecl.fDefault.toString().equals(content))
reportSchemaError("cvc-elt.5.2.2.2.1", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.toString()});
}
// 5.2.2.2.2 If the {content type} of the actual type definition is a simple type definition, then the actual value of the item must match the canonical lexical representation of the {value constraint} value.
else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) {
// REVISIT: compare should be equal, and takes object, instead of string
// do it in the new datatype design
if (ctype.fDatatypeValidator.compare((String)actualValue, (String)fCurrentElemDecl.fDefault) != 0)
reportSchemaError("cvc-elt.5.2.2.2.2", new Object[]{element.rawname, content, fCurrentElemDecl.fDefault.toString()});
}
}
}
}
} // if fDoValidation
} // processElementContent
Object elementLocallyValidType(QName element, String textContent) {
if (fCurrentType == null)
return null;
Object retValue = null;
// Element Locally Valid (Type)
// 3 The appropriate case among the following must be true:
// 3.1 If the type definition is a simple type definition, then all of the following must be true:
if ((fCurrentType.getXSType() & XSTypeDecl.SIMPLE_TYPE) != 0) {
// 3.1.2 The element information item must have no element information item [children].
if (fChildCount != 0)
reportSchemaError("cvc-type.3.1.2", new Object[]{element.rawname});
// 3.1.3 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the normalized value must be valid with respect to the type definition as defined by String Valid (3.14.4).
if (!fNil) {
DatatypeValidator dv = (DatatypeValidator)fCurrentType;
// REVISIT: or should the normalize() be called within validate()?
String content = XSAttributeChecker.normalize(textContent, dv.getWSFacet());
try {
// REVISIT: use XSSimpleTypeDecl.ValidateContext to replace null
// retValue = dv.validate(content, null);
dv.validate(content, null);
} catch (InvalidDatatypeValueException e) {
reportSchemaError("cvc-type.3.1.3", new Object[]{element.rawname, content});
}
}
} else {
// 3.2 If the type definition is a complex type definition, then the element information item must be valid with respect to the type definition as per Element Locally Valid (Complex Type) (3.4.4);
elementLocallyValidComplexType(element, textContent);
}
return retValue;
} // elementLocallyValidType
void elementLocallyValidComplexType(QName element, String textContent) {
XSComplexTypeDecl ctype = (XSComplexTypeDecl)fCurrentType;
// Element Locally Valid (Complex Type)
// For an element information item to be locally valid with respect to a complex type definition all of the following must be true:
// 1 {abstract} is false.
// 2 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the appropriate case among the following must be true:
if (!fNil) {
// 2.1 If the {content type} is empty, then the element information item has no character or element information item [children].
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY &&
(fChildCount != 0 || textContent.length() != 0)) {
reportSchemaError("cvc-complex-type.2.1", new Object[]{element.rawname});
}
// 2.2 If the {content type} is a simple type definition, then the element information item has no element information item [children], and the normalized value of the element information item is valid with respect to that simple type definition as defined by String Valid (3.14.4).
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) {
if (fChildCount != 0)
reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname});
DatatypeValidator dv = ctype.fDatatypeValidator;
// REVISIT: or should the normalize() be called within validate()?
String content = XSAttributeChecker.normalize(textContent, dv.getWSFacet());
try {
// REVISIT: use XSSimpleTypeDecl.ValidateContext to replace null
dv.validate(content, null);
} catch (InvalidDatatypeValueException e) {
reportSchemaError("cvc-complex-type.2.2", new Object[]{element.rawname});
}
}
// 2.3 If the {content type} is element-only, then the element information item has no character information item [children] other than those whose [character code] is defined as a white space in [XML 1.0 (Second Edition)].
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) {
// REVISIT: how to check whether there is any text content?
if (fSawCharacters) {
reportSchemaError("cvc-complex-type.2.3", new Object[]{element.rawname});
}
}
// 2.4 If the {content type} is element-only or mixed, then the sequence of the element information item's element information item [children], if any, taken in order, is valid with respect to the {content type}'s particle, as defined in Element Sequence Locally Valid (Particle) (3.9.4).
if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT ||
ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) {
// if the current state is a valid state, check whether
// it's one of the final states.
if (DEBUG) {
System.out.println(fCurrCMState);
}
if (fCurrCMState[0] >= 0 &&
!fCurrentCM.endContentModel(fCurrCMState)) {
reportSchemaError("cvc-complex-type.2.4.b", new Object[]{element.rawname, ctype.fParticle.toString()});
}
}
}
} // elementLocallyValidComplexType
void reportSchemaError(String key, Object[] arguments) {
if (fDoValidation)
fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN,
key, arguments,
XMLErrorReporter.SEVERITY_ERROR);
}
// xpath matcher information
/**
* Stack of XPath matchers for identity constraints.
*
* @author Andy Clark, IBM
*/
protected static class XPathMatcherStack {
// Data
/** Active matchers. */
protected XPathMatcher[] fMatchers = new XPathMatcher[4];
/** Count of active matchers. */
protected int fMatchersCount;
/** Offset stack for contexts. */
protected IntStack fContextStack = new IntStack();
// Constructors
public XPathMatcherStack() {
} // <init>()
// Public methods
/** Resets the XPath matcher stack. */
public void clear() {
for (int i = 0; i < fMatchersCount; i++) {
fMatchers[i] = null;
}
fMatchersCount = 0;
fContextStack.clear();
} // clear()
/** Returns the size of the stack. */
public int size() {
return fContextStack.size();
} // size():int
/** Returns the count of XPath matchers. */
public int getMatcherCount() {
return fMatchersCount;
} // getMatcherCount():int
/** Adds a matcher. */
public void addMatcher(XPathMatcher matcher) {
ensureMatcherCapacity();
fMatchers[fMatchersCount++] = matcher;
} // addMatcher(XPathMatcher)
/** Returns the XPath matcher at the specified index. */
public XPathMatcher getMatcherAt(int index) {
return fMatchers[index];
} // getMatcherAt(index):XPathMatcher
/** Pushes a new context onto the stack. */
public void pushContext() {
fContextStack.push(fMatchersCount);
} // pushContext()
/** Pops a context off of the stack. */
public void popContext() {
fMatchersCount = fContextStack.pop();
} // popContext()
// Private methods
/** Ensures the size of the matchers array. */
private void ensureMatcherCapacity() {
if (fMatchersCount == fMatchers.length) {
XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2];
System.arraycopy(fMatchers, 0, array, 0, fMatchers.length);
fMatchers = array;
}
} // ensureMatcherCapacity()
} // class XPathMatcherStack
// value store implementations
/**
* Value store implementation base class. There are specific subclasses
* for handling unique, key, and keyref.
*
* @author Andy Clark, IBM
*/
protected abstract class ValueStoreBase
implements ValueStore {
// Constants
/** Not a value (Unicode: #FFFF). */
protected IDValue NOT_AN_IDVALUE = new IDValue("\uFFFF", null);
// Data
/** Identity constraint. */
protected IdentityConstraint fIdentityConstraint;
/** Current data values. */
protected final OrderedHashtable fValues = new OrderedHashtable();
/** Current data value count. */
protected int fValuesCount;
/** Data value tuples. */
protected final Vector fValueTuples = new Vector();
// Constructors
/** Constructs a value store for the specified identity constraint. */
protected ValueStoreBase(IdentityConstraint identityConstraint) {
fIdentityConstraint = identityConstraint;
} // <init>(IdentityConstraint)
// Public methods
// destroys this ValueStore; useful when, for instance, a
// locally-scoped ID constraint is involved.
public void destroy() {
fValuesCount = 0;
fValues.clear();
fValueTuples.removeAllElements();
} // end destroy():void
// appends the contents of one ValueStore to those of us.
public void append(ValueStoreBase newVal) {
for (int i = 0; i < newVal.fValueTuples.size(); i++) {
OrderedHashtable o = (OrderedHashtable)newVal.fValueTuples.elementAt(i);
if (!contains(o))
fValueTuples.addElement(o);
}
} // append(ValueStoreBase)
/** Start scope for value store. */
public void startValueScope() throws XNIException {
fValuesCount = 0;
int count = fIdentityConstraint.getFieldCount();
for (int i = 0; i < count; i++) {
fValues.put(fIdentityConstraint.getFieldAt(i), NOT_AN_IDVALUE);
}
} // startValueScope()
/** Ends scope for value store. */
public void endValueScope() throws XNIException {
// is there anything to do?
// REVISIT: This check solves the problem with field matchers
// that get activated because they are at the same
// level as the declaring element (e.g. selector xpath
// is ".") but never match.
// However, this doesn't help us catch the problem
// when we expect a field value but never see it. A
// better solution has to be found. -Ac
// REVISIT: Is this a problem? -Ac
// Yes - NG
if (fValuesCount == 0) {
if(fIdentityConstraint.getType() == IdentityConstraint.KEY) {
String code = "AbsentKeyValue";
String eName = fIdentityConstraint.getElementName();
reportSchemaError(code, new Object[]{eName});
}
return;
}
// do we have enough values?
if (fValuesCount != fIdentityConstraint.getFieldCount()) {
switch (fIdentityConstraint.getType()) {
case IdentityConstraint.UNIQUE: {
String code = "UniqueNotEnoughValues";
String ename = fIdentityConstraint.getElementName();
reportSchemaError(code, new Object[]{ename});
break;
}
case IdentityConstraint.KEY: {
String code = "KeyNotEnoughValues";
UniqueOrKey key = (UniqueOrKey)fIdentityConstraint;
String ename = fIdentityConstraint.getElementName();
String kname = key.getIdentityConstraintName();
reportSchemaError(code, new Object[]{ename,kname});
break;
}
case IdentityConstraint.KEYREF: {
String code = "KeyRefNotEnoughValues";
KeyRef keyref = (KeyRef)fIdentityConstraint;
String ename = fIdentityConstraint.getElementName();
String kname = (keyref.getKey()).getIdentityConstraintName();
reportSchemaError(code, new Object[]{ename,kname});
break;
}
}
return;
}
} // endValueScope()
// This is needed to allow keyref's to look for matched keys
// in the correct scope. Unique and Key may also need to
// override this method for purposes of their own.
// This method is called whenever the DocumentFragment
// of an ID Constraint goes out of scope.
public void endDocumentFragment() throws XNIException {
} // endDocumentFragment():void
/**
* Signals the end of the document. This is where the specific
* instances of value stores can verify the integrity of the
* identity constraints.
*/
public void endDocument() throws XNIException {
} // endDocument()
// ValueStore methods
/* reports an error if an element is matched
* has nillable true and is matched by a key.
*/
public void reportNilError(IdentityConstraint id) {
if(id.getType() == IdentityConstraint.KEY) {
String code = "KeyMatchesNillable";
reportSchemaError(code, new Object[]{id.getElementName()});
}
} // reportNilError
/**
* Adds the specified value to the value store.
*
* @param value The value to add.
* @param field The field associated to the value. This reference
* is used to ensure that each field only adds a value
* once within a selection scope.
*/
public void addValue(Field field, IDValue value) {
if(!field.mayMatch()) {
String code = "FieldMultipleMatch";
reportSchemaError(code, new Object[]{field.toString()});
}
// do we even know this field?
int index = fValues.indexOf(field);
if (index == -1) {
String code = "UnknownField";
reportSchemaError(code, new Object[]{field.toString()});
return;
}
// store value
IDValue storedValue = fValues.valueAt(index);
if (storedValue.isDuplicateOf(NOT_AN_IDVALUE)) {
fValuesCount++;
}
fValues.put(field, value);
if (fValuesCount == fValues.size()) {
// is this value as a group duplicated?
if (contains(fValues)) {
duplicateValue(fValues);
}
// store values
OrderedHashtable values = (OrderedHashtable)fValues.clone();
fValueTuples.addElement(values);
}
} // addValue(String,Field)
/**
* Returns true if this value store contains the specified
* values tuple.
*/
public boolean contains(OrderedHashtable tuple) {
// do sizes match?
int tcount = tuple.size();
// iterate over tuples to find it
int count = fValueTuples.size();
LOOP: for (int i = 0; i < count; i++) {
OrderedHashtable vtuple = (OrderedHashtable)fValueTuples.elementAt(i);
// compare values
for (int j = 0; j < tcount; j++) {
IDValue value1 = vtuple.valueAt(j);
IDValue value2 = tuple.valueAt(j);
if(!(value1.isDuplicateOf(value2))) {
continue LOOP;
}
}
// found it
return true;
}
// didn't find it
return false;
} // contains(Hashtable):boolean
// Protected methods
/**
* Called when a duplicate value is added. Subclasses should override
* this method to perform error checking.
*
* @param tuple The duplicate value tuple.
*/
protected void duplicateValue(OrderedHashtable tuple)
throws XNIException {
// no-op
} // duplicateValue(Hashtable)
/** Returns a string of the specified values. */
protected String toString(OrderedHashtable tuple) {
// no values
int size = tuple.size();
if (size == 0) {
return "";
}
// construct value string
StringBuffer str = new StringBuffer();
for (int i = 0; i < size; i++) {
if (i > 0) {
str.append(',');
}
str.append(tuple.valueAt(i));
}
return str.toString();
} // toString(OrderedHashtable):String
// Object methods
/** Returns a string representation of this object. */
public String toString() {
String s = super.toString();
int index1 = s.lastIndexOf('$');
if (index1 != -1) {
s = s.substring(index1 + 1);
}
int index2 = s.lastIndexOf('.');
if (index2 != -1) {
s = s.substring(index2 + 1);
}
return s + '[' + fIdentityConstraint + ']';
} // toString():String
} // class ValueStoreBase
/**
* Unique value store.
*
* @author Andy Clark, IBM
*/
protected class UniqueValueStore
extends ValueStoreBase {
// Constructors
/** Constructs a unique value store. */
public UniqueValueStore(UniqueOrKey unique) {
super(unique);
} // <init>(Unique)
// ValueStoreBase protected methods
/**
* Called when a duplicate value is added.
*
* @param tuple The duplicate value tuple.
*/
protected void duplicateValue(OrderedHashtable tuple)
throws XNIException {
String code = "DuplicateUnique";
String value = toString(tuple);
String ename = fIdentityConstraint.getElementName();
reportSchemaError(code, new Object[]{value,ename});
} // duplicateValue(Hashtable)
} // class UniqueValueStore
/**
* Key value store.
*
* @author Andy Clark, IBM
*/
protected class KeyValueStore
extends ValueStoreBase {
// REVISIT: Implement a more efficient storage mechanism. -Ac
// Constructors
/** Constructs a key value store. */
public KeyValueStore(UniqueOrKey key) {
super(key);
} // <init>(Key)
// ValueStoreBase protected methods
/**
* Called when a duplicate value is added.
*
* @param tuple The duplicate value tuple.
*/
protected void duplicateValue(OrderedHashtable tuple)
throws XNIException {
String code = "DuplicateKey";
String value = toString(tuple);
String ename = fIdentityConstraint.getElementName();
reportSchemaError(code, new Object[]{value,ename});
} // duplicateValue(Hashtable)
} // class KeyValueStore
/**
* Key reference value store.
*
* @author Andy Clark, IBM
*/
protected class KeyRefValueStore
extends ValueStoreBase {
// Data
/** Key value store. */
protected ValueStoreBase fKeyValueStore;
// Constructors
/** Constructs a key value store. */
public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore) {
super(keyRef);
fKeyValueStore = keyValueStore;
} // <init>(KeyRef)
// ValueStoreBase methods
// end the value Scope; here's where we have to tie
// up keyRef loose ends.
public void endDocumentFragment () throws XNIException {
// do all the necessary management...
super.endDocumentFragment ();
// verify references
// get the key store corresponding (if it exists):
fKeyValueStore = (ValueStoreBase)fValueStoreCache.fGlobalIDConstraintMap.get(((KeyRef)fIdentityConstraint).getKey());
if(fKeyValueStore == null) {
// report error
String code = "KeyRefOutOfScope";
String value = fIdentityConstraint.toString();
reportSchemaError(code, new Object[]{value});
return;
}
int count = fValueTuples.size();
for (int i = 0; i < count; i++) {
OrderedHashtable values = (OrderedHashtable)fValueTuples.elementAt(i);
if (!fKeyValueStore.contains(values)) {
String code = "KeyNotFound";
String value = toString(values);
String element = fIdentityConstraint.getElementName();
reportSchemaError(code, new Object[]{value,element});
}
}
} // endDocumentFragment()
/** End document. */
public void endDocument() throws XNIException {
super.endDocument();
} // endDocument()
} // class KeyRefValueStore
// value store management
/**
* Value store cache. This class is used to store the values for
* identity constraints.
*
* @author Andy Clark, IBM
*/
protected class ValueStoreCache {
// Data
// values stores
/** stores all global Values stores. */
protected final Vector fValueStores = new Vector();
/** Values stores associated to specific identity constraints. */
protected final Hashtable fIdentityConstraint2ValueStoreMap = new Hashtable();
// sketch of algorithm:
// - when a constraint is first encountered, its
// values are stored in the (local) fIdentityConstraint2ValueStoreMap;
// - Once it is validated (i.e., wen it goes out of scope),
// its values are merged into the fGlobalIDConstraintMap;
// - as we encounter keyref's, we look at the global table to
// validate them.
// the fGlobalIDMapStack has the following structure:
// - validation always occurs against the fGlobalIDConstraintMap
// (which comprises all the "eligible" id constraints);
// When an endelement is found, this Hashtable is merged with the one
// below in the stack.
// When a start tag is encountered, we create a new
// fGlobalIDConstraintMap.
// i.e., the top of the fGlobalIDMapStack always contains
// the preceding siblings' eligible id constraints;
// the fGlobalIDConstraintMap contains descendants+self.
// keyrefs can only match descendants+self.
protected final Stack fGlobalMapStack = new Stack();
protected final Hashtable fGlobalIDConstraintMap = new Hashtable();
// Constructors
/** Default constructor. */
public ValueStoreCache() {
} // <init>()
// Public methods
/** Resets the identity constraint cache. */
public void startDocument() throws XNIException {
fValueStores.removeAllElements();
fIdentityConstraint2ValueStoreMap.clear();
fGlobalIDConstraintMap.clear();
fGlobalMapStack.removeAllElements();
} // startDocument()
// startElement: pushes the current fGlobalIDConstraintMap
// onto fGlobalMapStack and clears fGlobalIDConstraint map.
public void startElement() {
fGlobalMapStack.push(fGlobalIDConstraintMap.clone());
fGlobalIDConstraintMap.clear();
} // startElement(void)
// endElement(): merges contents of fGlobalIDConstraintMap with the
// top of fGlobalMapStack into fGlobalIDConstraintMap.
public void endElement() {
if (fGlobalMapStack.isEmpty()) return; // must be an invalid doc!
Hashtable oldMap = (Hashtable)fGlobalMapStack.pop();
Enumeration keys = oldMap.keys();
while(keys.hasMoreElements()) {
IdentityConstraint id = (IdentityConstraint)keys.nextElement();
ValueStoreBase oldVal = (ValueStoreBase)oldMap.get(id);
if(oldVal != null) {
ValueStoreBase currVal = (ValueStoreBase)fGlobalIDConstraintMap.get(id);
if (currVal == null)
fGlobalIDConstraintMap.put(id, oldVal);
else {
currVal.append(oldVal);
fGlobalIDConstraintMap.put(id, currVal);
}
}
}
} // endElement()
/**
* Initializes the value stores for the specified element
* declaration.
*/
public void initValueStoresFor(XSElementDecl eDecl)
throws XNIException {
// initialize value stores for unique fields
IdentityConstraint [] icArray = eDecl.fIDConstraints;
int icCount = eDecl.fIDCPos;
for (int i = 0; i < icCount; i++) {
switch (icArray[i].getType()) {
case (IdentityConstraint.UNIQUE):
// initialize value stores for unique fields
UniqueOrKey unique = (UniqueOrKey)icArray[i];
UniqueValueStore uniqueValueStore = (UniqueValueStore)fIdentityConstraint2ValueStoreMap.get(unique);
if (uniqueValueStore != null) {
// NOTE: If already initialized, don't need to
// do it again. -Ac
continue;
}
uniqueValueStore = new UniqueValueStore(unique);
fValueStores.addElement(uniqueValueStore);
fIdentityConstraint2ValueStoreMap.put(unique, uniqueValueStore);
break;
case (IdentityConstraint.KEY):
// initialize value stores for key fields
UniqueOrKey key = (UniqueOrKey)icArray[i];
KeyValueStore keyValueStore = (KeyValueStore)fIdentityConstraint2ValueStoreMap.get(key);
if (keyValueStore != null) {
// NOTE: If already initialized, don't need to
// do it again. -Ac
continue;
}
keyValueStore = new KeyValueStore(key);
fValueStores.addElement(keyValueStore);
fIdentityConstraint2ValueStoreMap.put(key, keyValueStore);
break;
case (IdentityConstraint.KEYREF):
// initialize value stores for key reference fields
KeyRef keyRef = (KeyRef)icArray[i];
KeyRefValueStore keyRefValueStore = (KeyRefValueStore)fIdentityConstraint2ValueStoreMap.get(keyRef);
if (keyRefValueStore != null) {
// NOTE: If already initialized, don't need to
// do it again. -Ac
continue;
}
keyRefValueStore = new KeyRefValueStore(keyRef, null);
fValueStores.addElement(keyRefValueStore);
fIdentityConstraint2ValueStoreMap.put(keyRef, keyRefValueStore);
break;
}
}
} // initValueStoresFor(XSElementDecl)
/** Returns the value store associated to the specified field. */
public ValueStoreBase getValueStoreFor(Field field) {
IdentityConstraint identityConstraint = field.getIdentityConstraint();
return (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(identityConstraint);
} // getValueStoreFor(Field):ValueStoreBase
/** Returns the value store associated to the specified IdentityConstraint. */
public ValueStoreBase getValueStoreFor(IdentityConstraint id) {
return (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id);
} // getValueStoreFor(IdentityConstraint):ValueStoreBase
/** Returns the global value store associated to the specified IdentityConstraint. */
public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) {
return (ValueStoreBase)fGlobalIDConstraintMap.get(id);
} // getValueStoreFor(IdentityConstraint):ValueStoreBase
// This method takes the contents of the (local) ValueStore
// associated with id and moves them into the global
// hashtable, if id is a <unique> or a <key>.
// If it's a <keyRef>, then we leave it for later.
public void transplant(IdentityConstraint id) {
if (id.getType() == IdentityConstraint.KEYREF ) return;
ValueStoreBase newVals = (ValueStoreBase)fIdentityConstraint2ValueStoreMap.get(id);
fIdentityConstraint2ValueStoreMap.remove(id);
ValueStoreBase currVals = (ValueStoreBase)fGlobalIDConstraintMap.get(id);
if (currVals != null) {
currVals.append(newVals);
fGlobalIDConstraintMap.put(id, currVals);
} else
fGlobalIDConstraintMap.put(id, newVals);
} // transplant(id)
/** Check identity constraints. */
public void endDocument() throws XNIException {
int count = fValueStores.size();
for (int i = 0; i < count; i++) {
ValueStoreBase valueStore = (ValueStoreBase)fValueStores.elementAt(i);
valueStore.endDocument();
}
} // endDocument()
// Object methods
/** Returns a string representation of this object. */
public String toString() {
String s = super.toString();
int index1 = s.lastIndexOf('$');
if (index1 != -1) {
return s.substring(index1 + 1);
}
int index2 = s.lastIndexOf('.');
if (index2 != -1) {
return s.substring(index2 + 1);
}
return s;
} // toString():String
} // class ValueStoreCache
// utility classes
/**
* Ordered hashtable. This class acts as a hashtable with
* <code>put()</code> and <code>get()</code> operations but also
* allows values to be queried via the order that they were
* added to the hashtable.
* <p>
* <strong>Note:</strong> This class does not perform any error
* checking.
* <p>
* <strong>Note:</strong> This class is <em>not</em> efficient but
* is assumed to be used for a very small set of values.
*
* @author Andy Clark, IBM
*/
static final class OrderedHashtable
implements Cloneable {
// Data
/** Size. */
private int fSize;
/** Hashtable entries. */
private Entry[] fEntries = null;
// Public methods
/** Returns the number of entries in the hashtable. */
public int size() {
return fSize;
} // size():int
/** Puts an entry into the hashtable. */
public void put(Field key, IDValue value) {
int index = indexOf(key);
if (index == -1) {
ensureCapacity(fSize);
index = fSize++;
fEntries[index].key = key;
}
fEntries[index].value = value;
} // put(Field,String)
/** Returns the value associated to the specified key. */
public IDValue get(Field key) {
return fEntries[indexOf(key)].value;
} // get(Field):String
/** Returns the index of the entry with the specified key. */
public int indexOf(Field key) {
for (int i = 0; i < fSize; i++) {
// NOTE: Only way to be sure that the keys are the
// same is by using a reference comparison. In
// order to rely on the equals method, each
// field would have to take into account its
// position in the identity constraint, the
// identity constraint, the declaring element,
// and the grammar that it is defined in.
// Otherwise, you have the possibility that
// the equals method would return true for two
// fields that look *very* similar.
// The reference compare isn't bad, actually,
// because the field objects are cacheable. -Ac
if (fEntries[i].key == key) {
return i;
}
}
return -1;
} // indexOf(Field):int
/** Returns the key at the specified index. */
public Field keyAt(int index) {
return fEntries[index].key;
} // keyAt(int):Field
/** Returns the value at the specified index. */
public IDValue valueAt(int index) {
return fEntries[index].value;
} // valueAt(int):String
/** Removes all of the entries from the hashtable. */
public void clear() {
fSize = 0;
} // clear()
// Private methods
/** Ensures the capacity of the entries array. */
private void ensureCapacity(int size) {
// sizes
int osize = -1;
int nsize = -1;
// create array
if (fEntries == null) {
osize = 0;
nsize = 2;
fEntries = new Entry[nsize];
}
// resize array
else if (fEntries.length <= size) {
osize = fEntries.length;
nsize = 2 * osize;
Entry[] array = new Entry[nsize];
System.arraycopy(fEntries, 0, array, 0, osize);
fEntries = array;
}
// create new entries
for (int i = osize; i < nsize; i++) {
fEntries[i] = new Entry();
}
} // ensureCapacity(int)
// Cloneable methods
/** Clones this object. */
public Object clone() {
OrderedHashtable hashtable = new OrderedHashtable();
for (int i = 0; i < fSize; i++) {
hashtable.put(fEntries[i].key, fEntries[i].value);
}
return hashtable;
} // clone():Object
// Object methods
/** Returns a string representation of this object. */
public String toString() {
if (fSize == 0) {
return "[]";
}
StringBuffer str = new StringBuffer();
str.append('[');
for (int i = 0; i < fSize; i++) {
if (i > 0) {
str.append(',');
}
str.append('{');
str.append(fEntries[i].key);
str.append(',');
str.append(fEntries[i].value);
str.append('}');
}
str.append(']');
return str.toString();
} // toString():String
// Classes
/**
* Hashtable entry.
*/
public static final class Entry {
// Data
/** Key. */
public Field key;
/** Value. */
public IDValue value;
} // class Entry
} // class OrderedHashtable
} // class SchemaValidator
|
package org.clapper.curn.output;
import org.clapper.curn.util.Util;
import org.clapper.curn.ConfigFile;
import org.clapper.curn.ConfiguredOutputHandler;
import org.clapper.curn.CurnException;
import org.clapper.curn.FeedInfo;
import org.clapper.curn.OutputHandler;
import org.clapper.curn.parser.RSSChannel;
import org.clapper.curn.parser.RSSItem;
import org.clapper.util.io.WordWrapWriter;
import org.clapper.util.text.HTMLUtil;
import org.clapper.util.text.Unicode;
import org.clapper.util.misc.Logger;
import org.clapper.util.config.ConfigurationException;
import org.clapper.util.config.NoSuchSectionException;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.File;
import java.io.FileNotFoundException;
/**
* <p><tt>FileOutputHandler</tt> is an abstract base class for
* <tt>OutputHandler</tt> subclasses that write RSS feed summaries to a
* file. It consolidates common logic and configuration handling for such
* classes, providing both consistent implementation and configuration.
* It handles two additional output handler-specific configuration items:</p>
*
* <ul>
* <li><tt>SaveAs</tt> takes a file name argument and specifies a file
* where the handler should save its output permanently. It's useful
* if the user wants to keep a copy of the output the handler generates,
* in addition to having the output reported by <i>curn</i>.
* <li><tt>SaveOnly</tt> instructs the handler to save the output in the
* <tt>SaveAs</tt> file, but not report the output to <i>curn</i>.
* From <i>curn</i>'s perspective, the handler generates no output
* at all.
* </ul>
*
* @see OutputHandler
* @see org.clapper.curn.Curn
* @see org.clapper.curn.parser.RSSChannel
*
* @version <tt>$Revision$</tt>
*/
public abstract class FileOutputHandler implements OutputHandler
{
private File outputFile = null;
private ConfigFile config = null;
private boolean saveOnly = false;
private String name = null;
/**
* For logging
*/
private Logger log = null;
/**
* Construct a new <tt>FileOutputHandler</tt>
*/
public FileOutputHandler()
{
}
/**
* Initializes the output handler for another set of RSS channels.
*
* @param config the parsed <i>curn</i> configuration data
* @param cfgHandler the <tt>ConfiguredOutputHandler</tt> wrapper
* containing this object; the wrapper has some useful
* metadata, such as the object's configuration section
* name and extra variables.
*
* @throws ConfigurationException configuration error
* @throws CurnException some other initialization error
*/
public final void init (ConfigFile config,
ConfiguredOutputHandler cfgHandler)
throws ConfigurationException,
CurnException
{
String saveAs = null;
String sectionName = null;
this.config = config;
sectionName = cfgHandler.getSectionName();
this.name = sectionName;
log = new Logger (FileOutputHandler.class.getName()
+ "["
+ name
+ "]");
try
{
if (sectionName != null)
{
saveAs = config.getOptionalStringValue (sectionName,
"SaveAs",
null);
saveOnly = config.getOptionalBooleanValue (sectionName,
"SaveOnly",
false);
if (saveOnly && (saveAs == null))
{
throw new ConfigurationException (sectionName,
"SaveOnly can only be "
+ "specified if SaveAs "
+ "is defined.");
}
}
}
catch (NoSuchSectionException ex)
{
throw new ConfigurationException (ex);
}
if (saveAs != null)
outputFile = new File (saveAs);
else
{
try
{
outputFile = File.createTempFile ("curn", null);
outputFile.deleteOnExit();
}
catch (IOException ex)
{
throw new CurnException ("Can't create temporary file.");
}
}
log.debug ("Calling "
+ this.getClass().getName()
+ "initOutputHandler()");
initOutputHandler (config, cfgHandler);
}
/**
* Perform any subclass-specific initialization. Subclasses must
* override this method.
*
* @param config the parsed <i>curn</i> configuration data
* @param cfgHandler the <tt>ConfiguredOutputHandler</tt> wrapper
* containing this object; the wrapper has some useful
* metadata, such as the object's configuration section
* name and extra variables.
*
* @throws ConfigurationException configuration error
* @throws CurnException some other initialization error
*/
public abstract void initOutputHandler (ConfigFile config,
ConfiguredOutputHandler cfgHandler)
throws ConfigurationException,
CurnException;
/**
* Display the list of <tt>RSSItem</tt> news items to whatever output
* is defined for the underlying class. Output is written to the
* <tt>PrintWriter</tt> that was passed to the {@link #init init()}
* method.
*
* @param channel The channel containing the items to emit. The method
* should emit all the items in the channel; the caller
* is responsible for clearing out any items that should
* not be seen.
* @param feedInfo Information about the feed, from the configuration
*
* @throws CurnException unable to write output
*/
public abstract void displayChannel (RSSChannel channel,
FeedInfo feedInfo)
throws CurnException;
/**
* Flush any buffered-up output.
*
* @throws CurnException unable to write output
*/
public abstract void flush() throws CurnException;
/**
* Get the content (i.e., MIME) type for output produced by this output
* handler.
*
* @return the content type
*/
public abstract String getContentType();
/**
* Get an <tt>InputStream</tt> that can be used to read the output data
* produced by the handler, if applicable.
*
* @return an open input stream, or null if no suitable output was produced
*
* @throws CurnException an error occurred
*/
public final InputStream getGeneratedOutput()
throws CurnException
{
InputStream result = null;
if (hasGeneratedOutput())
{
try
{
result = new FileInputStream (outputFile);
}
catch (FileNotFoundException ex)
{
throw new CurnException ("Can't re-open file \""
+ outputFile
+ "\"",
ex);
}
}
return result;
}
/**
* Determine whether this handler has produced any actual output (i.e.,
* whether {@link #getGeneratedOutput()} will return a non-null
* <tt>InputStream</tt> if called).
*
* @return <tt>true</tt> if the handler has produced output,
* <tt>false</tt> if not
*
* @see #getGeneratedOutput
* @see #getContentType
*/
public final boolean hasGeneratedOutput()
{
boolean hasOutput = false;
if ((! saveOnly) && (outputFile != null))
{
long len = outputFile.length();
log.debug ("outputFile=" + outputFile.getPath() + ", size=" + len);
hasOutput = (len > 0);
}
log.debug ("hasGeneratedOutput? " + hasOutput);
return hasOutput;
}
/**
* Get the output file.
*
* @return the output file, or none if not created yet
*/
protected final File getOutputFile()
{
return outputFile;
}
/**
* Determine whether the handler is saving output only, or also reporting
* output to <i>curn</i>.
*
* @return <tt>true</tt> if saving output only, <tt>false</tt> if also
* reporting output to <i>curn</i>
*/
protected final boolean savingOutputOnly()
{
return saveOnly;
}
/**
* Convert certain Unicode characters in a string to plain text
* sequences. Also strips embedded HTML tags from the string. Useful
* primarily for handlers that produce plain text.
*
* @param s the string to convert
*
* @return the possibly converted string
*/
protected String convert (String s)
{
StringBuffer buf = new StringBuffer();
char[] ch;
s = HTMLUtil.textFromHTML (s);
ch = s.toCharArray();
buf.setLength (0);
for (int i = 0; i < ch.length; i++)
{
switch (ch[i])
{
case Unicode.LEFT_SINGLE_QUOTE:
case Unicode.RIGHT_SINGLE_QUOTE:
buf.append ('\'');
break;
case Unicode.LEFT_DOUBLE_QUOTE:
case Unicode.RIGHT_DOUBLE_QUOTE:
buf.append ('"');
break;
case Unicode.EM_DASH:
buf.append ("
break;
case Unicode.EN_DASH:
buf.append ('-');
break;
case Unicode.TRADEMARK:
buf.append ("[TM]");
break;
default:
buf.append (ch[i]);
break;
}
}
return buf.toString();
}
}
|
package jade.imtp.leap;
/**
This interface provides a callback method that is called
by the JADE runtime (front-end of a split container) when connection
specific events happen on the device.
Application developers wishing to handle these events may provide
a class implementating this interface and set the
<code>connection-listener</code> property to the fully qualified name
of that class. ConnectionListener implementation classes must have
an accessible default constructor;<br>
Alternatively an object implementing the ConnectionListener interface
may be put in the activation <code>Properties</code> specified ad
JADE runtime activation.
@author Giovanni Caire - TILAB
*/
public interface ConnectionListener {
/**
This event is rised just before each attempt to create
a network connection. A common use case consists in reacting to
it to set up an appropriate PDP context just if not in place
already.
*/
public static final int BEFORE_CONNECTION = 1;
/**
This event is raised whenever a temporary disconnection
is detected.
*/
public static final int DISCONNECTED = 2;
/**
This event is raised whenever a the device reconnects
after a temporary disconnection.
*/
public static final int RECONNECTED = 3;
/**
This event is raised when the device detects it is no longer
possible to reconnect (e.g. because the maximum disconnection
timeout expired)
*/
public static final int RECONNECTION_FAILURE = 4;
/**
This event is raised when the mediator replies with a BE Not Found
to a CONNECT_MEDIATOR request.
*/
public static final int BE_NOT_FOUND = 5;
/**
This event is raised when the mediator replies with an error
response of type Not Authorized to a CREATE_MEDIATOR or
CONNECT_MEDIATOR request.
*/
public static final int NOT_AUTHORIZED = 6;
/**
This callback method is called by the JADE runtime (front-end of
a split container) when connection specific events happen on the
device.
@param ev The event that happened
*/
public void handleConnectionEvent(int ev);
}
|
package org.exist.http.servlets;
import org.apache.log4j.Logger;
import org.exist.Namespaces;
import org.exist.source.FileSource;
import org.exist.xmldb.CollectionImpl;
import org.exist.xmldb.XQueryService;
import org.exist.xmldb.XmldbURI;
import org.exist.xquery.functions.request.RequestModule;
import org.exist.xquery.functions.response.ResponseModule;
import org.exist.xquery.functions.session.SessionModule;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;
* <url-pattern>/wiki/*</url-pattern>
* </servlet-mapping>
* </pre>
*/
public class RedirectorServlet extends HttpServlet {
private static final Logger LOG = Logger.getLogger(RedirectorServlet.class);
public final static String DEFAULT_USER = "guest";
public final static String DEFAULT_PASS = "guest";
public final static XmldbURI DEFAULT_URI = XmldbURI.EMBEDDED_SERVER_URI.append(XmldbURI.ROOT_COLLECTION_URI);
public final static String DRIVER = "org.exist.xmldb.DatabaseImpl";
private String user = null;
private String password = null;
private XmldbURI collectionURI = null;
private String query = null;
public void init(ServletConfig config) throws ServletException {
super.init(config);
query = config.getInitParameter("xquery");
if (query == null)
throw new ServletException("RedirectorServlet requires a parameter 'xquery'.");
user = config.getInitParameter("user");
if(user == null)
user = DEFAULT_USER;
password = config.getInitParameter("password");
if(password == null)
password = DEFAULT_PASS;
String confCollectionURI = config.getInitParameter("uri");
if(confCollectionURI == null) {
collectionURI = DEFAULT_URI;
} else {
try {
collectionURI = XmldbURI.xmldbUriFor(confCollectionURI);
} catch (URISyntaxException e) {
throw new ServletException("Invalid XmldbURI for parameter 'uri': "+e.getMessage(),e);
}
}
try {
Class driver = Class.forName(DRIVER);
Database database = (Database)driver.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
} catch(Exception e) {
String errorMessage="Failed to initialize database driver";
LOG.error(errorMessage,e);
throw new ServletException(errorMessage+": " + e.getMessage(), e);
}
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Try to find the XQuery
String qpath = getServletContext().getRealPath(query);
File f = new File(qpath);
if (!(f.canRead() && f.isFile()))
throw new ServletException("Cannot read XQuery source from " + f.getAbsolutePath());
FileSource source = new FileSource(f, "UTF-8", true);
try {
// Prepare and execute the XQuery
Collection collection = DatabaseManager.getCollection(collectionURI.toString(), user, password);
XQueryService service = (XQueryService) collection.getService("XQueryService", "1.0");
if(!((CollectionImpl)collection).isRemoteCollection()) {
service.declareVariable(RequestModule.PREFIX + ":request", new HttpRequestWrapper(request, "UTF-8", "UTF-8"));
service.declareVariable(ResponseModule.PREFIX + ":response", new HttpResponseWrapper(response));
service.declareVariable(SessionModule.PREFIX + ":session", new HttpSessionWrapper(request.getSession()));
}
ResourceSet result = service.execute(source);
String redirectTo = null;
String servletName = null;
String path = null;
RequestWrapper modifiedRequest = null;
// parse the query result element
if (result.getSize() == 1) {
XMLResource resource = (XMLResource) result.getResource(0);
Node node = resource.getContentAsDOM();
if (node.getNodeType() == Node.DOCUMENT_NODE)
node = ((Document) node).getDocumentElement();
if (node.getNodeType() != Node.ELEMENT_NODE) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Redirect XQuery should return an XML element. Received: " + resource.getContent());
return;
}
Element elem = (Element) node;
if (!(Namespaces.EXIST_NS.equals(elem.getNamespaceURI()) && "dispatch".equals(elem.getLocalName())))
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Redirect XQuery should return an element <exist:dispatch>. Received: " + resource.getContent());
return;
}
if (elem.hasAttribute("path"))
path = elem.getAttribute("path");
else if (elem.hasAttribute("servlet-name"))
servletName = elem.getAttribute("servlet-name");
else if (elem.hasAttribute("redirect"))
redirectTo = elem.getAttribute("redirect");
else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Element <exist:dispatch> should either provide an attribute 'path' or 'servlet-name'. Received: " +
resource.getContent());
return;
}
// Check for add-parameter elements etc.
if (elem.hasChildNodes()) {
node = elem.getFirstChild();
while (node != null) {
if (node.getNodeType() == Node.ELEMENT_NODE && Namespaces.EXIST_NS.equals(node.getNamespaceURI())) {
elem = (Element) node;
if ("add-parameter".equals(elem.getLocalName())) {
if (modifiedRequest == null)
modifiedRequest = new RequestWrapper(request);
modifiedRequest.addParameter(elem.getAttribute("name"), elem.getAttribute("value"));
}
}
node = node.getNextSibling();
}
}
}
if (redirectTo != null) {
// directly redirect to the specified URI
response.sendRedirect(redirectTo);
return;
}
// Get a RequestDispatcher, either from the servlet context or the request
RequestDispatcher dispatcher;
if (servletName != null && servletName.length() > 0)
dispatcher = getServletContext().getNamedDispatcher(servletName);
else {
LOG.debug("Dispatching to " + path);
dispatcher = getServletContext().getRequestDispatcher(path);
if (dispatcher == null)
dispatcher = request.getRequestDispatcher(path);
}
if (dispatcher == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Could not create a request dispatcher. Giving up.");
return;
}
if (modifiedRequest != null)
request = modifiedRequest;
// store the original request URI to org.exist.forward.request-uri
request.setAttribute("org.exist.forward.request-uri", request.getRequestURI());
request.setAttribute("org.exist.forward.servlet-path", request.getServletPath());
// finally, execute the forward
dispatcher.forward(request, response);
} catch (XMLDBException e) {
throw new ServletException("An error occurred while initializing RedirectorServlet: " + e.getMessage(), e);
}
}
private class RequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {
Map addedParams = new HashMap();
private RequestWrapper(HttpServletRequest request) {
super(request);
}
public void addParameter(String name, String value) {
addedParams.put(name, value);
}
public String getParameter(String name) {
String value = (String) addedParams.get(name);
if (value != null)
return value;
return super.getParameter(name);
}
public Map getParameterMap() {
return null;
}
public Enumeration getParameterNames() {
Vector v = new Vector();
for (Iterator i = addedParams.keySet().iterator(); i.hasNext(); ) {
String key = (String) i.next();
v.addElement(key);
}
for (Iterator i = super.getParameterMap().keySet().iterator(); i.hasNext(); ) {
String key = (String) i.next();
v.addElement(key);
}
return v.elements();
}
public String[] getParameterValues(String s) {
String value = (String) addedParams.get(s);
if (value != null)
return new String[] { value };
return super.getParameterValues(s);
}
}
}
|
// This file is part of OpenTSDB.
// This program is free software: you can redistribute it and/or modify it
// option) any later version. This program is distributed in the hope that it
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
package net.opentsdb.core;
import java.util.ArrayList;
import java.util.Arrays;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Groups multiple spans together and offers a dynamic "view" on them.
* <p>
* This is used for queries to the TSDB, where we might group multiple
* {@link Span}s that are for the same time series but different tags
* together. We need to "hide" data points that are outside of the
* time period of the query and do on-the-fly aggregation of the data
* points coming from the different Spans, using an {@link Aggregator}.
* Since not all the Spans will have their data points at exactly the
* same time, we also do on-the-fly linear interpolation. If needed,
* this view can also return the rate of change instead of the actual
* data points.
* <p>
* This is one of the rare (if not the only) implementations of
* {@link DataPoints} for which {@link #getTags} can potentially return
* an empty map.
* <p>
* The implementation can also dynamically downsample the data when a
* sampling interval a downsampling function (in the form of an
* {@link Aggregator}) are given. This is done by using a special
* iterator when using the {@link Span.DownsamplingIterator}.
*/
final class SpanGroup implements DataPoints {
private static final Logger LOG = LoggerFactory.getLogger(SpanGroup.class);
/** The TSDB we belong to. */
private final TSDB tsdb;
/** Start time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */
private final long start_time;
/** End time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */
private final long end_time;
/**
* The tags of this group.
* This is the intersection set between the tags of all the Spans
* in this group.
* @see #computeTags
*/
private HashMap<String, String> tags;
/**
* The names of the tags that aren't shared by every single data point.
* This is the symmetric difference between the tags of all the Spans
* in this group.
* @see #computeTags
*/
private ArrayList<String> aggregated_tags;
/** Spans in this group. They must all be for the same metric. */
private final ArrayList<Span> spans = new ArrayList<Span>();
/** If true, use rate of change instead of actual values. */
private boolean rate;
/** Aggregator to use to aggregate data points from different Spans. */
private final Aggregator aggregator;
/**
* Downsampling function to use, if any (can be {@code null}).
* If this is non-null, {@code sample_interval} must be strictly positive.
*/
private final Aggregator downsampler;
/** Minimum time interval (in seconds) wanted between each data point. */
private final int sample_interval;
/**
* Ctor.
* @param tsdb The TSDB we belong to.
* @param start_time Any data point strictly before this timestamp will be
* ignored.
* @param end_time Any data point strictly after this timestamp will be
* ignored.
* @param spans A sequence of initial {@link Spans} to add to this group.
* Ignored if {@code null}. Additional spans can be added with {@link #add}.
* @param rate If {@code true}, the rate of the series will be used instead
* of the actual values.
* @param aggregator The aggregation function to use.
* @param interval Number of seconds wanted between each data point.
* @param downsampler Aggregation function to use to group data points
* within an interval.
*/
SpanGroup(final TSDB tsdb,
final long start_time, final long end_time,
final Iterable<Span> spans,
final boolean rate,
final Aggregator aggregator,
final int interval, final Aggregator downsampler) {
this.tsdb = tsdb;
this.start_time = start_time;
this.end_time = end_time;
if (spans != null) {
for (final Span span : spans) {
add(span);
}
}
this.rate = rate;
this.aggregator = aggregator;
this.downsampler = downsampler;
this.sample_interval = interval;
}
/**
* Adds a span to this group, provided that it's in the right time range.
* <b>Must not</b> be called once {@link #getTags} or
* {@link #getAggregatedTags} has been called on this instance.
* @param span The span to add to this group. If none of the data points
* fall within our time range, this method will silently ignore that span.
*/
void add(final Span span) {
if (tags != null) {
throw new AssertionError("The set of tags has already been computed"
+ ", you can't add more Spans to " + this);
}
if (span.timestamp(0) <= end_time
// The following call to timestamp() will throw an
// IndexOutOfBoundsException if size == 0, which is OK since it would
// be a programming error.
&& span.timestamp(span.size() - 1) >= start_time) {
this.spans.add(span);
}
}
/**
* Computes the intersection set + symmetric difference of tags in all spans.
* @param spans A collection of spans for which to find the common tags.
* @return A (possibly empty) map of the tags common to all the spans given.
*/
private void computeTags() {
if (spans.isEmpty()) {
tags = new HashMap<String, String>(0);
aggregated_tags = new ArrayList<String>(0);
return;
}
final Iterator<Span> it = spans.iterator();
tags = new HashMap<String, String>(it.next().getTags());
final HashSet<String> discarded_tags = new HashSet<String>(tags.size());
while (it.hasNext()) {
final Map<String, String> nexttags = it.next().getTags();
// OMG JAVA
final Iterator<Map.Entry<String, String>> i = tags.entrySet().iterator();
while (i.hasNext()) {
final Map.Entry<String, String> entry = i.next();
final String name = entry.getKey();
final String value = nexttags.get(name);
if (value == null || !value.equals(entry.getValue())) {
i.remove();
discarded_tags.add(name);
}
}
}
aggregated_tags = new ArrayList<String>(discarded_tags);
}
public String metricName() {
return spans.isEmpty() ? "" : spans.get(0).metricName();
}
public Map<String, String> getTags() {
if (tags == null) {
computeTags();
}
return tags;
}
public List<String> getAggregatedTags() {
if (tags == null) {
computeTags();
}
return aggregated_tags;
}
public int size() {
// TODO(tsuna): There is a way of doing this way more efficiently by
// inspecting the Spans and counting only data points that fall in
// our time range.
final SGIterator it = new SGIterator();
int size = 0;
while (it.hasNext()) {
it.next();
size++;
}
return size;
}
public int aggregatedSize() {
int size = 0;
for (final Span span : spans) {
size += span.size();
}
return size;
}
public SeekableView iterator() {
return new SGIterator();
}
/**
* Finds the {@code i}th data point of this group in {@code O(n)}.
* Where {@code n} is the number of data points in this group.
*/
private DataPoint getDataPoint(int i) {
if (i < 0) {
throw new IndexOutOfBoundsException("negative index: " + i);
}
final int saved_i = i;
final SGIterator it = new SGIterator();
DataPoint dp = null;
while (it.hasNext() && i >= 0) {
dp = it.next();
i
}
if (i != -1 || dp == null) {
throw new IndexOutOfBoundsException("index " + saved_i
+ " too large (it's >= " + size() + ") for " + this);
}
return dp;
}
public long timestamp(final int i) {
return getDataPoint(i).timestamp();
}
public boolean isInteger(final int i) {
return getDataPoint(i).isInteger();
}
public double doubleValue(final int i) {
return getDataPoint(i).doubleValue();
}
public long longValue(final int i) {
return getDataPoint(i).longValue();
}
private final class SGIterator
implements SeekableView, DataPoint,
Aggregator.Longs, Aggregator.Doubles {
/** Extra bit we set on the timestamp of floating point values. */
private static final long FLAG_FLOAT = 0x8000000000000000L;
/** Mask to use in order to get rid of the flag above.
* This value also conveniently represents the largest timestamp we can
* possibly store, provided that the most significant bit is reserved by
* FLAG_FLOAT.
*/
private static final long TIME_MASK = 0x7FFFFFFFFFFFFFFFL;
/**
* Where we are in each {@link Span} in the group.
* The iterators in this array always points to 2 values ahead of the
* current value, as we pre-load the current and the next values into the
* {@link #timestamps} and {@link #values} member.
* Once we reach the end of a Span, we'll null out its iterator from this
* array.
*/
private final SeekableView[] iterators;
/**
* The current and previous timestamps for the data points being used.
* <p>
* Are we computing a rate?
* <ul>
* <li>No: for {@code iterators[i]} the timestamp of the current data
* point is {@code timestamps[i]} and the timestamp of the next data
* point is {@code timestamps[iterators.length + i]}.</li>
* <li>Yes: In addition to the above, the previous data point is saved
* in {@code timestamps[iterators.length * 2 + i]}.
* </li></ul>
* <p>
* Each timestamp can have the {@code FLAG_FLOAT} applied so it's important
* to use the {@code TIME_MASK} when getting the actual timestamp value
* out of it.
* There are two special values for timestamps:
* <ul>
* <li>{@code 0} when in the first half of the array: this iterator has
* run out of data points and must not be used anymore.</li>
* <li>{@code TIME_MASK} when in the second half of the array: this
* iterator has reached its last data point and must not be used for
* linear interpolation anymore.</li>
* </ul>
*/
private final long[] timestamps; // 32 bit unsigned + flag
/**
* The current and next values for the data points being used.
* This array works exactly in the same fashion as the 'timestamps' array.
* This array is also used to store floating point values, in which case
* their binary representation just happens to be stored in a {@code long}.
*/
private final long[] values;
/** The index in {@link #iterators} of the current Span being used. */
private int current;
/** The index in {@link #values} of the current value being aggregated. */
private int pos;
/** Creates a new iterator for this {@link SpanGroup}. */
SGIterator() {
final int size = spans.size();
iterators = new SeekableView[size];
timestamps = new long[size * (rate ? 3 : 2)];
values = new long[size * (rate ? 3 : 2)];
// Initialize every Iterator, fetch their first values that fall
// within our time range.
for (int i = 0; i < size; i++) {
final SeekableView it =
(downsampler == null
? spans.get(i).spanIterator()
: spans.get(i).downsampler(sample_interval, downsampler));
iterators[i] = it;
it.seek(start_time);
final DataPoint dp;
try {
dp = it.next();
} catch (NoSuchElementException e) {
throw new AssertionError("Span #" + i + " is empty! span="
+ spans.get(i));
}
//LOG.debug("Creating iterator
if (dp.timestamp() >= start_time) {
//LOG.debug("First DP in range for
// + dp.timestamp() + " >= " + start_time);
putDataPoint(size + i, dp);
} else {
//LOG.debug("No DP in range for
// + dp.timestamp() + " < " + start_time);
endReached(i);
continue;
}
if (rate) { // Need two values to compute a rate. Load one more.
if (it.hasNext()) {
moveToNext(i);
} else {
endReached(i);
}
}
}
}
/**
* Indicates that an iterator in {@link #iterators} has reached the end.
* @param i The index in {@link #iterators} of the iterator.
*/
private void endReached(final int i) {
//LOG.debug("No more DP for
timestamps[iterators.length + i] = TIME_MASK;
iterators[i] = null; // We won't use it anymore, so free() it.
}
/**
* Puts the next data point of an iterator in the internal buffer.
* @param i The index in {@link #iterators} of the iterator.
* @param dp The last data point returned by that iterator.
*/
private void putDataPoint(final int i, final DataPoint dp) {
timestamps[i] = dp.timestamp();
if (dp.isInteger()) {
//LOG.debug("Putting #" + i + " (long) " + dp.longValue()
// + " @ time " + dp.timestamp());
values[i] = dp.longValue();
} else {
//LOG.debug("Putting #" + i + " (double) " + dp.doubleValue()
// + " @ time " + dp.timestamp());
values[i] = Double.doubleToRawLongBits(dp.doubleValue());
timestamps[i] |= FLAG_FLOAT;
}
}
// Iterator interface //
public boolean hasNext() {
final int size = iterators.length;
for (int i = 0; i < size; i++) {
// As long as any of the iterators has a data point with a timestamp
// that falls within our interval, we know we have at least one next.
if ((timestamps[size + i] & TIME_MASK) <= end_time) {
//LOG.debug("hasNext #" + (size + i));
return true;
}
}
//LOG.debug("No hasNext (return false)");
return false;
}
public DataPoint next() {
final int size = iterators.length;
long min_ts = Long.MAX_VALUE;
// In case we reached the end of one or more Spans, we need to make sure
// we mark them as such by zeroing their current timestamp. There may
// be multiple Spans that reached their end at once, so check them all.
for (int i = current; i < size; i++) {
if (timestamps[i + size] == TIME_MASK) {
//LOG.debug("Expiring last DP for #" + current);
timestamps[i] = 0;
}
}
// Now we need to find which Span we'll consume next. We'll pick the
// one that has the data point with the smallest timestamp since we want to
// return them in chronological order.
current = -1;
// If there's more than one Span with the same smallest timestamp, we'll
// set this to true so we can fetch the next data point in all of them at
// the same time.
boolean multiple = false;
for (int i = 0; i < size; i++) {
final long timestamp = timestamps[size + i] & TIME_MASK;
if (timestamp <= end_time) {
if (timestamp < min_ts) {
min_ts = timestamp;
current = i;
// We just found a new minimum so right now we can't possibly have
// multiple Spans with the same minimum.
multiple = false;
} else if (timestamp == min_ts) {
multiple = true;
}
}
}
if (current < 0) {
throw new NoSuchElementException("no more elements");
}
moveToNext(current);
if (multiple) {
//LOG.debug("Moving multiple DPs at time " + min_ts);
// We know we saw at least one other data point with the same minimum
// timestamp after `current', so let's move those ones too.
for (int i = current + 1; i < size; i++) {
final long timestamp = timestamps[size + i] & TIME_MASK;
if (timestamp == min_ts) {
moveToNext(i);
}
}
}
return this;
}
/**
* Makes iterator number {@code i} move forward to the next data point.
* @param i The index in {@link #iterators} of the iterator.
*/
private void moveToNext(final int i) {
final int size = iterators.length;
final int next = iterators.length + i;
if (rate) { // move "current" in "prev".
timestamps[next + size] = timestamps[i];
values[next + size] = values[i];
//LOG.debug("Saving #" + i + " -> #" + (next + size)
// + ((timestamps[i] & FLAG_FLOAT) == FLAG_FLOAT
// ? " float " + Double.longBitsToDouble(values[i])
// : " long " + values[i])
// + " @ time " + (timestamps[i] & TIME_MASK));
}
timestamps[i] = timestamps[next];
values[i] = values[next];
//LOG.debug("Moving #" + next + " -> #" + i
// + ((timestamps[i] & FLAG_FLOAT) == FLAG_FLOAT
// ? " float " + Double.longBitsToDouble(values[i])
// : " long " + values[i])
// + " @ time " + (timestamps[i] & TIME_MASK));
final SeekableView it = iterators[i];
if (it.hasNext()) {
putDataPoint(next, it.next());
} else {
endReached(i);
}
}
public void remove() {
throw new UnsupportedOperationException();
}
// SeekableView interface //
public void seek(final long timestamp) {
for (final SeekableView it : iterators) {
it.seek(timestamp);
}
}
// DataPoint interface //
public long timestamp() {
return timestamps[current] & TIME_MASK;
}
public boolean isInteger() {
if (rate) {
// An rate can never be precisely represented without floating point.
return false;
}
// If at least one of the values we're going to aggregate or interpolate
// with is a float, we have to convert everything to a float.
for (int i = timestamps.length - 1; i >= 0; i
if ((timestamps[i] & FLAG_FLOAT) == FLAG_FLOAT) {
return false;
}
}
return true;
}
public long longValue() {
if (isInteger()) {
pos = -1;
return aggregator.runLong(this);
}
throw new ClassCastException("current value is a double: " + this);
}
public double doubleValue() {
if (!isInteger()) {
pos = -1;
final double value = aggregator.runDouble(this);
//LOG.debug("aggregator returned " + value);
if (value != value || Double.isInfinite(value)) {
throw new IllegalStateException("Got NaN or Infinity: "
+ value + " in this " + this);
}
return value;
}
throw new ClassCastException("current value is a long: " + this);
}
public double toDouble() {
return isInteger() ? doubleValue() : longValue();
}
// Aggregator.Longs interface //
public boolean hasNextValue() {
return hasNextValue(false);
}
/**
* Returns whether or not there are more values to aggregate.
* @param update_pos Whether or not to also move the internal pointer
* {@link #pos} to the index of the next value to aggregate.
* @return true if there are more values to aggregate, false otherwise.
*/
private boolean hasNextValue(boolean update_pos) {
final int size = iterators.length;
for (int i = pos + 1; i < size; i++) {
if (timestamps[i] != 0) {
//LOG.debug("hasNextValue -> true
if (update_pos) {
pos = i;
}
return true;
}
}
//LOG.debug("hasNextValue -> false (ran out)");
return false;
}
public long nextLongValue() {
if (hasNextValue(true)) {
final long y0 = values[pos];
if (rate) {
throw new AssertionError("Should not be here, impossible! " + this);
}
if (current == pos) {
return y0;
}
final long x = timestamps[current] & TIME_MASK;
final long x0 = timestamps[pos] & TIME_MASK;
if (x == x0) {
return y0;
}
final long y1 = values[pos + iterators.length];
final long x1 = timestamps[pos + iterators.length] & TIME_MASK;
if (x == x1) {
return y1;
}
final long r = y0 + (x - x0) * (y1 - y0) / (x1 - x0);
//LOG.debug("Lerping to time " + x + ": " + y0 + " @ " + x0
// + " -> " + y1 + " @ " + x1 + " => " + r);
if ((x1 & 0xFFFFFFFF00000000L) != 0) {
throw new AssertionError("x1=" + x1 + " in " + this);
}
return r;
}
throw new NoSuchElementException("no more longs in " + this);
}
// Aggregator.Doubles interface //
public double nextDoubleValue() {
if (hasNextValue(true)) {
final double y0 = ((timestamps[pos] & FLAG_FLOAT) == FLAG_FLOAT
? Double.longBitsToDouble(values[pos])
: values[pos]);
if (rate) {
final long x0 = timestamps[pos] & TIME_MASK;
final int prev = pos + iterators.length * 2;
final double y1 = ((timestamps[prev] & FLAG_FLOAT) == FLAG_FLOAT
? Double.longBitsToDouble(values[prev])
: values[prev]);
final long x1 = timestamps[prev] & TIME_MASK;
final double r = (y0 - y1) / (x0 - x1);
//LOG.debug("Rate for " + y1 + " @ " + x1
// + " -> " + y0 + " @ " + x0 + " => " + r);
return r;
}
if (current == pos) {
//LOG.debug("Exact match, no lerp needed");
return y0;
}
final long x = timestamps[current] & TIME_MASK;
final long x0 = timestamps[pos] & TIME_MASK;
if (x == x0) {
//LOG.debug("No lerp needed x == x0 (" + x + " == "+x0+") => " + y0);
return y0;
}
final int next = pos + iterators.length;
final double y1 = ((timestamps[next] & FLAG_FLOAT) == FLAG_FLOAT
? Double.longBitsToDouble(values[next])
: values[next]);
final long x1 = timestamps[next] & TIME_MASK;
if (x == x1) {
//LOG.debug("No lerp needed x == x1 (" + x + " == "+x1+") => " + y1);
return y1;
}
final double r = y0 + (x - x0) * (y1 - y0) / (x1 - x0);
//LOG.debug("Lerping to time " + x + ": " + y0 + " @ " + x0
// + " -> " + y1 + " @ " + x1 + " => " + r);
if ((x1 & 0xFFFFFFFF00000000L) != 0) {
throw new AssertionError("x1=" + x1 + " in " + this);
}
return r;
}
throw new NoSuchElementException("no more doubles in " + this);
}
public String toString() {
return "SpanGroup.Iterator(timestamps=" + Arrays.toString(timestamps)
+ ", values=" + Arrays.toString(values)
+ ", current=" + current
+ ", pos=" + pos
+ ", (SpanGroup: " + toStringSharedAttributes()
+ "), iterators=" + Arrays.toString(iterators)
+ ')';
}
}
public String toString() {
return "SpanGroup(" + toStringSharedAttributes()
+ ", spans=" + spans
+ ')';
}
private String toStringSharedAttributes() {
return "start_time=" + start_time
+ ", end_time=" + end_time
+ ", tags=" + tags
+ ", aggregated_tags=" + aggregated_tags
+ ", rate=" + rate
+ ", aggregator=" + aggregator
+ ", downsampler=" + downsampler
+ ", sample_interval=" + sample_interval
+ ')';
}
}
|
package org.jaudiotagger.tag.reference;
import java.util.HashMap;
import java.util.Map;
public class ISOCountry
{
private static Map<String, Country> codeMap;
private static Map<String, Country> descriptionMap;
static
{
codeMap = new HashMap<String, Country>();
for (Country country : Country.values())
{
codeMap.put(country.code, country);
}
descriptionMap = new HashMap<String, Country>();
for (Country country : Country.values())
{
descriptionMap.put(country.description, country);
}
}
/**
* @param code
* @return enum with this two letter code
*/
public static Country getCountryByCode(String code)
{
return codeMap.get(code);
}
/**
* @param description
* @return enum with this description
*/
public static Country getCountryByDescription(String description)
{
return descriptionMap.get(description);
}
/**
* List of valid Iso Country, shows 2 letter abbreviation and country human readable name
*/
public static enum Country
{
AFGHANISTAN(" AF", "Afghanistan"),
LAND_ISLANDS("AX", "land Islands"),
ALBANIA("AL", "Albania"),
ALGERIA("DZ", "Algeria"),
AMERICAN_SAMOA("AS", "American Samoa"),
ANDORRA("AD", "Andorra"),
ANGOLA("AO", "Angola"),
ANGUILLA("AI", "Anguilla"),
ANTARCTICA("AQ", "Antarctica"),
ANTIGUA_AND_BARBUDA("AG", "Antigua and Barbuda"),
ARGENTINA("AR", "Argentina"),
ARMENIA("AM", "Armenia"),
ARUBA("AW", "Aruba"),
AUSTRALIA("AU", "Australia"),
AUSTRIA("AT", "Austria"),
AZERBAIJAN("AZ", "Azerbaijan"),
BAHAMAS("BS", "Bahamas"),
BAHRAIN("BH", "Bahrain"),
BANGLADESH("BD", "Bangladesh"),
BARBADOS("BB", "Barbados"),
BELARUS("BY", "Belarus"),
BELGIUM("BE", "Belgium"),
BELIZE("BZ", "Belize"),
BENIN("BJ", "Benin"),
BERMUDA("BM", "Bermuda"),
BHUTAN("BT", "Bhutan"),
BOLIVIA("BO", "Bolivia"),
BOSNIA_AND_HERZEGOVINA("BA", "Bosnia and herzegovina"),
BOTSWANA("BW", "Botswana"),
BOUVET_ISLAND("BV", "Bouvet_Island"),
BRAZIL("BR", "Brazil"),
BRITISH_INDIAN_OCEAN_TERRITORY("IO", "British Indian Ocean Territory"),
BRUNEI_DARUSSALAM("BN", "Brunei Darussalam"),
BULGARIA("BG", "Bulgaria"),
BURKINA_FASO("BF", "Burkina Faso"),
BURUNDI("BI", "Burundi"),
CAMBODIA("KH", "Cambodia"),
CAMEROON("CM", "Cameroon"),
CANADA("CA", "Canada"),
CAPE_VERDE("CV", "Cape Verde"),
CAYMAN_ISLANDS("KY", "Cayman Islands"),
CENTRAL_AFRICAN_REPUBLIC("CF", "Central African Republic"),
CHAD("TD", "Chad"),
CHILE("CL", "Chile"),
CHINA("CN", "China"),
CHRISTMAS_ISLAND("CX", "Christmas Island"),
COCOS_KEELING_ISLANDS("CC", "Cocos Keeling Islands"),
COLOMBIA("CO", "Colombia"),
COMOROS("KM", "Comoros"),
CONGO("CG", "Congo"),
THE_DEMOCRATIC_REPUBLIC_OF_CONGO("CD", "The Democratic Republic Of Congo"),
COOK_ISLANDS("CK", "Cook Islands"),
COSTA_RICA("CR", "Costa Rica"),
CTE_D_IVOIRE("CI", "Ivory Coast"),
CROATIA("HR", "Croatia"),
CUBA("CU", "Cuba"),
CYPRUS("CY", "Cyprus"),
CZECH_REPUBLIC("CZ", "Czech Republic"),
DENMARK("DK", "Denmark"),
DJIBOUTI("DJ", "Djibouti"),
DOMINICA("DM", "Dominica"),
DOMINICAN_REPUBLIC("DO", "Dominican Republic"),
ECUADOR("EC", "Ecuador"),
EGYPT("EG", "Egypt"),
EL_SALVADOR("SV", "El Salvador"),
EQUATORIAL_GUINEA("GQ", "Equatorial Guinea"),
ERITREA("ER", "Eritrea"),
ESTONIA("EE", "Estonia"),
ETHIOPIA("ET", "Ethiopia"),
FALKLAND_ISLANDS("FK", "Falkland Islands"),
FAROE_ISLANDS("FO", "Faroe Islands"),
FIJI("FJ", "Fiji"),
FINLAND("FI", "Finland"),
FRANCE("FR", "France"),
FRENCH_GUIANA("GF", "French Guiana"),
FRENCH_POLYNESIA("PF", "French Polynesia"),
FRENCH_SOUTHERN_TERRITORIES("TF", "French Southern Territories"),
GABON("GA", "Gabon"),
GAMBIA("GM", "Gambia"),
GEORGIA("GE", "Georgia"),
GERMANY("DE", "Germany"),
GHANA("GH", "Ghana"),
GIBRALTAR("GI", "Gibraltar"),
GREECE("GR", "Greece"),
GREENLAND("GL", "Greenland"),
GRENADA("GD", "Grenada"),
GUADELOUPE("GP", "Guadeloupe"),
GUAM("GU", "Guam"),
GUATEMALA("GT", "Guatemala"),
GUERNSEY("GG", "Guernsey"),
GUINEA("GN", "Guinea"),
GUINEA_BISSAU("GW", "Guinea_Bissau"),
GUYANA("GY", "Guyana"),
HAITI("HT", "Haiti"),
HEARD_ISLAND_AND_MCDONALD_ISLANDS("HM", "Heard Island and Mcdonald Islands"),
HONDURAS("HN", "Honduras"),
HONG_KONG("HK", "Hong_Kong"),
HUNGARY("HU", "Hungary"),
ICELAND("IS", "Iceland"),
INDIA("IN", "India"),
INDONESIA("ID", "Indonesia"),
IRAN("IR", "Iran"),
IRAQ("IQ", "Iraq"),
IRELAND("IE", "Ireland"),
ISLE_OF_MAN("IM", "Isle Of Man"),
ISRAEL("IL", "Israel"),
ITALY("IT", "Italy"),
JAMAICA("JM", "Jamaica"),
JAPAN("JP", "Japan"),
JERSEY("JE", "Jersey"),
JORDAN("JO", "Jordan"),
KAZAKHSTAN("KZ", "Kazakhstan"),
KENYA("KE", "Kenya"),
KIRIBATI("KI", "Kiribati"),
KOREA_NORTH("KP", "North Korea"),
KOREA_SOUTH("KR", "South Korea"),
KUWAIT("KW", "Kuwait"),
KYRGYZSTAN("KG", "Kyrgyzstan"),
LAO_PEOPLES_DEMOCRATIC_REPUBLIC("LA", "Lao"),
LATVIA("LV", "Latvia"),
LEBANON("LB", "Lebanon"),
LESOTHO("LS", "Lesotho"),
LIBERIA("LR", "Liberia"),
LIBYAN_ARAB_JAMAHIRIYA("LY", "Libyan Arab Jamahiriya"),
LIECHTENSTEIN("LI", "Liechtenstein"),
LITHUANIA("LT", "Lithuania"),
LUXEMBOURG("LU", "Luxembourg"),
MACAO("MO", "Macao"),
MACEDONIA("MK", "Macedonia"),
MADAGASCAR("MG", "Madagascar"),
MALAWI("MW", "Malawi"),
MALAYSIA("MY", "Malaysia"),
MALDIVES("MV", "Maldives"),
MALI("ML", "Mali"),
MALTA("MT", "Malta"),
MARSHALL_ISLANDS("MH", "Marshall Islands"),
MARTINIQUE("MQ", "Martinique"),
MAURITANIA("MR", "Mauritania"),
MAURITIUS("MU", "Mauritius"),
MAYOTTE("YT", "Mayotte"),
MEXICO("MX", "Mexico"),
MICRONESIA("FM", "Micronesia"),
MOLDOVA("MD", "Moldova"),
MONACO("MC", "Monaco"),
MONGOLIA("MN", "Mongolia"),
MONTENEGRO("ME", "Montenegro"),
MONTSERRAT("MS", "Montserrat"),
MOROCCO("MA", "Morocco"),
MOZAMBIQUE("MZ", "Mozambique"),
MYANMAR("MM", "Myanmar"),
NAMIBIA("NA", "Namibia"),
NAURU("NR", "Nauru"),
NEPAL("NP", "Nepal"),
NETHERLANDS("NL", "Netherlands"),
NETHERLANDS_ANTILLES("AN", "Netherlands Antilles"),
NEW_CALEDONIA("NC", "New Caledonia"),
NEW_ZEALAND("NZ", "New Zealand"),
NICARAGUA("NI", "Nicaragua"),
NIGER("NE", "Niger"),
NIGERIA("NG", "Nigeria"),
NIUE("NU", "Niue"),
NORFOLK_ISLAND("NF", "Norfolk Island"),
NORTHERN_MARIANA_ISLANDS("MP", "Northern Mariana Islands"),
NORWAY("NO", "Norway"),
OMAN("OM", "Oman"),
PAKISTAN("PK", "Pakistan"),
PALAU("PW", "Palau"),
PALESTINIAN_TERRITORY_OCCUPIED("PS", "Palestinian Territory Occupied"),
PANAMA("PA", "Panama"),
PAPUA_NEW_GUINEA("PG", "Papua New Guinea"),
PARAGUAY("PY", "Paraguay"),
PERU("PE", "Peru"),
PHILIPPINES("PH", "Philippines"),
PITCAIRN("PN", "Pitcairn"),
POLAND("PL", "Poland"),
PORTUGAL("PT", "Portugal"),
PUERTO_RICO("PR", "Puerto Rico"),
QATAR("QA", "Qatar"),
RUNION("RE", "Union"),
ROMANIA("RO", "Romania"),
RUSSIAN_FEDERATION("RU", "Russia"),
RWANDA("RW", "Rwanda"),
SAINT_BARTHLEMY("BL", "Lemy"),
SAINT_HELENA("SH", "St Helena"),
SAINT_KITTS_AND_NEVIS("KN", "St Kitts and Nevis"),
SAINT_LUCIA("LC", "St Lucia"),
SAINT_MARTIN("MF", "St Martin"),
SAINT_PIERRE_AND_MIQUELON("PM", "St Pierre and Miquelon"),
SAINT_VINCENT_AND_THE_GRENADINES("VC", "St Vincent and the Grenadines"),
SAMOA("WS", "Samoa"),
SAN_MARINO("SM", "San_Marino"),
SAO_TOME_AND_PRINCIPE("ST", "Sao Tome and Principe"),
SAUDI_ARABIA("SA", "Saudi Arabia"),
SENEGAL("SN", "Senegal"),
SERBIA("RS", "Serbia"),
SEYCHELLES("SC", "Seychelles"),
SIERRA_LEONE("SL", "Sierra Leone"),
SINGAPORE("SG", "Singapore"),
SLOVAKIA("SK", "Slovakia"),
SLOVENIA("SI", "Slovenia"),
SOLOMON_ISLANDS("SB", "Solomon Islands"),
SOMALIA("SO", "Somalia"),
SOUTH_AFRICA("ZA", "South Africa"),
SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_Islands("GS", "South Georgia and the South Sandwich Islands"),
SPAIN("ES", "Spain"),
SRI_LANKA("LK", "Sri Lanka"),
SUDAN("SD", "Sudan"),
SURINAME("SR", "Suriname"),
SVALBARD_AND_JAN_MAYEN("SJ", "Svalbard and Jan Mayen"),
SWAZILAND("SZ", "Swaziland"),
SWEDEN("SE", "Sweden"),
SWITZERLAND("CH", "Switzerland"),
SYRIA("SY", "Syria"),
TAIWAN("TW", "Taiwan"),
TAJIKISTAN("TJ", "Tajikistan"),
TANZANIA("TZ", "Tanzania"),
THAILAND("TH", "Thailand"),
TIMOR_LESTE("TL", "Timor Leste"),
TOGO("TG", "Togo"),
TOKELAU("TK", "Tokelau"),
TONGA("TO", "Tonga"),
TRINIDAD_AND_TOBAGO("TT", "Trinidad and Tobago"),
TUNISIA("TN", "Tunisia"),
TURKEY("TR", "Turkey"),
TURKMENISTAN("TM", "Turkmenistan"),
TURKS_AND_CAICOS_ISLANDS("TC", "Turks and Caicos Islands"),
TUVALU("TV", "Tuvalu"),
UGANDA("UG", "Uganda"),
UKRAINE("UA", "Ukraine"),
UNITED_ARAB_EMIRATES("AE", "United Arab Emirates"),
UNITED_KINGDOM("GB", "United Kingdom"),
UNITED_STATES("US", "United States"),
UNITED_STATES_MINOR_OUTLYING_ISLANDS("UM", "United States Minor Outlying Islands"),
URUGUAY("UY", "Uruguay"),
UZBEKISTAN("UZ", "Uzbekistan"),
VANUATU("VU", "Vanuatu"),
VATICAN_CITY("VA", "Vatican City"),
VENEZUELA("VE", "Venezuela"),
VIETNAM("VN", "Vietnam"),
VIRGIN_ISLANDS_BRITISH("VG", "British Virgin Islands"),
VIRGIN_ISLANDS_US("VI", "US Virgin Islands"),
WALLIS_AND_FUTUNA("WF", "Wallis and Futuna"),
WESTERN_SAHARA("EH", "Western Sahara"),
YEMEN("YE", "Yemen"),
ZAMBIA("ZM", "Zambia"),
ZIMBABWE("ZW", "Zimbabwe");
private String code;
private String description;
Country(String code, String description)
{
this.code = code;
this.description = description;
}
public String getCode()
{
return code;
}
public String getDescription()
{
return description;
}
public String toString()
{
return getDescription();
}
}
}
|
// This file is part of OpenTSDB.
// This program is free software: you can redistribute it and/or modify it
// option) any later version. This program is distributed in the hope that it
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
package net.opentsdb.core;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hbase.async.Bytes;
import org.hbase.async.HBaseException;
import org.hbase.async.KeyValue;
import org.hbase.async.Scanner;
import static org.hbase.async.Bytes.ByteMap;
import net.opentsdb.stats.Histogram;
import net.opentsdb.uid.NoSuchUniqueId;
import net.opentsdb.uid.NoSuchUniqueName;
/**
* Non-synchronized implementation of {@link Query}.
*/
final class TsdbQuery implements Query {
private static final Logger LOG = LoggerFactory.getLogger(TsdbQuery.class);
/** Used whenever there are no results. */
private static final DataPoints[] NO_RESULT = new DataPoints[0];
/**
* Keep track of the latency we perceive when doing Scans on HBase.
* We want buckets up to 16s, with 2 ms interval between each bucket up to
* 100 ms after we which we switch to exponential buckets.
*/
static final Histogram scanlatency = new Histogram(16000, (short) 2, 100);
/**
* Charset to use with our server-side row-filter.
* We use this one because it preserves every possible byte unchanged.
*/
private static final Charset CHARSET = Charset.forName("ISO-8859-1");
/** The TSDB we belong to. */
private final TSDB tsdb;
/** Start time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */
private int start_time;
/** End time (UNIX timestamp in seconds) on 32 bits ("unsigned" int). */
private int end_time;
/** ID of the metric being looked up. */
private byte[] metric;
/**
* Tags of the metrics being looked up.
* Each tag is a byte array holding the ID of both the name and value
* of the tag.
* Invariant: an element cannot be both in this array and in group_bys.
*/
private ArrayList<byte[]> tags;
/**
* Tags by which we must group the results.
* Each element is a tag ID.
* Invariant: an element cannot be both in this array and in {@code tags}.
*/
private ArrayList<byte[]> group_bys;
/**
* Values we may be grouping on.
* For certain elements in {@code group_bys}, we may have a specific list of
* values IDs we're looking for. Those IDs are stored in this map. The key
* is an element of {@code group_bys} (so a tag name ID) and the values are
* tag value IDs (at least two).
*/
private ByteMap<byte[][]> group_by_values;
/** If true, use rate of change instead of actual values. */
private boolean rate;
/** Aggregator function to use. */
private Aggregator aggregator;
/**
* Downsampling function to use, if any (can be {@code null}).
* If this is non-null, {@code sample_interval} must be strictly positive.
*/
private Aggregator downsampler;
/** Minimum time interval (in seconds) wanted between each data point. */
private int sample_interval;
/** Constructor. */
public TsdbQuery(final TSDB tsdb) {
this.tsdb = tsdb;
}
public void setStartTime(final long timestamp) {
if ((timestamp & 0xFFFFFFFF00000000L) != 0) {
throw new IllegalArgumentException("Invalid timestamp: " + timestamp);
} else if (end_time != 0 && timestamp >= getEndTime()) {
throw new IllegalArgumentException("new start time (" + timestamp
+ ") is greater than or equal to end time: " + getEndTime());
}
// Keep the 32 bits.
start_time = (int) timestamp;
}
public long getStartTime() {
if (start_time == 0) {
throw new IllegalStateException("setStartTime was never called!");
}
return start_time & 0x00000000FFFFFFFFL;
}
public void setEndTime(final long timestamp) {
if ((timestamp & 0xFFFFFFFF00000000L) != 0) {
throw new IllegalArgumentException("Invalid timestamp: " + timestamp);
} else if (start_time != 0 && timestamp <= getStartTime()) {
throw new IllegalArgumentException("new end time (" + timestamp
+ ") is less than or equal to start time: " + getStartTime());
}
// Keep the 32 bits.
end_time = (int) timestamp;
}
public long getEndTime() {
if (end_time == 0) {
setEndTime(System.currentTimeMillis() / 1000);
}
return end_time;
}
public void setTimeSeries(final String metric,
final Map<String, String> tags,
final Aggregator function,
final boolean rate) throws NoSuchUniqueName {
findGroupBys(tags);
this.metric = tsdb.metrics.getId(metric);
this.tags = Tags.resolveAll(tsdb, tags);
aggregator = function;
this.rate = rate;
}
public void downsample(final int interval, final Aggregator downsampler) {
if (downsampler == null) {
throw new NullPointerException("downsampler");
} else if (interval <= 0) {
throw new IllegalArgumentException("interval not > 0: " + interval);
}
this.downsampler = downsampler;
this.sample_interval = interval;
}
/**
* Extracts all the tags we must use to group results.
* <ul>
* <li>If a tag has the form {@code name=*} then we'll create one
* group per value we find for that tag.</li>
* <li>If a tag has the form {@code name={v1,v2,..,vN}} then we'll
* create {@code N} groups.</li>
* </ul>
* In the both cases above, {@code name} will be stored in the
* {@code group_bys} attribute. In the second case specifically,
* the {@code N} values would be stored in {@code group_by_values},
* the key in this map being {@code name}.
* @param tags The tags from which to extract the 'GROUP BY's.
* Each tag that represents a 'GROUP BY' will be removed from the map
* passed in argument.
*/
private void findGroupBys(final Map<String, String> tags) {
final Iterator<Map.Entry<String, String>> i = tags.entrySet().iterator();
while (i.hasNext()) {
final Map.Entry<String, String> tag = i.next();
final String tagvalue = tag.getValue();
if (tagvalue.equals("*") // 'GROUP BY' with any value.
|| tagvalue.indexOf('|', 1) >= 0) { // Multiple possible values.
if (group_bys == null) {
group_bys = new ArrayList<byte[]>();
}
group_bys.add(tsdb.tag_names.getId(tag.getKey()));
i.remove();
if (tagvalue.charAt(0) == '*') {
continue; // For a 'GROUP BY' with any value, we're done.
}
// 'GROUP BY' with specific values. Need to split the values
// to group on and store their IDs in group_by_values.
final String[] values = Tags.splitString(tagvalue, '|');
if (group_by_values == null) {
group_by_values = new ByteMap<byte[][]>();
}
final short value_width = tsdb.tag_values.width();
final byte[][] value_ids = new byte[values.length][value_width];
group_by_values.put(tsdb.tag_names.getId(tag.getKey()),
value_ids);
for (int j = 0; j < values.length; j++) {
final byte[] value_id = tsdb.tag_values.getId(values[j]);
System.arraycopy(value_id, 0, value_ids[j], 0, value_width);
}
}
}
}
public DataPoints[] run() throws HBaseException {
return groupByAndAggregate(findSpans());
}
private TreeMap<byte[], Span> findSpans() throws HBaseException {
final short metric_width = tsdb.metrics.width();
final TreeMap<byte[], Span> spans = // The key is a row key from HBase.
new TreeMap<byte[], Span>(new SpanCmp(metric_width));
int nrows = 0;
int hbase_time = 0; // milliseconds.
long starttime = System.nanoTime();
final Scanner scanner = getScanner();
try {
ArrayList<ArrayList<KeyValue>> rows;
while ((rows = scanner.nextRows().joinUninterruptibly()) != null) {
hbase_time += (System.nanoTime() - starttime) / 1000000;
for (final ArrayList<KeyValue> row : rows) {
final byte[] key = row.get(0).key();
if (Bytes.memcmp(metric, key, 0, metric_width) != 0) {
throw new IllegalDataException("HBase returned a row that doesn't match"
+ " our scanner (" + scanner + ")! " + row + " does not start"
+ " with " + Arrays.toString(metric));
}
Span datapoints = spans.get(key);
if (datapoints == null) {
datapoints = new Span(tsdb);
spans.put(key, datapoints);
}
datapoints.addRow(row);
nrows++;
starttime = System.nanoTime();
}
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Should never be here", e);
} finally {
hbase_time += (System.nanoTime() - starttime) / 1000000;
scanlatency.add(hbase_time);
}
LOG.info(this + " matched " + nrows + " rows in " + spans.size() + " spans");
if (nrows == 0) {
return null;
}
return spans;
}
/**
* Creates the {@link SpanGroup}s to form the final results of this query.
* @param spans The {@link Span}s found for this query ({@link #findSpans}).
* Can be {@code null}, in which case the array returned will be empty.
* @return A possibly empty array of {@link SpanGroup}s built according to
* any 'GROUP BY' formulated in this query.
*/
private DataPoints[] groupByAndAggregate(final TreeMap<byte[], Span> spans) {
if (spans == null || spans.size() <= 0) {
return NO_RESULT;
}
if (group_bys == null) {
// We haven't been asked to find groups, so let's put all the spans
// together in the same group.
final SpanGroup group = new SpanGroup(tsdb,
getScanStartTime(),
getScanEndTime(),
spans.values(),
rate,
aggregator,
sample_interval, downsampler);
return new SpanGroup[] { group };
}
// Maps group value IDs to the SpanGroup for those values. Say we've
// been asked to group by two things: foo=* bar=* Then the keys in this
// map will contain all the value IDs combinations we've seen. If the
// name IDs for `foo' and `bar' are respectively [0, 0, 7] and [0, 0, 2]
// then we'll have group_bys=[[0, 0, 2], [0, 0, 7]] (notice it's sorted
// by ID, so bar is first) and say we find foo=LOL bar=OMG as well as
// foo=LOL bar=WTF and that the IDs of the tag values are:
// LOL=[0, 0, 1] OMG=[0, 0, 4] WTF=[0, 0, 3]
// then the map will have two keys:
// - one for the LOL-OMG combination: [0, 0, 1, 0, 0, 4] and,
// - one for the LOL-WTF combination: [0, 0, 1, 0, 0, 3].
final ByteMap<SpanGroup> groups = new ByteMap<SpanGroup>();
final short value_width = tsdb.tag_values.width();
final byte[] group = new byte[group_bys.size() * value_width];
for (final Map.Entry<byte[], Span> entry : spans.entrySet()) {
final byte[] row = entry.getKey();
byte[] value_id = null;
int i = 0;
// TODO(tsuna): The following loop has a quadratic behavior. We can
// make it much better since both the row key and group_bys are sorted.
for (final byte[] tag_id : group_bys) {
value_id = Tags.getValueId(tsdb, row, tag_id);
if (value_id == null) {
break;
}
System.arraycopy(value_id, 0, group, i, value_width);
i += value_width;
}
if (value_id == null) {
LOG.error("WTF? Dropping span for row " + Arrays.toString(row)
+ " as it had no matching tag from the requested groups,"
+ " which is unexpected. Query=" + this);
continue;
}
//LOG.info("Span belongs to group " + Arrays.toString(group) + ": " + Arrays.toString(row));
SpanGroup thegroup = groups.get(group);
if (thegroup == null) {
thegroup = new SpanGroup(tsdb, getScanStartTime(), getScanEndTime(),
null, rate, aggregator,
sample_interval, downsampler);
// Copy the array because we're going to keep `group' and overwrite
// its contents. So we want the collection to have an immutable copy.
final byte[] group_copy = new byte[group.length];
System.arraycopy(group, 0, group_copy, 0, group.length);
groups.put(group_copy, thegroup);
}
thegroup.add(entry.getValue());
}
//for (final Map.Entry<byte[], SpanGroup> entry : groups) {
// LOG.info("group for " + Arrays.toString(entry.getKey()) + ": " + entry.getValue());
return groups.values().toArray(new SpanGroup[groups.size()]);
}
/**
* Creates the {@link Scanner} to use for this query.
*/
private Scanner getScanner() throws HBaseException {
final short metric_width = tsdb.metrics.width();
final byte[] start_row = new byte[metric_width + Const.TIMESTAMP_BYTES];
final byte[] end_row = new byte[metric_width + Const.TIMESTAMP_BYTES];
// We search at least one row before and one row after the start & end
// time we've been given as it's quite likely that the exact timestamp
// we're looking for is in the middle of a row. Plus, a number of things
// rely on having a few extra data points before & after the exact start
// & end dates in order to do proper rate calculation or downsampling near
// the "edges" of the graph.
Bytes.setInt(start_row, (int) getScanStartTime(), metric_width);
Bytes.setInt(end_row, (end_time == 0
? -1 // Will scan until the end (0xFFF...).
: (int) getScanEndTime()),
metric_width);
System.arraycopy(metric, 0, start_row, 0, metric_width);
System.arraycopy(metric, 0, end_row, 0, metric_width);
final Scanner scanner = tsdb.client.newScanner(tsdb.table);
scanner.setStartKey(start_row);
scanner.setStopKey(end_row);
if (tags.size() > 0 || group_bys != null) {
createAndSetFilter(scanner);
}
scanner.setFamily(TSDB.FAMILY);
return scanner;
}
/** Returns the UNIX timestamp from which we must start scanning. */
private long getScanStartTime() {
// The reason we look before by `MAX_TIMESPAN * 2' seconds is because of
// the following. Let's assume MAX_TIMESPAN = 600 (10 minutes) and the
// start_time = ... 12:31:00. If we initialize the scanner to look
// only 10 minutes before, we'll start scanning at time=12:21, which will
// give us the row that starts at 12:30 (remember: rows are always aligned
// on MAX_TIMESPAN boundaries -- so in this example, on 10m boundaries).
// But we need to start scanning at least 1 row before, so we actually
// look back by twice MAX_TIMESPAN. Only when start_time is aligned on a
// MAX_TIMESPAN boundary then we'll mistakenly scan back by an extra row,
// but this doesn't really matter.
// Additionally, in case our sample_interval is large, we need to look
// even further before/after, so use that too.
final long ts = getStartTime() - Const.MAX_TIMESPAN * 2 - sample_interval;
return ts > 0 ? ts : 0;
}
/** Returns the UNIX timestamp at which we must stop scanning. */
private long getScanEndTime() {
// For the end_time, we have a different problem. For instance if our
// end_time = ... 12:30:00, we'll stop scanning when we get to 12:40, but
// once again we wanna try to look ahead one more row, so to avoid this
// problem we always add 1 second to the end_time. Only when the end_time
// is of the form HH:59:59 then we will scan ahead an extra row, but once
// again that doesn't really matter.
// Additionally, in case our sample_interval is large, we need to look
// even further before/after, so use that too.
return getEndTime() + Const.MAX_TIMESPAN + 1 + sample_interval;
}
/**
* Sets the server-side regexp filter on the scanner.
* In order to find the rows with the relevant tags, we use a
* server-side filter that matches a regular expression on the row key.
* @param scanner The scanner on which to add the filter.
*/
void createAndSetFilter(final Scanner scanner) {
if (group_bys != null) {
Collections.sort(group_bys, Bytes.MEMCMP);
}
final short name_width = tsdb.tag_names.width();
final short value_width = tsdb.tag_values.width();
final short tagsize = (short) (name_width + value_width);
// Generate a regexp for our tags. Say we have 2 tags: { 0 0 1 0 0 2 }
// and { 4 5 6 9 8 7 }, the regexp will be:
// "^.{7}(?:.{6})*\\Q\000\000\001\000\000\002\\E(?:.{6})*\\Q\004\005\006\011\010\007\\E(?:.{6})*$"
final StringBuilder buf = new StringBuilder(
15 // "^.{N}" + "(?:.{M})*" + "$"
+ ((13 + tagsize) // "(?:.{M})*\\Q" + tagsize bytes + "\\E"
* (tags.size() + (group_bys == null ? 0 : group_bys.size() * 3))));
// In order to avoid re-allocations, reserve a bit more w/ groups ^^^
// Alright, let's build this regexp. From the beginning...
buf.append("(?s)" // Ensure we use the DOTALL flag.
+ "^.{")
// ... start by skipping the metric ID and timestamp.
.append(tsdb.metrics.width() + Const.TIMESTAMP_BYTES)
.append("}");
final Iterator<byte[]> tags = this.tags.iterator();
final Iterator<byte[]> group_bys = (this.group_bys == null
? new ArrayList<byte[]>(0).iterator()
: this.group_bys.iterator());
byte[] tag = tags.hasNext() ? tags.next() : null;
byte[] group_by = group_bys.hasNext() ? group_bys.next() : null;
// Tags and group_bys are already sorted. We need to put them in the
// regexp in order by ID, which means we just merge two sorted lists.
do {
// Skip any number of tags.
buf.append("(?:.{").append(tagsize).append("})*\\Q");
if (isTagNext(name_width, tag, group_by)) {
addId(buf, tag);
tag = tags.hasNext() ? tags.next() : null;
} else { // Add a group_by.
addId(buf, group_by);
final byte[][] value_ids = (group_by_values == null
? null
: group_by_values.get(group_by));
if (value_ids == null) { // We don't want any specific ID...
buf.append(".{").append(value_width).append('}'); // Any value ID.
} else { // We want specific IDs. List them: /(AAA|BBB|CCC|..)/
buf.append("(?:");
for (final byte[] value_id : value_ids) {
buf.append("\\Q");
addId(buf, value_id);
buf.append('|');
}
// Replace the pipe of the last iteration.
buf.setCharAt(buf.length() - 1, ')');
}
group_by = group_bys.hasNext() ? group_bys.next() : null;
}
} while (tag != group_by); // Stop when they both become null.
// Skip any number of tags before the end.
buf.append("(?:.{").append(tagsize).append("})*$");
scanner.setKeyRegexp(buf.toString(), CHARSET);
}
/**
* Helper comparison function to compare tag name IDs.
* @param name_width Number of bytes used by a tag name ID.
* @param tag A tag (array containing a tag name ID and a tag value ID).
* @param group_by A tag name ID.
* @return {@code true} number if {@code tag} should be used next (because
* it contains a smaller ID), {@code false} otherwise.
*/
private boolean isTagNext(final short name_width,
final byte[] tag,
final byte[] group_by) {
if (tag == null) {
return false;
} else if (group_by == null) {
return true;
}
final int cmp = Bytes.memcmp(tag, group_by, 0, name_width);
if (cmp == 0) {
throw new AssertionError("invariant violation: tag ID "
+ Arrays.toString(group_by) + " is both in 'tags' and"
+ " 'group_bys' in " + this);
}
return cmp < 0;
}
/**
* Appends the given ID to the given buffer, followed by "\\E".
*/
private static void addId(final StringBuilder buf, final byte[] id) {
boolean backslash = false;
for (final byte b : id) {
buf.append((char) (b & 0xFF));
if (b == 'E' && backslash) { // If we saw a `\' and now we have a `E'.
// So we just terminated the quoted section because we just added \E
// to `buf'. So let's put a litteral \E now and start quoting again.
buf.append("\\\\E\\Q");
} else {
backslash = b == '\\';
}
}
buf.append("\\E");
}
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append("TsdbQuery(start_time=")
.append(getStartTime())
.append(", end_time=")
.append(getEndTime())
.append(", metric=").append(Arrays.toString(metric));
try {
buf.append(" (").append(tsdb.metrics.getName(metric));
} catch (NoSuchUniqueId e) {
buf.append(" (<").append(e.getMessage()).append('>');
}
try {
buf.append("), tags=").append(Tags.resolveIds(tsdb, tags));
} catch (NoSuchUniqueId e) {
buf.append("), tags=<").append(e.getMessage()).append('>');
}
buf.append(", rate=").append(rate)
.append(", aggregator=").append(aggregator)
.append(", group_bys=(");
if (group_bys != null) {
for (final byte[] tag_id : group_bys) {
try {
buf.append(tsdb.tag_names.getName(tag_id));
} catch (NoSuchUniqueId e) {
buf.append('<').append(e.getMessage()).append('>');
}
buf.append(' ')
.append(Arrays.toString(tag_id));
if (group_by_values != null) {
final byte[][] value_ids = group_by_values.get(tag_id);
if (value_ids == null) {
continue;
}
buf.append("={");
for (final byte[] value_id : value_ids) {
try {
buf.append(tsdb.tag_values.getName(value_id));
} catch (NoSuchUniqueId e) {
buf.append('<').append(e.getMessage()).append('>');
}
buf.append(' ')
.append(Arrays.toString(value_id))
.append(", ");
}
buf.append('}');
}
buf.append(", ");
}
}
buf.append("))");
return buf.toString();
}
/**
* Comparator that ignores timestamps in row keys.
*/
private static final class SpanCmp implements Comparator<byte[]> {
private final short metric_width;
public SpanCmp(final short metric_width) {
this.metric_width = metric_width;
}
public int compare(final byte[] a, final byte[] b) {
final int length = Math.min(a.length, b.length);
if (a == b) { // Do this after accessing a.length and b.length
return 0; // in order to NPE if either a or b is null.
}
int i;
// First compare the metric ID.
for (i = 0; i < metric_width; i++) {
if (a[i] != b[i]) {
return (a[i] & 0xFF) - (b[i] & 0xFF); // "promote" to unsigned.
}
}
// Then skip the timestamp and compare the rest.
for (i += Const.TIMESTAMP_BYTES; i < length; i++) {
if (a[i] != b[i]) {
return (a[i] & 0xFF) - (b[i] & 0xFF); // "promote" to unsigned.
}
}
return a.length - b.length;
}
}
}
|
package org.mtransit.android.data;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import org.mtransit.android.R;
import org.mtransit.android.commons.CollectionUtils;
import org.mtransit.android.commons.Constants;
import org.mtransit.android.commons.LocationUtils;
import org.mtransit.android.commons.MTLog;
import org.mtransit.android.commons.SensorUtils;
import org.mtransit.android.commons.TaskUtils;
import org.mtransit.android.commons.ThemeUtils;
import org.mtransit.android.commons.TimeUtils;
import org.mtransit.android.commons.api.SupportFactory;
import org.mtransit.android.commons.data.AppStatus;
import org.mtransit.android.commons.data.AvailabilityPercent;
import org.mtransit.android.commons.data.POI;
import org.mtransit.android.commons.data.POIStatus;
import org.mtransit.android.commons.data.Route;
import org.mtransit.android.commons.data.RouteTripStop;
import org.mtransit.android.commons.data.Schedule;
import org.mtransit.android.commons.data.ServiceUpdate;
import org.mtransit.android.commons.task.MTAsyncTask;
import org.mtransit.android.commons.ui.widget.MTArrayAdapter;
import org.mtransit.android.provider.FavoriteManager;
import org.mtransit.android.task.ServiceUpdateLoader;
import org.mtransit.android.task.StatusLoader;
import org.mtransit.android.ui.MainActivity;
import org.mtransit.android.ui.fragment.AgencyTypeFragment;
import org.mtransit.android.ui.fragment.NearbyFragment;
import org.mtransit.android.ui.fragment.RTSRouteFragment;
import org.mtransit.android.ui.view.MTCompassView;
import org.mtransit.android.ui.view.MTJPathsView;
import org.mtransit.android.ui.view.MTOnClickListener;
import org.mtransit.android.ui.view.MTOnItemClickListener;
import org.mtransit.android.ui.view.MTOnItemLongClickListener;
import org.mtransit.android.ui.view.MTOnLongClickListener;
import org.mtransit.android.ui.view.MTPieChartPercentView;
import org.mtransit.android.util.CrashUtils;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class POIArrayAdapter extends MTArrayAdapter<POIManager> implements SensorUtils.CompassListener, AdapterView.OnItemClickListener,
AdapterView.OnItemLongClickListener, SensorEventListener, AbsListView.OnScrollListener, StatusLoader.StatusLoaderListener,
ServiceUpdateLoader.ServiceUpdateLoaderListener, FavoriteManager.FavoriteUpdateListener, SensorUtils.SensorTaskCompleted,
TimeUtils.TimeChangedReceiver.TimeChangedListener {
private static final String TAG = POIArrayAdapter.class.getSimpleName();
private String tag = TAG;
@Override
public String getLogTag() {
return tag;
}
public void setTag(String tag) {
this.tag = TAG + "-" + tag;
}
public static final int TYPE_HEADER_NONE = 0;
public static final int TYPE_HEADER_BASIC = 1;
public static final int TYPE_HEADER_ALL_NEARBY = 2;
public static final int TYPE_HEADER_MORE = 3;
private LayoutInflater layoutInflater;
private LinkedHashMap<Integer, ArrayList<POIManager>> poisByType;
private HashSet<String> favUUIDs;
private HashMap<String, Integer> favUUIDsFolderIds;
private WeakReference<Activity> activityWR;
private Location location;
private int lastCompassInDegree = -1;
private float locationDeclination;
private HashSet<String> closestPoiUuids;
private float[] accelerometerValues = new float[3];
private float[] magneticFieldValues = new float[3];
private boolean showStatus = true; // show times / availability
private boolean showServiceUpdate = true; // show warning icon
private boolean showFavorite = true; // show favorite star
private boolean showBrowseHeaderSection = false; // show header with shortcut to agency type screens
private int showTypeHeader = TYPE_HEADER_NONE;
private boolean showTypeHeaderNearby = false; // show nearby header instead of default type header
private boolean infiniteLoading = false; // infinite loading
private InfiniteLoadingListener infiniteLoadingListener;
private ViewGroup manualLayout;
private ScrollView manualScrollView;
private long lastNotifyDataSetChanged = -1L;
private int scrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
private long nowToTheMinute = -1L;
private boolean timeChangedReceiverEnabled = false;
private boolean compassUpdatesEnabled = false;
private long lastCompassChanged = -1L;
private FavoriteManager.FavoriteUpdateListener favoriteUpdateListener = this;
public POIArrayAdapter(Activity activity) {
super(activity, -1);
setActivity(activity);
this.layoutInflater = LayoutInflater.from(getContext());
}
public void setManualLayout(ViewGroup manualLayout) {
this.manualLayout = manualLayout;
}
public void setFavoriteUpdateListener(FavoriteManager.FavoriteUpdateListener favoriteUpdateListener) {
this.favoriteUpdateListener = favoriteUpdateListener;
}
public void setShowStatus(boolean showData) {
this.showStatus = showData;
}
public void setShowServiceUpdate(boolean showServiceUpdate) {
this.showServiceUpdate = showServiceUpdate;
}
public void setShowFavorite(boolean showFavorite) {
this.showFavorite = showFavorite;
}
public void setShowBrowseHeaderSection(boolean showBrowseHeaderSection) {
this.showBrowseHeaderSection = showBrowseHeaderSection;
}
public void setShowTypeHeader(int showTypeHeader) {
this.showTypeHeader = showTypeHeader;
}
public void setShowTypeHeaderNearby(boolean showTypeHeaderNearby) {
this.showTypeHeaderNearby = showTypeHeaderNearby;
}
public void setInfiniteLoading(boolean infiniteLoading) {
this.infiniteLoading = infiniteLoading;
}
public void setInfiniteLoadingListener(InfiniteLoadingListener infiniteLoadingListener) {
this.infiniteLoadingListener = infiniteLoadingListener;
}
public interface InfiniteLoadingListener {
boolean isLoadingMore();
boolean showingDone();
}
private static final int VIEW_TYPE_COUNT = 11;
/**
* @see #getItemViewType(int)
*/
@Override
public int getViewTypeCount() {
return VIEW_TYPE_COUNT;
}
/**
* @see #getViewTypeCount()
*/
@Override
public int getItemViewType(int position) {
POIManager poim = getItem(position);
if (poim == null) {
if (this.showBrowseHeaderSection && position == 0) {
return 0; // BROWSE SECTION
}
if (this.infiniteLoading && position + 1 == getCount()) {
return 9; // LOADING FOOTER
}
if (this.showTypeHeader != TYPE_HEADER_NONE) {
if (this.poisByType != null) {
Integer typeId = getItemTypeHeader(position);
if (typeId != null) {
if (FavoriteManager.isFavoriteDataSourceId(typeId)) {
return 10; // TYPE FAVORITE FOLDER
}
return 8; // TYPE HEADER
}
}
}
CrashUtils.w(this, "Cannot find type for at position '%s'!", position);
return IGNORE_ITEM_VIEW_TYPE;
}
int type = poim.poi.getType();
int statusType = poim.getStatusType();
switch (type) {
case POI.ITEM_VIEW_TYPE_TEXT_MESSAGE:
return 7; // TEXT MESSAGE
case POI.ITEM_VIEW_TYPE_MODULE:
switch (statusType) {
case POI.ITEM_STATUS_TYPE_SCHEDULE:
return 5; // MODULE & APP STATUS
default:
return 6; // MODULE
}
case POI.ITEM_VIEW_TYPE_ROUTE_TRIP_STOP:
switch (statusType) {
case POI.ITEM_STATUS_TYPE_SCHEDULE:
return 3; // RTS & SCHEDULE
default:
return 4; // RTS
}
case POI.ITEM_VIEW_TYPE_BASIC_POI:
switch (statusType) {
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
return 1; // DEFAULT & AVAILABILITY %
default:
return 2; // DEFAULT
}
default:
CrashUtils.w(this, "Cannot find POI type for at position '%s'!", position);
return 2; // DEFAULT
}
}
private int count = -1;
@Override
public int getCount() {
if (this.count < 0) {
initCount();
}
return this.count;
}
private void initCount() {
this.count = 0;
if (this.showBrowseHeaderSection) {
this.count++;
}
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
if (this.showTypeHeader != TYPE_HEADER_NONE) {
this.count++;
}
this.count += this.poisByType.get(type).size();
}
}
if (this.infiniteLoading) {
this.count++;
}
}
@Override
public int getPosition(POIManager item) {
int position = 0;
if (this.showBrowseHeaderSection) {
position++;
}
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
if (this.showTypeHeader != TYPE_HEADER_NONE) {
position++;
}
int indexOf = this.poisByType.get(type).indexOf(item);
if (indexOf >= 0) {
return position + indexOf;
}
position += this.poisByType.get(type).size();
}
}
return position;
}
@Override
public POIManager getItem(int position) {
int index = 0;
if (this.showBrowseHeaderSection) {
index++;
}
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
if (this.showTypeHeader != TYPE_HEADER_NONE) {
index++;
}
if (position >= index && position < index + this.poisByType.get(type).size()) {
return this.poisByType.get(type).get(position - index);
}
index += this.poisByType.get(type).size();
}
}
return null;
}
public POIManager getItem(String uuid) {
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
for (POIManager poim : this.poisByType.get(type)) {
if (poim.poi.getUUID().equals(uuid)) {
return poim;
}
}
}
}
return null;
}
public Integer getItemTypeHeader(int position) {
int index = 0;
if (this.showBrowseHeaderSection) {
index++;
}
if (this.showTypeHeader != TYPE_HEADER_NONE && this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
if (index == position) {
return type;
}
index++;
index += this.poisByType.get(type).size();
}
}
return null;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @Nullable ViewGroup parent) {
POIManager poim = getItem(position);
if (poim == null) {
if (this.showBrowseHeaderSection && position == 0) {
return getBrowseHeaderSectionView(convertView, parent);
}
if (this.infiniteLoading && position + 1 == getCount()) {
return getInfiniteLoadingView(convertView, parent);
}
if (this.showTypeHeader != TYPE_HEADER_NONE) {
Integer typeId = getItemTypeHeader(position);
if (typeId != null) {
if (FavoriteManager.isFavoriteDataSourceId(typeId)) {
int favoriteFolderId = FavoriteManager.extractFavoriteFolderId(typeId);
if (FavoriteManager.get(getContext()).hasFavoriteFolder(favoriteFolderId)) {
return getFavoriteFolderHeaderView(FavoriteManager.get(getContext()).getFolder(favoriteFolderId), convertView, parent);
}
}
DataSourceType dst = DataSourceType.parseId(typeId);
if (dst != null) {
return getTypeHeaderView(dst, convertView, parent);
}
}
}
CrashUtils.w(this, "getView() > Cannot create view for null poi at position '%s'!", position);
return getInfiniteLoadingView(convertView, parent);
}
switch (poim.poi.getType()) {
case POI.ITEM_VIEW_TYPE_TEXT_MESSAGE:
return getTextMessageView(poim, convertView, parent);
case POI.ITEM_VIEW_TYPE_MODULE:
return getModuleView(poim, convertView, parent);
case POI.ITEM_VIEW_TYPE_ROUTE_TRIP_STOP:
return getRouteTripStopView(poim, convertView, parent);
case POI.ITEM_VIEW_TYPE_BASIC_POI:
return getBasicPOIView(poim, convertView, parent);
default:
CrashUtils.w(this, "getView() > Unknown view type at position %s!", position);
return getBasicPOIView(poim, convertView, parent);
}
}
@NonNull
private View getInfiniteLoadingView(@Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_infinite_loading, parent, false);
InfiniteLoadingViewHolder holder = new InfiniteLoadingViewHolder();
holder.progressBar = convertView.findViewById(R.id.progress_bar);
holder.worldExplored = convertView.findViewById(R.id.worldExploredTv);
convertView.setTag(holder);
}
InfiniteLoadingViewHolder holder = (InfiniteLoadingViewHolder) convertView.getTag();
if (this.infiniteLoadingListener != null) {
if (this.infiniteLoadingListener.isLoadingMore()) {
holder.worldExplored.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.VISIBLE);
convertView.setVisibility(View.VISIBLE);
} else if (this.infiniteLoadingListener.showingDone()) {
holder.progressBar.setVisibility(View.GONE);
holder.worldExplored.setVisibility(View.VISIBLE);
convertView.setVisibility(View.VISIBLE);
} else {
convertView.setVisibility(View.GONE);
}
} else {
convertView.setVisibility(View.GONE);
}
return convertView;
}
private int nbAgencyTypes = -1;
private View getBrowseHeaderSectionView(@Nullable View convertView, @Nullable ViewGroup parent) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
DataSourceProvider dataSourceProvider = DataSourceProvider.get(activity);
int agenciesCount = dataSourceProvider == null ? 0 : dataSourceProvider.getAllAgenciesCount();
if (convertView == null || this.nbAgencyTypes != agenciesCount) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_list_browse_header, parent, false);
}
LinearLayout gridLL = (LinearLayout) convertView.findViewById(R.id.gridLL);
gridLL.removeAllViews();
ArrayList<DataSourceType> allAgencyTypes = dataSourceProvider == null ? null : dataSourceProvider.getAvailableAgencyTypes();
this.nbAgencyTypes = CollectionUtils.getSize(allAgencyTypes);
if (allAgencyTypes == null) {
gridLL.setVisibility(View.GONE);
} else {
int availableButtons = 0;
View gridLine = null;
View btn;
TextView btnTv;
for (final DataSourceType dst : allAgencyTypes) {
if (dst.getId() == DataSourceType.TYPE_MODULE.getId() && availableButtons == 0 && allAgencyTypes.size() > 2) {
continue;
}
if (dst.getId() == DataSourceType.TYPE_PLACE.getId()) {
continue;
}
if (availableButtons == 0) {
gridLine = this.layoutInflater.inflate(R.layout.layout_poi_list_browse_header_line, this.manualLayout, false);
gridLL.addView(gridLine);
availableButtons = 2;
}
btn = gridLine.findViewById(availableButtons == 2 ? R.id.btn1 : R.id.btn2);
btnTv = (TextView) gridLine.findViewById(availableButtons == 2 ? R.id.btn1Tv : R.id.btn2Tv);
btnTv.setText(dst.getAllStringResId());
if (dst.getWhiteIconResId() != -1) {
btnTv.setCompoundDrawablesWithIntrinsicBounds(dst.getWhiteIconResId(), 0, 0, 0);
} else {
btnTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
}
btn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
onTypeHeaderButtonClick(TypeHeaderButtonsClickListener.BUTTON_ALL, dst);
}
});
btn.setVisibility(View.VISIBLE);
availableButtons
}
if (gridLine != null && availableButtons == 1) {
gridLine.findViewById(R.id.btn2).setVisibility(View.GONE);
}
gridLL.setVisibility(View.VISIBLE);
}
}
return convertView;
}
private void updateCommonViewManual(int position, View convertView) {
if (convertView == null || convertView.getTag() == null || !(convertView.getTag() instanceof CommonViewHolder)) {
return;
}
CommonViewHolder holder = (CommonViewHolder) convertView.getTag();
POIManager poim = getItem(position);
updateCommonView(holder, poim);
updatePOIStatus(holder.statusViewHolder, poim);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MTOnItemClickListener.onItemClickS(parent, view, position, id, new MTOnItemClickListener() {
@Override
public void onItemClickMT(AdapterView<?> parent, View view, int position, long id) {
showPoiViewerScreen(position);
}
});
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return MTOnItemLongClickListener.onItemLongClickS(parent, view, position, id, new MTOnItemLongClickListener() {
@Override
public boolean onItemLongClickMT(AdapterView<?> parent, View view, int position, long id) {
return showPoiMenu(position);
}
});
}
public interface OnClickHandledListener {
void onLeaving();
}
private WeakReference<OnClickHandledListener> onClickHandledListenerWR;
public void setOnClickHandledListener(OnClickHandledListener onClickHandledListener) {
this.onClickHandledListenerWR = new WeakReference<OnClickHandledListener>(onClickHandledListener);
}
public interface OnPOISelectedListener {
boolean onPOISelected(POIManager poim);
boolean onPOILongSelected(POIManager poim);
}
private WeakReference<OnPOISelectedListener> onPoiSelectedListenerWR;
public void setOnPoiSelectedListener(OnPOISelectedListener onPoiSelectedListener) {
this.onPoiSelectedListenerWR = new WeakReference<OnPOISelectedListener>(onPoiSelectedListener);
}
public boolean showPoiViewerScreen(int position) {
boolean handled = false;
POIManager poim = getItem(position);
if (poim != null) {
OnPOISelectedListener listener = this.onPoiSelectedListenerWR == null ? null : this.onPoiSelectedListenerWR.get();
handled = listener != null && listener.onPOISelected(poim);
if (!handled) {
handled = showPoiViewerScreen(poim);
}
}
return handled;
}
public boolean showPoiMenu(int position) {
boolean handled = false;
POIManager poim = getItem(position);
if (poim != null) {
OnPOISelectedListener listener = this.onPoiSelectedListenerWR == null ? null : this.onPoiSelectedListenerWR.get();
handled = listener != null && listener.onPOILongSelected(poim);
if (!handled) {
handled = showPoiMenu(poim);
}
}
return handled;
}
@Override
public boolean areAllItemsEnabled() {
return false; // to hide divider around disabled items (list view background visible behind hidden divider)
// return true; // to show divider around disabled items
}
@Override
public boolean isEnabled(int position) {
return getItemTypeHeader(position) == null; // is NOT separator
}
public boolean showPoiViewerScreen(POIManager poim) {
if (poim == null) {
return false;
}
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity == null) {
return false;
}
OnClickHandledListener listener = this.onClickHandledListenerWR == null ? null : this.onClickHandledListenerWR.get();
return poim.onActionItemClick(activity, FavoriteManager.get(getContext()).getFavoriteFolders(), this.favoriteUpdateListener, listener);
}
public boolean showPoiMenu(POIManager poim) {
if (poim == null) {
return false;
}
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity == null) {
return false;
}
OnClickHandledListener listener = this.onClickHandledListenerWR == null ? null : this.onClickHandledListenerWR.get();
return poim.onActionItemLongClick(activity, FavoriteManager.get(getContext()).getFavoriteFolders(), this.favoriteUpdateListener, listener);
}
@Override
public void onFavoriteUpdated() {
refreshFavorites();
}
public void setPois(ArrayList<POIManager> pois) {
if (this.poisByType != null) {
this.poisByType.clear();
}
this.poiUUID.clear();
boolean dataSetChanged = append(pois, true);
if (dataSetChanged) {
notifyDataSetChanged();
}
}
private HashSet<String> poiUUID = new HashSet<String>();
public void appendPois(ArrayList<POIManager> pois) {
boolean dataSetChanged = append(pois, false);
if (dataSetChanged) {
notifyDataSetChanged();
}
}
private boolean append(ArrayList<POIManager> pois, boolean dataSetChanged) {
if (pois != null) {
if (this.poisByType == null) {
this.poisByType = new LinkedHashMap<Integer, ArrayList<POIManager>>();
}
for (POIManager poim : pois) {
if (!this.poisByType.containsKey(poim.poi.getDataSourceTypeId())) {
this.poisByType.put(poim.poi.getDataSourceTypeId(), new ArrayList<POIManager>());
}
if (!this.poiUUID.contains(poim.poi.getUUID())) {
this.poisByType.get(poim.poi.getDataSourceTypeId()).add(poim);
this.poiUUID.add(poim.poi.getUUID());
dataSetChanged = true;
}
}
}
if (dataSetChanged) {
this.lastNotifyDataSetChanged = -1; // last notify was with old data
initCount();
initPoisCount();
refreshFavorites();
updateClosestPoi();
}
return dataSetChanged;
}
private void resetCounts() {
this.count = -1;
this.poisCount = -1;
}
public boolean isInitialized() {
return this.poisByType != null;
}
private int poisCount = -1;
public int getPoisCount() {
if (this.poisCount < 0) {
initPoisCount();
}
return this.poisCount;
}
private void initPoisCount() {
this.poisCount = 0;
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
this.poisCount += this.poisByType.get(type).size();
}
}
}
public boolean hasPois() {
return getPoisCount() > 0;
}
private void updateClosestPoi() {
if (getPoisCount() == 0) {
this.closestPoiUuids = null;
return;
}
this.closestPoiUuids = new HashSet<String>();
if (this.poisByType != null) {
for (Integer type : this.poisByType.keySet()) {
ArrayList<POIManager> orderedPoims = new ArrayList<POIManager>(this.poisByType.get(type));
if (orderedPoims.size() > 0) {
CollectionUtils.sort(orderedPoims, LocationUtils.POI_DISTANCE_COMPARATOR);
POIManager theClosestOne = orderedPoims.get(0);
float theClosestDistance = theClosestOne.getDistance();
if (theClosestDistance > 0) {
for (POIManager poim : orderedPoims) {
if (poim.getDistance() <= theClosestDistance) {
this.closestPoiUuids.add(poim.poi.getUUID());
continue;
}
break;
}
}
}
}
}
}
public boolean hasClosestPOI() {
return this.closestPoiUuids != null && this.closestPoiUuids.size() > 0;
}
public boolean isClosestPOI(int position) {
if (this.closestPoiUuids == null) {
return false;
}
POIManager poim = getItem(position);
return poim != null && this.closestPoiUuids.contains(poim.poi.getUUID());
}
public POIManager getClosestPOI() {
if (this.closestPoiUuids == null || this.closestPoiUuids.size() == 0) {
return null;
}
String closestPOIUUID = this.closestPoiUuids.iterator().next();
return getItem(closestPOIUUID);
}
private MTAsyncTask<Location, Void, Void> updateDistanceWithStringTask;
private void updateDistances(Location currentLocation) {
TaskUtils.cancelQuietly(this.updateDistanceWithStringTask, true);
if (currentLocation != null && getPoisCount() > 0) {
this.updateDistanceWithStringTask = new MTAsyncTask<Location, Void, Void>() {
@Override
public String getLogTag() {
return POIArrayAdapter.class.getSimpleName() + ">updateDistanceWithStringTask";
}
@Override
protected Void doInBackgroundMT(Location... params) {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
try {
if (POIArrayAdapter.this.poisByType != null) {
Iterator<ArrayList<POIManager>> it = POIArrayAdapter.this.poisByType.values().iterator();
while (it.hasNext()) {
if (isCancelled()) {
break;
}
LocationUtils.updateDistanceWithString(POIArrayAdapter.this.getContext(), it.next(), params[0], this);
}
}
} catch (Exception e) {
MTLog.w(POIArrayAdapter.this, e, "Error while update POIs distance strings!");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (isCancelled()) {
return;
}
updateClosestPoi();
notifyDataSetChanged(true);
}
};
TaskUtils.execute(this.updateDistanceWithStringTask, currentLocation);
}
}
@Deprecated
public void updateDistancesNowSync(Location currentLocation) {
if (currentLocation != null) {
if (this.poisByType != null) {
Iterator<ArrayList<POIManager>> it = this.poisByType.values().iterator();
while (it.hasNext()) {
ArrayList<POIManager> pois = it.next();
LocationUtils.updateDistanceWithString(getContext(), pois, currentLocation, null);
}
}
updateClosestPoi();
}
setLocation(currentLocation);
}
public void updateDistanceNowAsync(Location currentLocation) {
this.location = null; // clear current location to force refresh
setLocation(currentLocation);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
setScrollState(scrollState);
}
public void setScrollState(int scrollState) {
this.scrollState = scrollState;
}
@Override
public void onStatusLoaded(POIStatus status) {
if (this.showStatus) {
CommonStatusViewHolder statusViewHolder = this.poiStatusViewHoldersWR.get(status.getTargetUUID());
if (statusViewHolder != null && status.getTargetUUID().equals(statusViewHolder.uuid)) {
updatePOIStatus(statusViewHolder, status);
} else {
notifyDataSetChanged(false);
}
}
}
@Override
public void onServiceUpdatesLoaded(String targetUUID, ArrayList<ServiceUpdate> serviceUpdates) {
if (this.showServiceUpdate) {
CommonStatusViewHolder statusViewHolder = this.poiStatusViewHoldersWR.get(targetUUID);
if (statusViewHolder != null && targetUUID.equals(statusViewHolder.uuid)) {
updateServiceUpdate(statusViewHolder, ServiceUpdate.isSeverityWarning(serviceUpdates));
} else {
notifyDataSetChanged(false);
}
}
}
public void notifyDataSetChanged(boolean force) {
notifyDataSetChanged(force, Constants.ADAPTER_NOTIFY_THRESHOLD_IN_MS);
}
private Handler handler = new Handler();
private Runnable notifyDataSetChangedLater = new Runnable() {
@Override
public void run() {
notifyDataSetChanged(true); // still really need to show new data
}
};
public void notifyDataSetChanged(boolean force, long minAdapterThresholdInMs) {
long now = TimeUtils.currentTimeMillis();
long adapterThreshold = Math.max(minAdapterThresholdInMs, Constants.ADAPTER_NOTIFY_THRESHOLD_IN_MS);
if (this.scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && (force || (now - this.lastNotifyDataSetChanged) > adapterThreshold)) {
notifyDataSetChanged();
notifyDataSetChangedManual();
this.lastNotifyDataSetChanged = now;
this.handler.removeCallbacks(this.notifyDataSetChangedLater);
} else {
if (force) {
this.handler.postDelayed(this.notifyDataSetChangedLater, adapterThreshold);
}
}
}
private void notifyDataSetChangedManual() {
if (this.manualLayout != null && hasPois()) {
int position = 0;
for (int i = 0; i < this.manualLayout.getChildCount(); i++) {
View view = this.manualLayout.getChildAt(i);
if (view instanceof FrameLayout) {
view = ((FrameLayout) view).getChildAt(0);
}
Object tag = view.getTag();
if (tag != null && tag instanceof CommonViewHolder) {
updateCommonViewManual(position, view);
position++;
}
}
}
}
public void setListView(AbsListView listView) {
listView.setOnItemClickListener(this);
listView.setOnItemLongClickListener(this);
listView.setOnScrollListener(this);
listView.setAdapter(this);
}
public void initManual() {
if (this.manualLayout != null && hasPois()) {
this.manualLayout.removeAllViews(); // clear the previous list
for (int i = 0; i < getPoisCount(); i++) {
if (this.manualLayout.getChildCount() > 0) {
this.manualLayout.addView(this.layoutInflater.inflate(R.layout.list_view_divider, this.manualLayout, false));
}
View view = getView(i, null, this.manualLayout);
FrameLayout frameLayout = new FrameLayout(getContext());
frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
frameLayout.addView(view);
View selectorView = new View(getContext());
SupportFactory.get().setBackground(selectorView, ThemeUtils.obtainStyledDrawable(getContext(), R.attr.selectableItemBackground));
selectorView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
frameLayout.addView(selectorView);
final int position = i;
frameLayout.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
showPoiViewerScreen(position);
}
});
frameLayout.setOnLongClickListener(new MTOnLongClickListener() {
@Override
public boolean onLongClickkMT(View view) {
return showPoiMenu(position);
}
});
this.manualLayout.addView(frameLayout);
}
}
}
public void scrollManualScrollViewTo(int x, int y) {
if (this.manualScrollView != null) {
this.manualScrollView.scrollTo(x, y);
}
}
public void setManualScrollView(ScrollView scrollView) {
this.manualScrollView = scrollView;
if (scrollView == null) {
return;
}
scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_SCROLL:
case MotionEvent.ACTION_MOVE:
setScrollState(AbsListView.OnScrollListener.SCROLL_STATE_FLING);
break;
case MotionEvent.ACTION_DOWN:
setScrollState(AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// scroll view can still by flying
setScrollState(AbsListView.OnScrollListener.SCROLL_STATE_IDLE);
break;
default:
MTLog.v(POIArrayAdapter.this, "Unexpected event %s", event);
}
return false;
}
});
}
public void setLocation(Location newLocation) {
if (newLocation != null) {
if (this.location == null || LocationUtils.isMoreRelevant(getLogTag(), this.location, newLocation)) {
this.location = newLocation;
this.locationDeclination = SensorUtils.getLocationDeclination(this.location);
if (!this.compassUpdatesEnabled) {
SensorUtils.registerCompassListener(getContext(), this);
this.compassUpdatesEnabled = true;
}
updateDistances(this.location);
}
}
}
public void onPause() {
if (this.activityWR != null) {
this.activityWR.clear();
this.activityWR = null;
}
if (this.compassUpdatesEnabled) {
SensorUtils.unregisterSensorListener(getContext(), this);
this.compassUpdatesEnabled = false;
}
this.handler.removeCallbacks(this.notifyDataSetChangedLater);
TaskUtils.cancelQuietly(this.refreshFavoritesTask, true);
disableTimeChangedReceiver();
}
@Override
public String toString() {
return new StringBuilder().append(POIArrayAdapter.class.getSimpleName())
.append(getLogTag())
.toString();
}
public void onResume(Activity activity, Location userLocation) {
setActivity(activity);
this.location = null; // clear current location to force refresh
setLocation(userLocation);
refreshFavorites();
}
public void setActivity(Activity activity) {
this.activityWR = new WeakReference<Activity>(activity);
}
@Override
public void clear() {
if (this.poisByType != null) {
this.poisByType.clear();
this.poisByType = null; // not initialized
}
resetCounts();
if (this.poiUUID != null) {
this.poiUUID.clear();
}
if (this.closestPoiUuids != null) {
this.closestPoiUuids.clear();
this.closestPoiUuids = null;
}
disableTimeChangedReceiver();
if (this.compassImgsWR != null) {
this.compassImgsWR.clear();
}
this.lastCompassChanged = -1;
this.lastCompassInDegree = -1;
this.accelerometerValues = new float[3];
this.magneticFieldValues = new float[3];
this.lastNotifyDataSetChanged = -1L;
this.handler.removeCallbacks(this.notifyDataSetChangedLater);
this.poiStatusViewHoldersWR.clear();
TaskUtils.cancelQuietly(this.refreshFavoritesTask, true);
TaskUtils.cancelQuietly(this.updateDistanceWithStringTask, true);
this.location = null;
this.locationDeclination = 0f;
super.clear();
}
public void onDestroy() {
disableTimeChangedReceiver();
if (this.poisByType != null) {
this.poisByType.clear();
this.poisByType = null;
}
resetCounts();
if (this.poiUUID != null) {
this.poiUUID.clear();
}
if (this.compassImgsWR != null) {
this.compassImgsWR.clear();
}
this.poiStatusViewHoldersWR.clear();
if (this.onClickHandledListenerWR != null) {
this.onClickHandledListenerWR.clear();
}
if (this.onPoiSelectedListenerWR != null) {
this.onPoiSelectedListenerWR.clear();
}
}
@Override
public void updateCompass(float orientation, boolean force) {
if (getPoisCount() == 0) {
return;
}
long now = TimeUtils.currentTimeMillis();
int roundedOrientation = SensorUtils.convertToPosivite360Degree((int) orientation);
SensorUtils.updateCompass(force, this.location, roundedOrientation, now, this.scrollState, this.lastCompassChanged, this.lastCompassInDegree,
Constants.ADAPTER_NOTIFY_THRESHOLD_IN_MS, this);
}
@Override
public void onSensorTaskCompleted(boolean result, int roundedOrientation, long now) {
if (!result) {
return;
}
this.lastCompassInDegree = roundedOrientation;
this.lastCompassChanged = now;
if (!this.compassUpdatesEnabled || this.location == null || this.lastCompassInDegree < 0) {
return;
}
if (this.compassImgsWR == null) {
return;
}
for (WeakHashMap.Entry<MTCompassView, View> compassAndDistance : this.compassImgsWR.entrySet()) {
MTCompassView compassView = compassAndDistance.getKey();
if (compassView != null && compassView.isHeadingSet()) {
compassView.generateAndSetHeading(this.location, this.lastCompassInDegree, this.locationDeclination);
}
}
}
@Override
public void onSensorChanged(SensorEvent se) {
SensorUtils.checkForCompass(getContext(), se, this.accelerometerValues, this.magneticFieldValues, this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private int getTypeHeaderLayoutResId() {
switch (this.showTypeHeader) {
case TYPE_HEADER_BASIC:
return R.layout.layout_poi_list_header;
case TYPE_HEADER_MORE:
return R.layout.layout_poi_list_header_with_more;
case TYPE_HEADER_ALL_NEARBY:
return R.layout.layout_poi_list_header_with_all_nearby;
default:
MTLog.w(this, "Unexpected header type '%s'!", this.showTypeHeader);
return R.layout.layout_poi_list_header;
}
}
private WeakReference<TypeHeaderButtonsClickListener> typeHeaderButtonsClickListenerWR;
public void setOnTypeHeaderButtonsClickListener(TypeHeaderButtonsClickListener listener) {
this.typeHeaderButtonsClickListenerWR = new WeakReference<TypeHeaderButtonsClickListener>(listener);
}
private void onTypeHeaderButtonClick(int buttonId, DataSourceType type) {
TypeHeaderButtonsClickListener listener = this.typeHeaderButtonsClickListenerWR == null ? null : this.typeHeaderButtonsClickListenerWR.get();
if (listener != null && listener.onTypeHeaderButtonClick(buttonId, type)) {
return;
}
switch (buttonId) {
case TypeHeaderButtonsClickListener.BUTTON_ALL:
if (type != null) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
leaving();
((MainActivity) activity).addFragmentToStack(AgencyTypeFragment.newInstance(type.getId(), type));
}
}
break;
case TypeHeaderButtonsClickListener.BUTTON_NEARBY:
if (type != null) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
leaving();
((MainActivity) activity).addFragmentToStack(NearbyFragment.newNearbyInstance(null, type.getId()));
}
}
break;
case TypeHeaderButtonsClickListener.BUTTON_MORE:
if (type != null) {
Activity activity = this.activityWR == null ? null : this.activityWR.get();
if (activity != null) {
leaving();
((MainActivity) activity).addFragmentToStack(AgencyTypeFragment.newInstance(type.getId(), type));
}
}
break;
default:
MTLog.w(this, "Unexected type header button %s'' click", type);
}
}
private void leaving() {
OnClickHandledListener onClickHandledListener = this.onClickHandledListenerWR == null ? null : this.onClickHandledListenerWR.get();
if (onClickHandledListener != null) {
onClickHandledListener.onLeaving();
}
}
@NonNull
private View getTypeHeaderView(final DataSourceType type, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
int layoutRes = getTypeHeaderLayoutResId();
convertView = this.layoutInflater.inflate(layoutRes, parent, false);
TypeHeaderViewHolder holder = new TypeHeaderViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.name);
holder.nearbyBtn = convertView.findViewById(R.id.nearbyBtn);
holder.allBtn = convertView.findViewById(R.id.allBtn);
holder.allBtnTv = (TextView) convertView.findViewById(R.id.allBtnTv);
holder.moreBtn = convertView.findViewById(R.id.moreBtn);
convertView.setTag(holder);
}
TypeHeaderViewHolder holder = (TypeHeaderViewHolder) convertView.getTag();
holder.nameTv.setText(this.showTypeHeaderNearby ? type.getNearbyNameResId() : type.getPoiShortNameResId());
if (type.getGrey600IconResId() != -1) {
holder.nameTv.setCompoundDrawablesWithIntrinsicBounds(type.getGrey600IconResId(), 0, 0, 0);
}
if (holder.allBtn != null) {
holder.allBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
onTypeHeaderButtonClick(TypeHeaderButtonsClickListener.BUTTON_ALL, type);
}
});
}
if (holder.nearbyBtn != null) {
holder.nearbyBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
onTypeHeaderButtonClick(TypeHeaderButtonsClickListener.BUTTON_NEARBY, type);
}
});
}
if (holder.moreBtn != null) {
holder.moreBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
onTypeHeaderButtonClick(TypeHeaderButtonsClickListener.BUTTON_MORE, type);
}
});
}
return convertView;
}
private View getFavoriteFolderHeaderView(final Favorite.Folder favoriteFolder, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_list_header_with_delete, parent, false);
FavoriteFolderHeaderViewHolder holder = new FavoriteFolderHeaderViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.name);
holder.renameBtn = convertView.findViewById(R.id.renameBtn);
holder.deleteBtn = convertView.findViewById(R.id.deleteBtn);
convertView.setTag(holder);
}
FavoriteFolderHeaderViewHolder holder = (FavoriteFolderHeaderViewHolder) convertView.getTag();
holder.nameTv.setText(favoriteFolder == null ? null : favoriteFolder.getName());
if (holder.renameBtn != null) {
holder.renameBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
FavoriteManager.showUpdateFolderDialog(getContext(), POIArrayAdapter.this.layoutInflater, favoriteFolder,
POIArrayAdapter.this.favoriteUpdateListener);
}
});
}
if (holder.deleteBtn != null) {
holder.deleteBtn.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
FavoriteManager.showDeleteFolderDialog(POIArrayAdapter.this.getContext(), favoriteFolder, POIArrayAdapter.this.favoriteUpdateListener);
}
});
}
return convertView;
}
private WeakHashMap<String, CommonStatusViewHolder> poiStatusViewHoldersWR = new WeakHashMap<String, CommonStatusViewHolder>();
@NonNull
private View getBasicPOIView(POIManager poim, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(getBasicPOILayout(poim.getStatusType()), parent, false);
BasicPOIViewHolder holder = new BasicPOIViewHolder();
initCommonViewHolder(holder, convertView, poim.poi.getUUID());
holder.statusViewHolder = initPOIStatusViewHolder(poim.getStatusType(), convertView);
convertView.setTag(holder);
}
updateBasicPOIView(poim, convertView);
return convertView;
}
private CommonStatusViewHolder initPOIStatusViewHolder(int status, View convertView) {
switch (status) {
case POI.ITEM_STATUS_TYPE_NONE:
return null;
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
return initAvailabilityPercentViewHolder(convertView);
case POI.ITEM_STATUS_TYPE_SCHEDULE:
return initScheduleViewHolder(convertView);
case POI.ITEM_STATUS_TYPE_APP:
return initAppStatusViewHolder(convertView);
default:
MTLog.w(this, "Unexpected status '%s' (no view holder)!", status);
return null;
}
}
private CommonStatusViewHolder initScheduleViewHolder(View convertView) {
ScheduleStatusViewHolder scheduleStatusViewHolder = new ScheduleStatusViewHolder();
initCommonStatusViewHolderHolder(scheduleStatusViewHolder, convertView);
scheduleStatusViewHolder.dataNextLine1Tv = (TextView) convertView.findViewById(R.id.data_next_line_1);
scheduleStatusViewHolder.dataNextLine2Tv = (TextView) convertView.findViewById(R.id.data_next_line_2);
return scheduleStatusViewHolder;
}
private CommonStatusViewHolder initAppStatusViewHolder(View convertView) {
AppStatusViewHolder appStatusViewHolder = new AppStatusViewHolder();
initCommonStatusViewHolderHolder(appStatusViewHolder, convertView);
appStatusViewHolder.textTv = (TextView) convertView.findViewById(R.id.textTv);
return appStatusViewHolder;
}
private CommonStatusViewHolder initAvailabilityPercentViewHolder(View convertView) {
AvailabilityPercentStatusViewHolder availabilityPercentStatusViewHolder = new AvailabilityPercentStatusViewHolder();
initCommonStatusViewHolderHolder(availabilityPercentStatusViewHolder, convertView);
availabilityPercentStatusViewHolder.textTv = (TextView) convertView.findViewById(R.id.textTv);
availabilityPercentStatusViewHolder.piePercentV = (MTPieChartPercentView) convertView.findViewById(R.id.pie);
return availabilityPercentStatusViewHolder;
}
private int getBasicPOILayout(int status) {
int layoutRes = R.layout.layout_poi_basic;
switch (status) {
case POI.ITEM_STATUS_TYPE_NONE:
break;
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
layoutRes = R.layout.layout_poi_basic_with_availability_percent;
break;
default:
MTLog.w(this, "Unexpected status '%s' (basic view w/o status)!", status);
break;
}
return layoutRes;
}
private WeakHashMap<MTCompassView, View> compassImgsWR = new WeakHashMap<MTCompassView, View>();
private void initCommonViewHolder(CommonViewHolder holder, View convertView, String poiUUID) {
holder.view = convertView;
holder.nameTv = (TextView) convertView.findViewById(R.id.name);
holder.favImg = (ImageView) convertView.findViewById(R.id.fav);
holder.locationTv = (TextView) convertView.findViewById(R.id.location);
holder.distanceTv = (TextView) convertView.findViewById(R.id.distance);
holder.compassV = (MTCompassView) convertView.findViewById(R.id.compass);
}
private static void initCommonStatusViewHolderHolder(CommonStatusViewHolder holder, View convertView) {
holder.statusV = convertView.findViewById(R.id.status);
holder.warningImg = (ImageView) convertView.findViewById(R.id.service_update_warning);
}
private View updateBasicPOIView(POIManager poim, View convertView) {
if (convertView == null || poim == null) {
return convertView;
}
BasicPOIViewHolder holder = (BasicPOIViewHolder) convertView.getTag();
updateCommonView(holder, poim);
updatePOIStatus(holder.statusViewHolder, poim);
return convertView;
}
private void updateAppStatus(CommonStatusViewHolder statusViewHolder, POIManager poim) {
if (this.showStatus && poim != null && statusViewHolder instanceof AppStatusViewHolder) {
poim.setStatusLoaderListener(this);
updateAppStatus(statusViewHolder, poim.getStatus(getContext()));
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
if (poim != null) {
poim.setServiceUpdateLoaderListener(this);
updateServiceUpdate(statusViewHolder, poim.isServiceUpdateWarning(getContext()));
}
}
private void updateAppStatus(CommonStatusViewHolder statusViewHolder, POIStatus status) {
AppStatusViewHolder appStatusViewHolder = (AppStatusViewHolder) statusViewHolder;
if (status != null && status instanceof AppStatus) {
AppStatus appStatus = (AppStatus) status;
appStatusViewHolder.textTv.setText(appStatus.getStatusMsg(getContext()));
appStatusViewHolder.textTv.setVisibility(View.VISIBLE);
statusViewHolder.statusV.setVisibility(View.VISIBLE);
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
}
private void updateServiceUpdate(CommonStatusViewHolder statusViewHolder, Boolean isServiceUpdateWarning) {
if (statusViewHolder.warningImg == null) {
return;
}
if (this.showServiceUpdate && isServiceUpdateWarning != null) {
statusViewHolder.warningImg.setVisibility(isServiceUpdateWarning ? View.VISIBLE : View.GONE);
} else {
statusViewHolder.warningImg.setVisibility(View.GONE);
}
}
private void updateAvailabilityPercent(CommonStatusViewHolder statusViewHolder, POIManager poim) {
if (this.showStatus && poim != null && statusViewHolder instanceof AvailabilityPercentStatusViewHolder) {
poim.setStatusLoaderListener(this);
updateAvailabilityPercent(statusViewHolder, poim.getStatus(getContext()));
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
if (poim != null) {
poim.setServiceUpdateLoaderListener(this);
updateServiceUpdate(statusViewHolder, poim.isServiceUpdateWarning(getContext()));
}
}
private void updateAvailabilityPercent(CommonStatusViewHolder statusViewHolder, POIStatus status) {
AvailabilityPercentStatusViewHolder availabilityPercentStatusViewHolder = (AvailabilityPercentStatusViewHolder) statusViewHolder;
if (status != null && status instanceof AvailabilityPercent) {
AvailabilityPercent availabilityPercent = (AvailabilityPercent) status;
if (!availabilityPercent.isStatusOK()) {
availabilityPercentStatusViewHolder.piePercentV.setVisibility(View.GONE);
availabilityPercentStatusViewHolder.textTv.setText(availabilityPercent.getStatusMsg(getContext()));
availabilityPercentStatusViewHolder.textTv.setVisibility(View.VISIBLE);
} else if (availabilityPercent.isShowingLowerValue()) {
availabilityPercentStatusViewHolder.piePercentV.setVisibility(View.GONE);
availabilityPercentStatusViewHolder.textTv.setText(availabilityPercent.getLowerValueText(getContext()));
availabilityPercentStatusViewHolder.textTv.setVisibility(View.VISIBLE);
} else {
availabilityPercentStatusViewHolder.textTv.setVisibility(View.GONE);
availabilityPercentStatusViewHolder.piePercentV.setValueColors(
availabilityPercent.getValue1Color(),
availabilityPercent.getValue1ColorBg(),
availabilityPercent.getValue2Color(),
availabilityPercent.getValue2ColorBg()
);
availabilityPercentStatusViewHolder.piePercentV.setValues(availabilityPercent.getValue1(), availabilityPercent.getValue2());
availabilityPercentStatusViewHolder.piePercentV.setVisibility(View.VISIBLE);
}
statusViewHolder.statusV.setVisibility(View.VISIBLE);
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
}
private int getRTSLayout(int status) {
int layoutRes = R.layout.layout_poi_rts;
switch (status) {
case POI.ITEM_STATUS_TYPE_NONE:
break;
case POI.ITEM_STATUS_TYPE_SCHEDULE:
if (this.showExtra) {
layoutRes = R.layout.layout_poi_rts_with_schedule;
} else {
layoutRes = R.layout.layout_poi_basic_with_schedule;
}
break;
default:
MTLog.w(this, "Unexpected status '%s' (rts view w/o status)!", status);
break;
}
return layoutRes;
}
private View getTextMessageView(POIManager poim, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(R.layout.layout_poi_basic, parent, false);
TextViewViewHolder holder = new TextViewViewHolder();
initCommonViewHolder(holder, convertView, poim.poi.getUUID());
convertView.setTag(holder);
}
updateTextMessageView(poim, convertView);
return convertView;
}
private View updateTextMessageView(POIManager poim, View convertView) {
if (convertView == null || poim == null) {
return convertView;
}
TextViewViewHolder holder = (TextViewViewHolder) convertView.getTag();
updateCommonView(holder, poim);
return convertView;
}
@NonNull
private View getModuleView(POIManager poim, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(getModuleLayout(poim.getStatusType()), parent, false);
ModuleViewHolder holder = new ModuleViewHolder();
initCommonViewHolder(holder, convertView, poim.poi.getUUID());
initModuleExtra(convertView, holder);
holder.statusViewHolder = initPOIStatusViewHolder(poim.getStatusType(), convertView);
convertView.setTag(holder);
}
updateModuleView(poim, convertView);
return convertView;
}
private void initModuleExtra(View convertView, ModuleViewHolder holder) {
holder.moduleExtraTypeImg = (ImageView) convertView.findViewById(R.id.extra);
}
private View updateModuleView(POIManager poim, View convertView) {
if (convertView == null || poim == null) {
return convertView;
}
ModuleViewHolder holder = (ModuleViewHolder) convertView.getTag();
updateCommonView(holder, poim);
updateModuleExtra(poim, holder);
updatePOIStatus(holder.statusViewHolder, poim);
return convertView;
}
private void updateModuleExtra(POIManager poim, ModuleViewHolder holder) {
if (this.showExtra && poim.poi != null && poim.poi instanceof Module) {
Module module = (Module) poim.poi;
holder.moduleExtraTypeImg.setBackgroundColor(poim.getColor(getContext()));
DataSourceType moduleType = DataSourceType.parseId(module.getTargetTypeId());
if (moduleType != null) {
holder.moduleExtraTypeImg.setImageResource(moduleType.getWhiteIconResId());
} else {
holder.moduleExtraTypeImg.setImageResource(0);
}
holder.moduleExtraTypeImg.setVisibility(View.VISIBLE);
} else {
holder.moduleExtraTypeImg.setVisibility(View.GONE);
}
}
private int getModuleLayout(int status) {
int layoutRes = R.layout.layout_poi_module;
switch (status) {
case POI.ITEM_STATUS_TYPE_NONE:
break;
case POI.ITEM_STATUS_TYPE_APP:
layoutRes = R.layout.layout_poi_module_with_app_status;
break;
default:
MTLog.w(this, "Unexpected status '%s' (module view w/o status)!", status);
break;
}
return layoutRes;
}
@NonNull
private View getRouteTripStopView(POIManager poim, @Nullable View convertView, @Nullable ViewGroup parent) {
if (convertView == null) {
convertView = this.layoutInflater.inflate(getRTSLayout(poim.getStatusType()), parent, false);
RouteTripStopViewHolder holder = new RouteTripStopViewHolder();
initCommonViewHolder(holder, convertView, poim.poi.getUUID());
initRTSExtra(convertView, holder);
holder.statusViewHolder = initPOIStatusViewHolder(poim.getStatusType(), convertView);
convertView.setTag(holder);
}
updateRouteTripStopView(poim, convertView);
return convertView;
}
private void initRTSExtra(View convertView, RouteTripStopViewHolder holder) {
holder.rtsExtraV = convertView.findViewById(R.id.extra);
holder.routeFL = convertView.findViewById(R.id.route);
holder.routeShortNameTv = (TextView) convertView.findViewById(R.id.route_short_name);
holder.routeTypeImg = (MTJPathsView) convertView.findViewById(R.id.route_type_img);
holder.tripHeadingTv = (TextView) convertView.findViewById(R.id.trip_heading);
holder.tripHeadingBg = convertView.findViewById(R.id.trip_heading_bg);
}
private View updateRouteTripStopView(POIManager poim, View convertView) {
if (convertView == null || poim == null) {
return convertView;
}
RouteTripStopViewHolder holder = (RouteTripStopViewHolder) convertView.getTag();
updateCommonView(holder, poim);
updateRTSExtra(poim, holder);
updatePOIStatus(holder.statusViewHolder, poim);
return convertView;
}
private boolean showExtra = true;
public void setShowExtra(boolean showExtra) {
this.showExtra = showExtra;
}
private void updateRTSExtra(POIManager poim, RouteTripStopViewHolder holder) {
if (poim.poi instanceof RouteTripStop) {
RouteTripStop rts = (RouteTripStop) poim.poi;
if (!this.showExtra || rts.getRoute() == null) {
if (holder.rtsExtraV != null) {
holder.rtsExtraV.setVisibility(View.GONE);
}
if (holder.routeFL != null) {
holder.routeFL.setVisibility(View.GONE);
}
if (holder.tripHeadingBg != null) {
holder.tripHeadingBg.setVisibility(View.GONE);
}
} else {
final String authority = rts.getAuthority();
final Route route = rts.getRoute();
if (TextUtils.isEmpty(route.getShortName())) {
holder.routeShortNameTv.setVisibility(View.INVISIBLE);
if (holder.routeTypeImg.hasPaths() && poim.poi.getAuthority().equals(holder.routeTypeImg.getTag())) {
holder.routeTypeImg.setVisibility(View.VISIBLE);
} else {
AgencyProperties agency = DataSourceProvider.get(getContext()).getAgency(getContext(), poim.poi.getAuthority());
JPaths rtsRouteLogo = agency == null ? null : agency.getLogo(getContext());
if (rtsRouteLogo != null) {
holder.routeTypeImg.setJSON(rtsRouteLogo);
holder.routeTypeImg.setTag(poim.poi.getAuthority());
holder.routeTypeImg.setVisibility(View.VISIBLE);
} else {
holder.routeTypeImg.setVisibility(View.GONE);
}
}
} else {
holder.routeTypeImg.setVisibility(View.GONE);
holder.routeShortNameTv.setText(Route.setShortNameSize(route.getShortName()));
holder.routeShortNameTv.setVisibility(View.VISIBLE);
}
holder.routeFL.setVisibility(View.VISIBLE);
holder.rtsExtraV.setVisibility(View.VISIBLE);
final Long tripId;
if (rts.getTrip() == null) {
holder.tripHeadingBg.setVisibility(View.GONE);
tripId = null;
} else {
tripId = rts.getTrip().getId();
holder.tripHeadingTv.setText(rts.getTrip().getHeading(getContext()).toUpperCase(Locale.getDefault()));
holder.tripHeadingBg.setVisibility(View.VISIBLE);
}
holder.rtsExtraV.setBackgroundColor(poim.getColor(getContext()));
final Integer stopId = rts.getStop() == null ? null : rts.getStop().getId();
holder.rtsExtraV.setOnClickListener(new MTOnClickListener() {
@Override
public void onClickMT(View view) {
Activity activity = POIArrayAdapter.this.activityWR == null ? null : POIArrayAdapter.this.activityWR.get();
if (activity == null || !(activity instanceof MainActivity)) {
MTLog.w(POIArrayAdapter.this, "No activity available to open RTS fragment!");
return;
}
leaving();
((MainActivity) activity).addFragmentToStack(RTSRouteFragment.newInstance(authority, route.getId(), tripId, stopId, route));
}
});
}
}
}
private void updatePOIStatus(CommonStatusViewHolder statusViewHolder, POIStatus status) {
if (!this.showStatus || status == null || statusViewHolder == null) {
if (statusViewHolder != null) {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
return;
}
switch (status.getType()) {
case POI.ITEM_STATUS_TYPE_NONE:
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
break;
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
updateAvailabilityPercent(statusViewHolder, status);
break;
case POI.ITEM_STATUS_TYPE_SCHEDULE:
updateRTSSchedule(statusViewHolder, status);
break;
case POI.ITEM_STATUS_TYPE_APP:
updateAppStatus(statusViewHolder, status);
break;
default:
MTLog.w(this, "Unexpected status type '%s'!", status.getType());
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
}
private void updatePOIStatus(CommonStatusViewHolder statusViewHolder, POIManager poim) {
if (!this.showStatus || poim == null || statusViewHolder == null) {
if (statusViewHolder != null) {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
return;
}
switch (poim.getStatusType()) {
case POI.ITEM_STATUS_TYPE_NONE:
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
break;
case POI.ITEM_STATUS_TYPE_AVAILABILITY_PERCENT:
updateAvailabilityPercent(statusViewHolder, poim);
break;
case POI.ITEM_STATUS_TYPE_SCHEDULE:
updateRTSSchedule(statusViewHolder, poim);
break;
case POI.ITEM_STATUS_TYPE_APP:
updateAppStatus(statusViewHolder, poim);
break;
default:
MTLog.w(this, "Unexpected status type '%s'!", poim.getStatusType());
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
}
private void updateRTSSchedule(CommonStatusViewHolder statusViewHolder, POIManager poim) {
if (this.showStatus && poim != null && statusViewHolder instanceof ScheduleStatusViewHolder) {
poim.setStatusLoaderListener(this);
updateRTSSchedule(statusViewHolder, poim.getStatus(getContext()));
} else {
statusViewHolder.statusV.setVisibility(View.INVISIBLE);
}
if (poim != null) {
poim.setServiceUpdateLoaderListener(this);
updateServiceUpdate(statusViewHolder, poim.isServiceUpdateWarning(getContext()));
}
}
private void updateRTSSchedule(CommonStatusViewHolder statusViewHolder, POIStatus status) {
CharSequence line1CS = null;
CharSequence line2CS = null;
if (status != null && status instanceof Schedule) {
Schedule schedule = (Schedule) status;
ArrayList<Pair<CharSequence, CharSequence>> lines = schedule.getStatus(getContext(), getNowToTheMinute(), TimeUnit.MINUTES.toMillis(30), null, 10,
null);
if (lines != null && lines.size() >= 1) {
line1CS = lines.get(0).first;
line2CS = lines.get(0).second;
}
}
ScheduleStatusViewHolder scheduleStatusViewHolder = (ScheduleStatusViewHolder) statusViewHolder;
scheduleStatusViewHolder.dataNextLine1Tv.setText(line1CS);
scheduleStatusViewHolder.dataNextLine2Tv.setText(line2CS);
scheduleStatusViewHolder.dataNextLine2Tv.setVisibility(line2CS != null && line2CS.length() > 0 ? View.VISIBLE : View.GONE);
statusViewHolder.statusV.setVisibility(line1CS != null && line1CS.length() > 0 ? View.VISIBLE : View.INVISIBLE);
}
private long getNowToTheMinute() {
if (this.nowToTheMinute < 0) {
resetNowToTheMinute();
enableTimeChangedReceiver();
}
return this.nowToTheMinute;
}
private void resetNowToTheMinute() {
this.nowToTheMinute = TimeUtils.currentTimeToTheMinuteMillis();
notifyDataSetChanged(false);
}
@Override
public void onTimeChanged() {
resetNowToTheMinute();
}
private final BroadcastReceiver timeChangedReceiver = new TimeUtils.TimeChangedReceiver(this);
private void enableTimeChangedReceiver() {
if (!this.timeChangedReceiverEnabled) {
getContext().registerReceiver(timeChangedReceiver, TimeUtils.TIME_CHANGED_INTENT_FILTER);
this.timeChangedReceiverEnabled = true;
}
}
private void disableTimeChangedReceiver() {
if (this.timeChangedReceiverEnabled) {
getContext().unregisterReceiver(this.timeChangedReceiver);
this.timeChangedReceiverEnabled = false;
this.nowToTheMinute = -1L;
}
}
private void updateCommonView(CommonViewHolder holder, POIManager poim) {
if (poim == null || poim.poi == null || holder == null) {
return;
}
final POI poi = poim.poi;
holder.uuid = poi.getUUID();
if (holder.statusViewHolder != null) {
holder.statusViewHolder.uuid = holder.uuid;
}
if (holder.uuid != null) {
this.poiStatusViewHoldersWR.put(holder.uuid, holder.statusViewHolder);
}
if (holder.compassV != null) {
holder.compassV.setLatLng(poim.getLat(), poim.getLng());
this.compassImgsWR.put(holder.compassV, holder.distanceTv);
}
holder.nameTv.setText(poi.getName());
if (holder.distanceTv != null) {
if (!TextUtils.isEmpty(poim.getDistanceString())) {
if (!poim.getDistanceString().equals(holder.distanceTv.getText())) {
holder.distanceTv.setText(poim.getDistanceString());
}
holder.distanceTv.setVisibility(View.VISIBLE);
} else {
holder.distanceTv.setVisibility(View.GONE);
holder.distanceTv.setText(null);
}
}
if (holder.compassV != null) {
if (holder.distanceTv != null && holder.distanceTv.getVisibility() == View.VISIBLE) {
if (this.location != null && this.lastCompassInDegree >= 0 && this.location.getAccuracy() <= poim.getDistance()) {
holder.compassV.generateAndSetHeading(this.location, this.lastCompassInDegree, this.locationDeclination);
} else {
holder.compassV.resetHeading();
}
holder.compassV.setVisibility(View.VISIBLE);
} else {
holder.compassV.resetHeading();
holder.compassV.setVisibility(View.GONE);
}
}
if (holder.locationTv != null) {
if (TextUtils.isEmpty(poim.getLocation())) {
holder.locationTv.setVisibility(View.GONE);
holder.locationTv.setText(null);
} else {
holder.locationTv.setText(poim.getLocation());
holder.locationTv.setVisibility(View.VISIBLE);
}
}
if (this.showFavorite && this.favUUIDs != null && this.favUUIDs.contains(poi.getUUID())) {
holder.favImg.setVisibility(View.VISIBLE);
} else {
holder.favImg.setVisibility(View.GONE);
}
int index;
if (this.closestPoiUuids != null && this.closestPoiUuids.contains(poi.getUUID())) {
index = 0;
} else {
index = -1;
}
switch (index) {
case 0:
holder.nameTv.setTypeface(Typeface.DEFAULT_BOLD);
if (holder.distanceTv != null) {
holder.distanceTv.setTypeface(Typeface.DEFAULT_BOLD);
}
break;
default:
holder.nameTv.setTypeface(Typeface.DEFAULT);
if (holder.distanceTv != null) {
holder.distanceTv.setTypeface(Typeface.DEFAULT);
}
break;
}
}
private MTAsyncTask<Integer, Void, ArrayList<Favorite>> refreshFavoritesTask;
public void refreshFavorites() {
if (this.refreshFavoritesTask != null && this.refreshFavoritesTask.getStatus() == MTAsyncTask.Status.RUNNING) {
return; // skipped, last refresh still in progress so probably good enough
}
this.refreshFavoritesTask = new MTAsyncTask<Integer, Void, ArrayList<Favorite>>() {
@Override
public String getLogTag() {
return POIArrayAdapter.class.getSimpleName() + ">refreshFavoritesTask";
}
@Override
protected ArrayList<Favorite> doInBackgroundMT(Integer... params) {
return FavoriteManager.findFavorites(POIArrayAdapter.this.getContext());
}
@Override
protected void onPostExecute(ArrayList<Favorite> result) {
setFavorites(result);
}
};
TaskUtils.execute(this.refreshFavoritesTask);
}
private void setFavorites(ArrayList<Favorite> favorites) {
boolean newFav = false; // don't trigger update if favorites are the same
boolean updatedFav = false; // don't trigger it favorites are the same OR were not set
if (this.favUUIDs == null) {
newFav = true; // favorite never set before
updatedFav = false; // never set before so not updated
} else if (CollectionUtils.getSize(favorites) != CollectionUtils.getSize(this.favUUIDs)) {
newFav = true; // different size => different favorites
updatedFav = true; // different size => different favorites
}
HashSet<String> newFavUUIDs = new HashSet<String>();
HashMap<String, Integer> newfavUUIDsFolderIds = new HashMap<String, Integer>();
if (favorites != null) {
for (Favorite favorite : favorites) {
String uid = favorite.getFkId();
if (!newFav && (
(this.favUUIDs != null && !this.favUUIDs.contains(uid)) ||
(this.favUUIDsFolderIds != null && this.favUUIDsFolderIds.containsKey(uid) && this.favUUIDsFolderIds.get(uid) != favorite.getFolderId())
)) {
newFav = true;
updatedFav = true;
}
newFavUUIDs.add(uid);
newfavUUIDsFolderIds.put(uid, favorite.getFolderId());
}
}
if (!newFav) {
if (this.favUUIDsFolderIds == null) {
newFav = true; // favorite never set before
updatedFav = false; // never set before so not updated
} else {
HashSet<Integer> oldFolderIds = new HashSet<Integer>();
for (Integer folderId : this.favUUIDsFolderIds.values()) {
oldFolderIds.add(folderId);
}
HashSet<Integer> newFolderIds = new HashSet<Integer>();
for (Integer folderId : newfavUUIDsFolderIds.values()) {
newFolderIds.add(folderId);
}
if (CollectionUtils.getSize(oldFolderIds) != CollectionUtils.getSize(newFolderIds)) {
newFav = true; // different size => different favorites
updatedFav = true; // different size => different favorites
}
}
}
this.favUUIDs = newFavUUIDs;
this.favUUIDsFolderIds = newfavUUIDsFolderIds;
if (newFav) {
notifyDataSetChanged(true);
}
if (updatedFav) {
if (this.favoriteUpdateListener != null) {
this.favoriteUpdateListener.onFavoriteUpdated();
}
}
}
public static class InfiniteLoadingViewHolder {
View progressBar;
View worldExplored;
}
public static class ModuleViewHolder extends CommonViewHolder {
ImageView moduleExtraTypeImg;
}
public static class RouteTripStopViewHolder extends CommonViewHolder {
TextView routeShortNameTv;
View routeFL;
View rtsExtraV;
MTJPathsView routeTypeImg;
TextView tripHeadingTv;
View tripHeadingBg;
}
public static class BasicPOIViewHolder extends CommonViewHolder {
}
public static class TextViewViewHolder extends CommonViewHolder {
}
public static class CommonViewHolder {
String uuid;
View view;
TextView nameTv;
TextView distanceTv;
TextView locationTv;
ImageView favImg;
MTCompassView compassV;
CommonStatusViewHolder statusViewHolder;
}
public static class AppStatusViewHolder extends CommonStatusViewHolder {
TextView textTv;
}
public static class ScheduleStatusViewHolder extends CommonStatusViewHolder {
TextView dataNextLine1Tv;
TextView dataNextLine2Tv;
}
public static class AvailabilityPercentStatusViewHolder extends CommonStatusViewHolder {
TextView textTv;
MTPieChartPercentView piePercentV;
}
public static class CommonStatusViewHolder {
String uuid;
View statusV;
ImageView warningImg;
}
public static class FavoriteFolderHeaderViewHolder {
TextView nameTv;
View deleteBtn;
View renameBtn;
}
public static class TypeHeaderViewHolder {
TextView nameTv;
TextView allBtnTv;
View allBtn;
View nearbyBtn;
View moreBtn;
}
public interface TypeHeaderButtonsClickListener {
int BUTTON_MORE = 0;
int BUTTON_NEARBY = 1;
int BUTTON_ALL = 2;
boolean onTypeHeaderButtonClick(int buttonId, DataSourceType type);
}
}
|
package org.opencms.file.types;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.db.CmsDriverManager;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsResource;
import org.opencms.i18n.CmsEncoder;
import org.opencms.loader.CmsJspLoader;
import org.opencms.main.CmsException;
import org.opencms.main.I_CmsConstants;
import org.opencms.main.OpenCms;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ExtendedProperties;
/**
* Resource type descriptor for the type "jsp".<p>
*
* Ensures that some required file properties are attached to new JSPs.<p>
*
* The value for the encoding properies of a new JSP usually is the
* system default encoding, but this can be overwritten by
* a configuration parameters set in <code>opencms-vfs.xml</code>.<p>
*
* @author Alexander Kandzior (a.kandzior@alkacon.com)
*
* @version $Revision: 1.6 $
*/
public class CmsResourceTypeJsp extends A_CmsResourceType {
/** The configuration parameter for "default JSP encoding". */
public static final String C_CONFIGURATION_JSP_ENCODING = "default.encoding";
/** The type id of this resource type. */
public static final int C_RESOURCE_TYPE_ID = 8;
/** The name of this resource type. */
public static final String C_RESOURCE_TYPE_NAME = "jsp";
/** The default encoding to use when creating new JSP pages. */
private String m_defaultEncoding;
/**
* @see org.opencms.file.types.A_CmsResourceType#addConfigurationParameter(java.lang.String, java.lang.String)
*/
public void addConfigurationParameter(String paramName, String paramValue) {
if (C_CONFIGURATION_JSP_ENCODING.equalsIgnoreCase(paramName)) {
m_defaultEncoding = CmsEncoder.lookupEncoding(paramValue.trim(), OpenCms.getSystemInfo()
.getDefaultEncoding());
}
}
/**
* @see org.opencms.file.types.I_CmsResourceType#createResource(org.opencms.file.CmsObject, org.opencms.db.CmsDriverManager, java.lang.String, byte[], java.util.List)
*/
public CmsResource createResource(
CmsObject cms,
CmsDriverManager driverManager,
String resourcename,
byte[] content,
List properties
) throws CmsException {
List newProperties;
if (properties == null) {
newProperties = new ArrayList();
} else {
newProperties = new ArrayList(properties);
}
newProperties.add(new CmsProperty(I_CmsConstants.C_PROPERTY_EXPORT, null, "false"));
newProperties.add(new CmsProperty(I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, null, m_defaultEncoding));
return super.createResource(cms, driverManager, resourcename, content, newProperties);
}
/**
* @see org.opencms.file.types.A_CmsResourceType#getConfiguration()
*/
public ExtendedProperties getConfiguration() {
ExtendedProperties result = new ExtendedProperties();
result.put(C_CONFIGURATION_JSP_ENCODING, m_defaultEncoding);
return result;
}
/**
* @see org.opencms.file.types.I_CmsResourceType#getLoaderId()
*/
public int getLoaderId() {
return CmsJspLoader.C_RESOURCE_LOADER_ID;
}
/**
* @see org.opencms.file.types.I_CmsResourceType#getTypeId()
*/
public int getTypeId() {
return C_RESOURCE_TYPE_ID;
}
/**
* @see org.opencms.file.types.A_CmsResourceType#getTypeName()
*/
public String getTypeName() {
return C_RESOURCE_TYPE_NAME;
}
/**
* @see org.opencms.file.types.I_CmsResourceType#initConfiguration()
*/
public void initConfiguration() throws CmsConfigurationException {
super.initConfiguration();
// ensure default content encoding is set
if (m_defaultEncoding == null) {
m_defaultEncoding = OpenCms.getSystemInfo().getDefaultEncoding();
}
m_defaultEncoding = m_defaultEncoding.intern();
}
}
|
package org.opencms.jsp.util;
import org.opencms.file.CmsObject;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.staticexport.CmsLinkManager;
import org.opencms.util.CmsCollectionsGenericWrapper;
import org.opencms.util.CmsStringUtil;
import java.util.AbstractCollection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.collections.Transformer;
import org.apache.commons.logging.Log;
/**
* Common value wrapper class that provides generic functions.<p>
*
* Wrappers that extend this are usually used for the values in lazy initialized transformer maps.<p>
*/
abstract class A_CmsJspValueWrapper extends AbstractCollection<String> {
/**
* Provides a Map with Booleans that
* indicate if a given String is contained in the wrapped objects String representation.<p>
*/
public class CmsContainsTransformer implements Transformer {
/**
* @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
*/
@Override
public Object transform(Object input) {
Object o = getObjectValue();
if ((o instanceof A_CmsJspValueWrapper) && (input != null)) {
return Boolean.valueOf(((A_CmsJspValueWrapper)o).getToString().indexOf(input.toString()) > -1);
}
return Boolean.FALSE;
}
}
/**
* Provides a Map with Booleans that
* indicate if a given Object is equal to the wrapped object.<p>
*/
public class CmsIsEqualTransformer implements Transformer {
/**
* @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
*/
@Override
public Object transform(Object input) {
Object o = getObjectValue();
if ((o instanceof A_CmsJspValueWrapper) && (input instanceof String)) {
return Boolean.valueOf(((A_CmsJspValueWrapper)o).getToString().equals(input));
}
if (o == null) {
return Boolean.valueOf(input == null);
}
return Boolean.valueOf(o.equals(input));
}
}
/**
* Provides trimmed to size string values.<p>
*/
public class CmsTrimToSizeTransformer implements Transformer {
/**
* @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
*/
@Override
public Object transform(Object input) {
try {
int lenght = Integer.parseInt(String.valueOf(input));
return CmsJspElFunctions.trimToSize(getToString(), lenght);
} catch (Exception e) {
return getToString();
}
}
}
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(A_CmsJspValueWrapper.class);
/** The wrapped OpenCms user context. */
protected CmsObject m_cms;
/** Boolean representation of the wrapped value. */
private Boolean m_boolean;
/** Date created from the wrapped value. */
private Date m_date;
/** Double created from the wrapped value. */
private Double m_double;
/** Image bean instance created from the wrapped value. */
private CmsJspImageBean m_imageBean;
/** The lazy initialized Map that checks if a Object is equal. */
private Map<Object, Boolean> m_isEqual;
/** The lazy initialized Map that checks if the String representation of this wrapper contains specific words. */
private Map<Object, Boolean> m_contains;
/** Link created from the wrapped value. */
private String m_link;
/** Long created from the wrapped value. */
private Long m_long;
/** String representation of the wrapped value. */
private String m_string;
/** String representation of the wrapped value with HTML stripped off. */
private String m_stripHtml;
/** The lazy initialized trim to size map. */
private Map<Object, String> m_trimToSize;
/**
* Returns the substituted link to the given target.<p>
*
* @param cms the cms context
* @param target the link target
*
* @return the substituted link
*/
protected static String substituteLink(CmsObject cms, String target) {
if (cms != null) {
return OpenCms.getLinkManager().substituteLinkForUnknownTarget(
cms,
CmsLinkManager.getAbsoluteUri(String.valueOf(target), cms.getRequestContext().getUri()));
} else {
return "";
}
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if ((obj != null) && (obj.getClass() == getClass())) {
// rely on hash code implementation for equals method
return hashCode() == ((A_CmsJspValueWrapper)obj).hashCode();
}
return false;
}
/**
* Returns the current cms context.<p>
*
* @return the cms context
*/
public CmsObject getCmsObject() {
return m_cms;
}
/**
* Returns a lazy initialized Map that provides Booleans which
* indicate if if the wrapped values String representation contains a specific String.<p>
*
* The Object parameter is transformed to it's String representation to perform this check.
*
* @return a lazy initialized Map that provides Booleans which
* indicate if if the wrapped values String representation contains a specific String
*/
public Map<Object, Boolean> getContains() {
if (m_contains == null) {
m_contains = CmsCollectionsGenericWrapper.createLazyMap(new CmsContainsTransformer());
}
return m_contains;
}
/**
* Returns <code>true</code> if the wrapped value has been somehow initialized.<p>
*
* @return <code>true</code> if the wrapped value has been somehow initialized
*/
public abstract boolean getExists();
/**
* Returns <code>true</code> in case the wrapped value is empty, that is either <code>null</code> or an empty String.<p>
*
* @return <code>true</code> in case the wrapped value is empty
*/
public abstract boolean getIsEmpty();
/**
* Returns <code>true</code> in case the wrapped value is empty or whitespace only,
* that is either <code>null</code> or String that contains only whitespace chars.<p>
*
* @return <code>true</code> in case the wrapped value is empty or whitespace only
*/
public abstract boolean getIsEmptyOrWhitespaceOnly();
/**
* Returns a lazy initialized Map that provides Booleans which
* indicate if an Object is equal to the wrapped object.<p>
*
* @return a lazy initialized Map that provides Booleans which
* indicate if an Object is equal to the wrapped object
*/
public Map<Object, Boolean> getIsEqual() {
if (m_isEqual == null) {
m_isEqual = CmsCollectionsGenericWrapper.createLazyMap(new CmsIsEqualTransformer());
}
return m_isEqual;
}
/**
* Returns <code>true</code> in case the wrapped value exists and is not empty or whitespace only.<p>
*
* @return <code>true</code> in case the wrapped value exists and is not empty or whitespace only
*/
public boolean getIsSet() {
return !getIsEmptyOrWhitespaceOnly();
}
/**
* Returns <code>true</code> in case the wrapped value exists, is not empty or whitespace only
* and is also not equal to the String <code>'none'</code>.<p>
*
* @return <code>true</code> in case the wrapped value exists, is not empty or whitespace only
* and is also not equal to the String <code>'none'</code>
*/
public boolean getIsSetNotNone() {
return getIsEmptyOrWhitespaceOnly() ? false : !"none".equals(getToString());
}
/**
* Calculates the next largest integer from the wrapped value.<p>
*
* Note that the result is an Object of type {@link java.lang.Long},
* so in case the wrapped value can not be converted to a number, <code>null</code> is returned.
* This means you can check for an <code>empty</code> result in the EL.<p>
*
* @return the next largest integer for the wrapped value
*/
public Long getMathCeil() {
return CmsJspElFunctions.mathCeil(getToDouble());
}
/**
* Calculates the next smallest integer from the wrapped value.<p>
*
* Note that the result is an Object of type {@link java.lang.Long},
* so in case the wrapped value can not be converted to a number, <code>null</code> is returned.
* This means you can check for an <code>empty</code> result in the EL.<p>
*
* @return the next smallest integer for the wrapped value
*/
public Long getMathFloor() {
return CmsJspElFunctions.mathFloor(getToDouble());
}
/**
* Calculates the next integer from the wrapped value by rounding.<p>
*
* Note that the result is an Object of type {@link java.lang.Long},
* so in case the wrapped value can not be converted to a number, <code>null</code> is returned.
* This means you can check for an <code>empty</code> result in the EL.<p>
*
* @return the next integer for the wrapped value calculated by rounding
*/
public Long getMathRound() {
return CmsJspElFunctions.mathRound(getToDouble());
}
/**
* Returns the raw instance of the wrapped value.<p>
*
* @return the raw instance of the wrapped value
*/
public abstract Object getObjectValue();
/**
* Returns the String value for the wrapped content value.<p>
*
* This will return the empty String <code>""</code> when {@link #getExists()} returns <code>false</code><p>.
*
* @return the String value of the wrapped content value
*
* @deprecated use {@link #getToString()} instead
*/
@Deprecated
public String getStringValue() {
return getToString();
}
/**
* Assumes the wrapped value is a String and strips all HTML markup from this String.<p>
*
* @return the wrapped value with all HTML stripped.
*/
public String getStripHtml() {
if (m_stripHtml == null) {
m_stripHtml = CmsJspElFunctions.stripHtml(this);
}
return m_stripHtml;
}
/**
* Converts the wrapped value to a boolean.<p>
*
* @return the boolean value
*/
public boolean getToBoolean() {
if (m_boolean == null) {
m_boolean = Boolean.valueOf(Boolean.parseBoolean(getToString()));
}
return m_boolean.booleanValue();
}
/**
* Converts the wrapped value to a date.<p>
*
* @return the date
*
* @see CmsJspElFunctions#convertDate(Object)
*/
public Date getToDate() {
if (m_date == null) {
m_date = CmsJspElFunctions.convertDate(getToString());
}
return m_date;
}
/**
* Parses the wrapped value to a Double precision float.<p>
*
* Note that the result is an Object of type {@link java.lang.Double},
* so in case the wrapped value can not be converted to a number, <code>null</code> is returned.
* This means you can check for an <code>empty</code> result in the EL.<p>
*
* @return the Double precision float value
*/
public Double getToDouble() {
if (m_double == null) {
try {
m_double = new Double(Double.parseDouble(getToString()));
} catch (NumberFormatException e) {
LOG.info(e.getLocalizedMessage());
}
}
return m_double;
}
/**
* Parses the wrapped value to a Double precision float.<p>
*
* Note that the result is an Object of type {@link java.lang.Double},
* so in case the wrapped value can not be converted to a number, <code>null</code> is returned.
* This means you can check for an <code>empty</code> result in the EL.<p>
*
* @return the Double precision float value
*/
public Double getToFloat() {
return getToDouble();
}
/**
* Returns a scaled image bean from the wrapped value.<p>
*
* In case the value does not point to an image resource, <code>null</code> is returned.
*
* @return the scaled image bean
*/
public CmsJspImageBean getToImage() {
if (m_imageBean == null) {
try {
m_imageBean = new CmsJspImageBean(getCmsObject(), getToString());
} catch (CmsException e) {
// this should only happen if the image path is not valid, in which case we will return null
LOG.info(e.getLocalizedMessage(), e);
}
}
return m_imageBean;
}
/**
* Parses the wrapped value to a Long integer.<p>
*
* Note that the result is an Object of type {@link java.lang.Long},
* so in case the wrapped value can not be converted to a number, <code>null</code> is returned.
* This means you can check for an <code>empty</code> result in the EL.<p>
*
* @return the Long integer value
*
* @see #getToLong()
*/
public Long getToInteger() {
return getToLong();
}
/**
* Returns the substituted link to the wrapped value.<p>
*
* In case no link can be substituted from the wrapped value, an empty String <code>""</code> is returned.
*
* @return the substituted link
*/
public String getToLink() {
if (m_link == null) {
String target = toString();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(target)) {
m_link = substituteLink(getCmsObject(), target);
} else {
m_link = "";
}
}
return m_link;
}
/**
* Parses the wrapped value to a Long integer.<p>
*
* Note that the result is an Object of type {@link java.lang.Long},
* so in case the wrapped value can not be converted to a number, <code>null</code> is returned.
* This means you can check for an <code>empty</code> result in the EL.<p>
*
* @return the Long integer value
*
* @see #getToInteger()
*/
public Long getToLong() {
if (m_long == null) {
try {
m_long = new Long(Long.parseLong(getToString()));
} catch (NumberFormatException e) {
LOG.info(e.getLocalizedMessage());
}
}
return m_long;
}
/**
* Returns the wrapped value as a String.<p>
*
* This will always be at least an empty String <code>""</code>, never <code>null</code>.
*
* @return the wrapped value as a String
*/
public String getToString() {
if (m_string == null) {
m_string = toString();
}
return m_string;
}
/**
* Returns a lazy initialized map that provides trimmed to size strings of the wrapped object string value.
* The size being the integer value of the key object.<p>
*
* @return a map that provides trimmed to size strings of the wrapped object string value
*/
public Map<Object, String> getTrimToSize() {
if (m_trimToSize == null) {
m_trimToSize = CmsCollectionsGenericWrapper.createLazyMap(new CmsTrimToSizeTransformer());
}
return m_trimToSize;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public abstract int hashCode();
/**
* Supports the use of the <code>empty</code> operator in the JSP EL by implementing the Collection interface.<p>
*
* @return the value from {@link #getIsEmptyOrWhitespaceOnly()} which is the inverse of {@link #getIsSet()}.<p>
*
* @see java.util.AbstractCollection#isEmpty()
* @see #getIsEmptyOrWhitespaceOnly()
* @see #getIsSet()
*/
@Override
public boolean isEmpty() {
return getIsEmptyOrWhitespaceOnly();
}
/**
* Supports the use of the <code>empty</code> operator in the JSP EL by implementing the Collection interface.<p>
*
* @return an empty Iterator in case {@link #isEmpty()} is <code>true</code>,
* otherwise an Iterator that will return the String value of this wrapper exactly once.<p>
*
* @see java.util.AbstractCollection#size()
*/
@Override
public Iterator<String> iterator() {
Iterator<String> it = new Iterator<String>() {
private boolean isFirst = true;
@Override
public boolean hasNext() {
return isFirst && !isEmpty();
}
@Override
public String next() {
isFirst = false;
return getToString();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
return it;
}
/**
* Supports the use of the <code>empty</code> operator in the JSP EL by implementing the Collection interface.<p>
*
* @return always returns 0.<p>
*
* @see java.util.AbstractCollection#size()
*/
@Override
public int size() {
return isEmpty() ? 0 : 1;
}
/**
* Parses the wrapped value to a Double precision float, returning the default in case the number can not be parsed.<p>
*
* @param def the default in case the wrapped value can not be converted to a number
* @return a Double precision float value
*
* @see #toFloat(Double)
*/
public Double toDouble(Double def) {
if (getToDouble() == null) {
return def;
}
return m_double;
}
/**
* Parses the wrapped value to a Double precision float, returning the default in case the number can not be parsed.<p>
*
* @param def the default in case the wrapped value can not be converted to a number
* @return a Double precision float value
*
* @see #toDouble(Double)
*/
public Double toFloat(Double def) {
return toDouble(def);
}
/**
* Parses the wrapped value to a Long integer, returning the default in case the number can not be parsed.<p>
*
* @param def the default in case the wrapped value can not be converted to a number
* @return a Long integer value
*
* @see #toLong(Long)
*/
public Long toInteger(Long def) {
return toLong(def);
}
/**
* Parses the wrapped value to a Long integer, returning the default in case the number can not be parsed.<p>
*
* @param def the default in case the wrapped value can not be converted to a number
* @return a Long integer value
*
* @see #toInteger(Long)
*/
public Long toLong(Long def) {
if (getToLong() == null) {
return def;
}
return m_long;
}
}
|
package org.usfirst.frc.team339.Utils;
import com.ctre.CANTalon;
import com.ctre.CANTalon.FeedbackDevice;
import com.ctre.CANTalon.TalonControlMode;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* Class to make tuning PID loops easier, either by the smartdashboard, or in
* the code via some other sensor (you'll have to write the code in teleop or
* something for another sensor)
*
* @author Alex Kneipp
* @written 1/21/17
*/
public class CANPIDTuner
{
private int CANID = 0;// TODO either use or remove
private CANTalon tunedMotorController = null;
private double P;
private double I;
private double D;
private double setpoint;
private boolean smartDashboard;
private double errorThresh = 20;
/**
* Constructs a PID tuner object for a specific CANTalon motor.
*
* @param canId
* Not currently used. There for future potential use.
* @param talon
* The motor we're tuning on. It needs to have some form of rate
* sensor attached to it's breakout board.
* @param smartDashboardAvailable
* If the smartdashboard is setup and used. We won't bother updating
* it if we have it.
* @param errorThreshold
* The maximum error we find it acceptable to have (always positive,
* we use absolute value of the actual error).
*/
public CANPIDTuner (int canId, CANTalon talon,
boolean smartDashboardAvailable, double errorThreshold)// TODO remove
// the
// smartDashboard
// thingy
{
this.tunedMotorController = talon;
this.CANID = canId;
this.P = 0;
this.I = 0;
this.D = 0;
this.setpoint = 0;
this.smartDashboard = smartDashboardAvailable;
this.errorThresh = errorThreshold;
}
private boolean wasIncorrect = false;
private Timer time = new Timer();
// TODO reference CTRE doc
/**
* Initializes all the CAN stuff for the motor controller.
*
* @param feedbackType
* The type of feedback device in the MotorController.
* @param tunetype
* Speed or position. See the CTRE doc for more info
* @param codesPerRev
* The number of signals the feedback devices gives per rotation, so
* the setpoint can function in rpm or revolutions.
* @param reverseSensor
* Is the feedback device reversed.
*/
public void setupMotorController (FeedbackDevice feedbackType,
TalonControlMode tunetype, int codesPerRev,
boolean reverseSensor)
{
this.tunedMotorController
.setFeedbackDevice(feedbackType);
this.tunedMotorController.changeControlMode(tunetype);
this.tunedMotorController.configEncoderCodesPerRev(codesPerRev);
this.tunedMotorController.reverseSensor(reverseSensor);
this.tunedMotorController.setProfile(0);
this.tunedMotorController.configPeakOutputVoltage(12f, 0f);
this.tunedMotorController.configNominalOutputVoltage(0f, 0f);
wasIncorrect = false;
time.stop();
time.reset();
}
/**
* Initializes everything on the smartDashboard if we have one. If not, does
* nothing.
* Puts P, I, D, Setpoint, Error, and Speed.
* P, I, D, and Setpoint are all editable and affect the function of the code.
* Setpoint is in units of RPM or revolutions if you provided a number other
* than 1 for the codesPerRev argument to setupMotorController.
*/
public void setupDashboard ()
{
if (this.smartDashboard)
{
SmartDashboard.putNumber("P", this.P);
SmartDashboard.putNumber("I", this.I);
SmartDashboard.putNumber("D", this.D);
SmartDashboard.putNumber("Setpoint", this.setpoint);
SmartDashboard.putNumber("Error",
this.setpoint - this.tunedMotorController.getSpeed());
SmartDashboard.putNumber("Speed",
this.tunedMotorController.getSpeed());
}
}
/**
* Gets information from the smartDashboard, puts more info back onto the
* smartDashboard, and updates the values on the tuned motor controller.
* Prints out when an error beyond the provided threshold is detected, and the
* time for the PID loop to correct for it.
*/
public void update ()
{
if (this.smartDashboard)
{
P = SmartDashboard.getNumber("P", 0);
I = SmartDashboard.getNumber("I", 0);
D = SmartDashboard.getNumber("D", 0);
this.setpoint = SmartDashboard.getNumber("Setpoint", 0);
SmartDashboard.putNumber("Error",
this.setpoint - this.tunedMotorController.getSpeed());
SmartDashboard.putNumber("Speed",
this.tunedMotorController.getSpeed());
}
this.tunedMotorController.setPID(this.P, this.I, this.D);
if (Math.abs(
this.tunedMotorController
.getClosedLoopError()) >= this.errorThresh
&& wasIncorrect == false)
{
wasIncorrect = true;
time.reset();
time.start();
System.out.println("Error detected, timing...");
}
if (Math.abs(
this.tunedMotorController
.getClosedLoopError()) <= this.errorThresh
&& wasIncorrect == true)
{
wasIncorrect = false;
time.stop();
System.out.println("Time to correct error: " + time.get());
}
}
/**
*
* @param P
* The proportional constant for the PID loop.
*/
public void setP (double P)
{
this.P = P;
}
/**
*
* @param I
* The integral constant for the PID loop.
*/
public void setI (double I)
{
this.I = I;
}
/**
*
* @param D
* The derivative constant for the PID loop.
*/
public void setD (double D)
{
this.D = D;
}
/**
*
* @param P
* The proportional constant for the PID loop.
* @param I
* The integral constant for the PID loop.
* @param D
* The derivative constant for the PID loop.
*/
public void setPID (double p, double i, double d)
{
this.P = p;
this.I = i;
this.D = d;
}
/**
*
* @return
* The current proportional constant for the PID loop
*/
public double getP ()
{
return this.P;
}
/**
*
* @return
* The current integral constant for the PID loop
*/
public double getI ()
{
return this.I;
}
/**
*
* @return
* The current derivative constant for the PID loop
*/
public double getD ()
{
return this.D;
}
/**
*
* @param errThresh
* Sets the error threshold that we find acceptable. Always positive.
*/
public void setErrorThreshold (double errThresh)
{
this.errorThresh = errThresh;
}
/**
*
* @return
* The current error threshold.
*/
public double getErrorThreshold ()
{
return this.errorThresh;
}
/**
*
* @param setpoint
* The target velocity or position of the motor being tuned.
* in revolutions or rpm depending on PID type.
*/
public void setSetpoint (double setpoint)
{
this.setpoint = setpoint;
}
/**
*
* @return
* The current setpoint.
*/
public double getSetpoint ()
{
return this.setpoint;
}
}
|
package org.wakatime.netbeans.plugin;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
public class Dependencies {
private static String pythonLocation = null;
private static String resourcesLocation = null;
public static boolean isPythonInstalled() {
return Dependencies.getPythonLocation() != null;
}
public static String getResourcesLocation() {
if (Dependencies.resourcesLocation == null) {
if (isWindows()) {
File appDataFolder = new File(System.getenv("APPDATA"));
File resourcesFolder = new File(appDataFolder, "WakaTime");
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
} else {
File userHomeDir = new File(System.getProperty("user.home"));
File resourcesFolder = new File(userHomeDir, ".wakatime");
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
}
}
return Dependencies.resourcesLocation;
}
public static String getPythonLocation() {
if (Dependencies.pythonLocation != null)
return Dependencies.pythonLocation;
ArrayList<String> paths = new ArrayList<String>();
paths.add(null);
paths.add("/");
paths.add("/usr/local/bin/");
paths.add("/usr/bin/");
if (System.getProperty("os.name").contains("Windows")) {
File resourcesLocation = new File(Dependencies.getResourcesLocation());
paths.add(combinePaths(resourcesLocation.getAbsolutePath(), "python"));
for (int i=26; i<=50; i++) {
paths.add(combinePaths("\\python" + i, "pythonw"));
paths.add(combinePaths("\\Python" + i, "pythonw"));
}
}
for (String path : paths) {
try {
String[] cmds = {combinePaths(path, "pythonw"), "--version"};
Runtime.getRuntime().exec(cmds);
Dependencies.pythonLocation = combinePaths(path, "pythonw");
break;
} catch (Exception e) {
try {
String[] cmds = {combinePaths(path, "python"), "--version"};
Runtime.getRuntime().exec(cmds);
Dependencies.pythonLocation = combinePaths(path, "python");
break;
} catch (Exception e2) { }
}
}
if (Dependencies.pythonLocation != null) {
WakaTime.debug("Found python binary: " + Dependencies.pythonLocation);
} else {
WakaTime.warn("Could not find python binary.");
}
return Dependencies.pythonLocation;
}
public static boolean isCLIInstalled() {
File cli = new File(Dependencies.getCLILocation());
WakaTime.debug("WakaTime Core Location: " + cli.getAbsolutePath());
WakaTime.debug("WakaTime Core Exists: " + cli.exists());
return cli.exists();
}
public static boolean isCLIOld() {
if (!Dependencies.isCLIInstalled()) {
return false;
}
ArrayList<String> cmds = new ArrayList<String>();
cmds.add(Dependencies.getPythonLocation());
cmds.add(Dependencies.getCLILocation());
cmds.add("--version");
try {
Process p = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
p.waitFor();
String output = "";
String s;
while ((s = stdInput.readLine()) != null) {
output += s;
}
while ((s = stdError.readLine()) != null) {
output += s;
}
WakaTime.debug("wakatime cli version check output: \"" + output + "\"");
WakaTime.debug("wakatime cli version check exit code: " + p.exitValue());
if (p.exitValue() == 0) {
String cliVersion = latestCliVersion();
WakaTime.debug("Current cli version from GitHub: " + cliVersion);
if (output.contains(cliVersion))
return false;
}
} catch (Exception e) { }
return true;
}
public static String latestCliVersion() {
String url = "https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py";
String aboutText = getUrlAsString(url);
Pattern p = Pattern.compile("__version_info__ = \\('([0-9]+)', '([0-9]+)', '([0-9]+)'\\)");
Matcher m = p.matcher(aboutText);
if (m.find()) {
return m.group(1) + "." + m.group(2) + "." + m.group(3);
}
return "Unknown";
}
public static String getCLILocation() {
return combinePaths(Dependencies.getResourcesLocation(), "legacy-python-cli-master", "wakatime", "cli.py");
}
public static void installCLI() {
File cli = new File(Dependencies.getCLILocation());
if (!cli.getParentFile().getParentFile().getParentFile().exists())
cli.getParentFile().getParentFile().getParentFile().mkdirs();
String url = "https://codeload.github.com/wakatime/wakatime/zip/master";
String zipFile = combinePaths(cli.getParentFile().getParentFile().getParentFile().getAbsolutePath(), "wakatime-cli.zip");
File outputDir = cli.getParentFile().getParentFile().getParentFile();
// Download wakatime-master.zip file
if (downloadFile(url, zipFile)) {
// Delete old wakatime-master directory if it exists
File dir = cli.getParentFile().getParentFile();
if (dir.exists()) {
deleteDirectory(dir);
}
// Unzip wakatime-cli
try {
Dependencies.unzip(zipFile, outputDir);
File oldZipFile = new File(zipFile);
oldZipFile.delete();
} catch (IOException e) {
WakaTime.error(e.toString());
}
}
}
public static void upgradeCLI() {
Dependencies.installCLI();
}
public static void installPython() {
if (System.getProperty("os.name").contains("Windows")) {
String pyVer = "3.5.0";
String arch = "win32";
if (is64bit()) arch = "amd64";
String url = "https:
File dir = new File(Dependencies.getResourcesLocation());
File zipFile = new File(combinePaths(dir.getAbsolutePath(), "python.zip"));
if (downloadFile(url, zipFile.getAbsolutePath())) {
File targetDir = new File(combinePaths(dir.getAbsolutePath(), "python"));
// extract python
try {
Dependencies.unzip(zipFile.getAbsolutePath(), targetDir);
} catch (IOException e) {
WakaTime.error(e.toString());
}
zipFile.delete();
}
}
}
public static boolean downloadFile(String url, String saveAs) {
File outFile = new File(saveAs);
// create output directory if does not exist
File outDir = outFile.getParentFile();
if (!outDir.exists())
outDir.mkdirs();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(downloadUrl.openStream());
fos = new FileOutputStream(saveAs);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
return true;
} catch (RuntimeException e) {
WakaTime.error(e.toString());
try {
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection)downloadUrl.openConnection();
InputStream inputStream = conn.getInputStream();
fos = new FileOutputStream(saveAs);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
inputStream.close();
fos.close();
return true;
} catch (NoSuchAlgorithmException e1) {
WakaTime.error(e1.toString());
} catch (KeyManagementException e1) {
WakaTime.error(e1.toString());
} catch (IOException e1) {
WakaTime.error(e1.toString());
}
} catch (IOException e) {
WakaTime.error(e.toString());
}
return false;
}
public static String getUrlAsString(String url) {
StringBuilder text = new StringBuilder();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
try {
InputStream inputStream = downloadUrl.openStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
} catch (RuntimeException e) {
WakaTime.error(e.toString());
try {
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection)downloadUrl.openConnection();
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
} catch (NoSuchAlgorithmException e1) {
WakaTime.error(e1.toString());
} catch (KeyManagementException e1) {
WakaTime.error(e1.toString());
} catch (IOException e1) {
WakaTime.error(e1.toString());
}
} catch (Exception e) {
WakaTime.error(e.toString());
}
return text.toString();
}
private static void unzip(String zipFile, File outputDir) throws IOException {
if(!outputDir.exists())
outputDir.mkdirs();
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir, fileName);
if (ze.isDirectory()) {
newFile.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private static void deleteDirectory(File path) {
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
path.delete();
}
public static boolean is64bit() {
boolean is64bit = false;
if (isWindows()) {
is64bit = (System.getenv("ProgramFiles(x86)") != null);
} else {
is64bit = (System.getProperty("os.arch").indexOf("64") != -1);
}
return is64bit;
}
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
private static String combinePaths(String... args) {
File path = null;
for (String arg : args) {
if (arg != null) {
if (path == null)
path = new File(arg);
else
path = new File(path, arg);
}
}
if (path == null)
return null;
return path.toString();
}
}
|
package com.intellij.openapi.util;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.TIntArrayList;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
/**
* @author max
*/
public class BuildNumber implements Comparable<BuildNumber> {
private static final Set<String> BUILD_NUMBER_PLACEHOLDERS = ContainerUtil.set("__BUILD_NUMBER__", "__BUILD__");
private static final String STAR = "*";
private static final String SNAPSHOT = "SNAPSHOT";
private static final String FALLBACK_VERSION = "999.SNAPSHOT";
public static final int SNAPSHOT_VALUE = Integer.MAX_VALUE;
@NotNull private final String myProductCode;
@NotNull private final int[] myComponents;
public BuildNumber(@NotNull String productCode, int baselineVersion, int buildNumber) {
this(productCode, new int[]{baselineVersion, buildNumber});
}
public BuildNumber(@NotNull String productCode, @NotNull int... components) {
myProductCode = productCode;
myComponents = components;
}
@NotNull
public String getProductCode() {
return myProductCode;
}
public int getBaselineVersion() {
return myComponents[0];
}
@NotNull
public int[] getComponents() {
return myComponents.clone();
}
public boolean isSnapshot() {
return ArrayUtil.indexOf(myComponents, SNAPSHOT_VALUE) >= 0;
}
@NotNull
@Contract(pure = true)
public BuildNumber withoutProductCode() {
return myProductCode.isEmpty() ? this : new BuildNumber("", myComponents);
}
@NotNull
public String asString() {
return asString(true, true);
}
@NotNull
public String asStringWithoutProductCode() {
return asString(false, true);
}
@NotNull
public String asStringWithoutProductCodeAndSnapshot() {
return asString(false, false);
}
@NotNull
private String asString(boolean includeProductCode, boolean withSnapshotMarker) {
StringBuilder builder = new StringBuilder();
if (includeProductCode && !StringUtil.isEmpty(myProductCode)) {
builder.append(myProductCode).append('-');
}
for (int each : myComponents) {
if (each != SNAPSHOT_VALUE) {
builder.append(each);
}
else if (withSnapshotMarker) {
builder.append(SNAPSHOT);
}
builder.append('.');
}
if (builder.charAt(builder.length() - 1) == '.') builder.setLength(builder.length() - 1);
return builder.toString();
}
/**
* Attempts to parse build number from the specified string.
* Returns {@code null} if the string is not a valid build number.
*/
@Nullable
public static BuildNumber fromStringOrNull(@NotNull String version) {
try {
return fromString(version);
} catch (RuntimeException ignored) {
return null;
}
}
public static BuildNumber fromString(String version) {
return fromString(version, null, null);
}
public static BuildNumber fromStringWithProductCode(String version, @NotNull String productCode) {
return fromString(version, null, productCode);
}
public static BuildNumber fromString(String version, @Nullable String pluginName, @Nullable String productCodeIfAbsentInVersion) {
if (StringUtil.isEmptyOrSpaces(version)) return null;
String code = version;
int productSeparator = code.indexOf('-');
String productCode;
if (productSeparator > 0) {
productCode = code.substring(0, productSeparator);
code = code.substring(productSeparator + 1);
}
else {
productCode = productCodeIfAbsentInVersion != null ? productCodeIfAbsentInVersion : "";
}
if (BUILD_NUMBER_PLACEHOLDERS.contains(code) || SNAPSHOT.equals(code)) {
return new BuildNumber(productCode, currentVersion().myComponents);
}
int baselineVersionSeparator = code.indexOf('.');
if (baselineVersionSeparator > 0) {
String baselineVersionString = code.substring(0, baselineVersionSeparator);
if (baselineVersionString.trim().isEmpty()) return null;
List<String> stringComponents = StringUtil.split(code, ".");
TIntArrayList intComponentsList = new TIntArrayList();
for (String stringComponent : stringComponents) {
int comp = parseBuildNumber(version, stringComponent, pluginName);
intComponentsList.add(comp);
if (comp == SNAPSHOT_VALUE) break;
}
int[] intComponents = intComponentsList.toNativeArray();
return new BuildNumber(productCode, intComponents);
}
else {
int buildNumber = parseBuildNumber(version, code, pluginName);
if (buildNumber <= 2000) {
// it's probably a baseline, not a build number
return new BuildNumber(productCode, buildNumber, 0);
}
int baselineVersion = getBaseLineForHistoricBuilds(buildNumber);
return new BuildNumber(productCode, baselineVersion, buildNumber);
}
}
private static int parseBuildNumber(String version, @NotNull String code, String pluginName) {
if (SNAPSHOT.equals(code) || BUILD_NUMBER_PLACEHOLDERS.contains(code) || STAR.equals(code)) {
return SNAPSHOT_VALUE;
}
try {
return Integer.parseInt(code);
}
catch (NumberFormatException e) {
throw new RuntimeException("Invalid version number: " + version + "; plugin name: " + pluginName);
}
}
@Override
public int compareTo(@NotNull BuildNumber o) {
int[] c1 = myComponents;
int[] c2 = o.myComponents;
for (int i = 0; i < Math.min(c1.length, c2.length); i++) {
if (c1[i] == c2[i] && c1[i] == SNAPSHOT_VALUE) return 0;
if (c1[i] == SNAPSHOT_VALUE) return 1;
if (c2[i] == SNAPSHOT_VALUE) return -1;
int result = c1[i] - c2[i];
if (result != 0) return result;
}
return c1.length - c2.length;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BuildNumber that = (BuildNumber)o;
if (!myProductCode.equals(that.myProductCode)) return false;
return Arrays.equals(myComponents, that.myComponents);
}
@Override
public int hashCode() {
int result = myProductCode.hashCode();
result = 31 * result + Arrays.hashCode(myComponents);
return result;
}
@Override
public String toString() {
return asString();
}
private static int getBaseLineForHistoricBuilds(int bn) {
if (bn >= 10000) return 88; // Maia, 9x builds
if (bn >= 9500) return 85; // 8.1 builds
if (bn >= 9100) return 81; // 8.0.x builds
if (bn >= 8000) return 80; // 8.0, including pre-release builds
if (bn >= 7500) return 75; // 7.0.2+
if (bn >= 7200) return 72; // 7.0 final
if (bn >= 6900) return 69; // 7.0 pre-M2
if (bn >= 6500) return 65; // 7.0 pre-M1
if (bn >= 6000) return 60; // 6.0.2+
if (bn >= 5000) return 55; // 6.0 branch, including all 6.0 EAP builds
if (bn >= 4000) return 50; // 5.1 branch
return 40;
}
private static class Holder {
private static final BuildNumber CURRENT_VERSION = fromFile();
private static BuildNumber fromFile() {
try {
String home = PathManager.getHomePath();
File buildTxtFile = FileUtil.findFirstThatExist(
home + "/build.txt",
home + "/Resources/build.txt",
PathManager.getCommunityHomePath() + "/build.txt");
if (buildTxtFile != null) {
String text = FileUtil.loadFile(buildTxtFile).trim();
return fromString(text);
}
}
catch (IOException ignored) { }
return fromString(FALLBACK_VERSION);
}
}
/**
* This method is for internal platform use only. In regular code use {@link com.intellij.openapi.application.ApplicationInfo#getBuild()} instead.
*/
@ApiStatus.Internal
public static BuildNumber currentVersion() {
return Holder.CURRENT_VERSION;
}
//<editor-fold desc="Deprecated stuff.">
/** @deprecated use {@link #getComponents()} (since IDEA 2016, a build number may contain more than two parts) */
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2019")
public int getBuildNumber() {
return myComponents[1];
}
//</editor-fold>
}
|
package org.workcraft.plugins.circuit.commands;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import org.workcraft.dom.Connection;
import org.workcraft.dom.Container;
import org.workcraft.dom.Node;
import org.workcraft.dom.visual.ConnectionHelper;
import org.workcraft.dom.visual.VisualComponent;
import org.workcraft.dom.visual.VisualModel;
import org.workcraft.dom.visual.VisualNode;
import org.workcraft.dom.visual.VisualTransformableNode;
import org.workcraft.dom.visual.connections.ConnectionGraphic;
import org.workcraft.dom.visual.connections.Polyline;
import org.workcraft.dom.visual.connections.VisualConnection;
import org.workcraft.dom.visual.connections.VisualConnection.ConnectionType;
import org.workcraft.exceptions.InvalidConnectionException;
import org.workcraft.gui.graph.commands.AbstractLayoutCommand;
import org.workcraft.plugins.circuit.CircuitUtils;
import org.workcraft.plugins.circuit.VisualCircuit;
import org.workcraft.plugins.circuit.VisualCircuitComponent;
import org.workcraft.plugins.circuit.VisualContact;
import org.workcraft.plugins.circuit.VisualJoint;
import org.workcraft.plugins.circuit.routing.RouterClient;
import org.workcraft.plugins.circuit.routing.basic.Point;
import org.workcraft.plugins.circuit.routing.impl.Route;
import org.workcraft.plugins.circuit.routing.impl.Router;
import org.workcraft.plugins.circuit.routing.impl.RouterTask;
import org.workcraft.util.Hierarchy;
import org.workcraft.workspace.WorkspaceEntry;
import org.workcraft.workspace.WorkspaceUtils;
public class CircuitLayoutCommand extends AbstractLayoutCommand {
private static final double DX = 10;
private static final double DY = 5;
@Override
public String getDisplayName() {
return "Circuit placement and routing";
}
@Override
public boolean isApplicableTo(WorkspaceEntry we) {
return WorkspaceUtils.isApplicable(we, VisualCircuit.class);
}
@Override
public void layout(VisualModel model) {
if (model instanceof VisualCircuit) {
VisualCircuit circuit = (VisualCircuit) model;
if (!skipLayoutPlacement()) {
setComponentPosition(circuit);
alignPorts(circuit);
}
setPolylineConnections(circuit, skipLayoutRouting());
if (!skipLayoutRouting()) {
routeWires(circuit);
}
}
}
public boolean skipLayoutPlacement() {
return false;
}
public boolean skipLayoutRouting() {
return false;
}
private void setComponentPosition(VisualCircuit circuit) {
LinkedList<HashSet<VisualComponent>> layers = rankComponents(circuit);
double x = (1.0 - layers.size()) * DX / 2.0;
for (HashSet<VisualComponent> layer: layers) {
double y = (1.0 - layer.size()) * DY / 2.0;
for (VisualComponent component: layer) {
Point2D pos = new Point2D.Double(x, y);
component.setPosition(pos);
if (component instanceof VisualCircuitComponent) {
VisualCircuitComponent circuitComponent = (VisualCircuitComponent) component;
setContactPositions(circuitComponent);
}
y += DY;
}
x += DX;
}
}
private void setContactPositions(VisualCircuitComponent circuitComponent) {
for (VisualContact contact: circuitComponent.getContacts()) {
if (contact.isInput()) {
contact.setPosition(new Point2D.Double(-1.0, 0.0));
} else {
contact.setPosition(new Point2D.Double(1.0, 0.0));
}
}
circuitComponent.setContactsDefaultPosition();
}
private LinkedList<HashSet<VisualComponent>> rankComponents(VisualCircuit model) {
LinkedList<HashSet<VisualComponent>> result = new LinkedList<>();
HashSet<VisualComponent> inputPorts = new HashSet<>();
for (VisualContact contact: Hierarchy.getDescendantsOfType(model.getRoot(), VisualContact.class)) {
if (contact.isPort() && contact.isInput()) {
inputPorts.add(contact);
}
}
HashSet<VisualCircuitComponent> remainingComponents = new HashSet<>(Hierarchy.getDescendantsOfType(
model.getRoot(), VisualCircuitComponent.class));
HashSet<VisualComponent> currentLayer = inputPorts;
HashSet<VisualComponent> firstLayer = null;
while (!currentLayer.isEmpty()) {
remainingComponents.removeAll(currentLayer);
result.add(currentLayer);
currentLayer = getNextLayer(model, currentLayer);
currentLayer.retainAll(remainingComponents);
if (firstLayer == null) {
firstLayer = currentLayer;
}
}
if (firstLayer == null) {
firstLayer = new HashSet<>();
}
firstLayer.addAll(remainingComponents);
if ((result.size() < 2) && !firstLayer.isEmpty()) {
result.add(firstLayer);
}
HashSet<VisualComponent> outputPorts = new HashSet<>();
for (VisualContact contact: Hierarchy.getDescendantsOfType(model.getRoot(), VisualContact.class)) {
if (contact.isPort() && contact.isOutput()) {
outputPorts.add(contact);
}
}
result.add(outputPorts);
return result;
}
private HashSet<VisualComponent> getNextLayer(final VisualCircuit model, HashSet<VisualComponent> layer) {
HashSet<VisualComponent> result = new HashSet<>();
for (VisualComponent component: layer) {
result.addAll(CircuitUtils.getComponentPostset(model, component));
}
return result;
}
private void setPolylineConnections(VisualCircuit circuit, boolean routeSelfLoops) {
for (VisualConnection connection: Hierarchy.getDescendantsOfType(circuit.getRoot(), VisualConnection.class)) {
connection.setConnectionType(ConnectionType.POLYLINE);
ConnectionGraphic graphic = connection.getGraphic();
graphic.setDefaultControlPoints();
if (routeSelfLoops) {
routeSelfLoop(connection);
}
}
}
private void routeSelfLoop(VisualConnection connection) {
VisualNode firstNode = connection.getFirst();
VisualNode secondNode = connection.getSecond();
if ((firstNode instanceof VisualContact) && (secondNode instanceof VisualContact)) {
VisualContact firstContact = (VisualContact) firstNode;
VisualContact secondContact = (VisualContact) secondNode;
if (!firstContact.isPort() && !secondContact.isPort()
&& (firstContact.getParent() == secondContact.getParent())) {
Point2D firstPos = firstContact.getRootSpacePosition();
Point2D secondPos = secondContact.getRootSpacePosition();
Node parent = firstContact.getParent();
double h = 2.0;
if (parent instanceof VisualCircuitComponent) {
VisualCircuitComponent component = (VisualCircuitComponent) parent;
Rectangle2D bb = component.getInternalBoundingBoxInLocalSpace();
h = bb.getHeight();
}
double d = firstPos.getY() - secondPos.getY();
double dx = 1.0 - Math.abs(d);
if (dx < 0.0) dx = 0.0;
double dy = (d > 0) ? h - d : -h - d;
ConnectionGraphic graphic = connection.getGraphic();
if (graphic instanceof Polyline) {
Polyline polyline = (Polyline) graphic;
polyline.addControlPoint(new Point2D.Double(firstPos.getX(), firstPos.getY() - dy));
polyline.addControlPoint(new Point2D.Double(secondPos.getX() - dx, firstPos.getY() - dy));
polyline.addControlPoint(new Point2D.Double(secondPos.getX() - dx, secondPos.getY()));
}
}
}
}
private void alignPorts(VisualCircuit circuit) {
for (VisualContact contact: circuit.getVisualPorts()) {
if (contact.isOutput()) {
VisualContact driver = CircuitUtils.findDriver(circuit, contact);
if (driver != null) {
contact.setRootSpaceY(driver.getRootSpaceY());
}
}
if (contact.isInput()) {
double y = 0.0;
int count = 0;
for (VisualContact driven: CircuitUtils.findDriven(circuit, contact)) {
y += driven.getRootSpaceY();
count++;
}
if (count > 0) {
contact.setRootSpaceY(y / (double) count);
}
}
}
}
private void routeWires(VisualCircuit circuit) {
Router router = new Router();
RouterClient routingClient = new RouterClient();
RouterTask routerTask = routingClient.registerObstacles(circuit);
router.setRouterTask(routerTask);
for (Route route: router.getRoutingResult()) {
VisualContact srcContact = routingClient.getContact(route.source);
VisualContact dstContact = routingClient.getContact(route.destination);
Connection connection = circuit.getConnection(srcContact, dstContact);
if (connection instanceof VisualConnection) {
List<Point2D> locationsInRootSpace = new ArrayList<>();
for (Point routePoint : route.getPoints()) {
locationsInRootSpace.add(new Point2D.Double(routePoint.getX(), routePoint.getY()));
}
ConnectionHelper.addControlPoints((VisualConnection) connection, locationsInRootSpace);
}
}
while (mergeConnections(circuit)) { }
}
private boolean mergeConnections(VisualCircuit circuit) {
Collection<VisualConnection> connections = Hierarchy.getDescendantsOfType(circuit.getRoot(), VisualConnection.class);
for (VisualConnection connection: connections) {
ConnectionGraphic grapic = connection.getGraphic();
if (grapic instanceof Polyline) {
ConnectionHelper.filterControlPoints((Polyline) grapic, 0.01, 0.01);
}
}
for (VisualConnection c1: connections) {
for (VisualConnection c2: connections) {
if (mergeConnections(circuit, c1, c2)) {
return true;
}
}
}
return false;
}
private boolean mergeConnections(VisualCircuit circuit, VisualConnection c1, VisualConnection c2) {
if ((c1 != c2) && (c1.getFirst() == c2.getFirst())) {
VisualTransformableNode src = (VisualTransformableNode) c1.getFirst();
Point2D p0 = src.getRootSpacePosition();
Point2D p = getLastCommonPoint(c1, c2);
if ((p != null) && (p0.distanceSq(p) > 0.01)) {
boolean processed = false;
if (c1.getSecond() instanceof VisualJoint) {
VisualJoint joint = (VisualJoint) c1.getSecond();
if (p.distanceSq(joint.getRootSpacePosition()) < 0.01) {
appendConnection(circuit, joint, c2);
processed = true;
}
} else if (c2.getSecond() instanceof VisualJoint) {
VisualJoint joint = (VisualJoint) c2.getSecond();
if (p.distanceSq(joint.getRootSpacePosition()) < 0.01) {
appendConnection(circuit, joint, c1);
processed = true;
}
}
if (!processed) {
mergeCommonConnectionSegment(circuit, c1, c2, p);
}
return true;
}
}
return false;
}
private Point2D getLastCommonPoint(VisualConnection c1, VisualConnection c2) {
if (c1.getFirst() != c2.getFirst()) {
return null;
}
Point2D pos = ((VisualTransformableNode) c1.getFirst()).getRootSpacePosition();
ConnectionGraphic g1 = c1.getGraphic();
ConnectionGraphic g2 = c2.getGraphic();
if ((g1 instanceof Polyline) && (g2 instanceof Polyline)) {
Polyline p1 = (Polyline) g1;
Polyline p2 = (Polyline) g2;
int count = Math.min(p1.getControlPointCount(), p2.getControlPointCount());
for (int i = 0; i <= count; i++) {
Point2D pos1 = (i < p1.getControlPointCount()) ? p1.getControlPoint(i).getRootSpacePosition()
: ((VisualTransformableNode) c1.getSecond()).getRootSpacePosition();
Point2D pos2 = (i < p2.getControlPointCount()) ? p2.getControlPoint(i).getRootSpacePosition()
: ((VisualTransformableNode) c2.getSecond()).getRootSpacePosition();
if (pos1.distanceSq(pos2) < 0.01) {
pos = pos1;
} else {
double gradient = ConnectionHelper.calcGradient(pos, pos1, pos2);
boolean sameSide = ((pos2.getX() > pos.getX()) == (pos1.getX() > pos.getX()))
&& ((pos2.getY() > pos.getY()) == (pos1.getY() > pos.getY()));
if ((Math.abs(gradient) < 0.01) && sameSide) {
pos = (pos.distanceSq(pos1) < pos.distanceSq(pos2)) ? pos1 : pos2;
}
break;
}
}
}
return pos;
}
private void appendConnection(VisualCircuit circuit, VisualJoint joint, VisualConnection connection) {
Point2D p = joint.getRootSpacePosition();
LinkedList<Point2D> suffixLocationsInRootSpace = ConnectionHelper.getSuffixControlPoints(connection, p);
circuit.remove(connection);
try {
VisualConnection succConnection = circuit.connect(joint, connection.getSecond());
ConnectionHelper.addControlPoints(succConnection, suffixLocationsInRootSpace);
succConnection.copyStyle(connection);
} catch (InvalidConnectionException e) {
}
}
private void mergeCommonConnectionSegment(VisualCircuit circuit, VisualConnection c1, VisualConnection c2, Point2D p) {
LinkedList<Point2D> commonLocationsInRootSpace = ConnectionHelper.getPrefixControlPoints(c1, p);
LinkedList<Point2D> c1LocationsInRootSpace = ConnectionHelper.getSuffixControlPoints(c1, p);
LinkedList<Point2D> c2LocationsInRootSpace = ConnectionHelper.getSuffixControlPoints(c2, p);
Container container = Hierarchy.getNearestContainer(c1, c2);
VisualJoint joint = circuit.createJoint(container);
joint.setPosition(p);
circuit.remove(c1);
circuit.remove(c2);
try {
VisualConnection commonConnection = circuit.connect(c1.getFirst(), joint);
commonConnection.mixStyle(c1, c2);
ConnectionHelper.addControlPoints(commonConnection, commonLocationsInRootSpace);
VisualConnection succ1Connection = circuit.connect(joint, c1.getSecond());
ConnectionHelper.addControlPoints(succ1Connection, c1LocationsInRootSpace);
succ1Connection.copyStyle(c1);
VisualConnection succ2Connection = circuit.connect(joint, c2.getSecond());
ConnectionHelper.addControlPoints(succ2Connection, c2LocationsInRootSpace);
succ2Connection.copyStyle(c2);
} catch (InvalidConnectionException e) {
}
}
}
|
package com.intellij.ui.jcef;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Disposer;
import com.intellij.ui.JBColor;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.callback.CefContextMenuParams;
import org.cef.callback.CefMenuModel;
import org.cef.handler.*;
import org.cef.network.CefCookieManager;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.locks.ReentrantLock;
import static org.cef.callback.CefMenuModel.MenuId.MENU_ID_USER_LAST;
/**
* A wrapper over {@link CefBrowser}.
* <p>
* Use {@link #getComponent()} as the browser's UI component.
* Use {@link #loadURL(String)} or {@link #loadHTML(String)} for loading.
*
* @author tav
*/
@ApiStatus.Experimental
public class JBCefBrowser implements JBCefDisposable {
private static final String BLANK_URI = "about:blank";
private static final String JBCEFBROWSER_INSTANCE_PROP = "JBCefBrowser.instance";
@NotNull private final JBCefClient myCefClient;
@NotNull private final JPanel myComponent;
@NotNull private final CefBrowser myCefBrowser;
@Nullable private volatile JBCefCookieManager myJBCefCookieManager;
@NotNull private final CefFocusHandler myCefFocusHandler;
@Nullable private final CefLifeSpanHandler myLifeSpanHandler;
@NotNull private final DisposeHelper myDisposeHelper = new DisposeHelper();
private final boolean myIsDefaultClient;
private volatile boolean myIsCefBrowserCreated;
@Nullable private volatile LoadDeferrer myLoadDeferrer;
private JDialog myDevtoolsFrame = null;
protected CefContextMenuHandler myDefaultContextMenuHandler;
private final ReentrantLock myCookieManagerLock = new ReentrantLock();
private static class LoadDeferrer {
@Nullable protected final String myHtml;
@NotNull protected final String myUrl;
private LoadDeferrer(@Nullable String html, @NotNull String url) {
myHtml = html;
myUrl = url;
}
@NotNull
public static LoadDeferrer urlDeferrer(String url) {
return new LoadDeferrer(null, url);
}
@NotNull
public static LoadDeferrer htmlDeferrer(String html, String url) {
return new LoadDeferrer(html, url);
}
public void load(@NotNull CefBrowser browser) {
// JCEF demands async loading.
SwingUtilities.invokeLater(
myHtml == null ?
() -> browser.loadURL(myUrl) :
() -> loadString(browser, myHtml, myUrl));
}
}
/**
* Creates a browser with the provided {@code JBCefClient} and initial URL. The client's lifecycle is the responsibility of the caller.
*/
public JBCefBrowser(@NotNull JBCefClient client, @Nullable String url) {
this(client, false, url);
}
public JBCefBrowser(@NotNull CefBrowser cefBrowser, @NotNull JBCefClient client) {
this(cefBrowser, client, false, null);
}
private JBCefBrowser(@NotNull JBCefClient client, boolean isDefaultClient, @Nullable String url) {
this(null, client, isDefaultClient, url);
}
private JBCefBrowser(@Nullable CefBrowser cefBrowser, @NotNull JBCefClient client, boolean isDefaultClient, @Nullable String url) {
if (client.isDisposed()) {
throw new IllegalArgumentException("JBCefClient is disposed");
}
myCefClient = client;
myIsDefaultClient = isDefaultClient;
myComponent = new JPanel(new BorderLayout());
myComponent.setBackground(JBColor.background());
myCefBrowser = cefBrowser != null ?
cefBrowser : myCefClient.getCefClient().createBrowser(url != null ? url : BLANK_URI, false, false);
JComponent uiComp = (JComponent)myCefBrowser.getUIComponent();
uiComp.putClientProperty(JBCEFBROWSER_INSTANCE_PROP, this);
myComponent.add(uiComp, BorderLayout.CENTER);
if (cefBrowser == null) {
myCefClient.addLifeSpanHandler(myLifeSpanHandler = new CefLifeSpanHandlerAdapter() {
@Override
public void onAfterCreated(CefBrowser browser) {
myIsCefBrowserCreated = true;
LoadDeferrer loader = myLoadDeferrer;
if (loader != null) {
loader.load(browser);
myLoadDeferrer = null;
}
}
}, myCefBrowser);
}
else {
myLifeSpanHandler = null;
}
myCefClient.addFocusHandler(myCefFocusHandler = new CefFocusHandlerAdapter() {
@Override
public boolean onSetFocus(CefBrowser browser, FocusSource source) {
if (source == FocusSource.FOCUS_SOURCE_NAVIGATION) return true;
// Workaround: JCEF doesn't change current focus on the client side.
// Clear the focus manually and this will report focus loss to the client
// and will let focus return to the client on mouse click.
// tav [todo]: the opposite is inadequate
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
return false;
}
}, myCefBrowser);
myDefaultContextMenuHandler = createDefaultContextMenuHandler();
myCefClient.addContextMenuHandler(myDefaultContextMenuHandler, this.getCefBrowser());
}
protected DefaultCefContextMenuHandler createDefaultContextMenuHandler() {
boolean isInternal = ApplicationManager.getApplication().isInternal();
return new DefaultCefContextMenuHandler(isInternal);
}
/**
* Loads URL.
*/
public void loadURL(@NotNull String url) {
if (myIsCefBrowserCreated) {
myCefBrowser.loadURL(url);
}
else {
myLoadDeferrer = LoadDeferrer.urlDeferrer(url);
}
}
/**
* Loads html content.
*
* @param html content to load
* @param url a dummy URL that may affect restriction policy applied to the content
*/
public void loadHTML(@NotNull String html, @NotNull String url) {
if (myIsCefBrowserCreated) {
loadString(myCefBrowser, html, url);
}
else {
myLoadDeferrer = LoadDeferrer.htmlDeferrer(html, url);
}
}
/**
* Loads html content.
*/
public void loadHTML(@NotNull String html) {
loadHTML(html, BLANK_URI);
}
private static void loadString(CefBrowser cefBrowser, String html, String url) {
url = JBCefFileSchemeHandler.registerLoadHTMLRequest(cefBrowser, html, url);
cefBrowser.loadURL(url);
}
/**
* Creates a browser with default {@link JBCefClient}. The default client is disposed with this browser and may not be used with other browsers.
*/
@SuppressWarnings("unused")
public JBCefBrowser() {
this(JBCefApp.getInstance().createClient(), true, null);
}
/**
* @see #JBCefBrowser()
* @param url initial url
*/
@SuppressWarnings("unused")
public JBCefBrowser(@NotNull String url) {
this(JBCefApp.getInstance().createClient(), true, url);
}
@NotNull
public JComponent getComponent() {
return myComponent;
}
@NotNull
public CefBrowser getCefBrowser() {
return myCefBrowser;
}
@NotNull
public JBCefClient getJBCefClient() {
return myCefClient;
}
@NotNull
public JBCefCookieManager getJBCefCookieManager() {
myCookieManagerLock.lock();
try {
if (myJBCefCookieManager == null) {
myJBCefCookieManager = new JBCefCookieManager(CefCookieManager.getGlobalManager());
}
return myJBCefCookieManager;
}
finally {
myCookieManagerLock.unlock();
}
}
@SuppressWarnings("unused")
public void setJBCefCookieManager(@NotNull JBCefCookieManager jBCefCookieManager) {
myCookieManagerLock.lock();
try {
myJBCefCookieManager = jBCefCookieManager;
}
finally {
myCookieManagerLock.unlock();
}
}
@Nullable
private static Window getActiveFrame() {
for (Frame frame : Frame.getFrames()) {
if (frame.isActive()) return frame;
}
return null;
}
public void openDevtools() {
if (myDevtoolsFrame != null) {
myDevtoolsFrame.toFront();
return;
}
Window activeFrame = getActiveFrame();
if (activeFrame == null) return;
Rectangle bounds = activeFrame.getGraphicsConfiguration().getBounds();
myDevtoolsFrame = new JDialog(activeFrame);
myDevtoolsFrame.setTitle("JCEF DevTools");
myDevtoolsFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
myDevtoolsFrame.setBounds(bounds.width / 4 + 100, bounds.height / 4 + 100, bounds.width / 2, bounds.height / 2);
myDevtoolsFrame.setLayout(new BorderLayout());
JBCefBrowser devTools = new JBCefBrowser(myCefBrowser.getDevTools(), myCefClient);
myDevtoolsFrame.add(devTools.getComponent(), BorderLayout.CENTER);
myDevtoolsFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
myDevtoolsFrame = null;
Disposer.dispose(devTools);
}
});
myDevtoolsFrame.setVisible(true);
}
@Override
public void dispose() {
myDisposeHelper.dispose(() -> {
myCefClient.removeFocusHandler(myCefFocusHandler, myCefBrowser);
if (myLifeSpanHandler != null) myCefClient.removeLifeSpanHandler(myLifeSpanHandler, myCefBrowser);
myCefBrowser.stopLoad();
myCefBrowser.close(false);
if (myIsDefaultClient) {
Disposer.dispose(myCefClient);
}
});
}
@Override
public boolean isDisposed() {
return myDisposeHelper.isDisposed();
}
/**
* Returns {@code JBCefBrowser} instance associated with this {@code CefBrowser}.
*/
public static JBCefBrowser getJBCefBrowser(@NotNull CefBrowser browser) {
return (JBCefBrowser)((JComponent)browser.getUIComponent()).getClientProperty(JBCEFBROWSER_INSTANCE_PROP);
}
protected class DefaultCefContextMenuHandler extends CefContextMenuHandlerAdapter {
protected static final int DEBUG_COMMAND_ID = MENU_ID_USER_LAST;
private final boolean isInternal;
public DefaultCefContextMenuHandler(boolean isInternal) {
this.isInternal = isInternal;
}
@Override
public void onBeforeContextMenu(CefBrowser browser, CefFrame frame, CefContextMenuParams params, CefMenuModel model) {
if (isInternal) {
model.addItem(DEBUG_COMMAND_ID, "Open DevTools");
}
}
@Override
public boolean onContextMenuCommand(CefBrowser browser, CefFrame frame, CefContextMenuParams params, int commandId, int eventFlags) {
if (commandId == DEBUG_COMMAND_ID) {
openDevtools();
return true;
}
return false;
}
}
}
|
package com.intellij;
import com.intellij.idea.Bombed;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.JITSensitive;
import com.intellij.testFramework.TeamCityLogger;
import com.intellij.testFramework.TestFrameworkUtil;
import com.intellij.util.containers.MultiMap;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.*;
@SuppressWarnings({"HardCodedStringLiteral", "UseOfSystemOutOrSystemErr", "CallToPrintStackTrace", "TestOnlyProblems"})
public class TestCaseLoader {
public static final String PERFORMANCE_TESTS_ONLY_FLAG = "idea.performance.tests";
public static final String INCLUDE_PERFORMANCE_TESTS_FLAG = "idea.include.performance.tests";
public static final String INCLUDE_UNCONVENTIONALLY_NAMED_TESTS_FLAG = "idea.include.unconventionally.named.tests";
private static final boolean PERFORMANCE_TESTS_ONLY = "true".equals(System.getProperty(PERFORMANCE_TESTS_ONLY_FLAG));
private static final boolean INCLUDE_PERFORMANCE_TESTS = "true".equals(System.getProperty(INCLUDE_PERFORMANCE_TESTS_FLAG));
private static final boolean INCLUDE_UNCONVENTIONALLY_NAMED_TESTS = "true".equals(System.getProperty(INCLUDE_UNCONVENTIONALLY_NAMED_TESTS_FLAG));
/**
* An implicit group which includes all tests from all defined groups and tests which don't belong to any group.
*/
private static final String ALL_TESTS_GROUP = "ALL";
private static final String PLATFORM_LITE_FIXTURE_NAME = "com.intellij.testFramework.PlatformLiteFixture";
private final List<Class> myClassList = new ArrayList<>();
private final List<Throwable> myClassLoadingErrors = new ArrayList<>();
private Class myFirstTestClass;
private Class myLastTestClass;
private final TestClassesFilter myTestClassesFilter;
private final boolean myForceLoadPerformanceTests;
public TestCaseLoader(String classFilterName) {
this(classFilterName, false);
}
public TestCaseLoader(String classFilterName, boolean forceLoadPerformanceTests) {
myForceLoadPerformanceTests = forceLoadPerformanceTests;
String patterns = getTestPatterns();
if (!StringUtil.isEmpty(patterns)) {
myTestClassesFilter = new PatternListTestClassFilter(StringUtil.split(patterns, ";"));
System.out.println("Using patterns: [" + patterns +"]");
}
else {
List<URL> groupingFileUrls = Collections.emptyList();
if (!StringUtil.isEmpty(classFilterName)) {
try {
groupingFileUrls = Collections.list(getClassLoader().getResources(classFilterName));
}
catch (IOException e) {
e.printStackTrace();
}
}
List<String> testGroupNames = getTestGroups();
MultiMap<String, String> groups = MultiMap.createLinked();
for (URL fileUrl : groupingFileUrls) {
try {
InputStreamReader reader = new InputStreamReader(fileUrl.openStream());
try {
groups.putAllValues(GroupBasedTestClassFilter.readGroups(reader));
}
finally {
reader.close();
}
}
catch (IOException e) {
e.printStackTrace();
System.err.println("Failed to load test groups from " + fileUrl);
}
}
if (groups.isEmpty() || testGroupNames.contains(ALL_TESTS_GROUP)) {
System.out.println("Using all classes");
myTestClassesFilter = TestClassesFilter.ALL_CLASSES;
}
else {
System.out.println("Using test groups: " + testGroupNames);
myTestClassesFilter = new GroupBasedTestClassFilter(groups, testGroupNames);
}
}
}
@Nullable
private static String getTestPatterns() {
return System.getProperty("intellij.build.test.patterns", System.getProperty("idea.test.patterns"));
}
@NotNull
private static List<String> getTestGroups() {
return StringUtil.split(System.getProperty("intellij.build.test.groups", System.getProperty("idea.test.group", "")).trim(), ";");
}
void addClassIfTestCase(Class testCaseClass, String moduleName) {
if (shouldAddTestCase(testCaseClass, moduleName, true) &&
testCaseClass != myFirstTestClass && testCaseClass != myLastTestClass &&
TestFrameworkUtil.canRunTest(testCaseClass)) {
myClassList.add(testCaseClass);
}
}
void addFirstTest(Class aClass) {
assert myFirstTestClass == null : "already added: "+aClass;
assert shouldAddTestCase(aClass, null, false) : "not a test: "+aClass;
myFirstTestClass = aClass;
}
void addLastTest(Class aClass) {
assert myLastTestClass == null : "already added: "+aClass;
assert shouldAddTestCase(aClass, null, false) : "not a test: "+aClass;
myLastTestClass = aClass;
}
private boolean shouldAddTestCase(final Class<?> testCaseClass, String moduleName, boolean testForExcluded) {
if ((testCaseClass.getModifiers() & Modifier.ABSTRACT) != 0) return false;
if (testForExcluded && shouldExcludeTestClass(moduleName, testCaseClass)) return false;
if (TestCase.class.isAssignableFrom(testCaseClass) || TestSuite.class.isAssignableFrom(testCaseClass)) {
return true;
}
try {
final Method suiteMethod = testCaseClass.getMethod("suite");
if (Test.class.isAssignableFrom(suiteMethod.getReturnType()) && (suiteMethod.getModifiers() & Modifier.STATIC) != 0) {
return true;
}
}
catch (NoSuchMethodException ignored) { }
return TestFrameworkUtil.isJUnit4TestClass(testCaseClass);
}
private boolean shouldExcludeTestClass(String moduleName, Class testCaseClass) {
if (!myForceLoadPerformanceTests && !shouldIncludePerformanceTestCase(testCaseClass)) return true;
String className = testCaseClass.getName();
return !myTestClassesFilter.matches(className, moduleName) || isBombed(testCaseClass);
}
public static boolean isBombed(final AnnotatedElement element) {
final Bombed bombedAnnotation = element.getAnnotation(Bombed.class);
if (bombedAnnotation == null) return false;
return !TestFrameworkUtil.bombExplodes(bombedAnnotation);
}
public void loadTestCases(final String moduleName, final Collection<String> classNamesIterator) {
for (String className : classNamesIterator) {
try {
Class candidateClass = Class.forName(className, false, getClassLoader());
addClassIfTestCase(candidateClass, moduleName);
}
catch (Throwable e) {
String message = "Cannot load class " + className + ": " + e.getMessage();
System.err.println(message);
myClassLoadingErrors.add(new Throwable(message, e));
}
}
}
protected ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
public List<Throwable> getClassLoadingErrors() {
return myClassLoadingErrors;
}
private static final List<String> ourRankList = getTeamCityRankList();
private static List<String> getTeamCityRankList() {
if (isPerformanceTestsRun()) {
// let performance test order be stable to decrease the variation in their timings
return Collections.emptyList();
}
String filePath = System.getProperty("teamcity.tests.recentlyFailedTests.file", null);
if (filePath != null) {
try {
return FileUtil.loadLines(filePath);
}
catch (IOException ignored) { }
}
return Collections.emptyList();
}
private static int getRank(Class aClass) {
if (isPerformanceTestsRun()) {
return moveToStart(aClass) ? 0 : 1;
}
// PlatformLiteFixture is the very special test case because it doesn't load all the XMLs with component/extension declarations
// (that is, uses a mock application). Instead, it allows to declare them manually using its registerComponent/registerExtension
// methods. The goal is to make tests which extend PlatformLiteFixture extremely fast. The problem appears when such tests are invoked
// together with other tests which rely on declarations in XML files (that is, use a real application). The nature of the IDEA
// application is such that static final fields are often used to cache extensions. While having a positive effect on performance,
// it creates problems during testing. Simply speaking, if the instance of PlatformLiteFixture is the first one in a suite, it pollutes
// static final fields (and all other kinds of caches) with invalid values. To avoid it, such tests should always be the last.
if (isPlatformLiteFixture(aClass)) {
return ourRankList.size() + 1;
}
int i = ourRankList.indexOf(aClass.getName());
if (i != -1) {
return i;
}
return ourRankList.size();
}
private static boolean moveToStart(Class testClass) {
return testClass.getAnnotation(JITSensitive.class) != null;
}
private static boolean isPlatformLiteFixture(Class aClass) {
while (aClass != null) {
if (PLATFORM_LITE_FIXTURE_NAME.equals(aClass.getName())) {
return true;
}
else {
aClass = aClass.getSuperclass();
}
}
return false;
}
public List<Class> getClasses() {
List<Class> result = new ArrayList<>(myClassList.size());
result.addAll(myClassList);
Collections.sort(result, Comparator.comparingInt(TestCaseLoader::getRank));
if (myFirstTestClass != null) {
result.add(0, myFirstTestClass);
}
if (myLastTestClass != null) {
result.add(myLastTestClass);
}
return result;
}
public void clearClasses() {
myClassList.clear();
}
static boolean isPerformanceTestsRun() {
return PERFORMANCE_TESTS_ONLY;
}
static boolean isIncludingPerformanceTestsRun() {
return INCLUDE_PERFORMANCE_TESTS;
}
static boolean shouldIncludePerformanceTestCase(Class aClass) {
return isIncludingPerformanceTestsRun() || isPerformanceTestsRun() || !isPerformanceTest(null,aClass);
}
static boolean isPerformanceTest(String methodName, Class aClass) {
return TestFrameworkUtil.isPerformanceTest(methodName, aClass.getSimpleName());
}
public void fillTestCases(String rootPackage, List<File> classesRoots) {
long before = System.currentTimeMillis();
for (File classesRoot : classesRoots) {
int oldCount = getClasses().size();
ClassFinder classFinder = new ClassFinder(classesRoot, rootPackage, INCLUDE_UNCONVENTIONALLY_NAMED_TESTS);
loadTestCases(classesRoot.getName(), classFinder.getClasses());
int newCount = getClasses().size();
if (newCount != oldCount) {
System.out.println("Loaded " + (newCount - oldCount) + " tests from class root " + classesRoot);
}
}
if (getClasses().size() == 1) {
clearClasses();
}
long after = System.currentTimeMillis();
String message = "Number of test classes found: " + getClasses().size()
+ " time to load: " + (after - before) / 1000 + "s.";
System.out.println(message);
TeamCityLogger.info(message);
}
}
|
package com.bigstar.curtainlistview;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import com.nineoldandroids.view.ViewPropertyAnimator;
public class BaseCurtainListView extends RelativeLayout {
private final String TAG = "CurtainListView";
public enum SCROLL_STATE {
SCROLL_TO_TOP, SCROLL_TO_BOTTOM, SCROLL_SLOWLY
}
private final int SCROLL_MIN_VELOCITY = 15;
private int TRANSFER_DURATION = 200;
private View curtainView;
private View handleView;
private int curtainViewId;
private int handleViewId;
private int curtainHeight = 0;
private int handleHeight = 0;
private ListView listView = null;
private View curtainHeaderView;
private View handleHeaderView;
private int distanceHandle;
private int distanceScroll;
private float dyHandle;
private int dyScroll;
private boolean isLocked = false;
private boolean isForceMaximized = false;
private boolean isMaximized = false;
private boolean isScrolling = false;
private SCROLL_STATE scrollState = SCROLL_STATE.SCROLL_SLOWLY;
public BaseCurtainListView(Context context) {
this(context, null);
}
public BaseCurtainListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BaseCurtainListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
listView = new ListView(context);
listView.setLayoutParams(
new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
listView.setOnTouchListener(listTouchListener);
listView.setOnScrollListener(scrollListener);
curtainHeaderView = new View(context);
handleHeaderView = new View(context);
listView.addHeaderView(curtainHeaderView);
listView.addHeaderView(handleHeaderView);
initAttrs(attrs);
}
private void initAttrs(AttributeSet attrs) {
TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.CurtainListView);
curtainViewId = ta.getResourceId(R.styleable.CurtainListView_curtain_view_id, R.id.curtain_view);
handleViewId = ta.getResourceId(R.styleable.CurtainListView_handle_view_id, R.id.handle_view);
curtainHeight = ta.getDimensionPixelSize(R.styleable.CurtainListView_curtain_view_height, 0);
handleHeight = ta.getDimensionPixelSize(R.styleable.CurtainListView_handle_view_height, 0);
ta.recycle();
}
@Override
protected void onFinishInflate() {
Log.v(TAG, "onFinishInflate");
super.onFinishInflate();
curtainView = findViewById(curtainViewId);
handleView = findViewById(handleViewId);
if(curtainHeight != 0) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) curtainView.getLayoutParams();
params.height = curtainHeight;
curtainView.setLayoutParams(params);
}
if(handleHeight != 0) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) handleView.getLayoutParams();
params.height = handleHeight;
handleView.setLayoutParams(params);
}
handleView.setOnTouchListener(handleTouchListener);
addView(listView, 0);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.v(TAG, "onMeasure");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if(curtainHeaderView.getHeight() != curtainView.getHeight()) {
AbsListView.LayoutParams params = new AbsListView.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, curtainView.getHeight());
curtainHeaderView.setLayoutParams(params);
}
if(handleHeaderView.getHeight() != handleView.getHeight()) {
AbsListView.LayoutParams params = new AbsListView.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, handleView.getHeight());
handleHeaderView.setLayoutParams(params);
}
curtainView.layout(0, 0, right, curtainView.getHeight());
handleView.layout(0, curtainView.getHeight(), right, curtainView.getHeight() + handleView.getHeight());
}
private void setScrolling() {
isScrolling = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
isScrolling = false;
}
}, TRANSFER_DURATION);
}
private void scrollStateChanged(int newScrollOffset, int oldScrollOffset) {
if (newScrollOffset > oldScrollOffset) {
scrollState = SCROLL_STATE.SCROLL_TO_BOTTOM;
} else {
scrollState = SCROLL_STATE.SCROLL_TO_TOP;
}
}
/**
* Curtain up by scroll
*/
public void minimize() {
isMaximized = false;
isForceMaximized = false;
listView.post(new Runnable() {
@Override
public void run() {
listView.clearFocus();
listView.requestFocusFromTouch();
listView.smoothScrollToPositionFromTop(0, -curtainHeaderView.getHeight());
listView.requestFocus();
}
});
}
/**
* Curtain down by scroll
*/
public void maximize() {
isMaximized = true;
isForceMaximized = false;
listView.post(new Runnable() {
@Override
public void run() {
listView.clearFocus();
listView.requestFocusFromTouch();
listView.smoothScrollToPositionFromTop(0, 0);
listView.requestFocus();
}
});
}
/**
* Curtain up by handle
*/
public void forceMinimize() {
isMaximized = false;
isForceMaximized = false;
ViewPropertyAnimator.animate(curtainView).setDuration(TRANSFER_DURATION).translationY(-curtainHeaderView.getHeight());
ViewPropertyAnimator.animate(handleView).setDuration(TRANSFER_DURATION).translationY(-curtainHeaderView.getHeight());
setScrolling();
}
/**
* Curtain up by handle
*/
public void forceMaximize() {
isMaximized = true;
isForceMaximized = true;
ViewPropertyAnimator.animate(curtainView).setDuration(TRANSFER_DURATION).translationY(0);
ViewPropertyAnimator.animate(handleView).setDuration(TRANSFER_DURATION).translationY(0);
setScrolling();
}
/**
* Lock Curtain Up, Down
*/
public void lockCurtain() {
isLocked = true;
}
/**
* Unlock Curtain Up, Down
*/
public void unlockCurtain() {
isLocked = false;
}
public boolean isMaximized() {
return isMaximized;
}
public boolean isForceMaximized() {
return isForceMaximized;
}
public boolean isScrolling() {
return isScrolling;
}
public boolean isLocked() {
return isLocked;
}
/**
* set CurtainView
*/
public void setCurtainView(View curtainView) {
//TODO update curtainView
}
/**
* set CurtainViewHeight
*/
public void setCurtainViewHeight(int curtainViewHeight) {
}
/**
* set HandleView
*/
public void setHandleView(View handleView) {
//TODO update handleView
}
/**
* set HandleViewHeight
*/
public void setHandleViewHeight(int handleViewHeight) {
}
public void addHeaderView(View header) {
if (header == null) {
}
}
public void addFooterView(View footer) {
if (footer == null) {
}
}
public void setAdapter(BaseAdapter adapter) {
listView.setAdapter(adapter);
}
private void setCurtainTranslationY(float translationY) {
if(curtainView == null) {
return;
}
curtainView.setTranslationY(translationY);
}
private void setHandleTranslationY(float translationY) {
if(handleView == null) {
return;
}
handleView.setTranslationY(translationY);
}
private void setBothTranslationY(float translationY) {
setCurtainTranslationY(translationY);
setHandleTranslationY(translationY);
}
private View.OnTouchListener handleTouchListener = new View.OnTouchListener() {
private float previousRawY = 0f;
private float distance = 0f;
@Override
public boolean onTouch(View v, MotionEvent event) {
if ((isMaximized && !isForceMaximized) || isLocked || isScrolling) {
return false;
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
previousRawY = event.getRawY();
distance = 0f;
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
float newDistance = event.getRawY() - previousRawY;
dyHandle = newDistance - distance;
distance = newDistance;
return isForceMaximized ? moveHandleInMaximized() : moveHandleInMinimized();
}
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
Log.v(TAG, "dyHandle : " + dyHandle);
return isForceMaximized ? actionUpInMaximized() : actionUpInMinimized();
}
return true;
}
private boolean moveHandleInMaximized() {
if(distance > 0) {
return true;
}
int curtainHeaderHeight = curtainHeaderView.getHeight();
if(Math.abs(distance) > curtainHeaderHeight) {
return true;
}
float handleBottom = curtainHeaderView.getHeight() + handleHeaderView.getHeight() + distance;
float handleHeaderBottom = handleHeaderView.getBottom();
if(handleBottom < handleHeaderBottom) {
minimize();
isForceMaximized = false;
return false;
}
setBothTranslationY(distance);
return true;
}
private boolean moveHandleInMinimized() {
if(distance < 0) {
return true;
}
int curtainHeaderHeight = curtainHeaderView.getHeight();
if(distance - curtainHeaderHeight > 0) {
return true;
}
setBothTranslationY(distance - curtainHeaderHeight);
return true;
}
private boolean actionUpInMaximized() {
if(distance > 0) {
forceMaximize();
return true;
}
if(dyHandle < -SCROLL_MIN_VELOCITY) {
if(listView.getFirstVisiblePosition() == 0 && handleHeaderView.getBottom() > handleHeaderView.getHeight()) {
minimize();
}
forceMinimize();
dyHandle = 0;
return true;
}
distance = Math.abs(distance);
int curtainHeaderHeight = curtainHeaderView.getHeight();
if(distance < curtainHeaderHeight / 2) {
forceMaximize();
return true;
}
if(listView.getFirstVisiblePosition() == 0 && handleHeaderView.getBottom() > handleHeaderView.getHeight()) {
minimize();
}
forceMinimize();
return true;
}
private boolean actionUpInMinimized() {
if(distance < 0) {
forceMinimize();
return true;
}
if(dyHandle > SCROLL_MIN_VELOCITY) {
forceMaximize();
dyHandle = 0;
return true;
}
distance = Math.abs(distance);
int curtainHeaderHeight = curtainHeaderView.getHeight();
if(distance < curtainHeaderHeight / 2) {
forceMinimize();
return true;
}
forceMaximize();
return true;
}
};
private AbsListView.OnScrollListener scrollListener = new AbsListView.OnScrollListener() {
private int previousCurtainHeaderTop = 0;
private int previousTopOffset = 0;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(curtainView == null || curtainHeaderView == null) {
Log.v(TAG, "curtainView or curtainHeaderView is null");
return;
}
View topChild = view.getChildAt(0);
int topOffset = 0;
if (topChild == null) {
topOffset = 0;
} else {
topOffset = -topChild.getTop() + view.getFirstVisiblePosition() * topChild.getHeight();
}
if (Math.abs(topOffset - previousTopOffset) >= SCROLL_MIN_VELOCITY) {
scrollStateChanged(topOffset, previousTopOffset);
} else {
scrollState = SCROLL_STATE.SCROLL_SLOWLY;
}
previousTopOffset = topOffset;
if(isLocked || isScrolling) {
return;
}
int curtainHeaderTop = Math.abs(curtainHeaderView.getTop());
dyScroll = curtainHeaderTop - previousCurtainHeaderTop;
previousCurtainHeaderTop = curtainHeaderTop;
if(isForceMaximized) {
if(curtainHeaderTop == 0) {
isForceMaximized = false;
isMaximized = true;
return;
}
if(scrollState.equals(SCROLL_STATE.SCROLL_TO_BOTTOM)) {
forceMinimize();
return;
}
return;
}
if(firstVisibleItem == 0) {
isForceMaximized = false;
isMaximized = true;
setBothTranslationY(- curtainHeaderTop);
return;
}
isMaximized = false;
int curtainHeaderHeight = curtainHeaderView.getHeight();
setBothTranslationY(-curtainHeaderHeight);
}
};
private View.OnTouchListener listTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
if(isLocked || isScrolling) {
return false;
}
if(listView.getFirstVisiblePosition() > 0) {
return false;
}
if(dyScroll < -SCROLL_MIN_VELOCITY) {
Log.v(TAG, "Maximize by velocity");
maximize();
return false;
}
if(dyScroll > SCROLL_MIN_VELOCITY) {
Log.v(TAG, "Minimize by velocity");
minimize();
return false;
}
int curtainHeaderTop = Math.abs(curtainHeaderView.getTop());
int curtainHeaderHeight = curtainHeaderView.getHeight();
if(curtainHeaderTop < curtainHeaderHeight / 2) {
Log.v(TAG, "Maximize");
maximize();
} else {
Log.v(TAG, "Minimize");
minimize();
}
return false;
}
};
}
|
package owltools.gaf.lego;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.semanticweb.elk.owlapi.ElkReasonerFactory;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import owltools.OWLToolsTestBasics;
import owltools.gaf.GafDocument;
import owltools.gaf.GafObjectsBuilder;
import owltools.graph.OWLGraphWrapper;
import owltools.io.ParserWrapper;
import owltools.util.MinimalModelGeneratorTest;
import owltools.vocab.OBOUpperVocabulary;
public class MolecularModelManagerTest extends AbstractLegoModelGeneratorTest {
private static Logger LOG = Logger.getLogger(MolecularModelManagerTest.class);
MolecularModelManager mmm;
static{
Logger.getLogger("org.semanticweb.elk").setLevel(Level.ERROR);
//Logger.getLogger("org.semanticweb.elk.reasoner.indexing.hierarchy").setLevel(Level.ERROR);
}
@Test
public void testM3() throws Exception {
ParserWrapper pw = new ParserWrapper();
//w = new FileWriter(new File("target/lego.out"));
g = pw.parseToOWLGraph(getResourceIRIString("go-mgi-signaling-test.obo"));
g.mergeOntology(pw.parseOBO(getResourceIRIString("disease.obo")));
mmm = new MolecularModelManager(g);
File gafPath = getResource("mgi-signaling.gaf");
mmm.loadGaf("mgi", gafPath);
OWLClass p = g.getOWLClassByIdentifier("GO:0014029"); // neural crest formation
String modelId = mmm.generateModel(p, "mgi");
LOG.info("Model: "+modelId);
LegoModelGenerator model = mmm.getModel(modelId);
Set<OWLNamedIndividual> inds = mmm.getIndividuals(modelId);
LOG.info("Individuals: "+inds.size());
for (OWLNamedIndividual i : inds) {
LOG.info("I="+i);
}
assertTrue(inds.size() == 15);
// GO:0001158 ! enhancer sequence-specific DNA binding
String bindingId = mmm.createActivityIndividual(modelId, g.getOWLClassByIdentifier("GO:0001158"));
LOG.info("New: "+bindingId);
// GO:0005654 ! nucleoplasm
mmm.addOccursIn(modelId, bindingId, "GO:0005654");
mmm.addEnabledBy(modelId, bindingId, "PR:P123456");
// todo - add a test that results in an inconsistency
List<Map> objs = mmm.getIndividualObjects(modelId);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String js = gson.toJson(objs);
LOG.info("INDS:" + js);
LOG.info(mmm.generateDot(modelId));
// LOG.info(mmm.generateImage(modelId)); // problematic due to missing dot application
}
}
|
package ch.openech.client.ewk.event;
import java.util.ArrayList;
import java.util.List;
import ch.openech.client.e44.SecondPersonField;
import ch.openech.dm.common.MunicipalityIdentification;
import ch.openech.dm.person.Person;
import ch.openech.dm.person.Relation;
import ch.openech.mj.db.model.Constants;
import ch.openech.mj.db.model.annotation.Boolean;
import ch.openech.mj.db.model.annotation.Date;
import ch.openech.mj.edit.fields.CheckBoxField;
import ch.openech.mj.edit.form.AbstractFormVisual;
import ch.openech.mj.edit.validation.ValidationMessage;
import ch.openech.mj.edit.value.Required;
import ch.openech.mj.util.BusinessRule;
import ch.openech.mj.util.StringUtils;
import ch.openech.xml.write.EchNamespaceContext;
import ch.openech.xml.write.WriterEch0020;
import ch.openech.xml.write.WriterEch0093;
public abstract class ChangeWithSecondPersonEvent extends
PersonEventEditor<ChangeWithSecondPersonEvent.ChangeWithSecondPersonEventData> {
public ChangeWithSecondPersonEvent(EchNamespaceContext namespaceContext) {
super(namespaceContext);
}
public static class ChangeWithSecondPersonEventData {
public static final ChangeWithSecondPersonEventData DATA = Constants.of(ChangeWithSecondPersonEventData.class);
@Required @Date
public String date;
public String separation;
public String cancelationReason;
@Boolean
public String registerPartner = "0";
public Relation relationPartner;
public boolean registerPartner() {
return "1".equals(registerPartner);
}
}
protected abstract void createSpecificForm(AbstractFormVisual<ChangeWithSecondPersonEventData> formPanel);
@Override
protected void fillForm(AbstractFormVisual<ChangeWithSecondPersonEventData> formPanel) {
createSpecificForm(formPanel);
formPanel.line(ChangeWithSecondPersonEventData.DATA.registerPartner);
formPanel.line(new SecondPersonField(ChangeWithSecondPersonEventData.DATA.relationPartner));
}
@Override
public ChangeWithSecondPersonEventData load() {
ChangeWithSecondPersonEventData data = new ChangeWithSecondPersonEventData();
if (getPerson().getPartner() != null) {
data.relationPartner = getPerson().getPartner();
data.registerPartner = "1";
}
return data;
}
public void validate(ChangeWithSecondPersonEventData data, List<ValidationMessage> validationMessages) {
if (data.registerPartner() && data.relationPartner == null) {
validationMessages.add(new ValidationMessage(ChangeWithSecondPersonEventData.DATA.registerPartner,
"Für Partnereintrag ist vorhandener Partner bei Person erforderlich"));
}
}
@BusinessRule("Neues Zivilstandsereignis darf nicht vor dem gültigen sein")
protected void validateEventNotBeforeDateOfMaritalStatus(ChangeWithSecondPersonEventData data, List<ValidationMessage> validationMessages) {
String date = data.date;
if (getPerson() != null && !StringUtils.isBlank(getPerson().maritalStatus.dateOfMaritalStatus)
&& !StringUtils.isBlank(date)) {
if (date.compareTo(getPerson().maritalStatus.dateOfMaritalStatus) < 0) {
validationMessages.add(new ValidationMessage(ChangeWithSecondPersonEventData.DATA.date,
"Datum darf nicht vor letztem Zivilstandsereignis sein"));
}
}
}
public static class DeathEvent extends ChangeWithSecondPersonEvent {
public DeathEvent(EchNamespaceContext namespaceContext) {
super(namespaceContext);
}
@Override
protected void createSpecificForm(AbstractFormVisual<ChangeWithSecondPersonEventData> formPanel) {
formPanel.line(ChangeWithSecondPersonEventData.DATA.date);
}
@Override
protected List<String> getXml(Person person, ChangeWithSecondPersonEventData data, WriterEch0020 writerEch0020)
throws Exception {
List<String> xmls = new ArrayList<String>();
xmls.add(writerEch0020.death(person.personIdentification, data.date));
if (data.registerPartner()) {
Relation relation = person.getPartner();
if ("1".equals(relation.typeOfRelationship)) {
// Ehe
xmls.add(writerEch0020.maritalStatusPartner(relation.partner, "3", data.date, null));
} else if ("2".equals(relation.typeOfRelationship)) {
// Eingetragene Partnerschaft
xmls.add(writerEch0020.maritalStatusPartner(relation.partner, "7", data.date, "4"));
}
}
return xmls;
}
@Override
public void generateSedexOutput(ChangeWithSecondPersonEventData object) throws Exception {
if (getPerson().isMainResidence() && getPerson().residence.secondary != null) {
for (MunicipalityIdentification secondaryResidence : getPerson().residence.secondary) {
WriterEch0093 sedexWriter = new WriterEch0093(getEchNamespaceContext());
sedexWriter.setRecepientMunicipality(secondaryResidence);
String sedexOutput = sedexWriter.death(getPerson().personIdentification, object.date);
SedexOutputGenerator.generateSedex(sedexOutput, sedexWriter.getEnvelope());
}
}
}
@Override
public void validate(ChangeWithSecondPersonEventData data, List<ValidationMessage> validationMessages) {
super.validate(data, validationMessages);
Person.validateEventNotBeforeBirth(validationMessages, getPerson().personIdentification, data.date, ChangeWithSecondPersonEventData.DATA.date);
}
}
public static class MissingEvent extends ChangeWithSecondPersonEvent {
public MissingEvent(EchNamespaceContext namespaceContext) {
super(namespaceContext);
}
@Override
protected void createSpecificForm(AbstractFormVisual<ChangeWithSecondPersonEventData> formPanel) {
formPanel.line(ChangeWithSecondPersonEventData.DATA.date);
}
@Override
protected List<String> getXml(Person person, ChangeWithSecondPersonEventData data, WriterEch0020 writerEch0020)
throws Exception {
List<String> xmls = new ArrayList<String>();
xmls.add(writerEch0020.missing(person.personIdentification, data.date));
if (data.registerPartner()) {
Relation relation = person.getPartner();
if ("1".equals(relation.typeOfRelationship)) {
// Ehe
xmls.add(writerEch0020.maritalStatusPartner(relation.partner, "3", data.date, null));
} else if ("2".equals(relation.typeOfRelationship)) {
// Eingetragene Partnerschaft
xmls.add(writerEch0020.maritalStatusPartner(relation.partner, "7", data.date, "4"));
}
}
return xmls;
}
@Override
public void validate(ChangeWithSecondPersonEventData data, List<ValidationMessage> validationMessages) {
super.validate(data, validationMessages);
Person.validateEventNotBeforeBirth(validationMessages, getPerson().personIdentification, data.date, ChangeWithSecondPersonEventData.DATA.date);
}
}
public static class SeparationEvent extends ChangeWithSecondPersonEvent {
public SeparationEvent(EchNamespaceContext namespaceContext) {
super(namespaceContext);
}
@Override
protected void createSpecificForm(AbstractFormVisual<ChangeWithSecondPersonEventData> formPanel) {
formPanel.line(Person.PERSON.separation);
formPanel.line(ChangeWithSecondPersonEventData.DATA.date);
}
@Override
public void validate(ChangeWithSecondPersonEventData data, List<ValidationMessage> validationMessages) {
super.validate(data, validationMessages);
validateEventNotBeforeDateOfMaritalStatus(data, validationMessages);
}
@Override
protected List<String> getXml(Person person, ChangeWithSecondPersonEventData data, WriterEch0020 writerEch0020)
throws Exception {
List<String> xmls = new ArrayList<String>();
xmls.add(writerEch0020.separation(person.personIdentification, data.separation, data.date));
if (data.registerPartner()) {
Relation relation = person.getPartner();
xmls.add(writerEch0020.separation(relation.partner, data.separation, data.date));
}
return xmls;
}
}
public static class UndoSeparationEvent extends ChangeWithSecondPersonEvent {
public UndoSeparationEvent(EchNamespaceContext namespaceContext) {
super(namespaceContext);
}
@Override
protected void createSpecificForm(AbstractFormVisual<ChangeWithSecondPersonEventData> formPanel) {
// nothing in it
}
@Override
protected List<String> getXml(Person person, ChangeWithSecondPersonEventData data, WriterEch0020 writerEch0020)
throws Exception {
List<String> xmls = new ArrayList<String>();
xmls.add(writerEch0020.undoSeparation(person.personIdentification));
if (data.registerPartner()) {
Relation relation = person.getPartner();
xmls.add(writerEch0020.undoSeparation(relation.partner));
}
return xmls;
}
}
public static class DivorceEvent extends ChangeWithSecondPersonEvent {
public DivorceEvent(EchNamespaceContext namespaceContext) {
super(namespaceContext);
}
@Override
protected void createSpecificForm(AbstractFormVisual<ChangeWithSecondPersonEventData> formPanel) {
formPanel.line(ChangeWithSecondPersonEventData.DATA.date);
}
@Override
public void validate(ChangeWithSecondPersonEventData data, List<ValidationMessage> validationMessages) {
super.validate(data, validationMessages);
validateEventNotBeforeDateOfMaritalStatus(data, validationMessages);
}
@Override
protected List<String> getXml(Person person, ChangeWithSecondPersonEventData data, WriterEch0020 writerEch0020)
throws Exception {
List<String> xmls = new ArrayList<String>();
xmls.add(writerEch0020.divorce(person.personIdentification, data.date));
if (data.registerPartner()) {
Relation relation = person.getPartner();
xmls.add(writerEch0020.divorce(relation.partner, data.date));
}
return xmls;
}
}
public static class UndoPartnershipEvent extends ChangeWithSecondPersonEvent {
public UndoPartnershipEvent(EchNamespaceContext namespaceContext) {
super(namespaceContext);
}
@Override
protected void createSpecificForm(AbstractFormVisual<ChangeWithSecondPersonEventData> formPanel) {
formPanel.line(ChangeWithSecondPersonEventData.DATA.date);
formPanel.line(ChangeWithSecondPersonEventData.DATA.cancelationReason);
}
@Override
public void validate(ChangeWithSecondPersonEventData data, List<ValidationMessage> validationMessages) {
super.validate(data, validationMessages);
validateEventNotBeforeDateOfMaritalStatus(data, validationMessages);
}
@Override
protected List<String> getXml(Person person, ChangeWithSecondPersonEventData data, WriterEch0020 writerEch0020)
throws Exception {
List<String> xmls = new ArrayList<String>();
xmls.add(writerEch0020.undoPartnership(person.personIdentification, data.date, data.cancelationReason));
if (data.registerPartner()) {
Relation relation = person.getPartner();
xmls.add(writerEch0020.undoPartnership(relation.partner, data.date, data.cancelationReason));
}
return xmls;
}
}
public static class UndoMarriageEvent extends ChangeWithSecondPersonEvent {
public UndoMarriageEvent(EchNamespaceContext namespaceContext) {
super(namespaceContext);
}
@Override
protected void createSpecificForm(AbstractFormVisual<ChangeWithSecondPersonEventData> formPanel) {
formPanel.line(ChangeWithSecondPersonEventData.DATA.date);
}
@Override
public void validate(ChangeWithSecondPersonEventData data, List<ValidationMessage> validationMessages) {
super.validate(data, validationMessages);
validateEventNotBeforeDateOfMaritalStatus(data, validationMessages);
}
@Override
protected List<String> getXml(Person person, ChangeWithSecondPersonEventData data, WriterEch0020 writerEch0020)
throws Exception {
List<String> xmls = new ArrayList<String>();
xmls.add(writerEch0020.undoMarriage(person.personIdentification, data.date));
if (data.registerPartner()) {
Relation relation = person.getPartner();
xmls.add(writerEch0020.undoMarriage(relation.partner, data.date));
}
return xmls;
}
}
}
|
package git4idea.checkin;
import com.intellij.CommonBundle;
import com.intellij.diff.util.Side;
import com.intellij.dvcs.AmendComponent;
import com.intellij.dvcs.DvcsUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.CheckinProjectPanel;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.ui.SelectFilePathsDialog;
import com.intellij.openapi.vcs.checkin.CheckinChangeListSpecificComponent;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker;
import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker.PartialCommitHelper;
import com.intellij.openapi.vcs.impl.LineStatusTrackerManager;
import com.intellij.openapi.vcs.impl.PartialChangesUtil;
import com.intellij.openapi.vcs.ui.RefreshableOnComponent;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.GuiUtils;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.FunctionUtil;
import com.intellij.util.NullableFunction;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PairConsumer;
import com.intellij.util.concurrency.FutureResult;
import com.intellij.util.textCompletion.DefaultTextCompletionValueDescriptor;
import com.intellij.util.textCompletion.TextCompletionProvider;
import com.intellij.util.textCompletion.TextFieldWithCompletion;
import com.intellij.util.textCompletion.ValuesCompletionProvider.ValuesCompletionProviderDumbAware;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.JBUI;
import com.intellij.vcs.log.VcsUser;
import com.intellij.vcs.log.VcsUserRegistry;
import com.intellij.vcs.log.util.VcsUserUtil;
import com.intellij.vcsUtil.VcsFileUtil;
import com.intellij.vcsUtil.VcsUtil;
import git4idea.GitUserRegistry;
import git4idea.branch.GitBranchUtil;
import git4idea.changes.GitChangeUtils;
import git4idea.commands.Git;
import git4idea.commands.GitCommand;
import git4idea.commands.GitLineHandler;
import git4idea.config.GitConfigUtil;
import git4idea.config.GitVcsSettings;
import git4idea.config.GitVersionSpecialty;
import git4idea.i18n.GitBundle;
import git4idea.index.GitIndexUtil;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import git4idea.util.GitFileUtils;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static com.intellij.dvcs.DvcsUtil.getShortRepositoryName;
import static com.intellij.openapi.ui.DialogWrapper.BALLOON_WARNING_BACKGROUND;
import static com.intellij.openapi.ui.DialogWrapper.BALLOON_WARNING_BORDER;
import static com.intellij.openapi.util.text.StringUtil.escapeXml;
import static com.intellij.openapi.vcs.changes.ChangesUtil.getAfterPath;
import static com.intellij.openapi.vcs.changes.ChangesUtil.getBeforePath;
import static com.intellij.util.containers.ContainerUtil.*;
import static com.intellij.vcs.log.util.VcsUserUtil.isSamePerson;
import static git4idea.GitUtil.*;
import static java.util.Arrays.asList;
import static one.util.streamex.StreamEx.of;
public class GitCheckinEnvironment implements CheckinEnvironment {
private static final Logger LOG = Logger.getInstance(GitCheckinEnvironment.class);
@NonNls private static final String GIT_COMMIT_MSG_FILE_PREFIX = "git-commit-msg-"; // the file name prefix for commit message file
@NonNls private static final String GIT_COMMIT_MSG_FILE_EXT = ".txt"; // the file extension for commit message file
private final Project myProject;
public static final SimpleDateFormat COMMIT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final VcsDirtyScopeManager myDirtyScopeManager;
private final GitVcsSettings mySettings;
private String myNextCommitAuthor = null; // The author for the next commit
private boolean myNextCommitAmend; // If true, the next commit is amended
private Boolean myNextCommitIsPushed = null; // The push option of the next commit
private Date myNextCommitAuthorDate;
private boolean myNextCommitSignOff;
private boolean myNextCommitSkipHook;
public GitCheckinEnvironment(@NotNull Project project,
@NotNull final VcsDirtyScopeManager dirtyScopeManager,
final GitVcsSettings settings) {
myProject = project;
myDirtyScopeManager = dirtyScopeManager;
mySettings = settings;
}
public boolean keepChangeListAfterCommit(ChangeList changeList) {
return false;
}
@Override
public boolean isRefreshAfterCommitNeeded() {
return true;
}
@Nullable
public RefreshableOnComponent createAdditionalOptionsPanel(CheckinProjectPanel panel,
PairConsumer<Object, Object> additionalDataConsumer) {
return new GitCheckinOptions(myProject, panel);
}
@Nullable
public String getDefaultMessageFor(FilePath[] filesToCheckin) {
LinkedHashSet<String> messages = newLinkedHashSet();
GitRepositoryManager manager = getRepositoryManager(myProject);
for (VirtualFile root : gitRoots(asList(filesToCheckin))) {
GitRepository repository = manager.getRepositoryForRoot(root);
if (repository == null) { // unregistered nested submodule found by GitUtil.getGitRoot
LOG.warn("Unregistered repository: " + root);
continue;
}
File mergeMsg = repository.getRepositoryFiles().getMergeMessageFile();
File squashMsg = repository.getRepositoryFiles().getSquashMessageFile();
try {
if (!mergeMsg.exists() && !squashMsg.exists()) {
continue;
}
String encoding = GitConfigUtil.getCommitEncoding(myProject, root);
if (mergeMsg.exists()) {
messages.add(loadMessage(mergeMsg, encoding));
}
else {
messages.add(loadMessage(squashMsg, encoding));
}
}
catch (IOException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Unable to load merge message", e);
}
}
}
return DvcsUtil.joinMessagesOrNull(messages);
}
private static String loadMessage(@NotNull File messageFile, @NotNull String encoding) throws IOException {
return FileUtil.loadFile(messageFile, encoding);
}
public String getHelpId() {
return null;
}
public String getCheckinOperationName() {
return GitBundle.getString("commit.action.name");
}
public List<VcsException> commit(@NotNull List<Change> changes,
@NotNull String message,
@NotNull NullableFunction<Object, Object> parametersHolder, Set<String> feedback) {
GitRepositoryManager manager = getRepositoryManager(myProject);
List<VcsException> exceptions = new ArrayList<>();
Map<VirtualFile, Collection<Change>> sortedChanges = sortChangesByGitRoot(changes, exceptions);
LOG.assertTrue(!sortedChanges.isEmpty(), "Trying to commit an empty list of changes: " + changes);
List<GitRepository> repositories = manager.sortByDependency(getRepositoriesFromRoots(manager, sortedChanges.keySet()));
for (GitRepository repository : repositories) {
Collection<Change> rootChanges = sortedChanges.get(repository.getRoot());
exceptions.addAll(commitRepository(repository, rootChanges, message));
}
if (myNextCommitIsPushed != null && myNextCommitIsPushed.booleanValue() && exceptions.isEmpty()) {
ModalityState modality = ModalityState.defaultModalityState();
TransactionGuard.getInstance().assertWriteSafeContext(modality);
List<GitRepository> preselectedRepositories = newArrayList(repositories);
GuiUtils.invokeLaterIfNeeded(
() -> new GitPushAfterCommitDialog(myProject, preselectedRepositories,
GitBranchUtil.getCurrentRepository(myProject)).showOrPush(),
modality, myProject.getDisposed());
}
return exceptions;
}
@NotNull
private List<VcsException> commitRepository(@NotNull GitRepository repository,
@NotNull Collection<Change> rootChanges,
@NotNull String message) {
List<VcsException> exceptions = new ArrayList<>();
VirtualFile root = repository.getRoot();
File messageFile;
try {
messageFile = createCommitMessageFile(myProject, root, message);
}
catch (IOException ex) {
return Collections.singletonList(new VcsException("Creation of commit message file failed", ex));
}
try {
// Stage partial changes
Pair<Runnable, List<Change>> partialAddResult = addPartialChangesToIndex(repository, rootChanges);
Runnable callback = partialAddResult.first;
Set<Change> partialChanges = newHashSet(partialAddResult.second);
Set<FilePath> added = new HashSet<>();
Set<FilePath> removed = new HashSet<>();
final Set<Change> caseOnlyRenames = new HashSet<>();
for (Change change : rootChanges) {
if (partialChanges.contains(change)) continue;
switch (change.getType()) {
case NEW:
case MODIFICATION:
added.add(change.getAfterRevision().getFile());
break;
case DELETED:
removed.add(change.getBeforeRevision().getFile());
break;
case MOVED:
FilePath afterPath = change.getAfterRevision().getFile();
FilePath beforePath = change.getBeforeRevision().getFile();
if (!SystemInfo.isFileSystemCaseSensitive && isCaseOnlyChange(beforePath.getPath(), afterPath.getPath())) {
caseOnlyRenames.add(change);
}
else {
added.add(afterPath);
removed.add(beforePath);
}
break;
default:
throw new IllegalStateException("Unknown change type: " + change.getType());
}
}
if (!caseOnlyRenames.isEmpty() || !partialChanges.isEmpty()) {
List<VcsException> exs = commitUsingIndex(myProject, root, caseOnlyRenames, partialChanges, added, removed, messageFile);
exceptions.addAll(exs);
if (exceptions.isEmpty()) {
callback.run();
}
}
else {
try {
Set<FilePath> files = new HashSet<>();
files.addAll(added);
files.addAll(removed);
commit(myProject, root, files, messageFile);
}
catch (VcsException ex) {
PartialOperation partialOperation = isMergeCommit(ex);
if (partialOperation == PartialOperation.NONE) {
throw ex;
}
if (!mergeCommit(myProject, root, added, removed, messageFile, exceptions, partialOperation)) {
throw ex;
}
}
}
getRepositoryManager(myProject).updateRepository(root);
}
catch (VcsException e) {
exceptions.add(e);
}
finally {
if (!messageFile.delete()) {
LOG.warn("Failed to remove temporary file: " + messageFile);
}
}
return exceptions;
}
@NotNull
private List<VcsException> commitUsingIndex(@NotNull Project project,
@NotNull VirtualFile root,
@NotNull Set<Change> caseOnlyRenames,
@NotNull Set<Change> partialChanges,
@NotNull Set<FilePath> added,
@NotNull Set<FilePath> removed,
@NotNull File messageFile) {
List<VcsException> exceptions = new ArrayList<>();
try {
String rootPath = root.getPath();
LOG.info("Committing case only rename: " + getLogString(rootPath, caseOnlyRenames) + " in " + getShortRepositoryName(project, root));
// 1. Check what is staged besides case-only renames
Collection<Change> stagedChanges;
try {
stagedChanges = GitChangeUtils.getStagedChanges(project, root);
LOG.debug("Found staged changes: " + getLogString(rootPath, stagedChanges));
}
catch (VcsException e) {
return Collections.singletonList(e);
}
// 2. Reset staged changes which are not selected for commit
Collection<Change> excludedStagedChanges = filter(stagedChanges, change -> !caseOnlyRenames.contains(change) &&
!partialChanges.contains(change) &&
!added.contains(getAfterPath(change)) &&
!removed.contains(getBeforePath(change)));
if (!excludedStagedChanges.isEmpty()) {
LOG.info("Staged changes excluded for commit: " + getLogString(rootPath, excludedStagedChanges));
reset(project, root, excludedStagedChanges);
}
try {
// 3. Stage what else is needed to commit
List<FilePath> newPathsOfCaseRenames = map(caseOnlyRenames, ChangesUtil::getAfterPath);
LOG.debug("Updating index for added:" + added + "\n, removed: " + removed + "\n, and case-renames: " + newPathsOfCaseRenames);
Set<FilePath> toAdd = new HashSet<>(added);
toAdd.addAll(newPathsOfCaseRenames);
updateIndex(project, root, toAdd, removed, exceptions);
if (!exceptions.isEmpty()) return exceptions;
// 4. Commit the staging area
LOG.debug("Performing commit...");
commitWithoutPaths(project, root, messageFile);
}
finally {
// 5. Stage back the changes unstaged before commit
if (!excludedStagedChanges.isEmpty()) {
LOG.debug("Restoring changes which were unstaged before commit: " + getLogString(rootPath, excludedStagedChanges));
Set<FilePath> toAdd = map2SetNotNull(excludedStagedChanges, ChangesUtil::getAfterPath);
Condition<Change> isMovedOrDeleted = change -> change.getType() == Change.Type.MOVED || change.getType() == Change.Type.DELETED;
Set<FilePath> toRemove = map2SetNotNull(filter(excludedStagedChanges, isMovedOrDeleted), ChangesUtil::getBeforePath);
updateIndex(project, root, toAdd, toRemove, exceptions);
}
}
}
catch (VcsException e) {
exceptions.add(e);
}
return exceptions;
}
@NotNull
private Pair<Runnable, List<Change>> addPartialChangesToIndex(@NotNull GitRepository repository,
@NotNull Collection<Change> changes) throws VcsException {
Set<String> changelistIds = map2SetNotNull(changes, change -> {
return change instanceof ChangeListChange ? ((ChangeListChange)change).getChangeListId() : null;
});
if (changelistIds.isEmpty()) return Pair.create(EmptyRunnable.INSTANCE, emptyList());
if (changelistIds.size() != 1) throw new VcsException("Can't commit changes from multiple changelists at once");
String changelistId = changelistIds.iterator().next();
Pair<List<PartialCommitHelper>, List<Change>> result = computeAfterLSTManagerUpdate(repository.getProject(), () -> {
List<PartialCommitHelper> helpers = new ArrayList<>();
List<Change> partialChanges = new ArrayList<>();
for (Change change : changes) {
if (change instanceof ChangeListChange) {
PartialLocalLineStatusTracker tracker = PartialChangesUtil.getPartialTracker(myProject, change);
if (tracker == null) continue;
if (!tracker.isOperational()) {
LOG.warn("Tracker is not operational for " + tracker.getVirtualFile().getPresentableUrl());
return null; // commit failure
}
if (tracker.hasPartialChangesToCommit()) {
helpers.add(tracker.handlePartialCommit(Side.LEFT, Collections.singletonList(changelistId)));
partialChanges.add(change);
}
}
}
return Pair.create(helpers, partialChanges);
});
if (result == null) throw new VcsException("Can't collect partial changes to commit");
List<PartialCommitHelper> helpers = result.first;
List<Change> partialChanges = result.second;
List<FilePath> pathsToDelete = new ArrayList<>();
for (Change change : partialChanges) {
if (change.getType() == Change.Type.MOVED) {
ContentRevision beforeRevision = ObjectUtils.assertNotNull(change.getBeforeRevision());
pathsToDelete.add(beforeRevision.getFile());
}
}
GitFileUtils.delete(myProject, repository.getRoot(), pathsToDelete, "--ignore-unmatch");
for (int i = 0; i < partialChanges.size(); i++) {
Change change = partialChanges.get(i);
CurrentContentRevision revision = (CurrentContentRevision)change.getAfterRevision();
assert revision != null;
FilePath path = revision.getFile();
PartialCommitHelper helper = helpers.get(i);
VirtualFile file = revision.getVirtualFile();
if (file == null) throw new VcsException("Can't find file: " + path.getPath());
GitIndexUtil.StagedFile stagedFile = getStagedFile(repository, change);
boolean isExecutable = stagedFile != null && stagedFile.isExecutable();
Pair.NonNull<Charset, byte[]> fileContent =
LoadTextUtil.charsetForWriting(repository.getProject(), file, helper.getContent(), file.getCharset());
GitIndexUtil.write(repository, path, fileContent.second, isExecutable);
}
Runnable callback = () -> ApplicationManager.getApplication().invokeLater(() -> {
for (PartialCommitHelper helper : helpers) {
try {
helper.applyChanges();
}
catch (Throwable e) {
LOG.error(e);
}
}
});
return Pair.create(callback, partialChanges);
}
@Nullable
private static GitIndexUtil.StagedFile getStagedFile(@NotNull GitRepository repository, @NotNull Change change) throws VcsException {
FilePath bPath = getBeforePath(change);
if (bPath != null) {
GitIndexUtil.StagedFile file = GitIndexUtil.list(repository, bPath);
if (file != null) return file;
}
FilePath aPath = getAfterPath(change);
if (aPath != null) {
GitIndexUtil.StagedFile file = GitIndexUtil.list(repository, aPath);
if (file != null) return file;
}
return null;
}
@Nullable
private static <T> T computeAfterLSTManagerUpdate(@NotNull Project project, @NotNull final Computable<T> computation) {
assert !ApplicationManager.getApplication().isDispatchThread();
FutureResult<T> ref = new FutureResult<>();
LineStatusTrackerManager.getInstance(project).invokeAfterUpdate(() -> {
try {
ref.set(computation.compute());
}
catch (Throwable e) {
ref.setException(e);
}
});
try {
return ref.get();
}
catch (InterruptedException | ExecutionException e) {
return null;
}
}
private static void reset(@NotNull Project project, @NotNull VirtualFile root, @NotNull Collection<Change> changes) throws VcsException {
Set<FilePath> allPaths = new HashSet<>();
allPaths.addAll(mapNotNull(changes, ChangesUtil::getAfterPath));
allPaths.addAll(mapNotNull(changes, ChangesUtil::getBeforePath));
for (List<String> paths : VcsFileUtil.chunkPaths(root, allPaths)) {
GitLineHandler handler = new GitLineHandler(project, root, GitCommand.RESET);
handler.endOptions();
handler.addParameters(paths);
Git.getInstance().runCommand(handler).getOutputOrThrow();
}
}
public List<VcsException> commit(List<Change> changes, String preparedComment) {
return commit(changes, preparedComment, FunctionUtil.nullConstant(), null);
}
/**
* Preform a merge commit
*
* @param project a project
* @param root a vcs root
* @param added added files
* @param removed removed files
* @param messageFile a message file for commit
* @param author an author
* @param exceptions the list of exceptions to report
* @param partialOperation
* @return true if merge commit was successful
*/
private boolean mergeCommit(final Project project,
final VirtualFile root,
final Set<FilePath> added,
final Set<FilePath> removed,
final File messageFile,
List<VcsException> exceptions,
@NotNull final PartialOperation partialOperation) {
HashSet<FilePath> realAdded = new HashSet<>();
HashSet<FilePath> realRemoved = new HashSet<>();
// perform diff
GitLineHandler diff = new GitLineHandler(project, root, GitCommand.DIFF);
diff.setSilent(true);
diff.setStdoutSuppressed(true);
diff.addParameters("--diff-filter=ADMRUX", "--name-status", "--no-renames", "HEAD");
diff.endOptions();
String output;
try {
output = Git.getInstance().runCommand(diff).getOutputOrThrow();
}
catch (VcsException ex) {
exceptions.add(ex);
return false;
}
String rootPath = root.getPath();
for (StringTokenizer lines = new StringTokenizer(output, "\n", false); lines.hasMoreTokens(); ) {
String line = lines.nextToken().trim();
if (line.length() == 0) {
continue;
}
String[] tk = line.split("\t");
switch (tk[0].charAt(0)) {
case 'M':
case 'A':
realAdded.add(VcsUtil.getFilePath(rootPath + "/" + tk[1]));
break;
case 'D':
realRemoved.add(VcsUtil.getFilePath(rootPath + "/" + tk[1], false));
break;
default:
throw new IllegalStateException("Unexpected status: " + line);
}
}
realAdded.removeAll(added);
realRemoved.removeAll(removed);
if (realAdded.size() != 0 || realRemoved.size() != 0) {
final List<FilePath> files = new ArrayList<>();
files.addAll(realAdded);
files.addAll(realRemoved);
Ref<Boolean> mergeAll = new Ref<>();
try {
ApplicationManager.getApplication().invokeAndWait(() -> {
String message = GitBundle.message("commit.partial.merge.message", partialOperation.getName());
SelectFilePathsDialog dialog = new SelectFilePathsDialog(project, files, message,
null, "Commit All Files", CommonBundle.getCancelButtonText(), false);
dialog.setTitle(GitBundle.getString("commit.partial.merge.title"));
dialog.show();
mergeAll.set(dialog.isOK());
});
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new RuntimeException("Unable to invoke a message box on AWT thread", ex);
}
if (!mergeAll.get()) {
return false;
}
// update non-indexed files
if (!updateIndex(project, root, realAdded, realRemoved, exceptions)) {
return false;
}
for (FilePath f : realAdded) {
VcsDirtyScopeManager.getInstance(project).fileDirty(f);
}
for (FilePath f : realRemoved) {
VcsDirtyScopeManager.getInstance(project).fileDirty(f);
}
}
// perform merge commit
try {
commitWithoutPaths(project, root, messageFile);
}
catch (VcsException ex) {
exceptions.add(ex);
return false;
}
return true;
}
private void commitWithoutPaths(@NotNull Project project,
@NotNull VirtualFile root,
@NotNull File messageFile) throws VcsException {
GitLineHandler handler = new GitLineHandler(project, root, GitCommand.COMMIT);
handler.setStdoutSuppressed(false);
handler.addParameters("-F", messageFile.getAbsolutePath());
if (myNextCommitAmend) {
handler.addParameters("--amend");
}
if (myNextCommitAuthor != null) {
handler.addParameters("--author=" + myNextCommitAuthor);
}
if (myNextCommitAuthorDate != null) {
handler.addParameters("--date", COMMIT_DATE_FORMAT.format(myNextCommitAuthorDate));
}
if (myNextCommitSignOff) {
handler.addParameters("--signoff");
}
if (myNextCommitSkipHook) {
handler.addParameters("--no-verify");
}
handler.endOptions();
Git.getInstance().runCommand(handler).getOutputOrThrow();
}
/**
* Check if commit has failed due to unfinished merge or cherry-pick.
*
* @param ex an exception to examine
* @return true if exception means that there is a partial commit during merge
*/
private static PartialOperation isMergeCommit(final VcsException ex) {
String message = ex.getMessage();
if (message.contains("cannot do a partial commit during a merge")) {
return PartialOperation.MERGE;
}
if (message.contains("cannot do a partial commit during a cherry-pick")) {
return PartialOperation.CHERRY_PICK;
}
return PartialOperation.NONE;
}
/**
* Update index (delete and remove files)
*
* @param project the project
* @param root a vcs root
* @param added added/modified files to commit
* @param removed removed files to commit
* @param exceptions a list of exceptions to update
* @return true if index was updated successfully
*/
private static boolean updateIndex(final Project project,
final VirtualFile root,
final Collection<FilePath> added,
final Collection<FilePath> removed,
final List<VcsException> exceptions) {
try {
List<FilePath> files = new ArrayList<>();
files.addAll(added);
files.addAll(removed);
GitFileUtils.addPaths(project, root, files);
return true;
}
catch (VcsException ex) {
exceptions.add(ex);
return false;
}
}
/**
* Create a file that contains the specified message
*
* @param root a git repository root
* @param message a message to write
* @return a file reference
* @throws IOException if file cannot be created
*/
@NotNull
public static File createCommitMessageFile(@NotNull Project project, @NotNull VirtualFile root, final String message) throws IOException {
// filter comment lines
File file = FileUtil.createTempFile(GIT_COMMIT_MSG_FILE_PREFIX, GIT_COMMIT_MSG_FILE_EXT);
file.deleteOnExit();
@NonNls String encoding = GitConfigUtil.getCommitEncoding(project, root);
Writer out = new OutputStreamWriter(new FileOutputStream(file), encoding);
try {
out.write(message);
}
finally {
out.close();
}
return file;
}
public List<VcsException> scheduleMissingFileForDeletion(List<FilePath> files) {
ArrayList<VcsException> rc = new ArrayList<>();
Map<VirtualFile, List<FilePath>> sortedFiles;
try {
sortedFiles = sortFilePathsByGitRoot(files);
}
catch (VcsException e) {
rc.add(e);
return rc;
}
for (Map.Entry<VirtualFile, List<FilePath>> e : sortedFiles.entrySet()) {
try {
final VirtualFile root = e.getKey();
GitFileUtils.delete(myProject, root, e.getValue());
markRootDirty(root);
}
catch (VcsException ex) {
rc.add(ex);
}
}
return rc;
}
private void commit(@NotNull Project project, @NotNull VirtualFile root, @NotNull Collection<FilePath> files, @NotNull File message)
throws VcsException {
boolean amend = myNextCommitAmend;
for (List<String> paths : VcsFileUtil.chunkPaths(root, files)) {
GitLineHandler handler = new GitLineHandler(project, root, GitCommand.COMMIT);
handler.setStdoutSuppressed(false);
if (myNextCommitSignOff) {
handler.addParameters("--signoff");
}
if (amend) {
handler.addParameters("--amend");
}
else {
amend = true;
}
if (myNextCommitSkipHook) {
handler.addParameters("--no-verify");
}
handler.addParameters("--only", "-F", message.getAbsolutePath());
if (myNextCommitAuthor != null) {
handler.addParameters("--author=" + myNextCommitAuthor);
}
if (myNextCommitAuthorDate != null) {
handler.addParameters("--date", COMMIT_DATE_FORMAT.format(myNextCommitAuthorDate));
}
handler.endOptions();
handler.addParameters(paths);
Git.getInstance().runCommand(handler).getOutputOrThrow();
}
}
public List<VcsException> scheduleUnversionedFilesForAddition(List<VirtualFile> files) {
ArrayList<VcsException> rc = new ArrayList<>();
Map<VirtualFile, List<VirtualFile>> sortedFiles;
try {
sortedFiles = sortFilesByGitRoot(files);
}
catch (VcsException e) {
rc.add(e);
return rc;
}
for (Map.Entry<VirtualFile, List<VirtualFile>> e : sortedFiles.entrySet()) {
try {
final VirtualFile root = e.getKey();
GitFileUtils.addFiles(myProject, root, e.getValue());
markRootDirty(root);
}
catch (VcsException ex) {
rc.add(ex);
}
}
return rc;
}
private enum PartialOperation {
NONE("none"),
MERGE("merge"),
CHERRY_PICK("cherry-pick");
private final String myName;
PartialOperation(String name) {
myName = name;
}
String getName() {
return myName;
}
}
private static Map<VirtualFile, Collection<Change>> sortChangesByGitRoot(@NotNull List<Change> changes, List<VcsException> exceptions) {
Map<VirtualFile, Collection<Change>> result = new HashMap<>();
for (Change change : changes) {
final ContentRevision afterRevision = change.getAfterRevision();
final ContentRevision beforeRevision = change.getBeforeRevision();
// nothing-to-nothing change cannot happen.
assert beforeRevision != null || afterRevision != null;
// note that any path will work, because changes could happen within single vcs root
final FilePath filePath = afterRevision != null ? afterRevision.getFile() : beforeRevision.getFile();
final VirtualFile vcsRoot;
try {
// the parent paths for calculating roots in order to account for submodules that contribute
// to the parent change. The path "." is never is valid change, so there should be no problem
// with it.
vcsRoot = getGitRoot(filePath.getParentPath());
}
catch (VcsException e) {
exceptions.add(e);
continue;
}
Collection<Change> changeList = result.get(vcsRoot);
if (changeList == null) {
changeList = new ArrayList<>();
result.put(vcsRoot, changeList);
}
changeList.add(change);
}
return result;
}
private void markRootDirty(final VirtualFile root) {
// Note that the root is invalidated because changes are detected per-root anyway.
// Otherwise it is not possible to detect moves.
myDirtyScopeManager.dirDirtyRecursively(root);
}
public void reset() {
myNextCommitAmend = false;
myNextCommitAuthor = null;
myNextCommitIsPushed = null;
myNextCommitAuthorDate = null;
myNextCommitSkipHook = false;
}
public class GitCheckinOptions implements CheckinChangeListSpecificComponent, RefreshableOnComponent {
@NotNull private final CheckinProjectPanel myCheckinProjectPanel;
@NotNull private final JPanel myPanel;
@NotNull private final EditorTextField myAuthorField;
@Nullable private Date myAuthorDate;
@NotNull private final AmendComponent myAmendComponent;
@NotNull private final JCheckBox mySignOffCheckbox;
@NotNull private final BalloonBuilder myAuthorNotificationBuilder;
@Nullable private Balloon myAuthorBalloon;
GitCheckinOptions(@NotNull Project project, @NotNull CheckinProjectPanel panel) {
myCheckinProjectPanel = panel;
myAuthorField = createTextField(project, getAuthors(project));
myAuthorField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
clearAuthorWarn();
}
});
myAuthorNotificationBuilder = JBPopupFactory.getInstance().
createBalloonBuilder(new JLabel(GitBundle.getString("commit.author.diffs"))).
setBorderInsets(UIManager.getInsets("Balloon.error.textInsets")).
setBorderColor(BALLOON_WARNING_BORDER).
setFillColor(BALLOON_WARNING_BACKGROUND).
setHideOnClickOutside(true).
setHideOnFrameResize(false);
myAuthorField.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && myAuthorField.isShowing()) {
if (!StringUtil.isEmptyOrSpaces(myAuthorField.getText())) {
showAuthorBalloonNotification();
myAuthorField.removeHierarchyListener(this);
}
}
}
});
JLabel authorLabel = new JBLabel(GitBundle.message("commit.author"));
authorLabel.setLabelFor(myAuthorField);
myAmendComponent = new MyAmendComponent(project, getRepositoryManager(project), panel);
mySignOffCheckbox = new JBCheckBox("Sign-off commit", mySettings.shouldSignOffCommit());
mySignOffCheckbox.setMnemonic(KeyEvent.VK_G);
mySignOffCheckbox.setToolTipText(getToolTip(project, panel));
GridBag gb = new GridBag().
setDefaultAnchor(GridBagConstraints.WEST).
setDefaultInsets(JBUI.insets(2));
myPanel = new JPanel(new GridBagLayout());
myPanel.add(authorLabel, gb.nextLine().next());
myPanel.add(myAuthorField, gb.next().fillCellHorizontally().weightx(1));
myPanel.add(myAmendComponent.getComponent(), gb.nextLine().next().coverLine());
myPanel.add(mySignOffCheckbox, gb.nextLine().next().coverLine());
}
public boolean isAmend() {
return myAmendComponent.isAmend();
}
@NotNull
private String getToolTip(@NotNull Project project, @NotNull CheckinProjectPanel panel) {
VcsUser user = getFirstItem(mapNotNull(panel.getRoots(), it -> GitUserRegistry.getInstance(project).getUser(it)));
String signature = user != null ? escapeXml(VcsUserUtil.toExactString(user)) : "";
return "<html>Adds the following line at the end of the commit message:<br/>" +
"Signed-off by: " + signature + "</html>";
}
@CalledInAwt
private void showAuthorBalloonNotification() {
if (myAuthorBalloon == null || myAuthorBalloon.isDisposed()) {
myAuthorBalloon = myAuthorNotificationBuilder.createBalloon();
myAuthorBalloon.show(new RelativePoint(myAuthorField, new Point(myAuthorField.getWidth() / 2, myAuthorField.getHeight())),
Balloon.Position.below);
}
}
@NotNull
private List<String> getAuthors(@NotNull Project project) {
Set<String> authors = new HashSet<>(getUsersList(project));
addAll(authors, mySettings.getCommitAuthors());
List<String> list = new ArrayList<>(authors);
Collections.sort(list);
return list;
}
@NotNull
private EditorTextField createTextField(@NotNull Project project, @NotNull List<String> list) {
TextCompletionProvider completionProvider =
new ValuesCompletionProviderDumbAware<>(new DefaultTextCompletionValueDescriptor.StringValueDescriptor(), list);
return new TextFieldWithCompletion(project, completionProvider, "", true, true, true);
}
private class MyAmendComponent extends AmendComponent {
public MyAmendComponent(@NotNull Project project, @NotNull GitRepositoryManager manager, @NotNull CheckinProjectPanel panel) {
super(project, manager, panel);
}
@NotNull
@Override
protected Set<VirtualFile> getVcsRoots(@NotNull Collection<FilePath> files) {
return gitRoots(files);
}
@Nullable
@Override
protected String getLastCommitMessage(@NotNull VirtualFile root) throws VcsException {
GitLineHandler h = new GitLineHandler(myProject, root, GitCommand.LOG);
h.addParameters("--max-count=1");
h.addParameters("--encoding=UTF-8");
String formatPattern;
if (GitVersionSpecialty.STARTED_USING_RAW_BODY_IN_FORMAT.existsIn(myProject)) {
formatPattern = "%B";
}
else {
// only message: subject + body; "%-b" means that preceding line-feeds will be deleted if the body is empty
// %s strips newlines from subject; there is no way to work around it before 1.7.2 with %B (unless parsing some fixed format)
formatPattern = "%s%n%n%-b";
}
h.addParameters("--pretty=format:" + formatPattern);
return Git.getInstance().runCommand(h).getOutputOrThrow();
}
}
@NotNull
private List<String> getUsersList(@NotNull Project project) {
VcsUserRegistry userRegistry = ServiceManager.getService(project, VcsUserRegistry.class);
return map(userRegistry.getUsers(), VcsUserUtil::toExactString);
}
@Override
public void refresh() {
myAmendComponent.refresh();
myAuthorField.setText(null);
clearAuthorWarn();
myAuthorDate = null;
reset();
}
@Override
public void saveState() {
String author = myAuthorField.getText();
if (StringUtil.isEmptyOrSpaces(author)) {
myNextCommitAuthor = null;
}
else {
myNextCommitAuthor = GitCommitAuthorCorrector.correct(author);
mySettings.saveCommitAuthor(myNextCommitAuthor);
}
myNextCommitAmend = isAmend();
myNextCommitAuthorDate = myAuthorDate;
mySettings.setSignOffCommit(mySignOffCheckbox.isSelected());
myNextCommitSignOff = mySignOffCheckbox.isSelected();
}
@Override
public void restoreState() {
refresh();
}
@Override
public void onChangeListSelected(LocalChangeList list) {
Object data = list.getData();
clearAuthorWarn();
if (data instanceof ChangeListData) {
fillAuthorAndDateFromData((ChangeListData)data);
}
else {
myAuthorField.setText(null);
myAuthorDate = null;
}
myPanel.revalidate();
myPanel.repaint();
}
private void fillAuthorAndDateFromData(@NotNull ChangeListData data) {
VcsUser author = data.getAuthor();
if (author != null && !isDefaultAuthor(author)) {
myAuthorField.setText(VcsUserUtil.toExactString(author));
myAuthorField.putClientProperty("JComponent.outline", "warning");
if (myAuthorField.isShowing()) {
showAuthorBalloonNotification();
}
}
else {
myAuthorField.setText(null);
}
myAuthorDate = data.getDate();
}
private void clearAuthorWarn() {
myAuthorField.putClientProperty("JComponent.outline", null);
if (myAuthorBalloon != null) {
myAuthorBalloon.hide();
myAuthorBalloon = null;
}
}
@Override
public JComponent getComponent() {
return myPanel;
}
public boolean isDefaultAuthor(@NotNull VcsUser author) {
Collection<VirtualFile> affectedGitRoots = filter(myCheckinProjectPanel.getRoots(), virtualFile -> findGitDir(virtualFile) != null);
GitUserRegistry gitUserRegistry = GitUserRegistry.getInstance(myProject);
return of(affectedGitRoots).map(vf -> gitUserRegistry.getUser(vf)).allMatch(user -> user != null && isSamePerson(author, user));
}
}
public void setNextCommitIsPushed(Boolean nextCommitIsPushed) {
myNextCommitIsPushed = nextCommitIsPushed;
}
public void setSkipHooksForNextCommit(boolean skipHooksForNextCommit) {
myNextCommitSkipHook = skipHooksForNextCommit;
}
}
|
package de.lmu.ifi.dbs.distance;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
/**
* Provides a Distance for a double-valued distance.
*
* @author Elke Achtert (<a
* href="mailto:achtert@dbs.ifi.lmu.de">achtert@dbs.ifi.lmu.de</a>)
*/
public class DoubleDistance extends NumberDistance<DoubleDistance>
{
/**
* Generated serialVersionUID.
*/
private static final long serialVersionUID = 3711413449321214862L;
/**
* The double value of this distance.
*/
double value;
/**
* Empty constructor for serialization purposes.
*/
public DoubleDistance()
{
super();
}
/**
* Constructs a new DoubleDistance object that represents the double
* argument.
*
* @param value
* the value to be represented by the DoubleDistance.
*/
public DoubleDistance(double value)
{
super();
this.value = value;
}
/**
* @see de.lmu.ifi.dbs.distance.Distance#plus(Distance)
*/
public DoubleDistance plus(DoubleDistance distance)
{
return new DoubleDistance(this.value + distance.value);
}
/**
* @see de.lmu.ifi.dbs.distance.Distance#minus(Distance)
*/
public DoubleDistance minus(DoubleDistance distance)
{
return new DoubleDistance(this.value - distance.value);
}
/**
* Returns a new distance as the product of this distance and the given
* distance.
*
* @param distance
* the distancce to be multiplied with this distance
* @return a new distance as the product of this distance and the given
* distance
*/
public DoubleDistance times(DoubleDistance distance)
{
return new DoubleDistance(this.value * distance.value);
}
/**
* Returns a new distance as the product of this distance and the given
* double value.
*
* @param lambda
* the double value this distance should be multiplied with
* @return a new distance as the product of this distance and the given
* double value
*/
public DoubleDistance times(double lambda)
{
return new DoubleDistance(this.value * lambda);
}
/**
* Compares this DoubleDistance with the given DoubleDistance
* wrt the representad double.
*
* <code>d1.compareTo(d2)</code> is the same as
* {@link Double#compare(double, double) Double.compare(d1.value, d2.value)}.
*
* @see Comparable#compareTo(Object)
*/
public int compareTo(DoubleDistance d)
{
return Double.compare(this.value, d.value);
}
/**
* The object implements the writeExternal method to save its contents by
* calling the methods of DataOutput for its primitive values or calling the
* writeObject method of ObjectOutput for objects, strings, and arrays.
*
* @param out
* the stream to write the object to
* @throws java.io.IOException
* Includes any I/O exceptions that may occur
* @serialData Overriding methods should use this tag to describe the data
* layout of this Externalizable object. List the sequence of
* element types and, if possible, relate the element to a
* public/protected field and/or method of this Externalizable
* class.
*/
public void writeExternal(ObjectOutput out) throws IOException
{
out.writeDouble(value);
}
/**
* The object implements the readExternal method to restore its contents by
* calling the methods of DataInput for primitive types and readObject for
* objects, strings and arrays. The readExternal method must read the values
* in the same sequence and with the same types as were written by
* writeExternal.
*
* @param in
* the stream to read data from in order to restore the object
* @throws java.io.IOException
* if I/O errors occur
* @throws ClassNotFoundException
* If the class for an object being restored cannot be found.
*/
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
{
value = in.readDouble();
}
/**
* Retuns the number of Bytes this distance uses if it is written to an
* external file.
*
* @return 8 (8 Byte for a double value)
*/
public int externalizableSize()
{
return 8;
}
/**
* Returns the double value of this distance.
*
* @return the double value of this distance
*/
public double getDoubleValue()
{
return value;
}
/**
* @see Object#equals(Object)
*/
public boolean equals(Object o)
{
if(this == o)
return true;
if(o == null || getClass() != o.getClass())
return false;
if(!super.equals(o))
return false;
final DoubleDistance that = (DoubleDistance) o;
return Double.compare(that.value, value) == 0;
}
/**
* @see Object#hashCode()
*/
public int hashCode()
{
final long temp = value != +0.0d ? Double.doubleToLongBits(value) : 0L;
return (int) (temp ^ (temp >>> 32));
}
/**
* Returns a string representation of this distance.
*
* @return a string representation of this distance.
*/
public String toString()
{
return Double.toString(value);
}
}
|
package de.unitrier.st.soposthistory.urls;
import de.unitrier.st.util.Patterns;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
public class Link {
String fullMatch;
String anchor; // the link anchor visible to the user
String reference; // internal Markdown reference for the link
String url;
String title;
String protocol;
String completeDomain;
String rootDomain;
String path;
public String getFullMatch() {
return fullMatch;
}
public String getAnchor() {
return anchor;
}
public String getReference() {
return reference;
}
public String getUrl() {
return url;
}
public String getTitle() {
return title;
}
public String getProtocol() {
return protocol;
}
public String getCompleteDomain() {
return completeDomain;
}
public String getRootDomain() {
return rootDomain;
}
public String getPath() {
return path;
}
private void extractURLComponents() {
this.protocol = Patterns.extractProtocol(url);
this.completeDomain = Patterns.extractCompleteDomain(url);
this.rootDomain = Patterns.extractRootDomain(completeDomain);
this.path = Patterns.extractPath(url);
}
public static List<Link> extractBare(String markdownContent) {
LinkedList<Link> extractedLinks = new LinkedList<>();
Matcher urlMatcher = Patterns.url.matcher(markdownContent);
while (urlMatcher.find()) {
Link extractedLink = new Link();
extractedLink.fullMatch = urlMatcher.group(0).trim();
extractedLink.url = extractedLink.fullMatch; // for bare links, the full match is equal to the url match
if (extractedLink.url.length() > 0) {
extractedLink.extractURLComponents();
extractedLinks.add(extractedLink);
}
}
return extractedLinks;
}
public static List<Link> extractTyped(String markdownContent) {
List<Link> extractedLinks = new LinkedList<>();
extractedLinks.addAll(MarkdownLinkAngleBrackets.extract(markdownContent));
extractedLinks.addAll(MarkdownLinkInline.extract(markdownContent));
extractedLinks.addAll(MarkdownLinkReference.extract(markdownContent));
extractedLinks.addAll(AnchorLink.extract(markdownContent));
List<Link> extractedBareLinks = extractBare(markdownContent);
// only add bare links that have not been matched before
Set<String> extractedUrls = extractedLinks.stream().map(Link::getUrl).collect(Collectors.toSet());
for (Link bareLink : extractedBareLinks) {
if (!extractedUrls.contains(bareLink.getUrl())) {
extractedLinks.add(bareLink);
}
}
// validate the extracted links (possible issues include posts 36273118 and 37625877 with "double[][]" and anchor tags where href does not point to a valid URL)
List<Link> validLinks = new LinkedList<>();
for (Link currentLink : extractedLinks) {
if (currentLink.url != null) {
Matcher urlMatcher = Patterns.url.matcher(currentLink.url.trim());
if (urlMatcher.matches()) {
validLinks.add(currentLink);
}
}
}
for (Link link : validLinks) {
link.extractURLComponents();
}
return validLinks;
}
public static String normalizeLinks(String markdownContent, List<Link> extractedLinks) {
String normalizedMarkdownContent = markdownContent;
for (Link currentLink : extractedLinks) {
if (currentLink instanceof MarkdownLinkInline // this is the normalized form
|| currentLink instanceof AnchorLink // this would be the result after markup
|| currentLink instanceof MarkdownLinkAngleBrackets) { // this URL will be converted by Commonmark)
continue;
}
if (currentLink instanceof MarkdownLinkReference) {
String[] usageAndDefinition = currentLink.getFullMatch().split("\n");
String usage = usageAndDefinition[0];
String definition = usageAndDefinition[1];
if (currentLink.getAnchor().isEmpty()) { // handles, e.g., post 42695138
normalizedMarkdownContent = normalizedMarkdownContent.replace(usage, "");
} else {
normalizedMarkdownContent = normalizedMarkdownContent.replace(usage,
"[" + currentLink.getAnchor() + "](" + currentLink.getUrl() +
((currentLink.getTitle() != null) ? " \"" + currentLink.getTitle() + "\"" : "")
+ ")"
);
}
normalizedMarkdownContent = normalizedMarkdownContent.replace(definition, "");
} else {
// bare link
normalizedMarkdownContent = normalizedMarkdownContent.replace(
currentLink.getFullMatch(),
"<" + currentLink.getUrl() + ">"
);
}
}
return normalizedMarkdownContent;
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class ProcessManager implements Client.ThreadFinishListener{
//port used to listen to connections
private static final int port = 5566;
private enum processState { Running, Migrated, Finished }
/*
* Hard-coded node's IP address
*
* 128.2.100.188 -> ghc55 (node 0)
* 128.2.100.189 -> ghc56 (node 1)
* 128.2.100.187 -> ghc54
*/
private String[] nodeIP = { "128.2.100.188", "128.2.100.189", "128.2.100.187"};
private int processNum;
//store existing threads and their corresponding numbers
ArrayList<MigratableProcess> mpObj;
ArrayList<MigratableProcess> allObj;
ArrayList<processState> mpState;
ArrayList<Integer> migraObj;
int [] nodeusage;
HashMap <MigratableProcess, Integer> mp2ip;
/* Store Constructed Thread */
ArrayList<Thread> threadInMaster;
public ProcessManager() {
//Bind port to this program, so other nodes can connect to here
try {
ServerSocket mServer = new ServerSocket(port); //server
Matser mMaster = new Matser(mServer);
Thread t = new Thread(mMaster);
t.start(); //keep listening to this port
} catch (IOException e) {
e.printStackTrace();
}
// Initialize threads management elements
mpObj = new ArrayList<MigratableProcess>();
allObj = new ArrayList<MigratableProcess>();
mpState = new ArrayList<processState>();
migraObj = new ArrayList<Integer>();
nodeusage = new int [2];
mp2ip = new HashMap <MigratableProcess, Integer>();
processNum = 0;
threadInMaster = new ArrayList<Thread>();
}
public void launch(MigratableProcess mp) {
mpObj.add(mp);
allObj.add(mp);
mpState.add(processState.Running);
migraObj.add(processNum);
processNum++;
Thread t = new Thread(mp);
threadInMaster.add(t);
t.start();
}
// migrate method
public void migrate() {
//System.out.println("Before Choosing, remove finished threads");
removeFinishedThread();
if (mpObj.size() == 0) {
System.out.println("No process available for migration!");
return;
}
System.out.println("Choose which process you want to migrate:");
for (int i = 0; i < migraObj.size(); i++)
System.out.println(migraObj.get(i) + ": " + mpObj.get(i).getName());
System.out.println();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int procNum = Integer.parseInt(br.readLine());
int migrateIdx = migraObj.indexOf((Integer)procNum);
MigratableProcess m = mpObj.get(migrateIdx);
mpObj.remove(migrateIdx);
migraObj.remove(migrateIdx);
mpState.set(procNum, processState.Migrated);
threadInMaster.remove(migrateIdx);
int ipidx = nodeusage[0] <= nodeusage[1]? 0: 1;
String targetIP = nodeIP[ipidx];
nodeusage[ipidx] ++;
mp2ip.put(m, ipidx);
System.out.println("Automatically migarte " + "\"" + m.getName() + "\"" +" to node:" + targetIP);
m.suspend();
Socket otherNodeSocket = new Socket(targetIP, port);
Client mClient = new Client(otherNodeSocket);
mClient.setTransmitProcess(m);
System.out.println("Start transmission");
mClient.setListener(this);
Thread t = new Thread(mClient);
t.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void removeFinishedThread() {
/*
for (int i = 0; i < migraObj.size(); i++) {
System.out.println(migraObj.get(i) + " alive? " + String.valueOf(threadInMaster.get(i).isAlive()));
}
*/
for (int i = 0; i < migraObj.size(); i++) {
if (!threadInMaster.get(i).isAlive()) {
mpState.set(migraObj.get(i), processState.Finished);
mpObj.remove(i);
migraObj.remove(i);
threadInMaster.remove(i);
}
}
}
@Override
public void onThreadFinish(MigratableProcess mp) {
System.out.println("Finished " + "\"" + mp.getName() + "\"" +" from node: " + nodeIP[mp2ip.get(mp)]);
nodeusage[mp2ip.get(mp)]
//allObj.remove(mp);
int mpIdx = allObj.indexOf(mp);
mpState.set(mpIdx, processState.Finished);
}
// read command at runtime
public String readCommand() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String a = br.readLine();
return a;
}
public void printStatus () {
removeFinishedThread();
System.out.println("=====Process in Master=====");
for (int i = 0; i < mpObj.size(); i++) {
System.out.println(migraObj.get(i) + " " + mpObj.get(i).getName());
}
System.out.println("=====Status of Every Process(finished or migrated)=====");
for (int i = 0; i < allObj.size(); i++) {
if (mpState.get(i) == processState.Migrated)
System.out.println("Process " + i + " " +
allObj.get(i).getName() + " " + mpState.get(i).toString() +
":node " + nodeIP[mp2ip.get(allObj.get(i))]);
else
System.out.println("Process " + i + " " +
allObj.get(i).getName() + " " + mpState.get(i).toString());
}
}
// Main program
public static void main(String[] args) throws Exception {
// Create ProcessManager object to handle different commands
ProcessManager mManager = new ProcessManager();
while (true) {
// listen to the system in
String command = mManager.readCommand();
String[] commandArr = command.split(" ");
String[] argsArr = Arrays.copyOfRange(commandArr, 1, commandArr.length);
if (commandArr[0].equals("migrate")) {// run migrate method
mManager.migrate();
} else if (commandArr[0].equals("exit")) {
System.exit(0);
} else if (commandArr[0].equals("ps")) {
mManager.printStatus();
} else {
//TODO need to handle exception?
// instantiate an object, using reflection in JAVA
try {
Class<?> myClass = Class.forName(commandArr[0]);
Constructor<?> myCons = myClass.getConstructor(String[].class);
Object object = myCons.newInstance((Object) argsArr);
mManager.launch((MigratableProcess) object);
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found!");
} catch (Exception e) {
System.out.println("Wrong Argument");
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.