answer
stringlengths 17
10.2M
|
|---|
package org.appwork.utils.swing.dialog;
import java.awt.Image;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class ContainerDialog extends AbstractDialog<Object> {
private static final long serialVersionUID = -8767494769584526940L;
protected JPanel panel;
/**
*
* @param flags
* @param title
* @param panel
* The JPanel which will be added to the dialog's contentpane
* @param icon
* @param ok
* @param cancel
*/
public ContainerDialog(final int flags, final String title, final JPanel panel, final Image icon, final String ok, final String cancel) {
super(flags, title, null, ok, cancel);
this.panel = panel;
this.setIconImage(icon);
}
/*
* (non-Javadoc)
*
* @see org.appwork.utils.swing.dialog.AbstractDialog#getRetValue()
*/
@Override
protected Object createReturnValue() {
// TODO Auto-generated method stub
return null;
}
@Override
public JComponent layoutDialogContent() {
return this.panel;
}
}
|
package org.camsrobotics.frc2016.auto.modes;
import org.camsrobotics.frc2016.Constants;
import org.camsrobotics.frc2016.auto.AutoMode;
import org.camsrobotics.frc2016.auto.actions.WaitForShooterRPMAction;
import org.camsrobotics.frc2016.auto.actions.WaitForUltrasonicAction;
import org.camsrobotics.frc2016.auto.actions.WaitForVisionTargetAction;
import org.camsrobotics.frc2016.subsystems.Drive.DriveSignal;
import org.camsrobotics.frc2016.subsystems.controllers.DriveRotationController;
import org.camsrobotics.frc2016.subsystems.controllers.DriveStraightController;
/**
* Lowbar and shoot
*
* @author Wesley
*
*/
public class LowBarAuto extends AutoMode {
@Override
public void run() {
// Pass the Low Bar
drive.setController(new DriveStraightController(3, .5));
runAction(new WaitForUltrasonicAction(60, 15));
// Turn until vision sees
drive.setController(new DriveRotationController(45, 0)); // Tolerance really does not matter
runAction(new WaitForVisionTargetAction(15));
// Stop
drive.driveOpenLoop(DriveSignal.kStop);
// Spin Wheels
shooter.setDesiredRPM(Constants.kLongRangeRPM);
runAction(new WaitForShooterRPMAction(15));
// Shoot
shooter.shoot();
}
}
|
package org.opencms.ade.configuration;
import org.opencms.ade.configuration.CmsADEConfigDataInternal.AttributeValue;
import org.opencms.ade.configuration.formatters.CmsFormatterBeanParser;
import org.opencms.ade.configuration.formatters.CmsFormatterChangeSet;
import org.opencms.ade.configuration.formatters.CmsFormatterConfigurationCacheState;
import org.opencms.ade.configuration.plugins.CmsTemplatePluginGroup;
import org.opencms.ade.containerpage.shared.CmsContainer;
import org.opencms.ade.containerpage.shared.CmsContainerElement;
import org.opencms.ade.containerpage.shared.CmsFormatterConfig;
import org.opencms.ade.detailpage.CmsDetailPageInfo;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypeFolder;
import org.opencms.file.types.CmsResourceTypeFunctionConfig;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.gwt.CmsIconUtil;
import org.opencms.jsp.util.CmsFunctionRenderer;
import org.opencms.loader.CmsLoaderException;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.main.OpenCmsServlet;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.editors.directedit.CmsAdvancedDirectEditProvider.SitemapDirectEditPermissions;
import org.opencms.xml.CmsXmlContentDefinition;
import org.opencms.xml.containerpage.CmsFormatterConfiguration;
import org.opencms.xml.containerpage.CmsXmlDynamicFunctionHandler;
import org.opencms.xml.containerpage.I_CmsFormatterBean;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.content.CmsXmlContentProperty;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.logging.Log;
import com.google.common.base.Optional;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
/**
* A class which represents the accessible configuration data at a given point in a sitemap.<p>
*/
public class CmsADEConfigData {
/**
* Bean which contains the detail information for a single sub-sitemap and resource type.<p>
*
* This includes both information about the detail page itself, as well as the path of the folder
* which is used to store that content type in this subsitemap.<p>
*
*/
public class DetailInfo {
/** The base path of the sitemap configuration where this information originates from. */
private String m_basePath;
/** The information about the detail page info itself. */
private CmsDetailPageInfo m_detailPageInfo;
/** The content folder path. */
private String m_folderPath;
/** The detail type. */
private String m_type;
/**
* Creates a new instance.<p>
*
* @param folderPath the content folder path
* @param detailPageInfo the detail page information
* @param type the detail type
* @param basePath the base path of the sitemap configuration
*/
public DetailInfo(String folderPath, CmsDetailPageInfo detailPageInfo, String type, String basePath) {
m_folderPath = folderPath;
m_detailPageInfo = detailPageInfo;
m_type = type;
m_basePath = basePath;
}
/**
* Gets the base path of the sitemap configuration from which this information is coming.<p>
*
* @return the base path
*/
public String getBasePath() {
return m_basePath;
}
/**
* Gets the detail page information.<p>
*
* @return the detail page information
*/
public CmsDetailPageInfo getDetailPageInfo() {
return m_detailPageInfo;
}
/**
* Gets the content folder path.<p>
*
* @return the content folder path
*/
public String getFolderPath() {
return m_folderPath;
}
/**
* Gets the detail type.<p>
*
* @return the detail type
*/
public String getType() {
return m_type;
}
/**
* Sets the base path.<p>
*
* @param basePath the new base path value
*/
public void setBasePath(String basePath) {
m_basePath = basePath;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
public static final String REQ_LOG_PREFIX = "[CmsADEConfigData] ";
public static final String REQUEST_LOG_CHANNEL = "org.opencms.ade.configuration.CmsADEConfigData.request";
/** The log instance for this class. */
private static final Log LOG = CmsLog.getLog(CmsADEConfigData.class);
/** Prefixes for internal settings which might be passed as formatter keys to findFormatter(). */
private static final HashSet<String> systemSettingPrefixes = new HashSet<>(
Arrays.asList("element", "model", "source", "use", "cms", "is"));
/** The wrapped configuration bean containing the actual data. */
protected CmsADEConfigDataInternal m_data;
/** Lazily initialized map of formatters. */
private Map<CmsUUID, I_CmsFormatterBean> m_activeFormatters;
/** Lazily initialized cache for active formatters by formatter key. */
private Multimap<String, I_CmsFormatterBean> m_activeFormattersByKey;
/** The sitemap attributes (may be null if not yet computed). */
private Map<String, AttributeValue> m_attributes;
/** The cache state to which the wrapped configuration bean belongs. */
private CmsADEConfigCacheState m_cache;
/** Current formatter configuration. */
private CmsFormatterConfigurationCacheState m_cachedFormatters;
/** The configuration sequence (contains the list of all sitemap configuration data beans to be used for inheritance). */
private CmsADEConfigurationSequence m_configSequence;
/** Lazily initialized cache for formatters by JSP id. */
private Multimap<CmsUUID, I_CmsFormatterBean> m_formattersByJspId;
/** Lazily initialized cache for formatters by formatter key. */
private Multimap<String, I_CmsFormatterBean> m_formattersByKey;
/** Set of names of active types.*/
private Set<String> m_typesActive;
/** Type names configured in this or ancestor sitemap configurations. */
private Set<String> m_typesInAncestors;
/**
* Creates a new configuration data object, based on an internal configuration data bean and a
* configuration cache state.<p>
*
* @param data the internal configuration data bean
* @param cache the configuration cache state
* @param configSequence the configuration sequence
*/
public CmsADEConfigData(
CmsADEConfigDataInternal data,
CmsADEConfigCacheState cache,
CmsADEConfigurationSequence configSequence) {
m_data = data;
m_cache = cache;
m_configSequence = configSequence;
}
/**
* Generic method to merge lists of named configuration objects.<p>
*
* The lists are merged such that the configuration objects from the child list rise to the front of the result list,
* and two configuration objects will be merged themselves if they share the same name.<p>
*
* For example, if we have two lists of configuration objects:<p>
*
* parent: A1, B1, C1<p>
* child: D2, B2<p>
*
* then the resulting list will look like:<p>
*
* D2, B3, A1, C1<p>
*
* where B3 is the result of merging B1 and B2.<p>
*
* @param <C> the type of configuration object
* @param parentConfigs the parent configurations
* @param childConfigs the child configurations
* @param preserveDisabled if true, try to merge parents with disabled children instead of discarding them
*
* @return the merged configuration object list
*/
public static <C extends I_CmsConfigurationObject<C>> List<C> combineConfigurationElements(
List<C> parentConfigs,
List<C> childConfigs,
boolean preserveDisabled) {
List<C> result = new ArrayList<C>();
Map<String, C> map = new LinkedHashMap<String, C>();
if (parentConfigs != null) {
for (C parent : Lists.reverse(parentConfigs)) {
map.put(parent.getKey(), parent);
}
}
if (childConfigs == null) {
childConfigs = Collections.emptyList();
}
for (C child : Lists.reverse(childConfigs)) {
String childKey = child.getKey();
if (child.isDisabled() && !preserveDisabled) {
map.remove(childKey);
} else {
C parent = map.get(childKey);
map.remove(childKey);
C newValue;
if (parent != null) {
newValue = parent.merge(child);
} else {
newValue = child;
}
map.put(childKey, newValue);
}
}
result = new ArrayList<C>(map.values());
Collections.reverse(result);
// those multiple "reverse" calls may a bit confusing. They are there because on the one hand we want to keep the
// configuration items from one configuration in the same order as they are defined, on the other hand we want
// configuration items from a child configuration to rise to the top of the configuration items.
// so for example, if the parent configuration has items with the keys A,B,C,E
// and the child configuration has items with the keys C,B,D
// we want the items of the combined configuration in the order C,B,D,A,E
return result;
}
/**
* Applies the formatter change sets of this and all parent configurations to a map of external (non-schema) formatters.<p>
*
* @param formatters the external formatter map which will be modified
*
* @param formatterCacheState the formatter cache state from which new external formatters should be fetched
*/
public void applyAllFormatterChanges(
Map<CmsUUID, I_CmsFormatterBean> formatters,
CmsFormatterConfigurationCacheState formatterCacheState) {
for (CmsFormatterChangeSet changeSet : getFormatterChangeSets()) {
changeSet.applyToFormatters(formatters, formatterCacheState);
}
}
/**
* Gets the 'best' formatter for the given ID.<p>
*
* If the formatter with the ID has a key, then the active formatter with the same key is returned. Otherwise, the
* formatter matching the ID is returned. So being active and having the same key is prioritized over an exact ID match.
*
* @param id the formatter ID
* @return the best formatter the given ID
*/
public I_CmsFormatterBean findFormatter(CmsUUID id) {
if (id == null) {
return null;
}
CmsFormatterConfigurationCacheState formatterState = getCachedFormatters();
I_CmsFormatterBean result = formatterState.getFormatters().get(id);
if ((result != null) && (result.getKey() != null)) {
String key = result.getKey();
Collection<I_CmsFormatterBean> activeFormattersForKey = getActiveFormattersByKey().get(key);
if (activeFormattersForKey.size() > 0) {
if (activeFormattersForKey.size() > 1) {
String labels = ""
+ activeFormattersForKey.stream().map(this::getFormatterLabel).collect(Collectors.toList());
String message = "Ambiguous formatter for key '"
+ key
+ "' at '"
+ getBasePath()
+ "': found "
+ labels;
LOG.warn(message);
OpenCmsServlet.withRequestCache(
reqCache -> reqCache.addLog(REQUEST_LOG_CHANNEL, "warn", REQ_LOG_PREFIX + message));
}
I_CmsFormatterBean original = result;
result = activeFormattersForKey.iterator().next();
String message = "Using substitute formatter "
+ getFormatterLabel(result)
+ " instead of "
+ getFormatterLabel(original)
+ " because of matching key.";
LOG.debug(message);
OpenCmsServlet.withRequestCache(
reqCache -> reqCache.addLog(REQUEST_LOG_CHANNEL, "debug", REQ_LOG_PREFIX + message));
}
}
return result;
}
/**
* Gets the 'best' formatter for the given name.<p>
*
* The name can be either a formatter key, or a formatter UUID. If it's a key, an active formatter with that key is returned.
* If it's a UUID, and the formatter with that UUID has no key, it will be returned. If it does have a key, the active formatter
* with that key is returned (so being active and having the same key is prioritized over an exact ID match).
*
* @param name a formatter name (key or ID)
* @return the best formatter for that name, or null if no formatter could be found
*/
public I_CmsFormatterBean findFormatter(String name) {
if (name == null) {
return null;
}
if (systemSettingPrefixes.contains(name) || name.startsWith(CmsContainerElement.SYSTEM_SETTING_PREFIX)) {
if (LOG.isDebugEnabled()) {
LOG.debug("System setting prefix used: " + name, new Exception());
}
return null;
}
if (CmsUUID.isValidUUID(name)) {
return findFormatter(new CmsUUID(name));
}
if (name.startsWith(CmsFormatterConfig.SCHEMA_FORMATTER_ID)) {
return null;
}
Collection<I_CmsFormatterBean> activeForKey = getActiveFormattersByKey().get(name);
if (activeForKey.size() > 0) {
if (activeForKey.size() > 1) {
String labels = "" + activeForKey.stream().map(this::getFormatterLabel).collect(Collectors.toList());
String message = "Ambiguous formatter for key '"
+ name
+ "' at '"
+ getBasePath()
+ "': found "
+ labels;
LOG.warn(message);
OpenCmsServlet.withRequestCache(rc -> rc.addLog(REQUEST_LOG_CHANNEL, "warn", REQ_LOG_PREFIX + message));
}
return activeForKey.iterator().next();
} else {
String message1 = "No local formatter found for key '"
+ name
+ "' at '"
+ getBasePath()
+ "', trying inactive formatters";
LOG.warn(message1);
OpenCmsServlet.withRequestCache(rc -> rc.addLog(REQUEST_LOG_CHANNEL, "warn", REQ_LOG_PREFIX + message1));
Collection<I_CmsFormatterBean> allForKey = getFormattersByKey().get(name);
if (allForKey.size() > 0) {
if (allForKey.size() > 1) {
String labels = "" + allForKey.stream().map(this::getFormatterLabel).collect(Collectors.toList());
String message = "Ambiguous formatter for key '"
+ name
+ "' at '"
+ getBasePath()
+ "': found "
+ labels;
LOG.warn(message);
OpenCmsServlet.withRequestCache(
rc -> rc.addLog(REQUEST_LOG_CHANNEL, "warn", REQ_LOG_PREFIX + message));
}
return allForKey.iterator().next();
}
}
OpenCmsServlet.withRequestCache(
rc -> rc.addLog(
REQUEST_LOG_CHANNEL,
"warn",
REQ_LOG_PREFIX + "No formatter found for key '" + name + "' at '" + getBasePath() + "'"));
return null;
}
/**
* Gets the active external (non-schema) formatters for this sub-sitemap.<p>
*
* @return the map of active external formatters by structure id
*/
public Map<CmsUUID, I_CmsFormatterBean> getActiveFormatters() {
if (m_activeFormatters == null) {
Map<CmsUUID, I_CmsFormatterBean> result = Maps.newHashMap(getCachedFormatters().getAutoEnabledFormatters());
applyAllFormatterChanges(result, getCachedFormatters());
m_activeFormatters = result;
}
return m_activeFormatters;
}
/**
* Gets the set of names of types active in this sitemap configuration.
*
* @return the set of type names of active types
*/
public Set<String> getActiveTypeNames() {
Set<String> result = m_typesActive;
if (result != null) {
return result;
} else {
Set<String> mutableResult = new HashSet<>();
for (CmsResourceTypeConfig typeConfig : internalGetResourceTypes(true)) {
mutableResult.add(typeConfig.getTypeName());
}
result = Collections.unmodifiableSet(mutableResult);
m_typesActive = result;
return result;
}
}
/**
* Gets the list of all detail pages.<p>
*
* @return the list of all detail pages
*/
public List<CmsDetailPageInfo> getAllDetailPages() {
return getAllDetailPages(true);
}
/**
* Gets a list of all detail pages.<p>
*
* @param update if true, this method will try to correct the root paths in the returned objects if the corresponding resources have been moved
*
* @return the list of all detail pages
*/
public List<CmsDetailPageInfo> getAllDetailPages(boolean update) {
CmsADEConfigData parentData = parent();
List<CmsDetailPageInfo> parentDetailPages;
if (parentData != null) {
parentDetailPages = parentData.getAllDetailPages(false);
} else {
parentDetailPages = Collections.emptyList();
}
List<CmsDetailPageInfo> result = mergeDetailPages(parentDetailPages, m_data.getOwnDetailPages());
if (update) {
result = updateUris(result);
}
return result;
}
/**
* Gets the set of names of types configured in this or any ancestor sitemap configurations.
*
* @return the set of type names from all ancestor configurations
*/
public Set<String> getAncestorTypeNames() {
Set<String> result = m_typesInAncestors;
if (result != null) {
return result;
} else {
Set<String> mutableResult = new HashSet<>();
for (CmsResourceTypeConfig typeConfig : internalGetResourceTypes(false)) {
mutableResult.add(typeConfig.getTypeName());
}
result = Collections.unmodifiableSet(mutableResult);
m_typesInAncestors = result;
return result;
}
}
/**
* Gets the value of an attribute, or a default value
*
* @param key the attribute key
* @param defaultValue the value to return if no attribute with the given name is found
*
* @return the attribute value
*/
public String getAttribute(String key, String defaultValue) {
AttributeValue value = getAttributes().get(key);
if (value != null) {
return value.getValue();
} else {
return defaultValue;
}
}
/**
* Gets the map of attributes configured for this sitemap, including values inherited from parent sitemaps.
*
* @return the map of attributes
*/
public Map<String, AttributeValue> getAttributes() {
if (m_attributes != null) {
return m_attributes;
}
CmsADEConfigData parentConfig = parent();
Map<String, AttributeValue> result = new HashMap<>();
if (parentConfig != null) {
result.putAll(parentConfig.getAttributes());
}
for (Map.Entry<String, AttributeValue> entry : m_data.getAttributes().entrySet()) {
result.put(entry.getKey(), entry.getValue());
}
Map<String, AttributeValue> immutableResult = Collections.unmodifiableMap(result);
m_attributes = immutableResult;
return immutableResult;
}
/**
* Gets the configuration base path.<p>
*
* For example, if the configuration file is located at /sites/default/.content/.config, the base path is /sites/default.<p>
*
* @return the base path of the configuration
*/
public String getBasePath() {
return m_data.getBasePath();
}
/**
* Gets the cached formatters.<p>
*
* @return the cached formatters
*/
public CmsFormatterConfigurationCacheState getCachedFormatters() {
if (m_cachedFormatters == null) {
m_cachedFormatters = OpenCms.getADEManager().getCachedFormatters(
getCms().getRequestContext().getCurrentProject().isOnlineProject());
}
return m_cachedFormatters;
}
/**
* Gets an (immutable) list of paths of configuration files in inheritance order.
*
* @return the list of configuration files
*/
public List<String> getConfigPaths() {
return m_configSequence.getConfigPaths();
}
/**
* Returns the names of the bundles configured as workplace bundles in any module configuration.<p>
*
* @return the names of the bundles configured as workplace bundles in any module configuration.
*/
public Set<String> getConfiguredWorkplaceBundles() {
Set<String> result = new HashSet<String>();
for (CmsResourceTypeConfig config : internalGetResourceTypes(false)) {
String bundlename = config.getConfiguredWorkplaceBundle();
if (null != bundlename) {
result.add(bundlename);
}
}
return result;
}
/**
* Gets the content folder path.<p>
*
* For example, if the configuration file is located at /sites/default/.content/.config, the content folder path is /sites/default/.content
*
* @return the content folder path
*/
public String getContentFolderPath() {
return CmsStringUtil.joinPaths(m_data.getBasePath(), CmsADEManager.CONTENT_FOLDER_NAME);
}
/**
* Returns a list of the creatable resource types.<p>
*
* @param cms the CMS context used to check whether the resource types are creatable
* @param pageFolderRootPath the root path of the current container page
* @return the list of creatable resource type
*
* @throws CmsException if something goes wrong
*/
public List<CmsResourceTypeConfig> getCreatableTypes(CmsObject cms, String pageFolderRootPath) throws CmsException {
List<CmsResourceTypeConfig> result = new ArrayList<CmsResourceTypeConfig>();
for (CmsResourceTypeConfig typeConfig : getResourceTypes()) {
if (typeConfig.checkCreatable(cms, pageFolderRootPath)) {
result.add(typeConfig);
}
}
return result;
}
/**
* Returns the default detail page.<p>
*
* @return the default detail page
*/
public CmsDetailPageInfo getDefaultDetailPage() {
for (CmsDetailPageInfo detailpage : getAllDetailPages(true)) {
if (CmsADEManager.DEFAULT_DETAILPAGE_TYPE.equals(detailpage.getType())) {
return detailpage;
}
}
return null;
}
/**
* Returns the default model page.<p>
*
* @return the default model page
*/
public CmsModelPageConfig getDefaultModelPage() {
List<CmsModelPageConfig> modelPages = getModelPages();
for (CmsModelPageConfig modelPageConfig : getModelPages()) {
if (modelPageConfig.isDefault()) {
return modelPageConfig;
}
}
if (modelPages.isEmpty()) {
return null;
}
return modelPages.get(0);
}
/**
* Gets the detail information for this sitemap config data object.<p>
*
* @param cms the CMS context
* @return the list of detail information
*/
public List<DetailInfo> getDetailInfos(CmsObject cms) {
List<DetailInfo> result = Lists.newArrayList();
List<CmsDetailPageInfo> detailPages = getAllDetailPages(true);
Collections.reverse(detailPages); // make sure primary detail pages come later in the list and override other detail pages for the same type
Map<String, CmsDetailPageInfo> primaryDetailPageMapByType = Maps.newHashMap();
for (CmsDetailPageInfo pageInfo : detailPages) {
primaryDetailPageMapByType.put(pageInfo.getType(), pageInfo);
}
for (CmsResourceTypeConfig typeConfig : getResourceTypes()) {
String typeName = typeConfig.getTypeName();
if (((typeConfig.getFolderOrName() == null) || !typeConfig.getFolderOrName().isPageRelative())
&& primaryDetailPageMapByType.containsKey(typeName)) {
String folderPath = typeConfig.getFolderPath(cms, null);
CmsDetailPageInfo pageInfo = primaryDetailPageMapByType.get(typeName);
result.add(new DetailInfo(folderPath, pageInfo, typeName, getBasePath()));
}
}
return result;
}
/**
* Gets the detail pages for a specific type.<p>
*
* @param type the type name
*
* @return the list of detail pages for that type
*/
public List<CmsDetailPageInfo> getDetailPagesForType(String type) {
List<CmsDetailPageInfo> result = new ArrayList<CmsDetailPageInfo>();
CmsResourceTypeConfig typeConfig = getResourceType(type);
if (type.startsWith(CmsDetailPageInfo.FUNCTION_PREFIX)
|| ((typeConfig != null) && !typeConfig.isDetailPagesDisabled())) {
CmsDetailPageInfo defaultPage = null;
for (CmsDetailPageInfo detailpage : getAllDetailPages(true)) {
if (detailpage.getType().equals(type)) {
result.add(detailpage);
} else
if ((defaultPage == null) && CmsADEManager.DEFAULT_DETAILPAGE_TYPE.equals(detailpage.getType())) {
defaultPage = detailpage;
}
}
if (defaultPage != null) {
// add default detail page last
result.add(defaultPage);
}
}
return result;
}
public SitemapDirectEditPermissions getDirectEditPermissions(String type) {
if (type == null) {
LOG.error("Null type in checkListEdit");
return SitemapDirectEditPermissions.all;
}
if (!getAncestorTypeNames().contains(type)) {
// not configured anywhere for ADE
return SitemapDirectEditPermissions.notInSitemapConfig;
}
CmsResourceTypeConfig typeConfig = getResourceType(type);
if (typeConfig == null) {
return SitemapDirectEditPermissions.none;
}
if (typeConfig.isCreateDisabled() || typeConfig.isAddDisabled()) {
return SitemapDirectEditPermissions.editOnly;
}
return SitemapDirectEditPermissions.all;
}
/**
* Returns all available display formatters.<p>
*
* @param cms the cms context
*
* @return the available display formatters
*/
public List<I_CmsFormatterBean> getDisplayFormatters(CmsObject cms) {
List<I_CmsFormatterBean> result = new ArrayList<I_CmsFormatterBean>();
for (I_CmsFormatterBean formatter : getCachedFormatters().getFormatters().values()) {
if (formatter.isDisplayFormatter()) {
result.add(formatter);
}
}
return result;
}
/**
* Gets the bean that represents the dynamic function availability.
*
* @return the dynamic function availability
*/
public CmsFunctionAvailability getDynamicFunctionAvailability(CmsFormatterConfigurationCacheState formatterConfig) {
CmsADEConfigData parentData = parent();
CmsFunctionAvailability result;
if (parentData == null) {
result = new CmsFunctionAvailability(formatterConfig);
} else {
result = parentData.getDynamicFunctionAvailability(formatterConfig);
}
Collection<CmsUUID> enabledIds = m_data.getDynamicFunctions();
Collection<CmsUUID> disabledIds = m_data.getFunctionsToRemove();
if (m_data.isRemoveAllFunctions()) {
result.removeAll();
}
if (enabledIds != null) {
result.addAll(enabledIds);
}
if (disabledIds != null) {
for (CmsUUID id : disabledIds) {
result.remove(id);
}
}
return result;
}
/**
* Gets the root path of the closest subsite going up the tree which has the 'exclude external detail contents' option enabled, or '/' if no such subsite exists.
*
* @return the root path of the closest subsite with 'external detail contents excluded'
*/
public String getExternalDetailContentExclusionFolder() {
if (m_data.isExcludeExternalDetailContents()) {
String basePath = m_data.getBasePath();
if (basePath == null) {
return "/";
} else {
return basePath;
}
} else {
CmsADEConfigData parent = parent();
if (parent != null) {
return parent.getExternalDetailContentExclusionFolder();
} else {
return "/";
}
}
}
/**
* Returns the formatter change sets for this and all parent sitemaps, ordered by increasing folder depth of the sitemap.<p>
*
* @return the formatter change sets for all ancestor sitemaps
*/
public List<CmsFormatterChangeSet> getFormatterChangeSets() {
CmsADEConfigData currentConfig = this;
List<CmsFormatterChangeSet> result = Lists.newArrayList();
while (currentConfig != null) {
CmsFormatterChangeSet changes = currentConfig.getOwnFormatterChangeSet();
if (changes != null) {
result.add(changes);
}
currentConfig = currentConfig.parent();
}
Collections.reverse(result);
return result;
}
/**
* Gets the formatter configuration for a resource.<p>
*
* @param cms the current CMS context
* @param res the resource for which the formatter configuration should be retrieved
*
* @return the configuration of formatters for the resource
*/
public CmsFormatterConfiguration getFormatters(CmsObject cms, CmsResource res) {
if (CmsResourceTypeFunctionConfig.isFunction(res)) {
CmsFormatterConfigurationCacheState formatters = getCachedFormatters();
I_CmsFormatterBean function = findFormatter(res.getStructureId());
if (function != null) {
return CmsFormatterConfiguration.create(cms, Collections.singletonList(function));
} else {
if ((!res.getStructureId().isNullUUID())
&& cms.existsResource(res.getStructureId(), CmsResourceFilter.IGNORE_EXPIRATION)) {
// usually if it's just been created, but not added to the configuration cache yet
CmsFormatterBeanParser parser = new CmsFormatterBeanParser(cms, new HashMap<>());
try {
function = parser.parse(
CmsXmlContentFactory.unmarshal(cms, cms.readFile(res)),
res.getRootPath(),
"" + res.getStructureId());
return CmsFormatterConfiguration.create(cms, Collections.singletonList(function));
} catch (Exception e) {
LOG.warn(e.getLocalizedMessage(), e);
return CmsFormatterConfiguration.EMPTY_CONFIGURATION;
}
} else {
// if a new function has been dragged on the page, it doesn't exist in the VFS yet, so we need a different
// instance as a replacement
CmsResource defaultFormatter = CmsFunctionRenderer.getDefaultFunctionInstance(cms);
if (defaultFormatter != null) {
I_CmsFormatterBean defaultFormatterBean = formatters.getFormatters().get(
defaultFormatter.getStructureId());
return CmsFormatterConfiguration.create(cms, Collections.singletonList(defaultFormatterBean));
} else {
LOG.warn("Could not read default formatter for functions.");
return CmsFormatterConfiguration.EMPTY_CONFIGURATION;
}
}
}
} else {
try {
int resTypeId = res.getTypeId();
return getFormatters(
cms,
OpenCms.getResourceManager().getResourceType(resTypeId),
getFormattersFromSchema(cms, res));
} catch (CmsLoaderException e) {
LOG.warn(e.getLocalizedMessage(), e);
return CmsFormatterConfiguration.EMPTY_CONFIGURATION;
}
}
}
/**
* Gets a named function reference.<p>
*
* @param name the name of the function reference
*
* @return the function reference for the given name
*/
public CmsFunctionReference getFunctionReference(String name) {
List<CmsFunctionReference> functionReferences = getFunctionReferences();
for (CmsFunctionReference functionRef : functionReferences) {
if (functionRef.getName().equals(name)) {
return functionRef;
}
}
return null;
}
/**
* Gets the list of configured function references.<p>
*
* @return the list of configured function references
*/
public List<CmsFunctionReference> getFunctionReferences() {
return internalGetFunctionReferences();
}
/**
* Gets the map of external (non-schema) formatters which are inactive in this sub-sitemap.<p>
*
* @return the map inactive external formatters
*/
public Map<CmsUUID, I_CmsFormatterBean> getInactiveFormatters() {
CmsFormatterConfigurationCacheState cacheState = getCachedFormatters();
Map<CmsUUID, I_CmsFormatterBean> result = Maps.newHashMap(cacheState.getFormatters());
result.keySet().removeAll(getActiveFormatters().keySet());
return result;
}
/**
* Gets the main detail page for a specific type.<p>
*
* @param type the type name
*
* @return the main detail page for that type
*/
public CmsDetailPageInfo getMainDetailPage(String type) {
List<CmsDetailPageInfo> detailPages = getDetailPagesForType(type);
if ((detailPages == null) || detailPages.isEmpty()) {
return null;
}
return detailPages.get(0);
}
/**
* Gets the list of available model pages.<p>
*
* @return the list of available model pages
*/
public List<CmsModelPageConfig> getModelPages() {
return getModelPages(false);
}
/**
* Gets the list of available model pages.<p>
*
* @param includeDisable <code>true</code> to include disabled model pages
*
* @return the list of available model pages
*/
public List<CmsModelPageConfig> getModelPages(boolean includeDisable) {
CmsADEConfigData parentData = parent();
List<CmsModelPageConfig> parentModelPages;
if ((parentData != null) && !m_data.isDiscardInheritedModelPages()) {
parentModelPages = parentData.getModelPages();
} else {
parentModelPages = Collections.emptyList();
}
List<CmsModelPageConfig> result = combineConfigurationElements(
parentModelPages,
m_data.getOwnModelPageConfig(),
includeDisable);
return result;
}
/**
* Gets the formatter changes for this sitemap configuration.<p>
*
* @return the formatter change set
*/
public CmsFormatterChangeSet getOwnFormatterChangeSet() {
return m_data.getFormatterChangeSet();
}
/**
* Gets the configuration for the available properties.<p>
*
* @return the configuration for the available properties
*/
public List<CmsPropertyConfig> getPropertyConfiguration() {
CmsADEConfigData parentData = parent();
List<CmsPropertyConfig> parentProperties;
if ((parentData != null) && !m_data.isDiscardInheritedProperties()) {
parentProperties = parentData.getPropertyConfiguration();
} else {
parentProperties = Collections.emptyList();
}
LinkedHashMap<String, CmsPropertyConfig> propMap = new LinkedHashMap<>();
for (CmsPropertyConfig conf : parentProperties) {
if (conf.isDisabled()) {
continue;
}
propMap.put(conf.getName(), conf);
}
for (CmsPropertyConfig conf : m_data.getOwnPropertyConfigurations()) {
if (conf.isDisabled()) {
propMap.remove(conf.getName());
} else if (propMap.containsKey(conf.getName())) {
propMap.put(conf.getName(), propMap.get(conf.getName()).merge(conf));
} else {
propMap.put(conf.getName(), conf);
}
}
List<CmsPropertyConfig> result = new ArrayList<>(propMap.values());
return result;
}
/**
* Computes the ordered map of properties to display in the property dialog, given the map of default property configurations passed as a parameter.
*
* @param defaultProperties the default property configurations
* @return the ordered map of property configurations for the property dialog
*/
public Map<String, CmsXmlContentProperty> getPropertyConfiguration(
Map<String, CmsXmlContentProperty> defaultProperties) {
List<CmsPropertyConfig> myPropConfigs = getPropertyConfiguration();
Map<String, CmsXmlContentProperty> allProps = new LinkedHashMap<>(defaultProperties);
Map<String, CmsXmlContentProperty> result = new LinkedHashMap<>();
for (CmsPropertyConfig prop : myPropConfigs) {
allProps.put(prop.getName(), prop.getPropertyData());
if (prop.isTop()) {
result.put(prop.getName(), prop.getPropertyData());
}
}
for (Map.Entry<String, CmsXmlContentProperty> entry : allProps.entrySet()) {
if (!result.containsKey(entry.getKey())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
/**
* Gets the property configuration as a map of CmsXmlContentProperty instances.<p>
*
* @return the map of property configurations
*/
public Map<String, CmsXmlContentProperty> getPropertyConfigurationAsMap() {
Map<String, CmsXmlContentProperty> result = new LinkedHashMap<String, CmsXmlContentProperty>();
for (CmsPropertyConfig propConf : getPropertyConfiguration()) {
result.put(propConf.getName(), propConf.getPropertyData());
}
return result;
}
/**
* Returns the resource from which this configuration was read.<p>
*
* @return the resource from which this configuration was read
*/
public CmsResource getResource() {
return m_data.getResource();
}
/**
* Returns the configuration for a specific resource type.<p>
*
* @param typeName the name of the type
*
* @return the resource type configuration for that type
*/
public CmsResourceTypeConfig getResourceType(String typeName) {
for (CmsResourceTypeConfig type : getResourceTypes()) {
if (typeName.equals(type.getTypeName())) {
return type;
}
}
return null;
}
/**
* Gets a list of all available resource type configurations.<p>
*
* @return the available resource type configurations
*/
public List<CmsResourceTypeConfig> getResourceTypes() {
List<CmsResourceTypeConfig> result = internalGetResourceTypes(true);
for (CmsResourceTypeConfig config : result) {
config.initialize(getCms());
}
return result;
}
/**
* Gets the searchable resource type configurations.<p>
*
* @param cms the current CMS context
* @return the searchable resource type configurations
*/
public Collection<CmsResourceTypeConfig> getSearchableTypes(CmsObject cms) {
return getResourceTypes();
}
/**
* Gets the ids of site plugins which are active in this sitemap configuration.
*
* @return the ids of active site plugins
*/
public Set<CmsUUID> getSitePluginIds() {
CmsADEConfigData parent = parent();
Set<CmsUUID> result;
if ((parent == null) || m_data.isRemoveAllPlugins()) {
result = new HashSet<>();
} else {
result = parent.getSitePluginIds();
}
result.removeAll(m_data.getRemovedPlugins());
result.addAll(m_data.getAddedPlugins());
return result;
}
/**
* Gets the list of site plugins active in this sitemap configuration.
*
* @return the list of active site plugins
*/
public List<CmsTemplatePluginGroup> getSitePlugins() {
Set<CmsUUID> pluginIds = getSitePluginIds();
List<CmsTemplatePluginGroup> result = new ArrayList<>();
Map<CmsUUID, CmsTemplatePluginGroup> plugins = m_cache.getSitePlugins();
for (CmsUUID id : pluginIds) {
CmsTemplatePluginGroup sitePlugin = plugins.get(id);
if (sitePlugin != null) {
result.add(sitePlugin);
}
}
return result;
}
/**
* Gets the type ordering mode.
*
* @return the type ordering mode
*/
public CmsTypeOrderingMode getTypeOrderingMode() {
CmsTypeOrderingMode ownOrderingMode = m_data.getTypeOrderingMode();
if (ownOrderingMode != null) {
return ownOrderingMode;
} else {
CmsADEConfigData parentConfig = parent();
CmsTypeOrderingMode parentMode = null;
if (parentConfig == null) {
parentMode = CmsTypeOrderingMode.latestOnTop;
} else {
parentMode = parentConfig.getTypeOrderingMode();
}
return parentMode;
}
}
/**
* Gets the set of resource type names for which schema formatters can be enabled or disabled and which are not disabled in this sub-sitemap.<p>
*
* @return the set of types for which schema formatters are active
*/
public Set<String> getTypesWithActiveSchemaFormatters() {
Set<String> result = Sets.newHashSet(getTypesWithModifiableFormatters());
for (CmsFormatterChangeSet changeSet : getFormatterChangeSets()) {
changeSet.applyToTypes(result);
}
return result;
}
/**
* Gets the set of names of resource types which have schema-based formatters that can be enabled or disabled.<p>
*
* @return the set of names of resource types which have schema-based formatters that can be enabled or disabled
*/
public Set<String> getTypesWithModifiableFormatters() {
Set<String> result = new HashSet<String>();
for (I_CmsResourceType type : OpenCms.getResourceManager().getResourceTypes()) {
if (type instanceof CmsResourceTypeXmlContent) {
CmsXmlContentDefinition contentDef = null;
try {
contentDef = CmsXmlContentDefinition.getContentDefinitionForType(getCms(), type.getTypeName());
if ((contentDef != null) && contentDef.getContentHandler().hasModifiableFormatters()) {
result.add(type.getTypeName());
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
return result;
}
/**
* Checks if there are any matching formatters for the given set of containers.<p>
*
* @param cms the current CMS context
* @param resType the resource type for which the formatter configuration should be retrieved
* @param containers the page containers
*
* @return if there are any matching formatters
*/
public boolean hasFormatters(CmsObject cms, I_CmsResourceType resType, Collection<CmsContainer> containers) {
try {
if (CmsXmlDynamicFunctionHandler.TYPE_FUNCTION.equals(resType.getTypeName())
|| CmsResourceTypeFunctionConfig.TYPE_NAME.equals(resType.getTypeName())) {
// dynamic function may match any container
return true;
}
CmsXmlContentDefinition def = CmsXmlContentDefinition.getContentDefinitionForType(
cms,
resType.getTypeName());
CmsFormatterConfiguration schemaFormatters = def.getContentHandler().getFormatterConfiguration(cms, null);
CmsFormatterConfiguration formatters = getFormatters(cms, resType, schemaFormatters);
for (CmsContainer cont : containers) {
if (cont.isEditable()
&& (formatters.getAllMatchingFormatters(cont.getType(), cont.getWidth()).size() > 0)) {
return true;
}
}
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
return false;
}
/**
* Returns the value of the "create contents locally" flag.<p>
*
* If this flag is set, contents of types configured in a super-sitemap will be created in the sub-sitemap (if the user
* creates them from the sub-sitemap).
*
* @return the "create contents locally" flag
*/
public boolean isCreateContentsLocally() {
return m_data.isCreateContentsLocally();
}
/**
* Returns the value of the "discard inherited model pages" flag.<p>
*
* If this flag is set, inherited model pages will be discarded for this sitemap.<p>
*
* @return the "discard inherited model pages" flag
*/
public boolean isDiscardInheritedModelPages() {
return m_data.isDiscardInheritedModelPages();
}
/**
* Returns the value of the "discard inherited properties" flag.<p>
*
* If this is flag is set, inherited property definitions will be discarded for this sitemap.<p>
*
* @return the "discard inherited properties" flag.<p>
*/
public boolean isDiscardInheritedProperties() {
return m_data.isDiscardInheritedProperties();
}
/**
* Returns the value of the "discard inherited types" flag.<p>
*
* If this flag is set, inherited resource types from a super-sitemap will be discarded for this sitemap.<p>
*
* @return the "discard inherited types" flag
*/
public boolean isDiscardInheritedTypes() {
return m_data.isDiscardInheritedTypes();
}
/**
* True if detail contents outside this sitemap should not be rendered in detail pages from this sitemap.
*
* @return true if detail contents outside this sitemap should not be rendered in detail pages from this sitemap.
*/
public boolean isExcludeExternalDetailContents() {
return m_data.isExcludeExternalDetailContents();
}
/**
* Returns true if the subsite should be included in the site selector.
*
* @return true if the subsite should be included in the site selector
*/
public boolean isIncludeInSiteSelector() {
return m_configSequence.getConfig().isIncludeInSiteSelector();
}
/**
* Returns true if this is a module configuration instead of a normal sitemap configuration.<p>
*
* @return true if this is a module configuration
*/
public boolean isModuleConfiguration() {
return m_data.isModuleConfig();
}
/**
* Returns true if detail pages from this sitemap should be preferred for links to contents in this sitemap.<p>
*
* @return true if detail pages from this sitemap should be preferred for links to contents in this sitemap
*/
public boolean isPreferDetailPagesForLocalContents() {
return m_data.isPreferDetailPagesForLocalContents();
}
/**
* Checks if any formatter with the given JSP id has the 'search content' option set to true.
*
* @param jspId the structure id of a formatter JSP
* @return true if any of the formatters
*/
public boolean isSearchContentFormatter(CmsUUID jspId) {
for (I_CmsFormatterBean formatter : getFormattersByJspId().get(jspId)) {
if (formatter.isSearchContent()) {
return true;
}
}
return false;
}
/**
* Returns true if the new container page format, which uses formatter keys (but also is different in other ways from the new format
*
* @return true if formatter keys should be used
*/
public boolean isUseFormatterKeys() {
Boolean result = m_data.getUseFormatterKeys();
if (result != null) {
LOG.debug("isUseFormatterKeys - found value " + result + " at " + getBasePath());
return result.booleanValue();
}
CmsADEConfigData parent = parent();
if (parent != null) {
return parent.isUseFormatterKeys();
}
boolean defaultValue = false;
LOG.debug("isUseFormatterKeys - using defaultValue " + defaultValue);
return defaultValue;
}
/**
* Fetches the parent configuration of this configuration.<p>
*
* If this configuration is a sitemap configuration with no direct parent configuration,
* the module configuration will be returned. If this configuration already is a module configuration,
* null will be returned.<p>
*
* @return the parent configuration
*/
public CmsADEConfigData parent() {
Optional<CmsADEConfigurationSequence> parentPath = m_configSequence.getParent();
if (parentPath.isPresent()) {
CmsADEConfigDataInternal internalData = parentPath.get().getConfig();
return new CmsADEConfigData(internalData, m_cache, parentPath.get());
} else {
return null;
}
}
/**
* Creates the content directory for this configuration node if possible.<p>
*
* @throws CmsException if something goes wrong
*/
protected void createContentDirectory() throws CmsException {
if (!isModuleConfiguration()) {
String contentFolder = getContentFolderPath();
if (!getCms().existsResource(contentFolder)) {
getCms().createResource(
contentFolder,
OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolder.getStaticTypeName()));
}
}
}
/**
* Gets the CMS object used for VFS operations.<p>
*
* @return the CMS object used for VFS operations
*/
protected CmsObject getCms() {
return m_cache.getCms();
}
/**
* Gets the CMS object used for VFS operations.<p>
*
* @return the CMS object
*/
protected CmsObject getCmsObject() {
return getCms();
}
/**
* Helper method to converts a list of detail pages to a map from type names to lists of detail pages for each type.<p>
*
* @param detailPages the list of detail pages
*
* @return the map of detail pages
*/
protected Map<String, List<CmsDetailPageInfo>> getDetailPagesMap(List<CmsDetailPageInfo> detailPages) {
Map<String, List<CmsDetailPageInfo>> result = Maps.newHashMap();
for (CmsDetailPageInfo detailpage : detailPages) {
String type = detailpage.getType();
if (!result.containsKey(type)) {
result.put(type, new ArrayList<CmsDetailPageInfo>());
}
result.get(type).add(detailpage);
}
return result;
}
/**
* Collects the folder types in a map.<p>
*
* @return the map of folder types
*
* @throws CmsException if something goes wrong
*/
protected Map<String, String> getFolderTypes() throws CmsException {
Map<String, String> result = new HashMap<String, String>();
CmsObject cms = OpenCms.initCmsObject(getCms());
if (m_data.isModuleConfig()) {
Set<String> siteRoots = OpenCms.getSiteManager().getSiteRoots();
for (String siteRoot : siteRoots) {
cms.getRequestContext().setSiteRoot(siteRoot);
for (CmsResourceTypeConfig config : getResourceTypes()) {
if (!config.isDetailPagesDisabled()) {
String typeName = config.getTypeName();
if (!config.isPageRelative()) { // elements stored with container pages can not be used as detail contents
String folderPath = config.getFolderPath(cms, null);
result.put(CmsStringUtil.joinPaths(folderPath, "/"), typeName);
}
}
}
}
} else {
for (CmsResourceTypeConfig config : getResourceTypes()) {
if (!config.isDetailPagesDisabled()) {
String typeName = config.getTypeName();
if (!config.isPageRelative()) { // elements stored with container pages can not be used as detail contents
String folderPath = config.getFolderPath(getCms(), null);
result.put(CmsStringUtil.joinPaths(folderPath, "/"), typeName);
}
}
}
}
return result;
}
/**
* Gets the formatter configuration for a resource type.<p>
*
* @param cms the current CMS context
* @param resType the resource type
* @param schemaFormatters the resource schema formatters
*
* @return the configuration of formatters for the resource type
*/
protected CmsFormatterConfiguration getFormatters(
CmsObject cms,
I_CmsResourceType resType,
CmsFormatterConfiguration schemaFormatters) {
String typeName = resType.getTypeName();
CmsFormatterConfigurationCacheState formatterCacheState = getCachedFormatters();
List<I_CmsFormatterBean> formatters = new ArrayList<I_CmsFormatterBean>();
Set<String> types = new HashSet<String>();
types.add(typeName);
for (CmsFormatterChangeSet changeSet : getFormatterChangeSets()) {
if (changeSet != null) {
changeSet.applyToTypes(types);
}
}
if ((schemaFormatters != null) && types.contains(typeName)) {
for (I_CmsFormatterBean formatter : schemaFormatters.getAllFormatters()) {
formatters.add(formatter);
}
}
Map<CmsUUID, I_CmsFormatterBean> externalFormattersById = Maps.newHashMap();
for (I_CmsFormatterBean formatter : formatterCacheState.getFormattersForType(typeName, true)) {
externalFormattersById.put(new CmsUUID(formatter.getId()), formatter);
}
applyAllFormatterChanges(externalFormattersById, formatterCacheState);
for (I_CmsFormatterBean formatter : externalFormattersById.values()) {
if (formatter.getResourceTypeNames().contains(typeName)) {
formatters.add(formatter);
}
}
return CmsFormatterConfiguration.create(cms, formatters);
}
/**
* Gets the formatters from the schema.<p>
*
* @param cms the current CMS context
* @param res the resource for which the formatters should be retrieved
*
* @return the formatters from the schema
*/
protected CmsFormatterConfiguration getFormattersFromSchema(CmsObject cms, CmsResource res) {
try {
return OpenCms.getResourceManager().getResourceType(res.getTypeId()).getFormattersForResource(cms, res);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
return CmsFormatterConfiguration.EMPTY_CONFIGURATION;
}
}
/**
* Internal method for getting the function references.<p>
*
* @return the function references
*/
protected List<CmsFunctionReference> internalGetFunctionReferences() {
CmsADEConfigData parentData = parent();
if ((parentData == null)) {
if (m_data.isModuleConfig()) {
return Collections.unmodifiableList(m_data.getFunctionReferences());
} else {
return Lists.newArrayList();
}
} else {
return parentData.internalGetFunctionReferences();
}
}
/**
* Helper method for getting the list of resource types.<p>
*
* @param filterDisabled true if disabled types should be filtered from the result
*
* @return the list of resource types
*/
protected List<CmsResourceTypeConfig> internalGetResourceTypes(boolean filterDisabled) {
CmsADEConfigData parentData = parent();
List<CmsResourceTypeConfig> parentResourceTypes = null;
if (parentData == null) {
parentResourceTypes = Lists.newArrayList();
} else {
parentResourceTypes = Lists.newArrayList();
for (CmsResourceTypeConfig typeConfig : parentData.internalGetResourceTypes(false)) {
CmsResourceTypeConfig copiedType = typeConfig.copy(m_data.isDiscardInheritedTypes());
parentResourceTypes.add(copiedType);
}
}
List<CmsResourceTypeConfig> result = combineConfigurationElements(
parentResourceTypes,
m_data.getOwnResourceTypes(),
true);
if (m_data.isCreateContentsLocally()) {
for (CmsResourceTypeConfig typeConfig : result) {
typeConfig.updateBasePath(
CmsStringUtil.joinPaths(m_data.getBasePath(), CmsADEManager.CONTENT_FOLDER_NAME));
}
}
if (filterDisabled) {
Iterator<CmsResourceTypeConfig> iter = result.iterator();
while (iter.hasNext()) {
CmsResourceTypeConfig typeConfig = iter.next();
if (typeConfig.isDisabled()) {
iter.remove();
}
}
}
if (getTypeOrderingMode() == CmsTypeOrderingMode.byDisplayOrder) {
Collections.sort(result, (a, b) -> Integer.compare(a.getOrder(), b.getOrder()));
}
return result;
}
/**
* Merges two lists of detail pages, one from a parent configuration and one from a child configuration.<p>
*
* @param parentDetailPages the parent's detail pages
* @param ownDetailPages the child's detail pages
*
* @return the merged detail pages
*/
protected List<CmsDetailPageInfo> mergeDetailPages(
List<CmsDetailPageInfo> parentDetailPages,
List<CmsDetailPageInfo> ownDetailPages) {
List<CmsDetailPageInfo> parentDetailPageCopies = Lists.newArrayList();
for (CmsDetailPageInfo info : parentDetailPages) {
parentDetailPageCopies.add(info.copyAsInherited());
}
List<CmsDetailPageInfo> result = new ArrayList<CmsDetailPageInfo>();
Map<String, List<CmsDetailPageInfo>> resultDetailPageMap = Maps.newHashMap();
resultDetailPageMap.putAll(getDetailPagesMap(parentDetailPageCopies));
resultDetailPageMap.putAll(getDetailPagesMap(ownDetailPages));
result = new ArrayList<CmsDetailPageInfo>();
for (List<CmsDetailPageInfo> pages : resultDetailPageMap.values()) {
result.addAll(pages);
}
return result;
}
/**
* Helper method to correct paths in detail page beans if the corresponding resources have been moved.<p>
*
* @param detailPages the original list of detail pages
*
* @return the corrected list of detail pages
*/
protected List<CmsDetailPageInfo> updateUris(List<CmsDetailPageInfo> detailPages) {
List<CmsDetailPageInfo> result = new ArrayList<CmsDetailPageInfo>();
for (CmsDetailPageInfo page : detailPages) {
CmsUUID structureId = page.getId();
try {
String rootPath = OpenCms.getADEManager().getRootPath(
structureId,
getCms().getRequestContext().getCurrentProject().isOnlineProject());
String iconClasses;
if (page.getType().startsWith(CmsDetailPageInfo.FUNCTION_PREFIX)) {
iconClasses = CmsIconUtil.getIconClasses(CmsXmlDynamicFunctionHandler.TYPE_FUNCTION, null, false);
} else {
iconClasses = CmsIconUtil.getIconClasses(page.getType(), null, false);
}
CmsDetailPageInfo correctedPage = new CmsDetailPageInfo(
structureId,
rootPath,
page.getType(),
iconClasses);
result.add(page.isInherited() ? correctedPage.copyAsInherited() : correctedPage);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
return result;
}
/**
* Gets a multimap of active formatters for which a formatter key is defined, with the formatter keys as map keys.
*
* @return the map of active formatters by key
*/
private Multimap<String, I_CmsFormatterBean> getActiveFormattersByKey() {
if (m_activeFormattersByKey == null) {
ArrayListMultimap<String, I_CmsFormatterBean> activeFormattersByKey = ArrayListMultimap.create();
for (I_CmsFormatterBean formatter : getActiveFormatters().values()) {
if (formatter.getKey() != null) {
activeFormattersByKey.put(formatter.getKey(), formatter);
}
}
m_activeFormattersByKey = activeFormattersByKey;
}
return m_activeFormattersByKey;
}
private String getFormatterLabel(I_CmsFormatterBean formatter) {
return formatter.getLocation() != null ? formatter.getLocation() : formatter.getId();
}
/**
* Gets formatters by JSP id.
*
* @return the multimap from JSP id to formatter beans
*/
private Multimap<CmsUUID, I_CmsFormatterBean> getFormattersByJspId() {
if (m_formattersByJspId == null) {
ArrayListMultimap<CmsUUID, I_CmsFormatterBean> formattersByJspId = ArrayListMultimap.create();
for (I_CmsFormatterBean formatter : getCachedFormatters().getFormatters().values()) {
formattersByJspId.put(formatter.getJspStructureId(), formatter);
}
m_formattersByJspId = formattersByJspId;
}
return m_formattersByJspId;
}
/**
* Gets a multimap of the formatters for which a formatter key is defined, with the formatter keys as map keys.
*
* @return the map of formatters by key
*/
private Multimap<String, I_CmsFormatterBean> getFormattersByKey() {
if (m_formattersByKey == null) {
ArrayListMultimap<String, I_CmsFormatterBean> formattersByKey = ArrayListMultimap.create();
for (I_CmsFormatterBean formatter : getCachedFormatters().getFormatters().values()) {
if (formatter.getKey() != null) {
formattersByKey.put(formatter.getKey(), formatter);
}
}
m_formattersByKey = formattersByKey;
}
return m_formattersByKey;
}
}
|
package org.opencms.jsp.util;
import org.opencms.ade.configuration.CmsADEConfigData;
import org.opencms.ade.configuration.CmsADEManager;
import org.opencms.ade.configuration.CmsFunctionReference;
import org.opencms.ade.detailpage.CmsDetailPageInfo;
import org.opencms.ade.detailpage.CmsDetailPageResourceHandler;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.flex.CmsFlexController;
import org.opencms.flex.CmsFlexRequest;
import org.opencms.jsp.CmsJspBean;
import org.opencms.jsp.Messages;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.CmsRuntimeException;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsUUID;
import org.opencms.xml.containerpage.CmsContainerBean;
import org.opencms.xml.containerpage.CmsContainerElementBean;
import org.opencms.xml.containerpage.CmsContainerPageBean;
import org.opencms.xml.containerpage.CmsDynamicFunctionBean;
import org.opencms.xml.containerpage.CmsDynamicFunctionParser;
import org.opencms.xml.containerpage.CmsFormatterBean;
import org.opencms.xml.containerpage.CmsFormatterConfiguration;
import org.opencms.xml.content.CmsXmlContent;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletRequest;
import org.apache.commons.logging.Log;
import com.google.common.base.Function;
import com.google.common.collect.MapMaker;
/**
* Allows convenient access to the most important OpenCms functions on a JSP page,
* indented to be used from a JSP with the JSTL or EL.<p>
*
* This bean is available by default in the context of an OpenCms managed JSP.<p>
*
* @since 8.0
*/
public final class CmsJspStandardContextBean {
/** The attribute name of the cms object.*/
public static final String ATTRIBUTE_CMS_OBJECT = "__cmsObject";
/** The attribute name of the standard JSP context bean. */
public static final String ATTRIBUTE_NAME = "cms";
/** The logger instance for this class. */
protected static final Log LOG = CmsLog.getLog(CmsJspStandardContextBean.class);
/** OpenCms user context. */
protected CmsObject m_cms;
/** The container the currently rendered element is part of. */
private CmsContainerBean m_container;
/** The current detail content resource if available. */
private CmsResource m_detailContentResource;
/** Flag to indicate if element was just edited. */
private boolean m_edited;
/** The currently rendered element. */
private CmsContainerElementBean m_element;
/** Cached object for the EL 'function' accessor. */
private Object m_function;
/** The currently displayed container page. */
private CmsContainerPageBean m_page;
/** The VFS content access bean. */
private CmsJspVfsAccessBean m_vfsBean;
/**
* Creates an empty instance.<p>
*/
private CmsJspStandardContextBean() {
// NOOP
}
/**
* Creates a new standard JSP context bean.
*
* @param req the current servlet request
*/
private CmsJspStandardContextBean(ServletRequest req) {
CmsFlexController controller = CmsFlexController.getController(req);
CmsObject cms;
if (controller != null) {
cms = controller.getCmsObject();
} else {
cms = (CmsObject)req.getAttribute(ATTRIBUTE_CMS_OBJECT);
}
if (cms == null) {
// cms object unavailable - this request was not initialized properly
throw new CmsRuntimeException(Messages.get().container(
Messages.ERR_MISSING_CMS_CONTROLLER_1,
CmsJspBean.class.getName()));
}
updateCmsObject(cms);
m_detailContentResource = CmsDetailPageResourceHandler.getDetailResource(req);
}
/**
* Creates a new instance of the standard JSP context bean.<p>
*
* To prevent multiple creations of the bean during a request, the OpenCms request context
* attributes are used to cache the created VFS access utility bean.<p>
*
* @param req the current servlet request
*
* @return a new instance of the standard JSP context bean
*/
public static CmsJspStandardContextBean getInstance(ServletRequest req) {
Object attribute = req.getAttribute(ATTRIBUTE_NAME);
CmsJspStandardContextBean result;
if ((attribute != null) && (attribute instanceof CmsJspStandardContextBean)) {
result = (CmsJspStandardContextBean)attribute;
} else {
result = new CmsJspStandardContextBean(req);
req.setAttribute(ATTRIBUTE_NAME, result);
}
return result;
}
/**
* Returns a copy of this JSP context bean.<p>
*
* @return a copy of this JSP context bean
*/
public CmsJspStandardContextBean createCopy() {
CmsJspStandardContextBean result = new CmsJspStandardContextBean();
result.m_container = getContainer();
if (getDetailContent() != null) {
result.m_detailContentResource = getDetailContent().getCopy();
}
result.m_element = getElement();
result.m_page = getPage();
return result;
}
/**
* Returns a caching hash specific to the element, it's properties and the current container width.<p>
*
* @return the caching hash
*/
public String elementCachingHash() {
if ((m_element != null) && (m_container != null)) {
return m_element.editorHash()
+ "w:"
+ m_container.getWidth()
+ "cName:"
+ m_container.getName()
+ "cType:"
+ m_container.getType();
}
return "";
}
/**
* Returns the container the currently rendered element is part of.<p>
*
* @return the currently the currently rendered element is part of
*/
public CmsContainerBean getContainer() {
return m_container;
}
/**
* Returns the current detail content, or <code>null</code> if no detail content is requested.<p>
*
* @return the current detail content, or <code>null</code> if no detail content is requested.<p>
*/
public CmsResource getDetailContent() {
return m_detailContentResource;
}
/**
* Returns the structure id of the current detail content, or <code>null</code> if no detail content is requested.<p>
*
* @return the structure id of the current detail content, or <code>null</code> if no detail content is requested.<p>
*/
public CmsUUID getDetailContentId() {
return m_detailContentResource == null ? null : m_detailContentResource.getStructureId();
}
/**
* Returns the detail content site path. Returns <code>null</code> if not available.<p>
*
* @return the detail content site path
*/
public String getDetailContentSitePath() {
return ((m_cms == null) || (m_detailContentResource == null))
? null
: m_cms.getSitePath(m_detailContentResource);
}
/**
* Returns the currently rendered element.<p>
*
* @return the currently rendered element
*/
public CmsContainerElementBean getElement() {
return m_element;
}
/**
* Returns a map which allows access to dynamic function beans using the JSP EL.<p>
*
* When given a key, the returned map will look up the corresponding dynamic function in the module configuration.<p>
*
* @return a map which allows access to dynamic function beans
*/
public Object getFunction() {
if (m_function != null) {
return m_function;
}
MapMaker mm = new MapMaker();
m_function = mm.makeComputingMap(new Function<String, Object>() {
public Object apply(String key) {
try {
CmsDynamicFunctionBean dynamicFunction = readDynamicFunctionBean(key);
CmsDynamicFunctionBeanWrapper wrapper = new CmsDynamicFunctionBeanWrapper(m_cms, dynamicFunction);
return wrapper;
} catch (CmsException e) {
return new CmsDynamicFunctionBeanWrapper(m_cms, null);
}
}
});
return m_function;
}
/**
* Returns a lazy map which computes the detail page link as a value when given the name of a (named) dynamic function
* as a key.<p>
*
* @return a lazy map for computing function detail page links
*/
public Map<String, String> getFunctionDetail() {
MapMaker mm = new MapMaker();
return mm.makeComputingMap(new Function<String, String>() {
public String apply(String key) {
String detailType = CmsDetailPageInfo.FUNCTION_PREFIX + key;
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(
m_cms,
m_cms.addSiteRoot(m_cms.getRequestContext().getUri()));
List<CmsDetailPageInfo> detailPages = config.getDetailPagesForType(detailType);
if ((detailPages == null) || (detailPages.size() == 0)) {
return "";
}
CmsDetailPageInfo mainDetailPage = detailPages.get(0);
CmsUUID id = mainDetailPage.getId();
CmsResource detailRes;
try {
detailRes = m_cms.readResource(id);
return OpenCms.getLinkManager().substituteLink(m_cms, detailRes);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
return "";
}
}
});
}
/**
* Returns a lazy map which creates a wrapper object for a dynamic function format when given an XML content
* as a key.<p>
*
* @return a lazy map for accessing function formats for a content
*/
public Map<CmsJspContentAccessBean, CmsDynamicFunctionFormatWrapper> getFunctionFormatFromContent() {
MapMaker mm = new MapMaker();
return mm.makeComputingMap(new Function<CmsJspContentAccessBean, CmsDynamicFunctionFormatWrapper>() {
public CmsDynamicFunctionFormatWrapper apply(CmsJspContentAccessBean contentAccess) {
CmsXmlContent content = (CmsXmlContent)(contentAccess.getRawContent());
CmsDynamicFunctionParser parser = new CmsDynamicFunctionParser();
CmsDynamicFunctionBean functionBean = null;
try {
functionBean = parser.parseFunctionBean(m_cms, content);
} catch (CmsException e) {
return new CmsDynamicFunctionFormatWrapper(m_cms, null);
}
String type = getContainer().getType();
String width = getContainer().getWidth();
int widthNum = -1;
try {
widthNum = Integer.parseInt(width);
} catch (NumberFormatException e) {
// NOOP
}
CmsDynamicFunctionBean.Format format = functionBean.getFormatForContainer(m_cms, type, widthNum);
CmsDynamicFunctionFormatWrapper wrapper = new CmsDynamicFunctionFormatWrapper(m_cms, format);
return wrapper;
}
});
}
/**
* Returns the current locale.<p>
*
* @return the current locale
*/
public Locale getLocale() {
return getRequestContext().getLocale();
}
/**
* Returns the currently displayed container page.<p>
*
* @return the currently displayed container page
*/
public CmsContainerPageBean getPage() {
return m_page;
}
/**
* JSP EL accessor method for retrieving the preview formatters.<p>
*
* @return a lazy map for accessing preview formatters
*/
public Map<String, String> getPreviewFormatter() {
MapMaker mm = new MapMaker();
return mm.makeComputingMap(new Function<String, String>() {
public String apply(String uri) {
try {
String rootPath = m_cms.getRequestContext().addSiteRoot(uri);
CmsResource resource = m_cms.readResource(uri);
CmsADEManager adeManager = OpenCms.getADEManager();
CmsADEConfigData configData = adeManager.lookupConfiguration(m_cms, rootPath);
CmsFormatterConfiguration formatterConfig = configData.getFormatters(m_cms, resource);
if (formatterConfig == null) {
return "";
}
CmsFormatterBean previewFormatter = formatterConfig.getPreviewFormatter();
if (previewFormatter == null) {
return "";
}
CmsUUID structureId = previewFormatter.getJspStructureId();
m_cms.readResource(structureId);
CmsResource formatterResource = m_cms.readResource(structureId);
String formatterSitePath = m_cms.getRequestContext().removeSiteRoot(formatterResource.getRootPath());
return formatterSitePath;
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
return "";
}
}
});
}
/**
* Returns the request context.<p>
*
* @return the request context
*/
public CmsRequestContext getRequestContext() {
return m_cms.getRequestContext();
}
/**
* Returns the subsite path for the currently requested URI.<p>
*
* @return the subsite path
*/
public String getSubSitePath() {
return m_cms.getRequestContext().removeSiteRoot(
OpenCms.getADEManager().getSubSiteRoot(m_cms, m_cms.getRequestContext().getRootUri()));
}
/**
* Returns an initialized VFS access bean.<p>
*
* @return an initialized VFS access bean
*/
public CmsJspVfsAccessBean getVfs() {
if (m_vfsBean == null) {
// create a new VVFS access bean
m_vfsBean = CmsJspVfsAccessBean.create(m_cms);
}
return m_vfsBean;
}
/**
* Returns the workplace locale from the current user's settings.<p>
*
* @return returns the workplace locale from the current user's settings
*/
public Locale getWorkplaceLocale() {
return OpenCms.getWorkplaceManager().getWorkplaceLocale(m_cms);
}
/**
* Checks whether a detail page is available for the container element.<p>
*
* @return true if there is a detail page for the container element
*/
public boolean isDetailPageAvailable() {
if (m_cms == null) {
return false;
}
CmsContainerElementBean element = getElement();
if (element == null) {
return false;
}
if (element.isInMemoryOnly()) {
return false;
}
CmsResource res = element.getResource();
if (res == null) {
return false;
}
try {
String detailPage = OpenCms.getADEManager().getDetailPageFinder().getDetailPage(
m_cms,
res.getRootPath(),
m_cms.getRequestContext().getUri());
return detailPage != null;
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
return false;
}
}
/**
* Returns <code>true</code> if this is a request to a detail resource, <code>false</code> otherwise.<p>
*
* Same as to check if {@link #getDetailContent()} is <code>null</code>.<p>
*
* @return <code>true</code> if this is a request to a detail resource, <code>false</code> otherwise
*/
public boolean isDetailRequest() {
return m_detailContentResource != null;
}
/**
* Returns the flag to indicate if in drag and drop mode.<p>
*
* @return <code>true</code> if in drag and drop mode
*/
public boolean isEdited() {
return m_edited;
}
/**
* Sets the container the currently rendered element is part of.<p>
*
* @param container the container the currently rendered element is part of
*/
public void setContainer(CmsContainerBean container) {
m_container = container;
}
/**
* Sets the flag to indicate if in drag and drop mode.<p>
*
* @param edited <code>true</code> if in drag and drop mode
*/
public void setEdited(boolean edited) {
m_edited = edited;
}
/**
* Sets the currently rendered element.<p>
*
* @param element the currently rendered element to set
*/
public void setElement(CmsContainerElementBean element) {
m_element = element;
}
/**
* Sets the currently displayed container page.<p>
*
* @param page the currently displayed container page to set
*/
public void setPage(CmsContainerPageBean page) {
m_page = page;
}
/**
* Updates the internally stored OpenCms user context.<p>
*
* @param cms the new OpenCms user context
*/
public void updateCmsObject(CmsObject cms) {
try {
m_cms = OpenCms.initCmsObject(cms);
} catch (CmsException e) {
// should not happen
m_cms = cms;
}
}
/**
* Updates the standard context bean from the request.<p>
*
* @param cmsFlexRequest the request from which to update the data
*/
public void updateRequestData(CmsFlexRequest cmsFlexRequest) {
CmsResource detailRes = CmsDetailPageResourceHandler.getDetailResource(cmsFlexRequest);
m_detailContentResource = detailRes;
}
/**
* Reads a dynamic function bean, given its name in the module configuration.<p>
*
* @param configuredName the name of the dynamic function in the module configuration
* @return the dynamic function bean for the dynamic function configured under that name
*
* @throws CmsException if something goes wrong
*/
protected CmsDynamicFunctionBean readDynamicFunctionBean(String configuredName) throws CmsException {
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(
m_cms,
m_cms.addSiteRoot(m_cms.getRequestContext().getUri()));
CmsFunctionReference functionRef = config.getFunctionReference(configuredName);
if (functionRef == null) {
return null;
}
CmsDynamicFunctionParser parser = new CmsDynamicFunctionParser();
CmsResource functionResource = m_cms.readResource(functionRef.getStructureId());
CmsDynamicFunctionBean result = parser.parseFunctionBean(m_cms, functionResource);
return result;
}
}
|
package org.pentaho.di.core.plugins;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.annotations.JobEntry;
import org.pentaho.di.core.exception.KettlePluginException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* This plugin type handles the job entries.
*
* @author matt
*
*/
@PluginTypeCategoriesOrder(getNaturalCategoriesOrder={"BaseStep.Category.Input",
"JobCategory.Category.General"
,"JobCategory.Category.Mail"
,"JobCategory.Category.FileManagement"
,"JobCategory.Category.Conditions"
,"JobCategory.Category.Scripting"
,"JobCategory.Category.BulkLoading"
,"JobCategory.Category.XML"
,"JobCategory.Category.Repository"
,"JobCategory.Category.FileTransfer"
,"JobCategory.Category.Experimental"},
i18nPackageClass = JobMeta.class)
@PluginMainClassType(JobEntryInterface.class)
public class JobEntryPluginType extends BasePluginType implements PluginTypeInterface {
private static Class<?> PKG = JobMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
public static final String GENERAL_CATEGORY = BaseMessages.getString(PKG, "JobCategory.Category.General");
private static JobEntryPluginType pluginType;
private JobEntryPluginType() {
super("JOBENTRY", "Job entry");
pluginFolders.add( new PluginFolder(Const.PLUGIN_DIRECTORY_PUBLIC, false, true) );
pluginFolders.add( new PluginFolder(Const.PLUGIN_DIRECTORY_PRIVATE, false, true) );
pluginFolders.add( new PluginFolder(Const.PLUGIN_JOBENTRIES_DIRECTORY_PUBLIC, true, false) );
pluginFolders.add( new PluginFolder(Const.PLUGIN_JOBENTRIES_DIRECTORY_PRIVATE, true, false) );
}
public static JobEntryPluginType getInstance() {
if (pluginType==null) {
pluginType=new JobEntryPluginType();
}
return pluginType;
}
/**
* Let's put in code here to search for the step plugins..
*/
public void searchPlugins() throws KettlePluginException {
registerNatives();
registerAnnotations();
registerPluginJars();
registerXmlPlugins();
}
/**
* Scan & register internal step plugins
*/
protected void registerNatives() throws KettlePluginException {
// Scan the native steps...
String kettleJobEntriesXmlFile = Const.XML_FILE_KETTLE_JOB_ENTRIES;
// Load the plugins for this file...
try {
InputStream inputStream = getClass().getResourceAsStream(kettleJobEntriesXmlFile);
if (inputStream==null) {
inputStream = getClass().getResourceAsStream("/"+kettleJobEntriesXmlFile);
}
if (inputStream==null) {
throw new KettlePluginException("Unable to find native step definition file: "+Const.XML_FILE_KETTLE_JOB_ENTRIES);
}
Document document = XMLHandler.loadXMLFile(inputStream, null, true, false);
// Document document = XMLHandler.loadXMLFile(kettleStepsXmlFile);
Node entriesNode = XMLHandler.getSubNode(document, "job-entries");
List<Node> entryNodes = XMLHandler.getNodes(entriesNode, "job-entry");
for (Node entryNode : entryNodes) {
registerPluginFromXmlResource(entryNode, null, this.getClass());
}
} catch (KettleXMLException e) {
throw new KettlePluginException("Unable to read the kettle job entries XML config file: "+kettleJobEntriesXmlFile, e);
}
}
/**
* Scan & register internal job entry plugins
*/
protected void registerAnnotations() throws KettlePluginException {
List<Class<?>> classes = getAnnotatedClasses(JobEntry.class);
for (Class<?> clazz : classes)
{
JobEntry jobEntry = clazz.getAnnotation(JobEntry.class);
handleJobEntryAnnotation(clazz, jobEntry, new ArrayList<String>(), true);
}
}
private void handleJobEntryAnnotation(Class<?> clazz, JobEntry jobEntry, List<String> libraries, boolean nativeJobEntry) throws KettlePluginException {
// Only one ID for now
String[] ids = new String[] { jobEntry.id(), };
if (ids.length == 1 && Const.isEmpty(ids[0])) {
throw new KettlePluginException("No ID specified for plugin with class: "+clazz.getName());
}
// The package name to get the descriptions or tool tip from...
String packageName = jobEntry.i18nPackageName();
if (Const.isEmpty(packageName)) packageName = JobEntryInterface.class.getPackage().getName();
// An alternative package to get the description or tool tip from...
String altPackageName = clazz.getPackage().getName();
// Determine the i18n descriptions of the step description (name), tool tip and category
String name = getTranslation(jobEntry.name(), packageName, altPackageName, clazz);
String description = getTranslation(jobEntry.description(), packageName, altPackageName, clazz);
String category = getTranslation(jobEntry.categoryDescription(), packageName, altPackageName, clazz);
// Register this step plugin...
Map<Class<?>, String> classMap = new HashMap<Class<?>, String>();
classMap.put(JobEntryInterface.class, clazz.getName());
PluginClassTypes classTypesAnnotation = clazz.getAnnotation(PluginClassTypes.class);
if(classTypesAnnotation != null){
for(int i=0; i< classTypesAnnotation.classTypes().length; i++){
Class<?> classType = classTypesAnnotation.classTypes()[i];
Class<?> implementationType = (classTypesAnnotation.implementationClass().length > i) ? classTypesAnnotation.implementationClass()[i] : null;
String className = implementationType.getName();
classMap.put(classType, className);
}
}
PluginInterface stepPlugin = new Plugin(ids, this.getClass(), JobEntryInterface.class, category, name, description, jobEntry.image(), false, nativeJobEntry, classMap, libraries, null);
registry.registerPlugin(this.getClass(), stepPlugin);
}
/**
* Scan jar files in a set of plugin folders. Open these jar files and scan for annotations if they are labeled for annotation scanning.
*
* @throws KettlePluginException in case something goes horribly wrong
*/
protected void registerPluginJars() throws KettlePluginException {
List<JarFileAnnotationPlugin> jarFilePlugins = findAnnotatedClassFiles(JobEntry.class.getName());
for (JarFileAnnotationPlugin jarFilePlugin : jarFilePlugins) {
URLClassLoader urlClassLoader = new KettleURLClassLoader(new URL[] { jarFilePlugin.getJarFile(), }, getClass().getClassLoader());
try {
Class<?> clazz = urlClassLoader.loadClass(jarFilePlugin.getClassFile().getName());
JobEntry jobEntry = clazz.getAnnotation(JobEntry.class);
List<String> libraries = new ArrayList<String>();
libraries.add(jarFilePlugin.getJarFile().getFile());
handleJobEntryAnnotation(clazz, jobEntry, libraries, false);
} catch(ClassNotFoundException e) {
// Ignore for now, don't know if it's even possible.
}
}
}
protected void registerXmlPlugins() throws KettlePluginException {
for (PluginFolderInterface folder : pluginFolders) {
if (folder.isPluginXmlFolder()) {
List<FileObject> pluginXmlFiles = findPluginXmlFiles(folder.getFolder());
for (FileObject file : pluginXmlFiles) {
try {
Document document = XMLHandler.loadXMLFile(file);
Node pluginNode = XMLHandler.getSubNode(document, "plugin");
registerPluginFromXmlResource(pluginNode, KettleVFS.getFilename(file.getParent()), this.getClass());
} catch(Exception e) {
// We want to report this plugin.xml error, perhaps an XML typo or something like that...
log.logError("Error found while reading job entry plugin.xml file: "+file.getName().toString(), e);
}
}
}
}
}
}
|
package org.swellrt.server.box.servlet;
import com.google.inject.Inject;
import org.waveprotocol.box.server.account.AccountData;
import org.waveprotocol.box.server.account.HumanAccountData;
import org.waveprotocol.box.server.account.SecretToken;
import org.waveprotocol.box.server.authentication.PasswordDigest;
import org.waveprotocol.box.server.authentication.SessionManager;
import org.waveprotocol.box.server.persistence.AccountStore;
import org.waveprotocol.box.server.persistence.PersistenceException;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PasswordService extends SwellRTService {
public static final String ID = "id";
public static final String TOKEN_OR_PASSWORD = "token-or-password";
public static final String NEW_PASSWORD = "new-password";
private final AccountStore accountStore;
@Inject
public PasswordService(SessionManager sessionManager, AccountStore accountStore) {
super(sessionManager);
this.accountStore = accountStore;
}
@Override
public void execute(HttpServletRequest req, HttpServletResponse response) throws IOException {
ParticipantId participantId = sessionManager.getLoggedInUser(req.getSession(false));
if (participantId == null) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
Enumeration<String> paramNames = req.getParameterNames();
if (!paramNames.hasMoreElements()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No parameters found!");
return;
}
String id = req.getParameter(ID);
String tokenOrPassword = req.getParameter(TOKEN_OR_PASSWORD);
String newPassword = req.getParameter(NEW_PASSWORD);
if (id == null || tokenOrPassword == null || newPassword == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required parameters");
}
try {
ParticipantId pId = new ParticipantId(id);
if (pId.isAnonymous()) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "User is anonymous");
return;
}
AccountData a = accountStore.getAccount(pId);
if (a != null) {
HumanAccountData account = a.asHuman();
SecretToken storedToken = account.getRecoveryToken();
if ((storedToken != null && storedToken.isActive() && storedToken.getToken().equals(
tokenOrPassword))
|| account.getPasswordDigest().verify(tokenOrPassword.toCharArray())) {
// Change the original account object to preserve all acount data
// during DB update.
account.setPasswordDigest(new PasswordDigest(newPassword.toCharArray()));
// Reset the token anyway
account.setRecoveryToken((String) null);
accountStore.putAccount(account);
response.setStatus(HttpServletResponse.SC_OK);
} else {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
} catch (PersistenceException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
|
package peergos.shared.user.fs;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.user.*;
import peergos.shared.util.*;
import java.io.*;
import java.util.concurrent.*;
public class LazyInputStreamCombiner implements AsyncReader {
private final UserContext context;
private final SymmetricKey dataKey;
private final ProgressConsumer<Long> monitor;
private final long totalLength;
private final byte[] original;
private final Location originalNext;
private long globalIndex = 0;
private byte[] current;
private int index;
private Location next;
public LazyInputStreamCombiner(FileRetriever stream, UserContext context, SymmetricKey dataKey, byte[] chunk, long totalLength, ProgressConsumer<Long> monitor) {
if (chunk == null)
throw new IllegalStateException("Null initial chunk!");
this.context = context;
this.dataKey = dataKey;
this.current = chunk;
this.index = 0;
this.next = stream.getNext();
this.totalLength = totalLength;
this.monitor = monitor;
this.original = chunk;
this.originalNext = next;
}
public CompletableFuture<byte[]> getNextStream(int len) {
if (this.next != null) {
Location nextLocation = this.next;
return context.getMetadata(nextLocation).thenCompose(meta -> {
if (!meta.isPresent()) {
CompletableFuture<byte[]> err = new CompletableFuture<>();
err.completeExceptionally(new EOFException());
return err;
}
FileRetriever nextRet = meta.get().retriever();
this.next = nextRet.getNext();
return nextRet.getChunkInputStream(context, dataKey, 0, len, nextLocation, monitor)
.thenApply(x -> x.get().chunk.data());
});
}
CompletableFuture<byte[]> err = new CompletableFuture<>();
err.completeExceptionally(new EOFException());
return err;
}
private CompletableFuture skip(long skip) {
long available = (long) bytesReady();
if (skip <= available) {
index = (int) skip;
return CompletableFuture.completedFuture(true);
}
long toRead = Math.min(available, skip);
globalIndex += toRead;
int remainingToRead = totalLength - globalIndex > Chunk.MAX_SIZE ? Chunk.MAX_SIZE : (int) (totalLength - globalIndex);
return getNextStream(remainingToRead)
.thenCompose(x -> skip(skip - remainingToRead));
}
@Override
public CompletableFuture<Boolean> seek(int hi32, int low32) {
long seek = ((long) (hi32) << 32) | low32;
if (totalLength < seek)
throw new IllegalStateException("Cannot seek to position "+ seek);
globalIndex = 0;
return reset()
.thenCompose(x -> skip(seek));
}
public int bytesReady() {
return this.current.length - this.index;
}
public void close() {}
public CompletableFuture<Boolean> reset() {
index = 0;
current = original;
next = originalNext;
return CompletableFuture.completedFuture(true);
}
/**
*
* @param res array to store data in
* @param offset initial index to store data in res
* @param length number of bytes to read
* @return number of bytes read
*/
public CompletableFuture<Integer> readIntoArray(byte[] res, int offset, int length) {
int available = bytesReady();
int toRead = Math.min(available, length);
System.arraycopy(current, index, res, offset, toRead);
globalIndex += toRead;
if (available >= length) // we are done
return CompletableFuture.completedFuture(length);
if (globalIndex >= totalLength) {
CompletableFuture<Integer> err= new CompletableFuture<>();
err.completeExceptionally(new EOFException());
return err;
}
int remainingToRead = totalLength - globalIndex > Chunk.MAX_SIZE ? Chunk.MAX_SIZE : (int) (totalLength - globalIndex);
return getNextStream(remainingToRead).thenCompose(nextChunk -> {
current = nextChunk;
index = 0;
return readIntoArray(res, offset + toRead, length - toRead).thenApply(bytesRead -> bytesRead + toRead);
});
}
}
|
package com.illposed.osc;
import com.illposed.osc.argument.ArgumentHandler;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class OSCSerializer {
private final ByteBuffer output;
/**
* Cache for Java classes of which we know, that we have no argument handler
* that supports serializing them.
*/
private final Set<Class> unsupportedTypes;
/**
* Cache for Java classes that are sub-classes of a supported argument handlers Java class,
* mapped to that base class.
* This does not include base classes
* (Java classes directly supported by one of our argument handlers).
*/
private final Map<Class, Class> subToSuperTypes;
/**
* For each base-class, indicates whether it is a marker-only type.
* @see ArgumentHandler#isMarkerOnly()
*/
private final Map<Class, Boolean> classToMarker;
/**
* Maps supported Java class to argument-handlers for all our non-marker-only base-classes.
* @see ArgumentHandler#isMarkerOnly()
*/
private final Map<Class, ArgumentHandler> classToType;
/**
* Maps values to argument-handlers for all our marker-only base-classes.
* @see ArgumentHandler#isMarkerOnly()
*/
private final Map<Object, ArgumentHandler> markerValueToType;
public OSCSerializer(final List<ArgumentHandler> types, final ByteBuffer output) {
final Map<Class, Boolean> classToMarkerTmp = new HashMap<Class, Boolean>(types.size());
final Map<Class, ArgumentHandler> classToTypeTmp = new HashMap<Class, ArgumentHandler>();
final Map<Object, ArgumentHandler> markerValueToTypeTmp = new HashMap<Object, ArgumentHandler>();
for (final ArgumentHandler type : types) {
final Class typeJava = type.getJavaClass();
final Boolean registeredIsMarker = classToMarkerTmp.get(typeJava);
if ((registeredIsMarker != null) && (registeredIsMarker != type.isMarkerOnly())) {
throw new IllegalStateException(ArgumentHandler.class.getSimpleName()
+ " implementations disagree on the marker nature of their class: "
+ typeJava);
}
classToMarkerTmp.put(typeJava, type.isMarkerOnly());
if (type.isMarkerOnly()) {
try {
final Object markerValue = type.parse(null);
final ArgumentHandler previousType = markerValueToTypeTmp.get(markerValue);
if (previousType != null) {
throw new IllegalStateException("Marker value \"" + markerValue
+ "\" is already used for type "
+ previousType.getClass().getCanonicalName());
}
markerValueToTypeTmp.put(markerValue, type);
} catch (final OSCParseException ex) {
throw new IllegalStateException("Developper error; this should never happen",
ex);
}
} else {
final ArgumentHandler previousType = classToTypeTmp.get(typeJava);
if (previousType != null) {
throw new IllegalStateException("Java argument type "
+ typeJava.getCanonicalName() + " is already used for type "
+ previousType.getClass().getCanonicalName());
}
classToTypeTmp.put(typeJava, type);
}
}
this.output = output;
// usually, we should not need a stack size of 16, which is the default initial size
this.unsupportedTypes = new HashSet<Class>(4);
this.subToSuperTypes = new HashMap<Class, Class>(4);
this.classToMarker = Collections.unmodifiableMap(classToMarkerTmp);
this.classToType = Collections.unmodifiableMap(classToTypeTmp);
this.markerValueToType = Collections.unmodifiableMap(markerValueToTypeTmp);
}
public Map<Class, ArgumentHandler> getClassToTypeMapping() {
return classToType;
}
public static byte[] toByteArray(final ByteBuffer buffer) {
final byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
return bytes;
}
/**
* Terminates the previously written piece of data with a single {@code (byte) '0'}.
* We always need to terminate with a zero, especially when the stream is already aligned.
* @param output to receive the data-piece termination
*/
public static void terminate(final ByteBuffer output) {
output.put((byte) 0);
}
/**
* Align a buffer by padding it with {@code (byte) '0'}s so it has a size divisible by 4.
* @param output to be aligned
*/
public static void align(final ByteBuffer output) {
final int alignmentOverlap = output.position() % 4;
final int padLen = (4 - alignmentOverlap) % 4;
for (int pci = 0; pci < padLen; pci++) {
output.put((byte) 0);
}
}
/**
* Terminates the previously written piece of data with a single {@code (byte) '0'},
* and then aligns the stream by padding it with {@code (byte) '0'}s so it has a size
* divisible by 4.
* We always need to terminate with a zero, especially when the stream is already aligned.
* @param output to receive the data-piece termination and alignment
*/
public static void terminateAndAlign(final ByteBuffer output) {
terminate(output);
align(output);
}
private void write(final OSCBundle bundle) throws OSCSerializeException {
write("#bundle");
write(bundle.getTimestamp());
for (final OSCPacket pkg : bundle.getPackets()) {
writeSizeAndData(pkg);
}
}
/**
* Serializes a messages address.
* @param message the address of this message will be serialized
* @throws OSCSerializeException if the message failed to serialize
*/
private void writeAddress(final OSCMessage message) throws OSCSerializeException {
final String address = message.getAddress();
if (!OSCMessage.isValidAddress(address)) {
throw new OSCSerializeException("Can not serialize a message with invalid address: \""
+ address + "\"");
}
write(address);
}
/**
* Serializes the arguments of a message.
* @param message the arguments of this message will be serialized
* @throws OSCSerializeException if the message arguments failed to serialize
*/
private void writeArguments(final OSCMessage message) throws OSCSerializeException {
output.put(OSCParser.TYPES_VALUES_SEPARATOR);
writeTypeTags(message.getArguments());
for (final Object argument : message.getArguments()) {
write(argument);
}
}
private void write(final OSCMessage message) throws OSCSerializeException {
writeAddress(message);
writeArguments(message);
}
/**
* Converts the packet into its OSC compliant byte array representation,
* then writes the number of bytes to the stream, followed by the actual data bytes.
* @param packet to be converted and written to the stream
* @throws OSCSerializeException if the packet failed to serialize
*/
private void writeSizeAndData(final OSCPacket packet) throws OSCSerializeException {
final int sizePosition = output.position();
write(Integer.valueOf(-1)); // write place-holder size
writePacket(packet);
final int afterPacketPosition = output.position();
final int packetSize = afterPacketPosition - sizePosition - 4;
output.position(sizePosition);
write(packetSize);
output.position(afterPacketPosition);
}
private void writePacket(final OSCPacket packet) throws OSCSerializeException {
if (packet instanceof OSCBundle) {
write((OSCBundle) packet);
} else if (packet instanceof OSCMessage) {
write((OSCMessage) packet);
} else {
throw new UnsupportedOperationException("We do not support writing packets of type: "
+ packet.getClass());
}
}
public void write(final OSCPacket packet) throws OSCSerializeException {
output.rewind();
writePacket(packet);
}
/**
* Write only the type tags for a given list of arguments.
* This is primarily used by the packet dispatcher.
* @param arguments to write the type tags from
* @throws OSCSerializeException if the arguments failed to serialize
*/
public void writeOnlyTypeTags(final List<?> arguments) throws OSCSerializeException {
output.rewind();
writeTypeTagsRaw(arguments);
}
private Set<ArgumentHandler> findSuperTypes(final Class argumentClass) {
final Set<ArgumentHandler> matchingSuperTypes = new HashSet<ArgumentHandler>();
// check all base-classes, for whether our argument-class is a sub-class
// of any of them
for (final Map.Entry<Class, ArgumentHandler> baseClassAndType
: classToType.entrySet())
{
final Class<?> baseClass = baseClassAndType.getKey();
if ((baseClass != Object.class)
&& baseClass.isAssignableFrom(argumentClass))
{
matchingSuperTypes.add(baseClassAndType.getValue());
}
}
return matchingSuperTypes;
}
private Class findSuperType(final Class argumentClass) throws OSCSerializeException {
Class superType;
// check if we already found the base-class for this argument-class before
superType = subToSuperTypes.get(argumentClass);
// ... if we did not, ...
if ((superType == null)
// check if we already know this argument-class to not be supported
&& !unsupportedTypes.contains(argumentClass))
{
final Set<ArgumentHandler> matchingSuperTypes = findSuperTypes(argumentClass);
if (matchingSuperTypes.isEmpty()) {
unsupportedTypes.add(argumentClass);
} else {
if (matchingSuperTypes.size() > 1) {
System.out.println("WARNING: Java class "
+ argumentClass.getCanonicalName()
+ " is a sub-class of multiple supported argument types:");
for (final ArgumentHandler matchingSuperType : matchingSuperTypes) {
System.out.println('\t'
+ matchingSuperType.getJavaClass().getCanonicalName()
+ " (supported by "
+ matchingSuperType.getClass().getCanonicalName()
+ ')');
}
}
final ArgumentHandler matchingSuperType = matchingSuperTypes.iterator().next();
System.out.println("INFO: Java class "
+ argumentClass.getCanonicalName()
+ " will be mapped to "
+ matchingSuperType.getJavaClass().getCanonicalName()
+ " (supported by "
+ matchingSuperType.getClass().getCanonicalName()
+ ')');
final Class matchingSuperClass = matchingSuperType.getJavaClass();
subToSuperTypes.put(argumentClass, matchingSuperClass);
superType = matchingSuperClass;
}
}
if (superType == null) {
throw new OSCSerializeException("No type handler registered for serializing class "
+ argumentClass.getCanonicalName());
}
return superType;
}
private ArgumentHandler findType(final Object argumentValue, final Class argumentClass)
throws OSCSerializeException
{
final ArgumentHandler type;
final Boolean markerType = classToMarker.get(argumentClass);
if (markerType == null) {
type = findType(argumentValue, findSuperType(argumentClass));
} else if (markerType) {
type = markerValueToType.get(argumentValue);
} else {
type = classToType.get(argumentClass);
}
return type;
}
private ArgumentHandler findType(final Object argumentValue) throws OSCSerializeException {
return findType(argumentValue, extractTypeClass(argumentValue));
}
/**
* Write an object into the byte stream.
* @param anObject (usually) one of Float, Double, String, Character, Integer, Long,
* or a Collection of these.
* See {@link #getClassToTypeMapping()} for a complete list of which classes may be used here.
* @throws OSCSerializeException if the argument object failed to serialize
*/
@SuppressWarnings("unchecked")
private void write(final Object anObject) throws OSCSerializeException {
if (anObject instanceof Collection) {
@SuppressWarnings("unchecked") final Collection<Object> theArray = (Collection<Object>) anObject;
for (final Object entry : theArray) {
write(entry);
}
} else {
final ArgumentHandler type = findType(anObject);
type.serialize(output, anObject);
}
}
private static Class extractTypeClass(final Object value) {
return (value == null) ? Object.class : value.getClass();
}
/**
* Write the OSC specification type tag for the type a certain Java type
* converts to.
* @param value of this argument, we need to write the type identifier
* @throws OSCSerializeException if the value failed to serialize
*/
private void writeType(final Object value) throws OSCSerializeException {
final ArgumentHandler type = findType(value);
output.put((byte) type.getDefaultIdentifier());
}
/**
* Write the type tags for a given list of arguments.
* @param arguments array of base Objects
* @throws OSCSerializeException if the arguments failed to serialize
*/
private void writeTypeTagsRaw(final List<?> arguments) throws OSCSerializeException
{
for (final Object argument : arguments) {
if (argument instanceof List) {
@SuppressWarnings("unchecked") final List<?> argumentsArray = (List<?>) argument;
// This is used for nested arguments.
// open the array
output.put((byte) OSCParser.TYPE_ARRAY_BEGIN);
// fill the [] with the nested argument types
writeTypeTagsRaw(argumentsArray);
// close the array
output.put((byte) OSCParser.TYPE_ARRAY_END);
} else {
// write a single, simple arguments type
writeType(argument);
}
}
}
/**
* Write the type tags for a given list of arguments, and cleanup the stream.
* @param arguments the arguments to an OSCMessage
* @throws OSCSerializeException if the arguments failed to serialize
*/
private void writeTypeTags(final List<?> arguments) throws OSCSerializeException {
writeTypeTagsRaw(arguments);
terminateAndAlign(output);
}
}
|
package edu.umd.cs.findbugs.ba;
import java.util.*;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.FieldInstruction;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.MethodGen;
/**
* A ClassContext caches all of the auxiliary objects used to analyze
* the methods of a class. That way, these objects don't need to
* be created over and over again.
*
* @author David Hovemeyer
*/
public class ClassContext implements AnalysisFeatures {
/**
* We only do pruning of infeasible exception edges
* if the <code>WORK_HARD</code> analysis feature
* is enabled.
*/
public static final boolean PRUNE_INFEASIBLE_EXCEPTION_EDGES = WORK_HARD;
/**
* Only try to determine unconditional exception throwers
* if we're not trying to conserve space.
*/
public static final boolean PRUNE_UNCONDITIONAL_EXCEPTION_THROWER_EDGES =
!CONSERVE_SPACE;
public static final boolean DEBUG = Boolean.getBoolean("classContext.debug");
private static final int PRUNED_INFEASIBLE_EXCEPTIONS = 1;
private static final int PRUNED_UNCONDITIONAL_THROWERS = 2;
private static final boolean TIME_ANALYSES = Boolean.getBoolean("classContext.timeAnalyses");
private static final boolean DEBUG_CFG = Boolean.getBoolean("classContext.debugCFG");
private static int depth;
private static void indent() {
for (int i = 0; i < depth; ++i) System.out.print(" ");
}
/**
* An AnalysisResult stores the result of requesting an analysis
* from an AnalysisFactory. It can represent a successful outcome
* (where the Analysis object can be returned), or an unsuccessful
* outcome (where an exception was thrown trying to create the
* analysis). For unsuccessful outcomes, we rethrow the original
* exception rather than making another attempt to create the analysis
* (since if it fails once, it will never succeed).
*/
private static class AnalysisResult<Analysis> {
private boolean analysisSetExplicitly;
private Analysis analysis;
private AnalysisException analysisException;
private CFGBuilderException cfgBuilderException;
private DataflowAnalysisException dataflowAnalysisException;
public Analysis getAnalysis() throws CFGBuilderException, DataflowAnalysisException {
if (analysisSetExplicitly)
return analysis;
if (dataflowAnalysisException != null)
throw dataflowAnalysisException;
if (analysisException != null)
throw analysisException;
if (cfgBuilderException != null)
throw cfgBuilderException;
throw new IllegalStateException();
}
/**
* Record a successful outcome, where the analysis was created.
*
* @param analysis the Analysis
*/
public void setAnalysis(Analysis analysis) {
this.analysisSetExplicitly = true;
this.analysis = analysis;
}
/**
* Record that an AnalysisException occurred while attempting
* to create the Analysis.
*
* @param analysisException the AnalysisException
*/
public void setAnalysisException(AnalysisException analysisException) {
this.analysisException = analysisException;
}
/**
* Record that a CFGBuilderException occurred while attempting
* to create the Analysis.
*
* @param cfgBuilderException the CFGBuilderException
*/
public void setCFGBuilderException(CFGBuilderException cfgBuilderException) {
this.cfgBuilderException = cfgBuilderException;
}
/**
* Record that a DataflowAnalysisException occurred while attempting
* to create the Analysis.
*
* @param dataflowException the DataflowAnalysisException
*/
public void setDataflowAnalysisException(DataflowAnalysisException dataflowException) {
this.dataflowAnalysisException = dataflowException;
}
}
/**
* Abstract factory class for creating analysis objects.
* Handles caching of analysis results for a method.
*/
private abstract class AnalysisFactory <Analysis> {
private String analysisName;
private HashMap<Method, ClassContext.AnalysisResult<Analysis>> map =
new HashMap<Method, ClassContext.AnalysisResult<Analysis>>();
/**
* Constructor.
*
* @param analysisName name of the analysis factory: for diagnostics/debugging
*/
public AnalysisFactory(String analysisName) {
this.analysisName = analysisName;
}
/**
* Get the Analysis for given method.
* If Analysis has already been performed, the cached result is
* returned.
*
* @param method the method to analyze
* @return the Analysis object representing the result of analyzing the method
* @throws CFGBuilderException if the CFG can't be constructed for the method
* @throws DataflowAnalysisException if dataflow analysis fails on the method
*/
public Analysis getAnalysis(Method method) throws CFGBuilderException, DataflowAnalysisException {
AnalysisResult<Analysis> result = map.get(method);
if (result == null) {
if (TIME_ANALYSES) {
++depth;
indent();
System.out.println("CC: Starting " + analysisName + " for " +
SignatureConverter.convertMethodSignature(jclass, method) + ":");
}
long begin = System.currentTimeMillis();
// Create a new AnalysisResult
result = new AnalysisResult<Analysis>();
// Attempt to create the Analysis and store it in the AnalysisResult.
// If an exception occurs, record it in the AnalysisResult.
Analysis analysis = null;
try {
analysis = analyze(method);
result.setAnalysis(analysis);
} catch (CFGBuilderException e) {
result.setCFGBuilderException(e);
} catch (DataflowAnalysisException e) {
if (TIME_ANALYSES) {
long end = System.currentTimeMillis();
indent();
System.out.println("CC: " + analysisName + " killed by exception after " +
(end - begin) + " millis");
e.printStackTrace();
--depth;
}
result.setDataflowAnalysisException(e);
} catch (AnalysisException e) {
result.setAnalysisException(e);
}
if (TIME_ANALYSES) {
long end = System.currentTimeMillis();
indent();
System.out.println("CC: finished " + analysisName + " in " + (end - begin) + " millis");
--depth;
}
// Cache the outcome of this analysis attempt.
map.put(method, result);
}
return result.getAnalysis();
}
protected abstract Analysis analyze(Method method)
throws CFGBuilderException, DataflowAnalysisException;
}
private abstract class NoExceptionAnalysisFactory <AnalysisResult> extends AnalysisFactory<AnalysisResult> {
public NoExceptionAnalysisFactory(String analysisName) {
super(analysisName);
}
public AnalysisResult getAnalysis(Method method) {
try {
return super.getAnalysis(method);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException("Should not happen");
} catch (CFGBuilderException e) {
throw new IllegalStateException("Should not happen");
}
}
}
private abstract class NoDataflowAnalysisFactory <AnalysisResult> extends AnalysisFactory<AnalysisResult> {
public NoDataflowAnalysisFactory(String analysisName) {
super(analysisName);
}
public AnalysisResult getAnalysis(Method method) throws CFGBuilderException {
try {
return super.getAnalysis(method);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException("Should not happen");
}
}
}
private static final Set<String> busyCFGSet = new HashSet<String>();
private class CFGFactory extends AnalysisFactory<CFG> {
public CFGFactory() {
super("CFG construction");
}
public CFG getAnalysis(Method method) throws CFGBuilderException {
try {
return super.getAnalysis(method);
} catch (DataflowAnalysisException e) {
throw new IllegalStateException("Should not happen");
}
}
public CFG getRawCFG(Method method) throws CFGBuilderException {
return getAnalysis(method);
}
public CFG getRefinedCFG(Method method) throws CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
CFG cfg = getRawCFG(method);
// HACK:
// Due to recursive method invocations, we may get a recursive
// request for the pruned CFG of a method. In this case,
// we just return the raw CFG.
String methodId = methodGen.getClassName() + "." + methodGen.getName() + ":" + methodGen.getSignature();
if (DEBUG_CFG) {
indent();
System.out.println("CC: getting refined CFG for " + methodId);
}
if (DEBUG) System.out.println("ClassContext: request to prune " + methodId);
if (!busyCFGSet.add(methodId))
return cfg;
if (PRUNE_INFEASIBLE_EXCEPTION_EDGES && !cfg.isFlagSet(PRUNED_INFEASIBLE_EXCEPTIONS)) {
try {
TypeDataflow typeDataflow = getTypeDataflow(method);
new PruneInfeasibleExceptionEdges(cfg, getMethodGen(method), typeDataflow).execute();
} catch (DataflowAnalysisException e) {
// FIXME: should report the error
} catch (ClassNotFoundException e) {
getLookupFailureCallback().reportMissingClass(e);
}
}
cfg.setFlags(cfg.getFlags() | PRUNED_INFEASIBLE_EXCEPTIONS);
if (PRUNE_UNCONDITIONAL_EXCEPTION_THROWER_EDGES && !cfg.isFlagSet(PRUNED_UNCONDITIONAL_THROWERS)) {
try {
new PruneUnconditionalExceptionThrowerEdges(methodGen, cfg, getConstantPoolGen(), analysisContext).execute();
} catch (DataflowAnalysisException e) {
// FIXME: should report the error
}
}
cfg.setFlags(cfg.getFlags() | PRUNED_UNCONDITIONAL_THROWERS);
busyCFGSet.remove(methodId);
return cfg;
}
protected CFG analyze(Method method) throws CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
CFGBuilder cfgBuilder = CFGBuilderFactory.create(methodGen);
cfgBuilder.build();
return cfgBuilder.getCFG();
}
}
private JavaClass jclass;
private AnalysisContext analysisContext;
private NoExceptionAnalysisFactory<MethodGen> methodGenFactory =
new NoExceptionAnalysisFactory<MethodGen>("MethodGen construction") {
protected MethodGen analyze(Method method) {
if (method.getCode() == null)
return null;
return new MethodGen(method, jclass.getClassName(), getConstantPoolGen());
}
};
private CFGFactory cfgFactory = new CFGFactory();
private AnalysisFactory<ValueNumberDataflow> vnaDataflowFactory =
new AnalysisFactory<ValueNumberDataflow>("value number analysis") {
protected ValueNumberDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
LoadedFieldSet loadedFieldSet = getLoadedFieldSet(method);
ValueNumberAnalysis analysis = new ValueNumberAnalysis(methodGen, dfs, loadedFieldSet,
getLookupFailureCallback());
CFG cfg = getCFG(method);
ValueNumberDataflow vnaDataflow = new ValueNumberDataflow(cfg, analysis);
vnaDataflow.execute();
return vnaDataflow;
}
};
private AnalysisFactory<IsNullValueDataflow> invDataflowFactory =
new AnalysisFactory<IsNullValueDataflow>("null value analysis") {
protected IsNullValueDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
CFG cfg = getCFG(method);
ValueNumberDataflow vnaDataflow = getValueNumberDataflow(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
AssertionMethods assertionMethods = getAssertionMethods();
IsNullValueAnalysis invAnalysis = new IsNullValueAnalysis(methodGen, cfg, vnaDataflow, dfs, assertionMethods);
IsNullValueDataflow invDataflow = new IsNullValueDataflow(cfg, invAnalysis);
invDataflow.execute();
return invDataflow;
}
};
private AnalysisFactory<TypeDataflow> typeDataflowFactory =
new AnalysisFactory<TypeDataflow>("type analysis") {
protected TypeDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
CFG cfg = getRawCFG(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
ExceptionSetFactory exceptionSetFactory = getExceptionSetFactory(method);
TypeAnalysis typeAnalysis =
new TypeAnalysis(methodGen, cfg, dfs, getLookupFailureCallback(), exceptionSetFactory);
TypeDataflow typeDataflow = new TypeDataflow(cfg, typeAnalysis);
typeDataflow.execute();
return typeDataflow;
}
};
private NoDataflowAnalysisFactory<DepthFirstSearch> dfsFactory =
new NoDataflowAnalysisFactory<DepthFirstSearch>("depth first search") {
protected DepthFirstSearch analyze(Method method) throws CFGBuilderException {
CFG cfg = getRawCFG(method);
DepthFirstSearch dfs = new DepthFirstSearch(cfg);
dfs.search();
return dfs;
}
};
private NoDataflowAnalysisFactory<ReverseDepthFirstSearch> rdfsFactory =
new NoDataflowAnalysisFactory<ReverseDepthFirstSearch>("reverse depth first search") {
protected ReverseDepthFirstSearch analyze(Method method) throws CFGBuilderException {
CFG cfg = getRawCFG(method);
ReverseDepthFirstSearch rdfs = new ReverseDepthFirstSearch(cfg);
rdfs.search();
return rdfs;
}
};
private NoExceptionAnalysisFactory<BitSet> bytecodeSetFactory =
new NoExceptionAnalysisFactory<BitSet>("bytecode set construction") {
protected BitSet analyze(Method method) {
final BitSet result = new BitSet();
Code code = method.getCode();
if (code != null) {
byte[] instructionList = code.getCode();
// Create a callback to put the opcodes of the method's
// bytecode instructions into the BitSet.
BytecodeScanner.Callback callback = new BytecodeScanner.Callback() {
public void handleInstruction(int opcode, int index) {
result.set(opcode, true);
}
};
// Scan the method.
BytecodeScanner scanner = new BytecodeScanner();
scanner.scan(instructionList, callback);
}
return result;
}
};
/*
private AnalysisFactory<LockCountDataflow> anyLockCountDataflowFactory =
new AnalysisFactory<LockCountDataflow>("lock count analysis (any lock)") {
protected LockCountDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
ValueNumberDataflow vnaDataflow = getValueNumberDataflow(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
CFG cfg = getCFG(method);
AnyLockCountAnalysis analysis = new AnyLockCountAnalysis(methodGen, vnaDataflow, dfs);
LockCountDataflow dataflow = new LockCountDataflow(cfg, analysis);
dataflow.execute();
return dataflow;
}
};
*/
private AnalysisFactory<LockDataflow> lockDataflowFactory =
new AnalysisFactory<LockDataflow>("lock set analysis") {
protected LockDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
MethodGen methodGen = getMethodGen(method);
ValueNumberDataflow vnaDataflow = getValueNumberDataflow(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
CFG cfg = getCFG(method);
LockAnalysis analysis = new LockAnalysis(methodGen, vnaDataflow, dfs);
LockDataflow dataflow = new LockDataflow(cfg, analysis);
dataflow.execute();
return dataflow;
}
};
private AnalysisFactory<ReturnPathDataflow> returnPathDataflowFactory =
new AnalysisFactory<ReturnPathDataflow>("return path analysis") {
protected ReturnPathDataflow analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
ReturnPathAnalysis analysis = new ReturnPathAnalysis(dfs);
ReturnPathDataflow dataflow = new ReturnPathDataflow(cfg, analysis);
dataflow.execute();
return dataflow;
}
};
private AnalysisFactory<DominatorsAnalysis> nonExceptionDominatorsAnalysisFactory =
new AnalysisFactory<DominatorsAnalysis>("non-exception dominators analysis") {
protected DominatorsAnalysis analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
DominatorsAnalysis analysis = new DominatorsAnalysis(cfg, dfs, true);
Dataflow<java.util.BitSet, DominatorsAnalysis> dataflow =
new Dataflow<java.util.BitSet, DominatorsAnalysis>(cfg, analysis);
dataflow.execute();
return analysis;
}
};
private AnalysisFactory<PostDominatorsAnalysis> nonExceptionPostDominatorsAnalysisFactory =
new AnalysisFactory<PostDominatorsAnalysis>("non-exception postdominators analysis") {
protected PostDominatorsAnalysis analyze(Method method) throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
ReverseDepthFirstSearch rdfs = getReverseDepthFirstSearch(method);
PostDominatorsAnalysis analysis = new PostDominatorsAnalysis(cfg, rdfs, true);
Dataflow<java.util.BitSet, PostDominatorsAnalysis> dataflow =
new Dataflow<java.util.BitSet, PostDominatorsAnalysis>(cfg, analysis);
dataflow.execute();
return analysis;
}
};
private NoExceptionAnalysisFactory<ExceptionSetFactory> exceptionSetFactoryFactory =
new NoExceptionAnalysisFactory<ExceptionSetFactory>("exception set factory") {
protected ExceptionSetFactory analyze(Method method) {
return new ExceptionSetFactory();
}
};
private NoExceptionAnalysisFactory<String[]> parameterSignatureListFactory =
new NoExceptionAnalysisFactory<String[]>("parameter signature list factory") {
protected String[] analyze(Method method) {
SignatureParser parser = new SignatureParser(method.getSignature());
ArrayList<String> resultList = new ArrayList<String>();
for (Iterator<String> i = parser.parameterSignatureIterator(); i.hasNext();) {
resultList.add(i.next());
}
return resultList.toArray(new String[resultList.size()]);
}
};
private static final BitSet fieldInstructionOpcodeSet = new BitSet();
static {
fieldInstructionOpcodeSet.set(Constants.GETFIELD);
fieldInstructionOpcodeSet.set(Constants.PUTFIELD);
fieldInstructionOpcodeSet.set(Constants.GETSTATIC);
fieldInstructionOpcodeSet.set(Constants.PUTSTATIC);
}
/**
* Factory to determine which fields are loaded and stored
* by the instructions in a method, and the overall method.
* The main purpose is to support efficient redundant load elimination
* and forward substitution in ValueNumberAnalysis (there is no need to
* remember stores of fields that are never read,
* or loads of fields that are only loaded in one location).
* However, it might be useful for other kinds of analysis.
*
* <p> The tricky part is that in addition to fields loaded and stored
* with get/putfield and get/putstatic, we also try to figure
* out field accessed through calls to inner-class access methods.
*/
private NoExceptionAnalysisFactory<LoadedFieldSet> loadedFieldSetFactory =
new NoExceptionAnalysisFactory<LoadedFieldSet>("loaded field set factory") {
protected LoadedFieldSet analyze(Method method) {
MethodGen methodGen = getMethodGen(method);
InstructionList il = methodGen.getInstructionList();
LoadedFieldSet loadedFieldSet = new LoadedFieldSet(methodGen);
for (InstructionHandle handle = il.getStart(); handle != null; handle = handle.getNext()) {
Instruction ins = handle.getInstruction();
short opcode = ins.getOpcode();
try {
if (opcode == Constants.INVOKESTATIC) {
INVOKESTATIC inv = (INVOKESTATIC) ins;
if (Hierarchy.isInnerClassAccess(inv, getConstantPoolGen())) {
InnerClassAccess access = Hierarchy.getInnerClassAccess(inv, getConstantPoolGen());
/*
if (access == null) {
System.out.println("Missing inner class access in " +
SignatureConverter.convertMethodSignature(methodGen) + " at " +
inv);
}
*/
if (access != null) {
if (access.isLoad())
loadedFieldSet.addLoad(handle, access.getField());
else
loadedFieldSet.addStore(handle, access.getField());
}
}
} else if (fieldInstructionOpcodeSet.get(opcode)) {
boolean isLoad = (opcode == Constants.GETFIELD || opcode == Constants.GETSTATIC);
XField field = Hierarchy.findXField((FieldInstruction) ins, getConstantPoolGen());
if (field != null) {
if (isLoad)
loadedFieldSet.addLoad(handle, field);
else
loadedFieldSet.addStore(handle, field);
}
}
} catch (ClassNotFoundException e) {
analysisContext.getLookupFailureCallback().reportMissingClass(e);
}
}
return loadedFieldSet;
}
};
private AnalysisFactory<LiveLocalStoreDataflow> liveLocalStoreDataflowFactory =
new AnalysisFactory<LiveLocalStoreDataflow>("live local stores analysis") {
protected LiveLocalStoreDataflow analyze(Method method)
throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
MethodGen methodGen = getMethodGen(method);
ReverseDepthFirstSearch rdfs = getReverseDepthFirstSearch(method);
LiveLocalStoreAnalysis analysis = new LiveLocalStoreAnalysis(methodGen, rdfs);
LiveLocalStoreDataflow dataflow = new LiveLocalStoreDataflow(cfg, analysis);
dataflow.execute();
return dataflow;
}
};
private AnalysisFactory<Dataflow<BlockType, BlockTypeAnalysis>> blockTypeDataflowFactory =
new AnalysisFactory<Dataflow<BlockType, BlockTypeAnalysis>>("block type analysis") {
protected Dataflow<BlockType, BlockTypeAnalysis> analyze(Method method)
throws DataflowAnalysisException, CFGBuilderException {
CFG cfg = getCFG(method);
DepthFirstSearch dfs = getDepthFirstSearch(method);
BlockTypeAnalysis analysis = new BlockTypeAnalysis(dfs);
Dataflow<BlockType, BlockTypeAnalysis> dataflow =
new Dataflow<BlockType, BlockTypeAnalysis>(cfg, analysis);
dataflow.execute();
return dataflow;
}
};
private ClassGen classGen;
private AssignedFieldMap assignedFieldMap;
private AssertionMethods assertionMethods;
/**
* Constructor.
*
* @param jclass the JavaClass
*/
public ClassContext(JavaClass jclass, AnalysisContext analysisContext) {
this.jclass = jclass;
this.analysisContext = analysisContext;
this.classGen = null;
this.assignedFieldMap = null;
this.assertionMethods = null;
}
/**
* Get the JavaClass.
*/
public JavaClass getJavaClass() {
return jclass;
}
/**
* Get the AnalysisContext.
*/
public AnalysisContext getAnalysisContext() {
return analysisContext;
}
/**
* Get the RepositoryLookupFailureCallback.
*
* @return the RepositoryLookupFailureCallback
*/
public RepositoryLookupFailureCallback getLookupFailureCallback() {
return analysisContext.getLookupFailureCallback();
}
/**
* Get a MethodGen object for given method.
*
* @param method the method
* @return the MethodGen object for the method, or null
* if the method has no Code attribute (and thus cannot be analyzed)
*/
public MethodGen getMethodGen(Method method) {
return methodGenFactory.getAnalysis(method);
}
/**
* Get a "raw" CFG for given method.
* No pruning is done, although the CFG may already be pruned.
*
* @param method the method
* @return the raw CFG
*/
public CFG getRawCFG(Method method) throws CFGBuilderException {
return cfgFactory.getRawCFG(method);
}
/**
* Get a CFG for given method.
* If pruning options are in effect, pruning will be done.
* Because the CFG pruning can involve interprocedural analysis,
* it is done on a best-effort basis, so the CFG returned might
* not actually be pruned.
*
* @param method the method
* @return the CFG
* @throws CFGBuilderException if a CFG cannot be constructed for the method
*/
public CFG getCFG(Method method) throws CFGBuilderException {
return cfgFactory.getRefinedCFG(method);
}
/**
* Get the ConstantPoolGen used to create the MethodGens
* for this class.
*
* @return the ConstantPoolGen
*/
public ConstantPoolGen getConstantPoolGen() {
if (classGen == null)
classGen = new ClassGen(jclass);
return classGen.getConstantPool();
}
/**
* Get a ValueNumberDataflow for given method.
*
* @param method the method
* @return the ValueNumberDataflow
*/
public ValueNumberDataflow getValueNumberDataflow(Method method) throws DataflowAnalysisException, CFGBuilderException {
return vnaDataflowFactory.getAnalysis(method);
}
/**
* Get an IsNullValueDataflow for given method.
*
* @param method the method
* @return the IsNullValueDataflow
*/
public IsNullValueDataflow getIsNullValueDataflow(Method method) throws DataflowAnalysisException, CFGBuilderException {
return invDataflowFactory.getAnalysis(method);
}
/**
* Get a TypeDataflow for given method.
*
* @param method the method
* @return the TypeDataflow
*/
public TypeDataflow getTypeDataflow(Method method) throws DataflowAnalysisException, CFGBuilderException {
return typeDataflowFactory.getAnalysis(method);
}
/**
* Get a DepthFirstSearch for given method.
*
* @param method the method
* @return the DepthFirstSearch
*/
public DepthFirstSearch getDepthFirstSearch(Method method) throws CFGBuilderException {
return dfsFactory.getAnalysis(method);
}
/**
* Get a ReverseDepthFirstSearch for given method.
*
* @param method the method
* @return the ReverseDepthFirstSearch
*/
public ReverseDepthFirstSearch getReverseDepthFirstSearch(Method method)
throws CFGBuilderException {
return rdfsFactory.getAnalysis(method);
}
/**
* Get a BitSet representing the bytecodes that are used in the given method.
* This is useful for prescreening a method for the existence of particular instructions.
* Because this step doesn't require building a MethodGen, it is very
* fast and memory-efficient. It may allow a Detector to avoid some
* very expensive analysis, which is a Big Win for the user.
*
* @param method the method
* @return the BitSet containing the opcodes which appear in the method
*/
public BitSet getBytecodeSet(Method method) {
return bytecodeSetFactory.getAnalysis(method);
}
// /**
// * Get dataflow for AnyLockCountAnalysis for given method.
// * @param method the method
// * @return the Dataflow
// */
// public LockCountDataflow getAnyLockCountDataflow(Method method)
// throws CFGBuilderException, DataflowAnalysisException {
// return anyLockCountDataflowFactory.getAnalysis(method);
/**
* Get dataflow for LockAnalysis for given method.
*
* @param method the method
* @return the LockDataflow
*/
public LockDataflow getLockDataflow(Method method)
throws CFGBuilderException, DataflowAnalysisException {
return lockDataflowFactory.getAnalysis(method);
}
/**
* Get ReturnPathDataflow for method.
*
* @param method the method
* @return the ReturnPathDataflow
*/
public ReturnPathDataflow getReturnPathDataflow(Method method)
throws CFGBuilderException, DataflowAnalysisException {
return returnPathDataflowFactory.getAnalysis(method);
}
/**
* Get DominatorsAnalysis for given method,
* where exception edges are ignored.
*
* @param method the method
* @return the DominatorsAnalysis
*/
public DominatorsAnalysis getNonExceptionDominatorsAnalysis(Method method)
throws CFGBuilderException, DataflowAnalysisException {
return nonExceptionDominatorsAnalysisFactory.getAnalysis(method);
}
/**
* Get PostDominatorsAnalysis for given method,
* where exception edges are ignored.
*
* @param method the method
* @return the PostDominatorsAnalysis
*/
public PostDominatorsAnalysis getNonExceptionPostDominatorsAnalysis(Method method)
throws CFGBuilderException, DataflowAnalysisException {
return nonExceptionPostDominatorsAnalysisFactory.getAnalysis(method);
}
/**
* Get ExceptionSetFactory for given method.
*
* @param method the method
* @return the ExceptionSetFactory
*/
public ExceptionSetFactory getExceptionSetFactory(Method method) {
return exceptionSetFactoryFactory.getAnalysis(method);
}
/**
* Get array of type signatures of parameters for given method.
*
* @param method the method
* @return an array of type signatures indicating the types
* of the method's parameters
*/
public String[] getParameterSignatureList(Method method) {
return parameterSignatureListFactory.getAnalysis(method);
}
/**
* Get the set of fields loaded by given method.
*
* @param method the method
* @return the set of fields loaded by the method
*/
public LoadedFieldSet getLoadedFieldSet(Method method) {
return loadedFieldSetFactory.getAnalysis(method);
}
/**
* Get LiveLocalStoreAnalysis dataflow for given method.
*
* @param method the method
* @return the Dataflow object for LiveLocalStoreAnalysis on the method
*/
public LiveLocalStoreDataflow getLiveLocalStoreDataflow(Method method)
throws DataflowAnalysisException, CFGBuilderException {
return liveLocalStoreDataflowFactory.getAnalysis(method);
}
/**
* Get BlockType dataflow for given method.
*
* @param method the method
* @return the Dataflow object for BlockTypeAnalysis on the method
*/
public Dataflow<BlockType, BlockTypeAnalysis> getBlockTypeDataflow(Method method)
throws DataflowAnalysisException, CFGBuilderException {
return blockTypeDataflowFactory.getAnalysis(method);
}
/**
* Get the assigned field map for the class.
*
* @return the AssignedFieldMap
* @throws ClassNotFoundException if a class lookup prevents
* the class's superclasses from being searched for
* assignable fields
*/
public AssignedFieldMap getAssignedFieldMap() throws ClassNotFoundException {
if (assignedFieldMap == null) {
assignedFieldMap = new AssignedFieldMap(this);
}
return assignedFieldMap;
}
/**
* Get AssertionMethods for class.
*
* @return the AssertionMethods
*/
public AssertionMethods getAssertionMethods() {
if (assertionMethods == null) {
assertionMethods = new AssertionMethods(jclass);
}
return assertionMethods;
}
}
// vim:ts=3
|
package io.debezium.util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
import java.util.Properties;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.debezium.annotation.Immutable;
/**
* A set of utilities for more easily performing I/O.
*/
@Immutable
public class IoUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(IoUtil.class);
/**
* Read and return the entire contents of the supplied {@link InputStream stream}. This method always closes the stream when
* finished reading.
*
* @param stream the stream to the contents; may be null
* @return the contents, or an empty byte array if the supplied reader is null
* @throws IOException if there is an error reading the content
*/
public static byte[] readBytes(InputStream stream) throws IOException {
if (stream == null) {
return new byte[]{};
}
byte[] buffer = new byte[1024];
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
int numRead = 0;
while ((numRead = stream.read(buffer)) > -1) {
output.write(buffer, 0, numRead);
}
output.flush();
return output.toByteArray();
}
}
/**
* Read and return the entire contents of the supplied {@link File file}.
*
* @param file the file containing the contents; may be null
* @return the contents, or an empty byte array if the supplied file is null
* @throws IOException if there is an error reading the content
*/
public static byte[] readBytes(File file) throws IOException {
if (file == null) {
return new byte[]{};
}
try (InputStream stream = new BufferedInputStream(new FileInputStream(file))) {
return readBytes(stream);
}
}
/**
* Read the lines from the content of the resource file at the given path on the classpath.
*
* @param resourcePath the logical path to the classpath, file, or URL resource
* @param classLoader the classloader that should be used to load the resource as a stream; may be null
* @param clazz the class that should be used to load the resource as a stream; may be null
* @param lineProcessor the function that this method calls for each line read from the supplied stream; may not be null
* @throws IOException if an I/O error occurs
*/
public static void readLines(String resourcePath, ClassLoader classLoader, Class<?> clazz, Consumer<String> lineProcessor)
throws IOException {
try (InputStream stream = IoUtil.getResourceAsStream(resourcePath, classLoader, clazz, null, null)) {
IoUtil.readLines(stream, lineProcessor);
}
}
/**
* Read the lines from the supplied stream. This function completely reads the stream and therefore closes the stream.
*
* @param stream the stream with the contents to be read; may not be null
* @param lineProcessor the function that this method calls for each line read from the supplied stream; may not be null
* @throws IOException if an I/O error occurs
*/
public static void readLines(InputStream stream, Consumer<String> lineProcessor) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
String line = null;
while ((line = reader.readLine()) != null) {
lineProcessor.accept(line);
}
}
}
/**
* Read the lines from the supplied stream. This function completely reads the stream and therefore closes the stream.
*
* @param stream the stream with the contents to be read; may not be null
* @param lineProcessor the function that this method calls for each line read from the supplied stream; may not be null
* @param charset the character set used to interpret the stream content
* @throws IOException if an I/O error occurs
*/
public static void readLines(InputStream stream, Consumer<String> lineProcessor, Charset charset) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset))) {
String line = null;
while ((line = reader.readLine()) != null) {
lineProcessor.accept(line);
}
}
}
/**
* Read the lines from the supplied stream. This function completely reads the stream and therefore closes the stream.
*
* @param path path to the file with the contents to be read; may not be null
* @param lineProcessor the function that this method calls for each line read from the supplied stream; may not be null
* @throws IOException if an I/O error occurs
*/
public static void readLines(Path path, Consumer<String> lineProcessor) throws IOException {
Files.lines(path).forEach(lineProcessor);
}
/**
* Read and return the entire contents of the supplied {@link Reader}. This method always closes the reader when finished
* reading.
*
* @param reader the reader of the contents; may be null
* @return the contents, or an empty string if the supplied reader is null
* @throws IOException if there is an error reading the content
*/
public static String read(Reader reader) throws IOException {
if (reader == null) {
return "";
}
StringBuilder sb = new StringBuilder();
try (Reader r = reader) {
int numRead = 0;
char[] buffer = new char[1024];
while ((numRead = reader.read(buffer)) > -1) {
sb.append(buffer, 0, numRead);
}
}
return sb.toString();
}
/**
* Read and return the entire contents of the supplied {@link InputStream}. This method always closes the stream when finished
* reading.
*
* @param stream the streamed contents; may be null
* @return the contents, or an empty string if the supplied stream is null
* @throws IOException if there is an error reading the content
*/
public static String read(InputStream stream) throws IOException {
return stream == null ? "" : read(new InputStreamReader(stream));
}
/**
* Read and return the entire contents of the supplied {@link InputStream}. This method always closes the stream when finished
* reading.
*
* @param stream the streamed contents; may be null
* @param charset character set of the stream data; may not be null
* @return the contents, or an empty string if the supplied stream is null
* @throws IOException if there is an error reading the content
*/
public static String read(InputStream stream,
String charset)
throws IOException {
return stream == null ? "" : read(new InputStreamReader(stream, charset));
}
/**
* Read and return the entire contents of the supplied {@link File}.
*
* @param file the file containing the information to be read; may be null
* @return the contents, or an empty string if the supplied reader is null
* @throws IOException if there is an error reading the content
*/
public static String read(File file) throws IOException {
if (file == null) {
return "";
}
StringBuilder sb = new StringBuilder();
try (Reader reader = new FileReader(file)) {
int numRead = 0;
char[] buffer = new char[1024];
while ((numRead = reader.read(buffer)) > -1) {
sb.append(buffer, 0, numRead);
}
}
return sb.toString();
}
public static InputStream getResourceAsStream(String resourcePath,
ClassLoader classLoader,
Class<?> clazz, String resourceDesc, Consumer<String> logger) {
if (resourcePath == null) {
throw new IllegalArgumentException("resourcePath may not be null");
}
if (resourceDesc == null && logger != null) {
resourceDesc = resourcePath;
}
InputStream result = null;
try {
// Try absolute path ...
Path filePath = FileSystems.getDefault().getPath(resourcePath).toAbsolutePath();
File f = filePath.toFile();
if (f.exists() && f.isFile() && f.canRead()) {
result = new BufferedInputStream(new FileInputStream(f));
}
logMessage(result, logger, resourceDesc, "on filesystem at " + filePath);
}
catch (InvalidPathException e) {
// just continue ...
}
catch (FileNotFoundException e) {
// just continue ...
}
if (result == null) {
try {
// Try relative to current working directory ...
Path current = FileSystems.getDefault().getPath(".").toAbsolutePath();
Path absolute = current.resolve(Paths.get(resourcePath)).toAbsolutePath();
File f = absolute.toFile();
if (f.exists() && f.isFile() && f.canRead()) {
result = new BufferedInputStream(new FileInputStream(f));
}
logMessage(result, logger, resourceDesc, "on filesystem relative to '" + current + "' at '" + absolute + "'");
}
catch (InvalidPathException e) {
// just continue ...
}
catch (FileNotFoundException e) {
// just continue ...
}
}
if (result == null && classLoader != null) {
// Try using the class loader ...
result = classLoader.getResourceAsStream(resourcePath);
logMessage(result, logger, resourceDesc, "on classpath");
}
if (result == null && clazz != null) {
// Not yet found, so try the class ...
result = clazz.getResourceAsStream(resourcePath);
if (result == null) {
// Not yet found, so try the class's class loader ...
result = clazz.getClassLoader().getResourceAsStream(resourcePath);
}
logMessage(result, logger, resourceDesc, "on classpath");
}
if (result == null) {
// Still not found, so try to construct a URL out of it ...
try {
URL url = new URL(resourcePath);
result = url.openStream();
logMessage(result, logger, resourceDesc, "at URL " + url.toExternalForm());
}
catch (MalformedURLException e) {
// just continue ...
}
catch (IOException err) {
// just continue ...
}
}
// May be null ...
return result;
}
/**
* Create a directory at the given absolute or relative path.
*
* @param path the relative or absolute path of the directory; may not be null
* @return the reference to the existing readable and writable directory
*/
public static File createDirectory(Path path) {
File dir = path.toAbsolutePath().toFile();
if (dir.exists() && dir.canRead() && dir.canWrite()) {
if (dir.isDirectory()) {
return dir;
}
throw new IllegalStateException("Expecting '" + path + "' to be a directory but found a file");
}
dir.mkdirs();
return dir;
}
/**
* Create a file at the given absolute or relative path.
*
* @param path the relative or absolute path of the file to create; may not be null
* @return the reference to the existing readable and writable file
*/
public static File createFile(Path path) {
File file = path.toAbsolutePath().toFile();
if (file.exists() && file.canRead() && file.canWrite()) {
if (file.isFile()) {
return file;
}
throw new IllegalStateException("Expecting '" + path + "' to be a file but found a directory");
}
file.getParentFile().mkdirs();
try {
Files.createFile(path);
}
catch (IOException e) {
throw new IllegalStateException("Unable to create the file '" + path + "': " + e.getMessage(), e);
}
return file;
}
/**
* Create a directory at the given absolute or relative path, removing any existing content beforehand.
*
* @param path the relative or absolute path of the directory to recreate; may not be null
* @param removeExistingContent true if any existing content should be removed
* @return the reference to the existing readable and writable directory
* @throws IOException if there is a problem deleting the files at this path
*/
public static File createDirectory(Path path, boolean removeExistingContent) throws IOException {
File dir = path.toAbsolutePath().toFile();
if (dir.exists() && dir.canRead() && dir.canWrite()) {
if (dir.isDirectory()) {
if (removeExistingContent) {
delete(path);
}
return dir;
}
throw new IllegalStateException("Expecting '" + path + "' to be a directory but found a file");
}
dir.mkdirs();
return dir;
}
/**
* A method that will delete a file or folder only if it is within the 'target' directory (for safety).
* Folders are removed recursively.
*
* @param path the path to the file or folder in the target directory
* @throws IOException if there is a problem deleting the file at the given path
*/
public static void delete(String path) throws IOException {
if (path != null) {
delete(Paths.get(path));
}
}
/**
* A method that will delete a file or folder. Folders are removed recursively.
*
* @param fileOrFolder the file or folder to be deleted
* @throws IOException if there is a problem deleting the file at the given path
*/
public static void delete(File fileOrFolder) throws IOException {
if (fileOrFolder != null) {
delete(fileOrFolder.toPath());
}
}
/**
* A method that will delete multiple file and/or folders. Folders are removed recursively.
*
* @param filesOrFolder the files and folders to be deleted
* @throws IOException if there is a problem deleting the file at the given path
*/
public static void delete(File... filesOrFolder) throws IOException {
for (File fileOrFolder : filesOrFolder) {
delete(fileOrFolder);
}
}
/**
* A method that will recursively delete a file or folder.
*
* @param path the path to the file or folder in the target directory
* @throws IOException if there is a problem deleting the file at the given path
*/
public static void delete(Path path) throws IOException {
if (path != null) {
if (path.toAbsolutePath().toFile().exists()) {
LOGGER.debug("Deleting '{}'...", path);
Set<FileVisitOption> options = EnumSet.noneOf(FileVisitOption.class);
int maxDepth = 10;
FileVisitor<Path> removingVisitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
java.nio.file.Files.delete(file);
return FileVisitResult.SKIP_SUBTREE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
java.nio.file.Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
LOGGER.error("Unable to remove '{}'", file.getFileName(), exc);
return FileVisitResult.CONTINUE;
}
};
java.nio.file.Files.walkFileTree(path, options, maxDepth, removingVisitor);
}
}
}
public static int getAvailablePort() {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
catch (IOException e) {
throw new IllegalStateException("Cannot find available port: " + e.getMessage(), e);
}
}
private static void logMessage(InputStream stream, Consumer<String> logger, String resourceDesc, String msg) {
if (stream != null && logger != null) {
logger.accept("Found " + resourceDesc + " " + msg);
}
}
public static Properties loadProperties(Supplier<ClassLoader> classLoader, String classpathResource) {
// This is idempotent, so we don't need to lock ...
try (InputStream stream = classLoader.get().getResourceAsStream(classpathResource)) {
Properties props = new Properties();
props.load(stream);
return props;
}
catch (IOException e) {
throw new IllegalStateException("Unable to find or read the '" + classpathResource + "' file using the " +
classLoader + " class loader", e);
}
}
public static Properties loadProperties(ClassLoader classLoader, String classpathResource) {
return loadProperties(() -> classLoader, classpathResource);
}
public static Properties loadProperties(Class<?> clazz, String classpathResource) {
return loadProperties(clazz::getClassLoader, classpathResource);
}
private IoUtil() {
// Prevent construction
}
}
|
package edu.umd.cs.findbugs.ba.obl;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class StateSet {
public interface StateCallback {
public void apply(State state) throws NonexistentObligationException;
}
private boolean isTop;
private boolean isBottom;
private Map<ObligationSet, State> stateMap;
public StateSet() {
this.isTop = this.isBottom = false;
this.stateMap = new HashMap<ObligationSet, State>();
}
public void setTop() {
this.isTop = true;
this.isBottom = false;
}
public boolean isTop() {
return isTop;
}
public void setBottom() {
this.isBottom = true;
this.isTop = false;
}
public boolean isBottom() {
return this.isBottom;
}
public boolean isValid() {
return !this.isTop && !this.isBottom;
}
/**
* Get the State which has the given ObligationSet.
* Returns null if there is no such state.
*
* @param obligationSet we want to get the State with this ObligationSet
* @return the State with the given ObligationSet, or null if there is no such State
*/
public State getStateWithObligationSet(ObligationSet obligationSet) {
return stateMap.get(obligationSet);
}
public void makeEmpty() {
this.isTop = this.isBottom = false;
this.stateMap.clear();
}
public void copyFrom(StateSet other) {
// Make this StateSet an exact copy of the given StateSet
this.isTop = other.isTop;
this.isBottom = other.isBottom;
this.stateMap.clear();
for (Iterator<State> i = other.stateMap.values().iterator(); i.hasNext(); ) {
State state = i.next();
State dup = state.duplicate();
this.stateMap.put(dup.getObligationSet(), dup);
}
}
/**
* Add an obligation to every State in the StateSet.
*
* @param obligation the obligation to add
*/
public void addObligation(final Obligation obligation) {
final Map<ObligationSet, State> updatedStateMap =
new HashMap<ObligationSet, State>();
try {
applyToAllStatesAndUpdateMap(new StateCallback() {
public void apply(State state) {
state.getObligationSet().add(obligation);
updatedStateMap.put(state.getObligationSet(), state);
}
}, updatedStateMap);
} catch (NonexistentObligationException e) {
// This can't actually happen.
}
}
/**
* Remove an Obligation from every State in the StateSet.
*
* @param obligation the obligation to remove
* @throws NonexistentObligationException
*/
public void deleteObligation(final Obligation obligation)
throws NonexistentObligationException {
final Map<ObligationSet, State> updatedStateMap =
new HashMap<ObligationSet, State>();
applyToAllStatesAndUpdateMap(new StateCallback() {
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.ba.obl.StateSet.StateCallback#apply(edu.umd.cs.findbugs.ba.obl.State)
*/
public void apply(State state)
throws NonexistentObligationException {
state.getObligationSet().remove(obligation);
updatedStateMap.put(state.getObligationSet(), state);
}
}, updatedStateMap);
}
public boolean equals(Object o) {
if (o == null || o.getClass() != this.getClass())
return false;
StateSet other = (StateSet) o;
return this.isTop == other.isTop
&& this.isBottom == other.isBottom
&& this.stateMap.equals(other.stateMap);
}
public int hashCode() {
throw new UnsupportedOperationException();
}
/**
* Apply a callback to all States and replace the
* ObligationSet -> State map with the one given
* (which is assumed to be updated by the callback.)
*
* @param callback the callback
* @param updatedStateMap updated map of ObligationSets to States
*/
public void applyToAllStatesAndUpdateMap(StateCallback callback,
Map<ObligationSet, State> updatedStateMap)
throws NonexistentObligationException {
applyToAllStates(callback);
this.stateMap = updatedStateMap;
}
/**
* Apply a callback to all States in the StateSet.
*
* @param callback
*/
public void applyToAllStates(StateCallback callback)
throws NonexistentObligationException {
for (Iterator<State> i = stateMap.values().iterator();
i.hasNext();) {
State state = i.next();
callback.apply(state);
}
}
}
// vim:ts=4
|
package edu.umd.cs.findbugs.gui2;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPInputStream;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.FontUIResource;
import javax.swing.plaf.basic.BasicTreeUI;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.text.JTextComponent;
import javax.swing.text.TextAction;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import edu.umd.cs.findbugs.BugAnnotation;
import edu.umd.cs.findbugs.BugCollection;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.ClassAnnotation;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.FindBugsDisplayFeatures;
import edu.umd.cs.findbugs.I18N;
import edu.umd.cs.findbugs.MethodAnnotation;
import edu.umd.cs.findbugs.PackageMemberAnnotation;
import edu.umd.cs.findbugs.Project;
import edu.umd.cs.findbugs.SortedBugCollection;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.SuppressionMatcher;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.SourceFinder;
import edu.umd.cs.findbugs.filter.Filter;
import edu.umd.cs.findbugs.filter.LastVersionMatcher;
import edu.umd.cs.findbugs.filter.Matcher;
import edu.umd.cs.findbugs.gui.ConsoleLogger;
import edu.umd.cs.findbugs.gui.LogSync;
import edu.umd.cs.findbugs.gui.Logger;
import edu.umd.cs.findbugs.gui2.BugTreeModel.BranchOperationException;
import edu.umd.cs.findbugs.gui2.BugTreeModel.TreeModification;
import edu.umd.cs.findbugs.sourceViewer.NavigableTextPane;
@SuppressWarnings("serial")
/*
* This is where it all happens... seriously... all of it...
* All the menus are set up, all the listeners, all the frames, dockable window functionality
* There is no one style used, no one naming convention, its all just kinda here. This is another one of those
* classes where no one knows quite why it works.
*/
/**
* The MainFrame is just that, the main application window where just about everything happens.
*/
public class MainFrame extends FBFrame implements LogSync
{
static JButton newButton(String key, String name) {
JButton b = new JButton();
edu.umd.cs.findbugs.L10N.localiseButton(b, key, name, false);
return b;
}
static JMenuItem newJMenuItem(String key, String string, int vkF) {
JMenuItem m = new JMenuItem();
edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, false);
m.setMnemonic(vkF);
return m;
}
static JMenuItem newJMenuItem(String key, String string) {
JMenuItem m = new JMenuItem();
edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, true);
return m;
}
static JMenu newJMenu(String key, String string) {
JMenu m = new JMenu();
edu.umd.cs.findbugs.L10N.localiseButton(m, key, string, true);
return m;
}
JTree tree;
private BasicTreeUI treeUI;
boolean userInputEnabled;
static boolean isMacLookAndFeel() {
return UIManager.getLookAndFeel().getClass().getName().startsWith("apple");
}
static final String DEFAULT_SOURCE_CODE_MSG = edu.umd.cs.findbugs.L10N.getLocalString("msg.nosource_txt", "No available source");
static final int COMMENTS_TAB_STRUT_SIZE = 5;
static final int COMMENTS_MARGIN = 5;
static final int SEARCH_TEXT_FIELD_SIZE = 32;
static final String TITLE_START_TXT = "FindBugs: ";
private JTextField sourceSearchTextField = new JTextField(SEARCH_TEXT_FIELD_SIZE);
private JButton findButton = newButton("button.find", "Find");
private JButton findNextButton = newButton("button.findNext", "Find Next");
private JButton findPreviousButton = newButton("button.findPrev", "Find Previous");
public static final boolean DEBUG = SystemProperties.getBoolean("gui2.debug");
static final boolean MAC_OS_X = SystemProperties.getProperty("os.name").toLowerCase().startsWith("mac os x");
final static String WINDOW_MODIFIED = "windowModified";
NavigableTextPane sourceCodeTextPane = new NavigableTextPane();
private JScrollPane sourceCodeScrollPane;
final CommentsArea comments;
private SorterTableColumnModel sorter;
private JTableHeader tableheader;
private JLabel statusBarLabel = new JLabel();
private JPanel summaryTopPanel;
private final HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
private final JEditorPane summaryHtmlArea = new JEditorPane();
private JScrollPane summaryHtmlScrollPane = new JScrollPane(summaryHtmlArea);
final private FindBugsLayoutManagerFactory findBugsLayoutManagerFactory;
final private FindBugsLayoutManager guiLayout;
/* To change this value must use setProjectChanged(boolean b).
* This is because saveProjectItemMenu is dependent on it for when
* saveProjectMenuItem should be enabled.
*/
boolean projectChanged = false;
final private JMenuItem reconfigMenuItem = newJMenuItem("menu.reconfig", "Reconfigure...", KeyEvent.VK_F);
private JMenuItem redoAnalysis;
BugLeafNode currentSelectedBugLeaf;
BugAspects currentSelectedBugAspects;
private JPopupMenu bugPopupMenu;
private JPopupMenu branchPopupMenu;
private static MainFrame instance;
private RecentMenu recentMenuCache;
private JMenu recentMenu;
private JMenuItem preferencesMenuItem;
private Project curProject = new Project();
private JScrollPane treeScrollPane;
SourceFinder sourceFinder;
private Object lock = new Object();
private boolean newProject = false;
private Class osxAdapter;
private Method osxPrefsEnableMethod;
private Logger logger = new ConsoleLogger(this);
SourceCodeDisplay displayer = new SourceCodeDisplay(this);
SaveType saveType = SaveType.NOT_KNOWN;
FBFileChooser saveOpenFileChooser;
@CheckForNull private File saveFile = null;
enum SaveReturn {SAVE_SUCCESSFUL, SAVE_IO_EXCEPTION, SAVE_ERROR};
JMenuItem saveMenuItem = newJMenuItem("menu.save_item", "Save", KeyEvent.VK_S);
static void makeInstance(FindBugsLayoutManagerFactory factory) {
if (instance != null) throw new IllegalStateException();
instance=new MainFrame(factory);
instance.initializeGUI();
}
/**
* @param string
* @param vkF
* @return
*/
static MainFrame getInstance() {
if (instance==null) throw new IllegalStateException();
return instance;
}
private void initializeGUI() {
SwingUtilities.invokeLater(new InitializeGUI());
}
private MainFrame(FindBugsLayoutManagerFactory factory)
{
this.findBugsLayoutManagerFactory = factory;
this.guiLayout = factory.getInstance(this);
this.comments = new CommentsArea(this);
FindBugsDisplayFeatures.setAbridgedMessages(true);
}
/**
* Show About
*/
void about() {
AboutDialog dialog = new AboutDialog(this, logger, true);
dialog.setSize(600, 554);
dialog.setLocationRelativeTo(this);
dialog.setVisible(true);
}
/**
* Show Preferences
*/
void preferences() {
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
PreferencesFrame.getInstance().setLocationRelativeTo(MainFrame.this);
PreferencesFrame.getInstance().setVisible(true);
}
/**
* enable/disable preferences menu
*/
void enablePreferences(boolean b) {
preferencesMenuItem.setEnabled(b);
if (MAC_OS_X) {
if (osxPrefsEnableMethod != null) {
Object args[] = {Boolean.valueOf(b)};
try {
osxPrefsEnableMethod.invoke(osxAdapter, args);
}
catch (Exception e) {
System.err.println("Exception while enabling Preferences menu: " + e);
}
}
}
}
/**
* This method is called when the application is closing. This is either by
* the exit menuItem or by clicking on the window's system menu.
*/
void callOnClose(){
comments.saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
if(projectChanged){
int value = JOptionPane.showConfirmDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("msg.you_are_closing_txt", "You are closing") + " " +
edu.umd.cs.findbugs.L10N.getLocalString("msg.without_saving_txt", "without saving. Do you want to save?"),
edu.umd.cs.findbugs.L10N.getLocalString("msg.confirm_save_txt", "Do you want to save?"), JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(value == JOptionPane.CANCEL_OPTION || value == JOptionPane.CLOSED_OPTION)
return ;
else if(value == JOptionPane.YES_OPTION){
if(saveFile == null){
if(!saveAs())
return;
}
else
save();
}
}
GUISaveState.getInstance().setPreviousComments(comments.prevCommentsList);
guiLayout.saveState();
GUISaveState.getInstance().setFrameBounds( getBounds() );
GUISaveState.getInstance().save();
System.exit(0);
}
JMenuItem createRecentItem(final File f, final SaveType localSaveType)
{
String name = f.getName();
if(!f.getName().endsWith(".xml"))
Debug.println("File does not end with .xml!!");
if(localSaveType == SaveType.PROJECT && f.getName().endsWith(".xml")){
name = f.getName().substring(0, f.getName().length()-4);
}
final JMenuItem item=new JMenuItem(name);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
setCursor(new Cursor(Cursor.WAIT_CURSOR));
if (!f.exists())
{
JOptionPane.showMessageDialog(null,edu.umd.cs.findbugs.L10N.getLocalString("msg.proj_not_found", "This project can no longer be found"));
GUISaveState.getInstance().projectNotFound(f,localSaveType);
return;
}
GUISaveState.getInstance().projectReused(f,localSaveType);//Move to front in GUISaveState, so it will be last thing to be removed from the list
MainFrame.this.recentMenuCache.addRecentFile(f,localSaveType);
if (!f.exists())
throw new IllegalStateException ("User used a recent projects menu item that didn't exist.");
//Moved this outside of the thread, and above the line saveFile=f.getParentFile()
//Since if this save goes on in the thread below, there is no way to stop the save from
//overwriting the files we are about to load.
if (curProject != null && projectChanged)
{
int response = JOptionPane.showConfirmDialog(MainFrame.this,
edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_current_changes", "The current project has been changed, Save current changes?")
,edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_changes", "Save Changes?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.YES_OPTION)
{
if(saveFile != null)
save();
else
saveAs();
}
else if (response == JOptionPane.CANCEL_OPTION)
return;
//IF no, do nothing.
}
if (localSaveType==SaveType.PROJECT)
{
if(false){ //Old stuff still here in case openProject doesn't work.
saveFile=f.getParentFile();
File fasFile=new File(saveFile.getAbsolutePath() + File.separator + saveFile.getName() + ".fas");
try
{
ProjectSettings.loadInstance(new FileInputStream(fasFile));
} catch (Exception exception)
{
Debug.println("We are in the recent menuitem FileNotFoundException.");
//Silently make a new instance
ProjectSettings.newInstance();
}
}
openProject(f.getParentFile());
}
else if (localSaveType==SaveType.XML_ANALYSIS)
{
if(false){
saveFile=f;
ProjectSettings.newInstance();//Just make up new filters and suppressions, cuz he doesn't have any
}
openAnalysis(f, localSaveType);
}
if(false){
final File extraFinalReferenceToXmlFile=f;
new Thread(new Runnable(){
public void run()
{
updateDesignationDisplay();
BugTreeModel model=(BugTreeModel)tree.getModel();
// Debug.println("please wait called by open menu item");
BugTreeModel.pleaseWait();
MainFrame.this.setRebuilding(true);
Project newProject = new Project();
SortedBugCollection bc=BugLoader.loadBugs(MainFrame.this, newProject, extraFinalReferenceToXmlFile);
setProjectAndBugCollection(newProject, bc);
}
}).start();
}
}
finally
{
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
saveType=localSaveType;
}
}
});
item.setFont(item.getFont().deriveFont(Driver.getFontSize()));
return item;
}
BugCollection bugCollection;
@SwingThread
void setProjectAndBugCollection(Project project, @CheckForNull BugCollection bugCollection) {
Filter suppressionMatcher = project.getSuppressionFilter();
if (suppressionMatcher != null) {
suppressionMatcher.softAdd(LastVersionMatcher.DEAD_BUG_MATCHER);
}
// setRebuilding(false);
if (bugCollection == null) {
showTreeCard();
} else {
curProject = project;
this.bugCollection = bugCollection;
displayer.clearCache();
BugTreeModel model = (BugTreeModel) getTree().getModel();
setSourceFinder(new SourceFinder());
getSourceFinder().setSourceBaseList(project.getSourceDirList());
BugSet bs = new BugSet(bugCollection);
model.getOffListenerList();
model.changeSet(bs);
if (bs.size() == 0 && bs.sizeUnfiltered() > 0) {
warnUserOfFilters();
}
updateStatusBar();
}
PreferencesFrame.getInstance().updateFilterPanel();
setProjectChanged(false);
reconfigMenuItem.setEnabled(true);
newProject();
clearSourcePane();
clearSummaryTab();
/* This is here due to a threading issue. It can only be called after
* curProject has been changed. Since this method is called by both open methods
* it is put here.*/
changeTitle();
}
void updateProjectAndBugCollection(Project project, BugCollection bugCollection, BugTreeModel previousModel) {
setRebuilding(false);
if (bugCollection != null)
{
displayer.clearCache();
BugSet bs = new BugSet(bugCollection);
//Dont clear data, the data's correct, just get the tree off the listener lists.
((BugTreeModel) tree.getModel()).getOffListenerList();
((BugTreeModel)tree.getModel()).changeSet(bs);
//curProject=BugLoader.getLoadedProject();
setProjectChanged(true);
}
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
/**
* Changes the title based on curProject and saveFile.
*
*/
public void changeTitle(){
String name = curProject.getProjectName();
if(name == null && saveFile != null)
name = saveFile.getAbsolutePath();
if(name == null)
name = Project.UNNAMED_PROJECT;
MainFrame.this.setTitle(TITLE_START_TXT + name);
}
/**
* Creates popup menu for bugs on tree.
* @return
*/
private JPopupMenu createBugPopupMenu() {
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem filterMenuItem = newJMenuItem("menu.filterBugsLikeThis", "Filter bugs like this");
filterMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
new NewFilterFromBug(currentSelectedBugLeaf.getBug());
setProjectChanged(true);
}
});
popupMenu.add(filterMenuItem);
JMenu changeDesignationMenu = newJMenu("menu.changeDesignation", "Change bug designation");
int i = 0;
int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9};
for(String key : I18N.instance().getUserDesignationKeys(true)) {
String name = I18N.instance().getUserDesignation(key);
comments.addDesignationItem(changeDesignationMenu, name, keyEvents[i++]);
}
popupMenu.add(changeDesignationMenu);
return popupMenu;
}
/**
* Creates the branch pop up menu that ask if the user wants
* to hide all the bugs in that branch.
* @return
*/
private JPopupMenu createBranchPopUpMenu(){
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem filterMenuItem = newJMenuItem("menu.filterTheseBugs", "Filter these bugs");
filterMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
//TODO This code does a smarter version of filtering that is only possible for branches, and does so correctly
//However, it is still somewhat of a hack, because if we ever add more tree listeners than simply the bugtreemodel,
//They will not be called by this code. Using FilterActivity to notify all listeners will however destroy any
//benefit of using the smarter deletion method.
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
int startCount;
TreePath path=MainFrame.getInstance().getTree().getSelectionPath();
TreePath deletePath=path;
startCount=((BugAspects)(path.getLastPathComponent())).getCount();
int count=((BugAspects)(path.getParentPath().getLastPathComponent())).getCount();
while(count==startCount)
{
deletePath=deletePath.getParentPath();
if (deletePath.getParentPath()==null)//We are at the top of the tree, don't let this be removed, rebuild tree from root.
{
Matcher m = currentSelectedBugAspects.getMatcher();
Filter suppressionFilter = MainFrame.getInstance().getProject().getSuppressionFilter();
suppressionFilter.addChild(m);
PreferencesFrame.getInstance().updateFilterPanel();
FilterActivity.notifyListeners(FilterListener.Action.FILTERING, null);
return;
}
count=((BugAspects)(deletePath.getParentPath().getLastPathComponent())).getCount();
}
/*
deletePath should now be a path to the highest
ancestor branch with the same number of elements
as the branch to be deleted
in other words, the branch that we actually have
to remove in order to correctly remove the selected branch.
*/
BugTreeModel model=MainFrame.getInstance().getBugTreeModel();
TreeModelEvent event=new TreeModelEvent(this,deletePath.getParentPath(),
new int[]{model.getIndexOfChild(deletePath.getParentPath().getLastPathComponent(),deletePath.getLastPathComponent())},
new Object[]{deletePath.getLastPathComponent()});
Matcher m = currentSelectedBugAspects.getMatcher();
Filter suppressionFilter = MainFrame.getInstance().getProject().getSuppressionFilter();
suppressionFilter.addChild(m);
PreferencesFrame.getInstance().updateFilterPanel();
model.sendEvent(event, TreeModification.REMOVE);
// FilterActivity.notifyListeners(FilterListener.Action.FILTERING, null);
setProjectChanged(true);
}
});
popupMenu.add(filterMenuItem);
JMenu changeDesignationMenu = newJMenu("menu.changeDesignation", "Change bug designation");
int i = 0;
int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9};
for(String key : I18N.instance().getUserDesignationKeys(true)) {
String name = I18N.instance().getUserDesignation(key);
addDesignationItem(changeDesignationMenu, name, keyEvents[i++]);
}
popupMenu.add(changeDesignationMenu);
return popupMenu;
}
/**
* Creates the MainFrame's menu bar.
* @return the menu bar for the MainFrame
*/
protected JMenuBar createMainMenuBar() {
JMenuBar menuBar = new JMenuBar();
//Create JMenus for menuBar.
JMenu fileMenu = newJMenu("menu.file_menu", "File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenu editMenu = newJMenu("menu.edit_menu", "Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
//Edit fileMenu JMenu object.
JMenuItem newProjectMenuItem = newJMenuItem("menu.new_item", "New Project", KeyEvent.VK_N);
JMenuItem openMenuItem = newJMenuItem("menu.open_item", "Open...", KeyEvent.VK_O);
recentMenu = newJMenu("menu.recent", "Recent");
recentMenuCache=new RecentMenu(recentMenu);
JMenuItem saveAsMenuItem = newJMenuItem("menu.saveas_item", "Save As...", KeyEvent.VK_A);;
redoAnalysis = newJMenuItem("menu.rerunAnalysis", "Redo Analysis", KeyEvent.VK_R);
JMenuItem exitMenuItem = null;
if (!MAC_OS_X) {
exitMenuItem = newJMenuItem("menu.exit", "Exit", KeyEvent.VK_X);
exitMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
callOnClose();
}
});
}
JMenu windowMenu = guiLayout.createWindowMenu();
attachAcceleratorKey(newProjectMenuItem, KeyEvent.VK_N);
newProjectMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
newProjectMenu();
}
});
reconfigMenuItem.setEnabled(false);
attachAcceleratorKey(reconfigMenuItem, KeyEvent.VK_F);
reconfigMenuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
new NewProjectWizard(curProject);
}
});
JMenuItem mergeMenuItem = newJMenuItem("menu.mergeAnalysis", "Merge Analysis...");
mergeMenuItem.setEnabled(true);
mergeMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
mergeAnalysis();
}
});
redoAnalysis.setEnabled(false);
attachAcceleratorKey(redoAnalysis, KeyEvent.VK_R);
redoAnalysis.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
redoAnalysis();
}
});
openMenuItem.setEnabled(true);
attachAcceleratorKey(openMenuItem, KeyEvent.VK_O);
openMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
open();
}
});
saveAsMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
saveAs();
}
});
saveMenuItem.setEnabled(false);
attachAcceleratorKey(saveMenuItem, KeyEvent.VK_S);
saveMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
save();
}
});
fileMenu.add(newProjectMenuItem);
fileMenu.add(reconfigMenuItem);
fileMenu.addSeparator();
fileMenu.add(openMenuItem);
fileMenu.add(recentMenu);
fileMenu.addSeparator();
fileMenu.add(saveAsMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(redoAnalysis);
// fileMenu.add(mergeMenuItem);
//TODO: This serves no purpose but to test something
if(false){
JMenuItem temp = new JMenuItem("Temp");
temp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
System.out.println("Current Project Name: " + curProject.getProjectName());
}
});
fileMenu.add(temp);
}
if (exitMenuItem != null) {
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
}
menuBar.add(fileMenu);
//Edit editMenu Menu object.
JMenuItem cutMenuItem = new JMenuItem(new CutAction());
JMenuItem copyMenuItem = new JMenuItem(new CopyAction());
JMenuItem pasteMenuItem = new JMenuItem(new PasteAction());
preferencesMenuItem = newJMenuItem("menu.preferences_menu", "Filters/Suppressions...");
JMenuItem sortMenuItem = newJMenuItem("menu.sortConfiguration", "Sort Configuration...");
JMenuItem goToLineMenuItem = newJMenuItem("menu.gotoLine", "Go to line...");
attachAcceleratorKey(cutMenuItem, KeyEvent.VK_X);
attachAcceleratorKey(copyMenuItem, KeyEvent.VK_C);
attachAcceleratorKey(pasteMenuItem, KeyEvent.VK_V);
preferencesMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
preferences();
}
});
sortMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
SorterDialog.getInstance().setLocationRelativeTo(MainFrame.this);
SorterDialog.getInstance().setVisible(true);
}
});
attachAcceleratorKey(goToLineMenuItem, KeyEvent.VK_L);
goToLineMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
guiLayout.makeSourceVisible();
try{
int num = Integer.parseInt(JOptionPane.showInputDialog(MainFrame.this, "", edu.umd.cs.findbugs.L10N.getLocalString("dlg.go_to_line_lbl", "Go To Line") + ":", JOptionPane.QUESTION_MESSAGE));
displayer.showLine(num);
}
catch(NumberFormatException e){}
}});
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
editMenu.addSeparator();
editMenu.add(goToLineMenuItem);
editMenu.addSeparator();
//editMenu.add(selectAllMenuItem);
// editMenu.addSeparator();
if (!MAC_OS_X) {
// Preferences goes in Findbugs menu and is handled by OSXAdapter
editMenu.add(preferencesMenuItem);
}
editMenu.add(sortMenuItem);
menuBar.add(editMenu);
if (windowMenu != null)
menuBar.add(windowMenu);
final ActionMap map = tree.getActionMap();
JMenu navMenu = newJMenu("menu.navigation", "Navigation");
addNavItem(map, navMenu, "menu.expand", "Expand", "expand", KeyEvent.VK_RIGHT );
addNavItem(map, navMenu, "menu.collapse", "Collapse", "collapse", KeyEvent.VK_LEFT);
addNavItem(map, navMenu, "menu.up", "Up", "selectPrevious", KeyEvent.VK_UP );
addNavItem(map, navMenu, "menu.down", "Down", "selectNext", KeyEvent.VK_DOWN);
menuBar.add(navMenu);
JMenu designationMenu = newJMenu("menu.designation", "Designation");
int i = 0;
int keyEvents [] = {KeyEvent.VK_1, KeyEvent.VK_2, KeyEvent.VK_3, KeyEvent.VK_4, KeyEvent.VK_5, KeyEvent.VK_6, KeyEvent.VK_7, KeyEvent.VK_8, KeyEvent.VK_9};
for(String key : I18N.instance().getUserDesignationKeys(true)) {
String name = I18N.instance().getUserDesignation(key);
addDesignationItem(designationMenu, name, keyEvents[i++]);
}
menuBar.add(designationMenu);
if (!MAC_OS_X) {
// On Mac, 'About' appears under Findbugs menu, so no need for it here
JMenu helpMenu = newJMenu("menu.help_menu", "Help");
JMenuItem aboutItem = newJMenuItem("menu.about_item", "About FindBugs");
helpMenu.add(aboutItem);
aboutItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
about();
}
});
menuBar.add(helpMenu);
}
return menuBar;
}
/**
* @param map
* @param navMenu
*/
private void addNavItem(final ActionMap map, JMenu navMenu, String menuNameKey, String menuNameDefault, String actionName, int keyEvent) {
JMenuItem toggleItem = newJMenuItem(menuNameKey, menuNameDefault);
toggleItem.addActionListener(treeActionAdapter(map, actionName));
attachAcceleratorKey(toggleItem, keyEvent);
navMenu.add(toggleItem);
}
ActionListener treeActionAdapter(ActionMap map, String actionName) {
final Action selectPrevious = map.get(actionName);
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.setSource(tree);
selectPrevious.actionPerformed(e);
}};
}
static void attachAcceleratorKey(JMenuItem item, int keystroke) {
attachAcceleratorKey(item, keystroke, 0);
}
static void attachAcceleratorKey(JMenuItem item, int keystroke,
int additionalMask) {
// As far as I know, Mac is the only platform on which it is normal
// practice to use accelerator masks such as Shift and Alt, so
// if we're not running on Mac, just ignore them
if (!MAC_OS_X && additionalMask != 0) {
return;
}
item.setAccelerator(KeyStroke.getKeyStroke(keystroke, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | additionalMask));
}
void newProject(){
clearSourcePane();
redoAnalysis.setEnabled(true);
if(newProject){
setProjectChanged(true);
// setTitle(TITLE_START_TXT + Project.UNNAMED_PROJECT);
saveFile = null;
saveMenuItem.setEnabled(false);
reconfigMenuItem.setEnabled(true);
newProject=false;
}
}
/**
* This method is for when the user wants to open a file.
*/
private void open(){
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
if (projectChanged)
{
int response = JOptionPane.showConfirmDialog(MainFrame.this,
edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_current_changes", "The current project has been changed, Save current changes?")
,edu.umd.cs.findbugs.L10N.getLocalString("dlg.save_changes", "Save Changes?"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.YES_OPTION)
{
if (saveFile!=null)
save();
else
saveAs();
}
else if (response == JOptionPane.CANCEL_OPTION)
return;
//IF no, do nothing.
}
boolean loading = true;
SaveType fileType = SaveType.NOT_KNOWN;
tryAgain: while (loading)
{
int value=saveOpenFileChooser.showOpenDialog(MainFrame.this);
if(value!=JFileChooser.APPROVE_OPTION) return;
loading = false;
fileType = convertFilterToType(saveOpenFileChooser.getFileFilter());
final File f = saveOpenFileChooser.getSelectedFile();
if(!fileType.isValid(f)){
JOptionPane.showMessageDialog(saveOpenFileChooser,
"That file is not compatible with the chosen file type", "Invalid File",
JOptionPane.WARNING_MESSAGE);
loading = true;
continue;
}
switch (fileType) {
case PROJECT:
File xmlFile = OriginalGUI2ProjectFile.fileContainingXMLData(f);
if (!xmlFile.exists())
{
JOptionPane.showMessageDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.no_xml_data_lbl", "This directory does not contain saved bug XML data, please choose a different directory."));
loading=true;
continue tryAgain;
}
openProject(f);
break;
case XML_ANALYSIS:
if(!f.getName().endsWith(".xml")){
JOptionPane.showMessageDialog(saveOpenFileChooser, edu.umd.cs.findbugs.L10N.getLocalString("dlg.not_xml_data_lbl", "This is not a saved bug XML data file."));
loading=true;
continue tryAgain;
}
if(!openAnalysis(f, fileType)){
//TODO: Deal if something happens when loading analysis
JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis.");
loading=true;
continue tryAgain;
}
break;
case FBP_FILE:
if(!openFBPFile(f)){
//TODO: Deal if something happens when loading analysis
JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis.");
loading=true;
continue tryAgain;
}
break;
case FBA_FILE:
if(!openFBAFile(f)){
//TODO: Deal if something happens when loading analysis
JOptionPane.showMessageDialog(saveOpenFileChooser, "An error occurred while trying to load the analysis.");
loading=true;
continue tryAgain;
}
break;
}
}
}
/**
* Method called to open FBA file.
* @param f
* @return
*/
private boolean openFBAFile(File f) {
return openAnalysis(f, SaveType.FBA_FILE);
}
/**
* Method called to open FBP file.
* @param f
* @return
*/
private boolean openFBPFile(File f) {
if (!f.exists() || !f.canRead()) {
return false;
}
prepareForFileLoad(f, SaveType.FBP_FILE);
loadProjectFromFile(f);
return true;
}
private boolean saveAs(){
saveOpenFileChooser.setDialogTitle(edu.umd.cs.findbugs.L10N.getLocalString("dlg.saveas_ttl", "Save as..."));
if (curProject==null)
{
JOptionPane.showMessageDialog(MainFrame.this,edu.umd.cs.findbugs.L10N.getLocalString("dlg.no_proj_save_lbl", "There is no project to save"));
return false;
}
boolean retry = true;
SaveType fileType = SaveType.NOT_KNOWN;
boolean alreadyExists = true;
File f = null;
while(retry){
retry = false;
int value=saveOpenFileChooser.showSaveDialog(MainFrame.this);
if (value!=JFileChooser.APPROVE_OPTION) return false;
fileType = convertFilterToType(saveOpenFileChooser.getFileFilter());
if(fileType == SaveType.NOT_KNOWN){
Debug.println("Error! fileType == SaveType.NOT_KNOWN");
//This should never happen b/c saveOpenFileChooser can only display filters
//given it.
retry = true;
continue;
}
f = saveOpenFileChooser.getSelectedFile();
if(fileType.isValid(f)){
JOptionPane.showMessageDialog(saveOpenFileChooser,
"That file is not compatible with the chosen file type", "Invalid File",
JOptionPane.WARNING_MESSAGE);
retry = true;
continue;
}
f = convertFile(f, fileType);
alreadyExists = fileAlreadyExists(f, fileType);
if(alreadyExists){
int response = -1;
switch(fileType){
case XML_ANALYSIS:
response = JOptionPane.showConfirmDialog(saveOpenFileChooser,
edu.umd.cs.findbugs.L10N.getLocalString("dlg.analysis_exists_lbl", "This analysis already exists.\nReplace it?"),
edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
break;
case PROJECT:
response = JOptionPane.showConfirmDialog(saveOpenFileChooser,
edu.umd.cs.findbugs.L10N.getLocalString("dlg.proj_already_exists_lbl", "This project already exists.\nDo you want to replace it?"),
edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
break;
case FBP_FILE:
response = JOptionPane.showConfirmDialog(saveOpenFileChooser,
edu.umd.cs.findbugs.L10N.getLocalString("FB Project File already exists", "This FB project file already exists.\nDo you want to replace it?"),
edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
break;
case FBA_FILE:
response = JOptionPane.showConfirmDialog(saveOpenFileChooser,
edu.umd.cs.findbugs.L10N.getLocalString("FB Analysis File already exists", "This FB analysis file already exists.\nDo you want to replace it?"),
edu.umd.cs.findbugs.L10N.getLocalString("dlg.warning_ttl", "Warning!"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
break;
}
if(response == JOptionPane.OK_OPTION)
retry = false;
if(response == JOptionPane.CANCEL_OPTION){
retry = true;
continue;
}
}
SaveReturn successful = SaveReturn.SAVE_ERROR;
switch(fileType){
case PROJECT:
successful = saveProject(f);
break;
case XML_ANALYSIS:
successful = saveAnalysis(f);
break;
case FBA_FILE:
successful = saveFBAFile(f);
break;
case FBP_FILE:
successful = saveFBPFile(f);
break;
}
if (successful != SaveReturn.SAVE_SUCCESSFUL)
{
JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.saving_error_lbl", "An error occurred in saving."));
return false;
}
}
// saveProjectMenuItem.setEnabled(false);
saveMenuItem.setEnabled(false);
saveType = fileType;
saveFile = f;
File xmlFile;
if (saveType==SaveType.PROJECT)
xmlFile=new File(f.getAbsolutePath() + File.separator + f.getName() + ".xml");
else
xmlFile=f;
addFileToRecent(xmlFile, saveType);
return true;
}
/*
* Returns SaveType equivalent depending on what kind of FileFilter passed.
*/
private SaveType convertFilterToType(FileFilter f){
if (f instanceof FindBugsFileFilter)
return ((FindBugsFileFilter)f).getSaveType();
return SaveType.NOT_KNOWN;
}
/*
* Depending on File and SaveType determines if f already exists. Returns false if not
* exist, true otherwise. For a project calls
* OriginalGUI2ProjectFile.fileContainingXMLData(f).exists
*/
private boolean fileAlreadyExists(File f, SaveType fileType){
if(fileType == SaveType.PROJECT){
/*File xmlFile=new File(f.getAbsolutePath() + File.separator + f.getName() + ".xml");
File fasFile=new File(f.getAbsolutePath() + File.separator + f.getName() + ".fas");
return xmlFile.exists() || fasFile.exists();*/
return (OriginalGUI2ProjectFile.fileContainingXMLData(f).exists());
}
return f.exists();
}
/*
* If f is not of type FileType will convert file so it is.
*/
private File convertFile(File f, SaveType fileType){
//WARNING: This assumes the filefilter for project is working so f can only be a directory.
if(fileType == SaveType.PROJECT)
return f;
//Checks that it has the correct file extension, makes a new file if it doesn't.
if(!f.getName().endsWith(fileType.getFileExtension()))
f = new File(f.getAbsolutePath() + fileType.getFileExtension());
return f;
}
private void save(){
SaveReturn result = SaveReturn.SAVE_ERROR;
switch(saveType){
case PROJECT:
result = saveProject(saveFile);
break;
case XML_ANALYSIS:
result = saveAnalysis(saveFile);
break;
case FBA_FILE:
result = saveFBAFile(saveFile);
break;
case FBP_FILE:
result = saveFBPFile(saveFile);
break;
}
if(result != SaveReturn.SAVE_SUCCESSFUL){
JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString(
"dlg.saving_error_lbl", "An error occurred in saving."));
}
}
/**
* @param saveFile2
* @return
*/
private SaveReturn saveFBAFile(File saveFile2) {
return saveAnalysis(saveFile2);
}
/**
* @param saveFile2
* @return
*/
private SaveReturn saveFBPFile(File saveFile2) {
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
try {
curProject.writeXML(saveFile2);
} catch (IOException e) {
AnalysisContext.logError("Couldn't save FBP file to " + saveFile2, e);
return SaveReturn.SAVE_IO_EXCEPTION;
}
setProjectChanged(false);
return SaveReturn.SAVE_SUCCESSFUL;
}
static final String TREECARD = "Tree";
static final String WAITCARD = "Wait";
public void showWaitCard() {
showCard(WAITCARD, new Cursor(Cursor.WAIT_CURSOR));
}
public void showTreeCard() {
showCard(TREECARD, new Cursor(Cursor.DEFAULT_CURSOR));
}
private void showCard(final String c, final Cursor cursor) {
if (SwingUtilities.isEventDispatchThread()) {
setCursor(cursor);
CardLayout layout = (CardLayout) cardPanel.getLayout();
layout.show(cardPanel, c);
} else
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setCursor(cursor);
CardLayout layout = (CardLayout) cardPanel.getLayout();
layout.show(cardPanel, c);
}
});
}
JPanel waitPanel, cardPanel;
/**
*
* @return
*/
JPanel bugListPanel()
{
cardPanel = new JPanel(new CardLayout());
JPanel topPanel = new JPanel();
waitPanel = new JPanel();
waitPanel.add(new JLabel("Please wait..."));
cardPanel.add(topPanel, TREECARD);
cardPanel.add(waitPanel, WAITCARD);
topPanel.setMinimumSize(new Dimension(200,200));
tableheader = new JTableHeader();
//Listener put here for when user double clicks on sorting
//column header SorterDialog appears.
tableheader.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
Debug.println("tableheader.getReorderingAllowed() = " + tableheader.getReorderingAllowed());
if (!tableheader.getReorderingAllowed())
return;
if (e.getClickCount()==2)
SorterDialog.getInstance().setVisible(true);
}
@Override
public void mouseReleased(MouseEvent arg0) {
if (!tableheader.getReorderingAllowed())
return;
BugTreeModel bt=(BugTreeModel) (MainFrame.this.getTree().getModel());
bt.checkSorter();
}
});
sorter = GUISaveState.getInstance().getStarterTable();
tableheader.setColumnModel(sorter);
tableheader.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.reorder_message", "Drag to reorder tree folder and sort order"));
tree = new JTree();
treeUI = (BasicTreeUI) tree.getUI();
tree.setLargeModel(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setCellRenderer(new BugRenderer());
tree.setRowHeight((int)(Driver.getFontSize() + 7));
if (false) {
System.out.println("Left indent had been " + treeUI.getLeftChildIndent());
System.out.println("Right indent had been " + treeUI.getRightChildIndent());
treeUI.setLeftChildIndent(30 );
treeUI.setRightChildIndent(30 );
}
tree.setModel(new BugTreeModel(tree, sorter, new BugSet(new ArrayList<BugLeafNode>())));
setupTreeListeners();
curProject= new Project();
treeScrollPane = new JScrollPane(tree);
topPanel.setLayout(new BorderLayout());
//New code to fix problem in Windows
JTable t = new JTable(new DefaultTableModel(0, Sortables.values().length));
t.setTableHeader(tableheader);
JScrollPane sp = new JScrollPane(t);
//This sets the height of the scrollpane so it is dependent on the fontsize.
int num = (int) (Driver.getFontSize()*1.2);
sp.setPreferredSize(new Dimension(0, 10+num));
//End of new code.
//Changed code.
topPanel.add(sp, BorderLayout.NORTH);
//topPanel.add(tableheader, BorderLayout.NORTH);
//End of changed code.
topPanel.add(treeScrollPane, BorderLayout.CENTER);
return cardPanel;
}
public void newTree(final JTree newTree, final BugTreeModel newModel)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
tree = newTree;
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setLargeModel(true);
tree.setCellRenderer(new BugRenderer());
showTreeCard();
Container container = treeScrollPane.getParent();
container.remove(treeScrollPane);
treeScrollPane = new JScrollPane(newTree);
container.add(treeScrollPane, BorderLayout.CENTER);
setFontSizeHelper(container.getComponents(), Driver.getFontSize());
tree.setRowHeight((int)(Driver.getFontSize() + 7));
MainFrame.getInstance().getContentPane().validate();
MainFrame.getInstance().getContentPane().repaint();
setupTreeListeners();
newModel.openPreviouslySelected(((BugTreeModel)(tree.getModel())).getOldSelectedBugs());
MainFrame.this.getSorter().addColumnModelListener(newModel);
FilterActivity.addFilterListener(newModel.bugTreeFilterListener);
MainFrame.this.setSorting(true);
}
});
}
private void setupTreeListeners()
{
tree.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(TreeSelectionEvent selectionEvent) {
TreePath path = selectionEvent.getNewLeadSelectionPath();
if (path != null)
{
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
Object lastPathComponent = path.getLastPathComponent();
if (lastPathComponent instanceof BugLeafNode)
{
boolean beforeProjectChanged = projectChanged;
currentSelectedBugLeaf = (BugLeafNode)lastPathComponent;
currentSelectedBugAspects = null;
syncBugInformation();
setProjectChanged(beforeProjectChanged);
}
else
{
boolean beforeProjectChanged = projectChanged;
updateDesignationDisplay();
currentSelectedBugLeaf = null;
currentSelectedBugAspects = (BugAspects)lastPathComponent;
syncBugInformation();
setProjectChanged(beforeProjectChanged);
}
}
// Debug.println("Tree selection count:" + tree.getSelectionCount());
if (tree.getSelectionCount() !=1)
{
Debug.println("Tree selection count not equal to 1, disabling comments tab" + selectionEvent);
MainFrame.this.setUserCommentInputEnable(false);
}
}
});
tree.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if(path == null)
return;
if ((e.getButton() == MouseEvent.BUTTON3) ||
(e.getButton() == MouseEvent.BUTTON1 && e.isControlDown())){
if (tree.getModel().isLeaf(path.getLastPathComponent())){
tree.setSelectionPath(path);
bugPopupMenu.show(tree, e.getX(), e.getY());
}
else{
tree.setSelectionPath(path);
if (!(path.getParentPath()==null))//If the path's parent path is null, the root was selected, dont allow them to filter out the root.
branchPopupMenu.show(tree, e.getX(), e.getY());
}
}
}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
});
}
void syncBugInformation (){
boolean prevProjectChanged = projectChanged;
if (currentSelectedBugLeaf != null) {
BugInstance bug = currentSelectedBugLeaf.getBug();
displayer.displaySource(bug, bug.getPrimarySourceLineAnnotation());
comments.updateCommentsFromLeafInformation(currentSelectedBugLeaf);
updateDesignationDisplay();
comments.updateCommentsFromLeafInformation(currentSelectedBugLeaf);
updateSummaryTab(currentSelectedBugLeaf);
} else if (currentSelectedBugAspects != null) {
updateDesignationDisplay();
comments.updateCommentsFromNonLeafInformation(currentSelectedBugAspects);
displayer.displaySource(null, null);
clearSummaryTab();
} else {
displayer.displaySource(null, null);
clearSummaryTab();
}
setProjectChanged(prevProjectChanged);
}
/**
* Clears the source code text pane.
*
*/
void clearSourcePane(){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
setSourceTabTitle("Source");
sourceCodeTextPane.setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT);
}
});
}
/**
* @param b
*/
private void setUserCommentInputEnable(boolean b) {
comments.setUserCommentInputEnable(b);
}
/**
* Creates the status bar of the GUI.
* @return
*/
JPanel statusBar()
{
JPanel statusBar = new JPanel();
// statusBar.setBackground(Color.WHITE);
statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED));
statusBar.setLayout(new BorderLayout());
statusBar.add(statusBarLabel,BorderLayout.WEST);
JLabel logoLabel = new JLabel();
ImageIcon logoIcon = new ImageIcon(MainFrame.class.getResource("logo_umd.png"));
logoLabel.setIcon(logoIcon);
statusBar.add(logoLabel, BorderLayout.EAST);
return statusBar;
}
void updateStatusBar()
{
int countFilteredBugs = BugSet.countFilteredBugs();
if (countFilteredBugs == 0)
statusBarLabel.setText(" http://findbugs.sourceforge.net/");
else if (countFilteredBugs == 1)
statusBarLabel.setText(" 1 " + edu.umd.cs.findbugs.L10N.getLocalString("statusbar.bug_hidden", "bug hidden"));
else
statusBarLabel.setText(" " + countFilteredBugs + " " + edu.umd.cs.findbugs.L10N.getLocalString("statusbar.bugs_hidden", "bugs hidden"));
}
private void updateSummaryTab(BugLeafNode node)
{
final BugInstance bug = node.getBug();
final ArrayList<BugAnnotation> primaryAnnotations = new ArrayList<BugAnnotation>();
boolean classIncluded = false;
//This ensures the order of the primary annotations of the bug
if(bug.getPrimarySourceLineAnnotation() != null)
primaryAnnotations.add(bug.getPrimarySourceLineAnnotation());
if(bug.getPrimaryMethod() != null)
primaryAnnotations.add(bug.getPrimaryMethod());
if(bug.getPrimaryField() != null)
primaryAnnotations.add(bug.getPrimaryField());
/*
* This makes the primary class annotation appear only when
* the visible field and method primary annotations don't have
* the same class.
*/
if(bug.getPrimaryClass() != null){
FieldAnnotation primeField = bug.getPrimaryField();
MethodAnnotation primeMethod = bug.getPrimaryMethod();
ClassAnnotation primeClass = bug.getPrimaryClass();
String fieldClass = "";
String methodClass = "";
if(primeField != null)
fieldClass = primeField.getClassName();
if(primeMethod != null)
methodClass = primeMethod.getClassName();
if((primaryAnnotations.size() < 2) || (!(primeClass.getClassName().equals(fieldClass) ||
primeClass.getClassName().equals(methodClass)))){
primaryAnnotations.add(primeClass);
classIncluded = true;
}
}
final boolean classIncluded2 = classIncluded;
SwingUtilities.invokeLater(new Runnable(){
public void run(){
summaryTopPanel.removeAll();
summaryTopPanel.add(bugSummaryComponent(bug.getMessageWithoutPrefix(), bug));
for(BugAnnotation b : primaryAnnotations)
summaryTopPanel.add(bugSummaryComponent(b, bug));
if(!classIncluded2 && bug.getPrimaryClass() != null)
primaryAnnotations.add(bug.getPrimaryClass());
for(Iterator<BugAnnotation> i = bug.annotationIterator(); i.hasNext();){
BugAnnotation b = i.next();
boolean cont = true;
for(BugAnnotation p : primaryAnnotations)
if(p == b)
cont = false;
if(cont)
summaryTopPanel.add(bugSummaryComponent(b, bug));
}
summaryHtmlArea.setText(bug.getBugPattern().getDetailHTML());
summaryTopPanel.add(Box.createVerticalGlue());
summaryTopPanel.revalidate();
SwingUtilities.invokeLater(new Runnable(){
public void run(){
summaryHtmlScrollPane.getVerticalScrollBar().setValue(summaryHtmlScrollPane.getVerticalScrollBar().getMinimum());
}
});
}
});
}
private void clearSummaryTab()
{
summaryHtmlArea.setText("");
summaryTopPanel.removeAll();
summaryTopPanel.revalidate();
}
/**
* Creates initial summary tab and sets everything up.
* @return
*/
JSplitPane summaryTab()
{
int fontSize = (int) Driver.getFontSize();
summaryTopPanel = new JPanel();
summaryTopPanel.setLayout(new GridLayout(0,1));
summaryTopPanel.setBorder(BorderFactory.createEmptyBorder(2,4,2,4));
summaryTopPanel.setMinimumSize(new Dimension(fontSize * 50, fontSize*5));
JPanel summaryTopOuter = new JPanel(new BorderLayout());
summaryTopOuter.add(summaryTopPanel, BorderLayout.NORTH);
summaryHtmlArea.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.longer_description", "This gives a longer description of the detected bug pattern"));
summaryHtmlArea.setContentType("text/html");
summaryHtmlArea.setEditable(false);
summaryHtmlArea.addHyperlinkListener(new javax.swing.event.HyperlinkListener() {
public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {
AboutDialog.editorPaneHyperlinkUpdate(evt);
}
});
setStyleSheets();
//JPanel temp = new JPanel(new BorderLayout());
//temp.add(summaryTopPanel, BorderLayout.CENTER);
JScrollPane summaryScrollPane = new JScrollPane(summaryTopOuter);
summaryScrollPane.getVerticalScrollBar().setUnitIncrement( (int)Driver.getFontSize() );
JSplitPane splitP = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false,
summaryScrollPane, summaryHtmlScrollPane);
splitP.setDividerLocation(GUISaveState.getInstance().getSplitSummary());
splitP.setOneTouchExpandable(true);
return splitP;
}
/**
* Creates bug summary component. If obj is a string will create a JLabel
* with that string as it's text and return it. If obj is an annotation
* will return a JLabel with the annotation's toString(). If that
* annotation is a SourceLineAnnotation or has a SourceLineAnnotation
* connected to it and the source file is available will attach
* a listener to the label.
* @param obj
* @param bug TODO
* @return
*/
private Component bugSummaryComponent(Object obj, BugInstance bug){
JLabel label = new JLabel();
label.setFont(label.getFont().deriveFont(Driver.getFontSize()));
label.setFont(label.getFont().deriveFont(Font.PLAIN));
label.setForeground(Color.BLACK);
if(obj instanceof String){
String str = (String) obj;
label.setText(str);
}
else{
BugAnnotation value = (BugAnnotation) obj;
if(value == null)
return new JLabel(edu.umd.cs.findbugs.L10N.getLocalString("summary.null", "null"));
if(value instanceof SourceLineAnnotation){
final SourceLineAnnotation note = (SourceLineAnnotation) value;
if(sourceCodeExist(note)){
String srcStr = "";
int start = note.getStartLine();
int end = note.getEndLine();
if(start < 0 && end < 0)
srcStr = edu.umd.cs.findbugs.L10N.getLocalString("summary.source_code", "source code.");
else if(start == end)
srcStr = " [" + edu.umd.cs.findbugs.L10N.getLocalString("summary.line", "Line") + " " + start + "]";
else if(start < end)
srcStr = " [" + edu.umd.cs.findbugs.L10N.getLocalString("summary.lines", "Lines") + " " + start + " - " + end + "]";
label.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.click_to_go_to", "Click to go to") + " " + srcStr);
label.addMouseListener(new BugSummaryMouseListener(bug, label, note));
}
label.setText(note.toString());
}
else if(value instanceof PackageMemberAnnotation){
PackageMemberAnnotation note = (PackageMemberAnnotation) value;
final SourceLineAnnotation noteSrc = note.getSourceLines();
String srcStr = "";
if(sourceCodeExist(noteSrc) && noteSrc != null){
int start = noteSrc.getStartLine();
int end = noteSrc.getEndLine();
if(start < 0 && end < 0)
srcStr = edu.umd.cs.findbugs.L10N.getLocalString("summary.source_code", "source code.");
else if(start == end)
srcStr = " [" + edu.umd.cs.findbugs.L10N.getLocalString("summary.line", "Line") + " " + start + "]";
else if(start < end)
srcStr = " [" + edu.umd.cs.findbugs.L10N.getLocalString("summary.lines", "Lines") + " " + start + " - " + end + "]";
if(!srcStr.equals("")){
label.setToolTipText(edu.umd.cs.findbugs.L10N.getLocalString("tooltip.click_to_go_to", "Click to go to") + " " + srcStr);
label.addMouseListener(new BugSummaryMouseListener(bug, label, noteSrc));
}
}
if(!srcStr.equals(edu.umd.cs.findbugs.L10N.getLocalString("summary.source_code", "source code.")))
label.setText(note.toString() + srcStr);
else
label.setText(note.toString());
}
else{
label.setText(((BugAnnotation) value).toString());
}
}
return label;
}
/**
* @author pugh
*/
private final class InitializeGUI implements Runnable {
public void run()
{
setTitle("FindBugs");
guiLayout.initialize();
bugPopupMenu = createBugPopupMenu();
branchPopupMenu = createBranchPopUpMenu();
comments.loadPrevCommentsList(GUISaveState.getInstance().getPreviousComments().toArray(new String[GUISaveState.getInstance().getPreviousComments().size()]));
updateStatusBar();
setBounds(GUISaveState.getInstance().getFrameBounds());
Toolkit.getDefaultToolkit().setDynamicLayout(true);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
setJMenuBar(createMainMenuBar());
setVisible(true);
//Initializes save and open filechooser. - Kristin
saveOpenFileChooser = new FBFileChooser();
saveOpenFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
saveOpenFileChooser.setAcceptAllFileFilterUsed(false);
saveOpenFileChooser.addChoosableFileFilter(FindBugsProjectFileFilter.INSTANCE);
saveOpenFileChooser.addChoosableFileFilter(FindBugsAnalysisFileFilter.INSTANCE);
saveOpenFileChooser.addChoosableFileFilter(FindBugsFBPFileFilter.INSTANCE);
saveOpenFileChooser.addChoosableFileFilter(FindBugsFBAFileFilter.INSTANCE);
saveOpenFileChooser.setFileFilter(FindBugsAnalysisFileFilter.INSTANCE);
//Sets the size of the tooltip to match the rest of the GUI. - Kristin
JToolTip tempToolTip = tableheader.createToolTip();
UIManager.put( "ToolTip.font", new FontUIResource(tempToolTip.getFont().deriveFont(Driver.getFontSize())));
if (MAC_OS_X)
{
try {
osxAdapter = Class.forName("edu.umd.cs.findbugs.gui2.OSXAdapter");
Class[] defArgs = {MainFrame.class};
Method registerMethod = osxAdapter.getDeclaredMethod("registerMacOSXApplication", defArgs);
if (registerMethod != null) {
registerMethod.invoke(osxAdapter, MainFrame.this);
}
defArgs[0] = boolean.class;
osxPrefsEnableMethod = osxAdapter.getDeclaredMethod("enablePrefs", defArgs);
enablePreferences(true);
} catch (NoClassDefFoundError e) {
// This will be thrown first if the OSXAdapter is loaded on a system without the EAWT
// because OSXAdapter extends ApplicationAdapter in its def
System.err.println("This version of Mac OS X does not support the Apple EAWT. Application Menu handling has been disabled (" + e + ")");
} catch (ClassNotFoundException e) {
// This shouldn't be reached; if there's a problem with the OSXAdapter we should get the
// above NoClassDefFoundError first.
System.err.println("This version of Mac OS X does not support the Apple EAWT. Application Menu handling has been disabled (" + e + ")");
} catch (Exception e) {
System.err.println("Exception while loading the OSXAdapter: " + e);
e.printStackTrace();
if (DEBUG) {
e.printStackTrace();
}
}
}
String loadFromURL = SystemProperties.getProperty("findbugs.loadBugsFromURL");
if (loadFromURL != null) {
InputStream in;
try {
in = new URL(loadFromURL).openConnection().getInputStream();
if (loadFromURL.endsWith(".gz"))
in = new GZIPInputStream(in);
BugTreeModel.pleaseWait(edu.umd.cs.findbugs.L10N.getLocalString("msg.loading_bugs_over_network_txt", "Loading bugs over network..."));
loadAnalysisFromInputStream(in);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(MainFrame.this, "Error loading " +e1.getMessage());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(MainFrame.this, "Error loading " +e1.getMessage());
}
}
addComponentListener(new ComponentAdapter(){
@Override
public void componentResized(ComponentEvent e){
comments.resized();
}
});
addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
if(comments.hasFocus())
setProjectChanged(true);
callOnClose();
}
});
Driver.removeSplashScreen();
}
}
/**
* Listens for when cursor is over the label and when it is clicked.
* When the cursor is over the label will make the label text blue
* and the cursor the hand cursor. When clicked will take the
* user to the source code tab and to the lines of code connected
* to the SourceLineAnnotation.
* @author Kristin Stephens
*
*/
private class BugSummaryMouseListener extends MouseAdapter{
private BugInstance bugInstance;
private JLabel label;
private SourceLineAnnotation note;
BugSummaryMouseListener(@NonNull BugInstance bugInstance, @NonNull JLabel label, @NonNull SourceLineAnnotation note){
this.bugInstance = bugInstance;
this.label = label;
this.note = note;
}
@Override
public void mouseClicked(MouseEvent e) {
displayer.displaySource(bugInstance, note);
}
@Override
public void mouseEntered(MouseEvent e){
label.setForeground(Color.blue);
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseExited(MouseEvent e){
label.setForeground(Color.black);
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
/**
* Checks if source code file exists/is available
* @param note
* @return
*/
private boolean sourceCodeExist(SourceLineAnnotation note){
try{
sourceFinder.findSourceFile(note);
}catch(FileNotFoundException e){
return false;
}catch(IOException e){
return false;
}
return true;
}
private void setStyleSheets() {
StyleSheet styleSheet = new StyleSheet();
styleSheet.addRule("body {font-size: " + Driver.getFontSize() +"pt}");
styleSheet.addRule("H1 {color: red; font-size: 120%; font-weight: bold;}");
styleSheet.addRule("code {font-family: courier; font-size: " + Driver.getFontSize() +"pt}");
htmlEditorKit.setStyleSheet(styleSheet);
summaryHtmlArea.setEditorKit(htmlEditorKit);
}
JPanel createCommentsInputPanel() {
return comments.createCommentsInputPanel();
}
/**
* Creates the source code panel, but does not put anything in it.
* @param text
* @return
*/
JPanel createSourceCodePanel()
{
Font sourceFont = new Font("Monospaced", Font.PLAIN, (int)Driver.getFontSize());
sourceCodeTextPane.setFont(sourceFont);
sourceCodeTextPane.setEditable(false);
sourceCodeTextPane.getCaret().setSelectionVisible(true);
sourceCodeTextPane.setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT);
sourceCodeScrollPane = new JScrollPane(sourceCodeTextPane);
sourceCodeScrollPane.getVerticalScrollBar().setUnitIncrement(20);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(sourceCodeScrollPane, BorderLayout.CENTER);
panel.revalidate();
if (DEBUG) System.out.println("Created source code panel");
return panel;
}
JPanel createSourceSearchPanel()
{
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
JPanel thePanel = new JPanel();
thePanel.setLayout(gridbag);
c.gridx = 0;
c.gridy = 0;
c.weightx = 1.0;
c.insets = new Insets(0, 5, 0, 5);
c.fill = GridBagConstraints.HORIZONTAL;
gridbag.setConstraints(sourceSearchTextField, c);
thePanel.add(sourceSearchTextField);
//add the buttons
findButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
searchSource(0);
}
});
c.gridx = 1;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
gridbag.setConstraints(findButton, c);
thePanel.add(findButton);
findNextButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
searchSource(1);
}
});
c.gridx = 2;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
gridbag.setConstraints(findNextButton, c);
thePanel.add(findNextButton);
findPreviousButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
searchSource(2);
}
});
c.gridx = 3;
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
gridbag.setConstraints(findPreviousButton, c);
thePanel.add(findPreviousButton);
return thePanel;
}
void searchSource(int type)
{
int targetLineNum = -1;
String targetString = sourceSearchTextField.getText();
switch(type)
{
case 0: targetLineNum = displayer.find(targetString);
break;
case 1: targetLineNum = displayer.findNext(targetString);
break;
case 2: targetLineNum = displayer.findPrevious(targetString);
break;
}
if(targetLineNum != -1)
displayer.foundItem(targetLineNum);
}
/**
* Sets the title of the source tabs for either docking or non-docking
* versions.
* @param title
*/
void setSourceTabTitle(String title){
guiLayout.setSourceTitle(title);
}
/**
* Returns the SorterTableColumnModel of the MainFrame.
* @return
*/
SorterTableColumnModel getSorter()
{
return sorter;
}
/*
* This is overridden for changing the font size
*/
@Override
public void addNotify(){
super.addNotify();
float size = Driver.getFontSize();
getJMenuBar().setFont(getJMenuBar().getFont().deriveFont(size));
for(int i = 0; i < getJMenuBar().getMenuCount(); i++){
for(int j = 0; j < getJMenuBar().getMenu(i).getMenuComponentCount(); j++){
Component temp = getJMenuBar().getMenu(i).getMenuComponent(j);
temp.setFont(temp.getFont().deriveFont(size));
}
}
bugPopupMenu.setFont(bugPopupMenu.getFont().deriveFont(size));
setFontSizeHelper(bugPopupMenu.getComponents(), size);
branchPopupMenu.setFont(branchPopupMenu.getFont().deriveFont(size));
setFontSizeHelper(branchPopupMenu.getComponents(), size);
}
public JTree getTree()
{
return tree;
}
public BugTreeModel getBugTreeModel() {
return (BugTreeModel)getTree().getModel();
}
static class CutAction extends TextAction {
public CutAction() {
super(edu.umd.cs.findbugs.L10N.getLocalString("txt.cut", "Cut"));
}
public void actionPerformed( ActionEvent evt ) {
JTextComponent text = getTextComponent( evt );
if(text == null)
return;
text.cut();
}
}
static class CopyAction extends TextAction {
public CopyAction() {
super(edu.umd.cs.findbugs.L10N.getLocalString("txt.copy", "Copy"));
}
public void actionPerformed( ActionEvent evt ) {
JTextComponent text = getTextComponent( evt );
if(text == null)
return;
text.copy();
}
}
static class PasteAction extends TextAction {
public PasteAction() {
super(edu.umd.cs.findbugs.L10N.getLocalString("txt.paste", "Paste"));
}
public void actionPerformed( ActionEvent evt ) {
JTextComponent text = getTextComponent( evt );
if(text == null)
return;
text.paste();
}
}
public Project getProject() {
return curProject;
}
public void setProject(Project p) {
curProject=p;
}
public SourceFinder getSourceFinder()
{
return sourceFinder;
}
public void setSourceFinder(SourceFinder sf)
{
sourceFinder=sf;
}
@SwingThread
public void setRebuilding(boolean b)
{
tableheader.setReorderingAllowed(!b);
enablePreferences(!b);
if (b) {
SorterDialog.getInstance().freeze();
showWaitCard();
}
else {
SorterDialog.getInstance().thaw();
showTreeCard();
}
recentMenu.setEnabled(!b);
}
public void setSorting(boolean b) {
tableheader.setReorderingAllowed(b);
}
private void setSaveMenu() {
saveMenuItem.setEnabled(projectChanged && saveFile != null && saveType != SaveType.FBP_FILE && saveFile.exists());
}
/**
* Called when something in the project is changed and the change needs to be saved.
* This method should be called instead of using projectChanged = b.
*/
public void setProjectChanged(boolean b){
if(curProject == null)
return;
if(projectChanged == b)
return;
projectChanged = b;
setSaveMenu();
// if(projectDirectory != null && projectDirectory.exists())
// saveProjectMenuItem.setEnabled(b);
getRootPane().putClientProperty(WINDOW_MODIFIED, Boolean.valueOf(b));
}
public boolean getProjectChanged(){
return projectChanged;
}
/*
* DO NOT use the projectDirectory variable to figure out the current project directory in this function
* use the passed in value, as that variable may or may not have been set to the passed in value at this point.
*/
private SaveReturn saveProject(File dir)
{
if (curProject == null) {
curProject = new Project();
JOptionPane.showMessageDialog(MainFrame.this, "Null project; this is unexpected. "
+" Creating a new Project so the bugs can be saved, but please report this error.");
}
// Saves current comment to current bug.
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
dir.mkdir();
//updateDesignationDisplay(); - Don't think we need this anymore - Kristin
File f = new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".xml");
File filtersAndSuppressions=new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".fas");
BugSaver.saveBugs(f,bugCollection,curProject);
try {
filtersAndSuppressions.createNewFile();
ProjectSettings.getInstance().save(new FileOutputStream(filtersAndSuppressions));
} catch (IOException e) {
Debug.println(e);
return SaveReturn.SAVE_IO_EXCEPTION;
}
setProjectChanged(false);
return SaveReturn.SAVE_SUCCESSFUL;
}
/**
* @param currentSelectedBugLeaf2
* @param currentSelectedBugAspects2
*/
private void saveComments(BugLeafNode theNode, BugAspects theAspects) {
comments.saveComments(theNode, theAspects);
}
void saveComments() {
comments.saveComments();
}
/**
* Returns the color of the source code pane's background.
* @return the color of the source code pane's background
*/
public Color getSourceColor(){
return sourceCodeTextPane.getBackground();
}
/**
* Show an error dialog.
*/
public void error(String message) {
JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE);
}
/**
* Write a message to the console window.
*
* @param message the message to write
*/
public void writeToLog(String message) {
if (DEBUG)
System.out.println(message);
// consoleMessageArea.append(message);
// consoleMessageArea.append("\n");
}
/**
* Save current analysis as file passed in. Return SAVE_SUCCESSFUL if save successful.
*/
/*
* Method doesn't do much. This method is more if need to do other things in the future for
* saving analysis. And to keep saving naming convention.
*/
private SaveReturn saveAnalysis(File f){
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
BugSaver.saveBugs(f, bugCollection, curProject);
setProjectChanged(false);
return SaveReturn.SAVE_SUCCESSFUL;
}
/**
* Opens the analysis. Also clears the source and summary panes. Makes comments enabled false.
* Sets the saveType and adds the file to the recent menu.
* @param f
* @return
*/
private boolean openAnalysis(File f, SaveType saveType){
if (!f.exists() || !f.canRead()) {
throw new IllegalArgumentException("Can't read " + f);
}
prepareForFileLoad(f, saveType);
try {
FileInputStream in = new FileInputStream(f);
loadAnalysisFromInputStream(in);
return true;
} catch (IOException e) {
return false;
}
}
private void prepareForFileLoad(File f, SaveType saveType) {
setRebuilding(true);
//This creates a new filters and suppressions so don't use the previoues one.
ProjectSettings.newInstance();
clearSourcePane();
clearSummaryTab();
comments.setUserCommentInputEnable(false);
reconfigMenuItem.setEnabled(true);
setProjectChanged(false);
this.saveType = saveType;
saveFile = f;
addFileToRecent(f, saveType);
}
/**
* @param file
* @return
*/
private void loadAnalysisFromInputStream(final InputStream in) {
Runnable runnable = new Runnable(){
public void run()
{
final Project project = new Project();
final SortedBugCollection bc=BugLoader.loadBugs(MainFrame.this, project, in);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setProjectAndBugCollection(project, bc);
}});
}
};
if (EventQueue.isDispatchThread())
new Thread(runnable).start();
else runnable.run();
return;
}
/**
* @param file
* @return
*/
private void loadProjectFromFile(final File f) {
Runnable runnable = new Runnable(){
public void run()
{
final Project project =BugLoader.loadProject(MainFrame.this, f);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setProjectAndBugCollection(project, new SortedBugCollection());
}});
}
};
if (EventQueue.isDispatchThread())
new Thread(runnable).start();
else runnable.run();
return;
}
/**
* Redo the analysis
*/
private void redoAnalysis() {
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
showWaitCard();
new Thread()
{
@Override
public void run()
{
updateDesignationDisplay();
BugCollection bc=BugLoader.redoAnalysisKeepComments(curProject);
updateProjectAndBugCollection(curProject, bc, null);
}
}.start();
}
private void mergeAnalysis() {
saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
showWaitCard();
Project p = new Project();
BugCollection bc=BugLoader.combineBugHistories(p);
setProjectAndBugCollection(p, bc);
}
/**
* This takes a directory and opens it as a project.
* @param dir
*/
private void openProject(final File dir){
File xmlFile= new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".xml");
File fasFile=new File(dir.getAbsolutePath() + File.separator + dir.getName() + ".fas");
if (!fasFile.exists())
{
JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString(
"dlg.filter_settings_not_found_lbl", "Filter settings not found, using default settings."));
ProjectSettings.newInstance();
}
else
{
try
{
ProjectSettings.loadInstance(new FileInputStream(fasFile));
} catch (FileNotFoundException e)
{
//Impossible.
if (MainFrame.DEBUG) System.err.println(".fas file not found, using default settings");
ProjectSettings.newInstance();
}
}
final File extraFinalReferenceToXmlFile=xmlFile;
new Thread(new Runnable(){
public void run()
{
BugTreeModel.pleaseWait();
MainFrame.this.setRebuilding(true);
Project project = new Project();
SortedBugCollection bc=BugLoader.loadBugs(MainFrame.this, project, extraFinalReferenceToXmlFile);
setProjectAndBugCollection(project, bc);
}
}).start();
addFileToRecent(xmlFile, SaveType.PROJECT);
clearSourcePane();
clearSummaryTab();
comments.setUserCommentInputEnable(false);
setProjectChanged(false);
saveType = SaveType.PROJECT;
saveFile = dir;
changeTitle();
}
/**
* This checks if the xmlFile is in the GUISaveState. If not adds it. Then adds the file
* to the recentMenuCache.
* @param xmlFile
*/
/*
* If the file already existed, its already in the preferences, as well as
* the recent projects menu items, only add it if they change the name,
* otherwise everything we're storing is still accurate since all we're
* storing is the location of the file.
*/
private void addFileToRecent(File xmlFile, SaveType st){
ArrayList<File> xmlFiles=GUISaveState.getInstance().getRecentProjects();
if (!xmlFiles.contains(xmlFile))
{
GUISaveState.getInstance().addRecentFile(xmlFile, st);
}
MainFrame.this.recentMenuCache.addRecentFile(xmlFile,st);
}
private void newProjectMenu() {
comments.saveComments(currentSelectedBugLeaf, currentSelectedBugAspects);
new NewProjectWizard();
newProject = true;
}
void updateDesignationDisplay() {
comments.updateDesignationComboBox();
}
void addDesignationItem(JMenu menu, final String menuName, int keyEvent) {
comments.addDesignationItem(menu, menuName, keyEvent);
}
void warnUserOfFilters()
{
JOptionPane.showMessageDialog(MainFrame.this, edu.umd.cs.findbugs.L10N.getLocalString("dlg.everything_is_filtered",
"All bugs in this project appear to be filtered out. \nYou may wish to check your filter settings in the preferences menu."),
"Warning",JOptionPane.WARNING_MESSAGE);
}
}
|
package com.trifork.hotruby.runtime;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;
import com.trifork.hotruby.compiler.CompilerConsts;
import com.trifork.hotruby.objects.IRubyClass;
import com.trifork.hotruby.objects.IRubyModule;
public class CodeGen implements Opcodes, CompilerConsts {
public static final boolean DEBUG_WRITE_CLASSES = true;
private final RubyRuntime runtime;
public CodeGen(RubyRuntime runtime) {
this.runtime = runtime;
}
static GeneratorAdapter begin_method(ClassVisitor cv, int access,
Method method) {
MethodVisitor mv = cv.visitMethod(access, method.getName(), method
.getDescriptor(), null, EMPTY_STRING_ARRAY);
GeneratorAdapter ga = new GeneratorAdapter(access, method, mv);
return ga;
}
public void make_special_selector(Selector old, Class selectInterface, RubyMethodAccessor acc)
{
Class old_class = old.getClass();
Field instance_field;
try {
instance_field = old_class.getField("instance");
} catch (Exception e1) {
throw new InternalError();
}
Class base_selector = instance_field.getDeclaringClass();
String class_name = "_" + next_counter() + "." + base_selector.getName();
Type self_type = Type.getType("L" + class_name.replace('.', '/') + ";");
Type super_type = Type.getType("L" + old_class.getName().replace('.', '/') + ";");
Type sel_type = Type.getType(selectInterface);
ClassWriter cw = new ClassWriter(true);
cw.visit(Opcodes.V1_4, ACC_PUBLIC, self_type.getInternalName(), null, super_type.getInternalName(), new String[] { sel_type.getInternalName() } );
String field_name = "acc$"+next_counter();
cw.visitField(ACC_PUBLIC|ACC_STATIC, field_name, METHODACCESSOR_TYPE.getDescriptor(), null, null);
java.lang.reflect.Method mm = selectInterface.getMethods()[0];
GeneratorAdapter ga = begin_method(cw, ACC_PUBLIC, new Method(mm.getName(), RUBYMETHOD, new Type[0]));
ga.getStatic(self_type, field_name, METHODACCESSOR_TYPE);
ga.invokeVirtual(METHODACCESSOR_TYPE, new Method("get", RUBYMETHOD, new Type[0]));
ga.returnValue();
ga.endMethod();
add_default_constructor(cw, super_type);
cw.visitEnd();
byte[] bytes = cw.toByteArray();
Class result = runtime.loader.doDefineClass(class_name, bytes);
Selector new_selector;
try {
new_selector = (Selector) result.newInstance();
result.getField(field_name).set(new_selector, acc);
instance_field.set(null, new_selector);
} catch (Exception e) {
e.printStackTrace();
throw new InternalError("cannot instantiate");
}
}
public Class make_selector_class(String class_name) {
String name = class_name.replace('.', '/');
Type selfType = Type.getType("L" + name + ";");
ClassWriter cw = new ClassWriter(true);
cw.visit(Opcodes.V1_4, ACC_PUBLIC, name, null, SELECTOR_CLASS_NAME,
EMPTY_STRING_ARRAY);
FieldVisitor fv = cw.visitField(ACC_STATIC | ACC_PUBLIC, "instance",
"L" + name + ";", null, null);
fv.visitEnd();
add_default_constructor(cw, SELECTOR_TYPE);
GeneratorAdapter ga = begin_method(cw, ACC_STATIC | ACC_PRIVATE,
CLASS_INITIALIZER);
ga.newInstance(selfType);
ga.dup();
ga.invokeConstructor(selfType, NOARG_CONSTRUCTOR);
ga.putStatic(selfType, "instance", selfType);
ga.returnValue();
ga.endMethod();
ga = begin_method(cw, ACC_PUBLIC, SELECTOR_SET);
ga.loadArg(0);
ga.checkCast(selfType);
ga.putStatic(selfType, "instance", selfType);
ga.returnValue();
ga.endMethod();
ga = begin_method(cw, ACC_PUBLIC, SELECTOR_GET);
ga.getStatic(selfType, "instance", selfType);
ga.returnValue();
ga.endMethod();;
cw.visitEnd();
byte[] bytes = cw.toByteArray();
debug_write_class(selfType, bytes);
Class result = runtime.loader.doDefineClass(class_name, bytes);
// System.out.println("defined selector "+class_name);
return result;
}
private void add_default_constructor(ClassWriter cw, Type super_type) {
GeneratorAdapter ga = begin_method(cw, ACC_PUBLIC, NOARG_CONSTRUCTOR);
ga.loadThis();
ga.invokeConstructor(super_type, NOARG_CONSTRUCTOR);
ga.returnValue();
ga.endMethod();
}
public IRubyModule make_module(MetaModule module) {
Type self_type = Type.getType("L" + module.get_base_class_name().replace('.', '/') + ";");
ClassWriter cw = new ClassWriter(true);
cw.visit(Opcodes.V1_4, ACC_PUBLIC, self_type.getInternalName(), null,
RUBYMODULE_TYPE.getInternalName(), new String[0]);
add_default_constructor(cw, RUBYMODULE_TYPE);
gen_self_instance(self_type, cw);
gen_module_init(self_type, cw);
/*
* interface SelectKernel { RubyMethod get_RubyModuleKernel(); } public
* RubyMethod select(Selector sel) { if(sel instanceof SelectKernel) {
* return ((SelectKernel)sel).get_RubyModuleKernel(); } else { return
* LoadedRubyRuntime.resolve_method((RubyModuleKernel)this,sel,SelectKernel.class); } }
*
*/
gen_get_class(cw, RUBYCLASSMODULE_TYPE);
Method select_method = new Method("select_" + next_counter(),
RUBYMETHOD, new Type[0]);
Type selector_type = gen_selector_interface(self_type, select_method);
GeneratorAdapter ga = begin_method(cw, ACC_PUBLIC, SELECT_METHOD);
Label slow_version = ga.newLabel();
ga.loadArg(0);
ga.instanceOf(selector_type);
ga.ifZCmp(GeneratorAdapter.EQ, slow_version);
ga.loadArg(0);
ga.cast(SELECTOR_TYPE, selector_type);
ga.invokeInterface(selector_type, select_method);
ga.returnValue();
ga.mark(slow_version);
ga.loadThis();
ga.loadArg(0);
ga.push(selector_type.getClassName());
ga.invokeStatic(LOADED_RUBY_RUNTIME, RESOLVE_METHOD);
ga.returnValue();
ga.endMethod();
cw.visitEnd();
byte[] data = cw.toByteArray();
debug_write_class(self_type, data);
Class module_class = runtime.loader.doDefineClass(self_type
.getClassName(), data);
IRubyModule result;
try {
result = (IRubyModule) module_class.newInstance();
} catch (Exception e) {
throw new InternalError("unable to create module");
}
result.init(module);
return result;
}
private void debug_write_class(Type self_type, byte[] data) {
debug_write_class(self_type.getClassName(), data);
}
public static void debug_write_class(String name, byte[] data) {
if (!DEBUG_WRITE_CLASSES) return;
String pkg = "dout";
String clazz = name;
int idx = name.lastIndexOf('.');
if (idx > 0) {
pkg = "dout/" + name.substring(0, idx).replace('.', '/');
clazz = name.substring(idx+1);
}
File dir = new File(pkg);
if (!dir.exists()) {
new File(pkg).mkdirs();
}
try {
String fileName = clazz+".class";
FileOutputStream fo = new FileOutputStream(new File(dir, fileName));
fo.write(data);
fo.close();
} catch (Exception ex) {
}
}
private Type gen_selector_interface(Type context_type, Method select_method2) {
String name = context_type.getClassName() + "$Selector";
Type self_type = Type.getType("L" + name.replace('.', '/') + ";");
ClassWriter cw = new ClassWriter(false);
cw.visit(Opcodes.V1_4, ACC_PUBLIC | ACC_INTERFACE, self_type
.getInternalName(), null, OBJECT_TYPE.getInternalName(),
new String[0]);
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_ABSTRACT,
select_method2.getName(), select_method2.getDescriptor(), null,
new String[0]);
mv.visitEnd();
cw.visitEnd();
byte[] data = cw.toByteArray();
runtime.loader.doDefineClass(self_type.getClassName(), data);
return self_type;
}
static int counter = 0;
private static synchronized int next_counter() {
return counter++;
}
private void gen_get_class(ClassWriter cw, Type class_type) {
GeneratorAdapter ga = begin_method(cw, ACC_PUBLIC, GET_CLASS_METHOD);
ga.getStatic(class_type, "instance", class_type);
ga.returnValue();
ga.endMethod();
}
private void gen_self_instance(Type self_type, ClassWriter cw) {
FieldVisitor fv = cw.visitField(ACC_PUBLIC|ACC_STATIC, "instance", self_type
.getDescriptor(), null, null);
fv.visitEnd();
}
private void gen_module_init(Type self_type, ClassWriter cw) {
GeneratorAdapter ga = begin_method(cw, ACC_PUBLIC, MODULE_INIT_METHOD);
// assign singleton self
ga.loadThis();
ga.putStatic(self_type, "instance", self_type);
// invoke super
ga.loadThis();
ga.loadArg(0);
ga.invokeConstructor(RUBYMODULE_TYPE, MODULE_INIT_METHOD);
ga.returnValue();
ga.visitMaxs(0, 0);
ga.visitEnd();
}
private void gen_class_init(Type self_type, ClassWriter cw) {
GeneratorAdapter ga = begin_method(cw, ACC_PUBLIC, CLASS_INIT_METHOD);
// assign singleton self
ga.loadThis();
ga.putStatic(self_type, "instance", self_type);
// invoke super
ga.loadThis();
ga.loadArg(0);
ga.invokeConstructor(RUBYCLASS_TYPE, CLASS_INIT_METHOD);
ga.returnValue();
ga.visitMaxs(0, 0);
ga.visitEnd();
}
public IRubyModule make_class(MetaClass klass) {
klass.set_instance_class_compiled(false);
Type self_type = Type.getType("L" + klass.get_base_class_name().replace('.', '/') + ";");
ClassWriter cw = new ClassWriter(true);
cw.visit(Opcodes.V1_4, ACC_PUBLIC, self_type.getInternalName(), null,
RUBYCLASS_TYPE.getInternalName(), new String[0]);
add_default_constructor(cw, RUBYCLASS_TYPE);
gen_self_instance(self_type, cw);
gen_class_init(self_type, cw);
/*
* interface SelectKernel { RubyMethod get_RubyModuleKernel(); } public
* RubyMethod select(Selector sel) { if(sel instanceof SelectKernel) {
* return ((SelectKernel)sel).get_RubyModuleKernel(); } else { return
* LoadedRubyRuntime.resolve_method((RubyModuleKernel)this,sel,SelectKernel.class); } }
*
*/
gen_get_class(cw, RUBYCLASSCLASS_TYPE);
Method select_method = new Method("select_" + next_counter(),
RUBYMETHOD, new Type[0]);
Type selector_type = gen_selector_interface(self_type, select_method);
// cw.visitInnerClass("Selector", self_type.getInternalName(), selector_type.getInternalName(), ACC_PUBLIC|ACC_INTERFACE);
gen_select_method(cw, select_method, selector_type);
gen_new_instance(klass, cw);
cw.visitEnd();
byte[] data = cw.toByteArray();
debug_write_class(self_type, data);
Class class_class = runtime.loader.doDefineClass(self_type
.getClassName(), data);
IRubyClass result;
try {
result = (IRubyClass) class_class.newInstance();
} catch (Exception e) {
throw new InternalError("unable to create module");
}
result.init(klass);
return result;
}
private void gen_new_instance(MetaClass klass, ClassWriter cw) {
GeneratorAdapter ga = begin_method(cw, ACC_PUBLIC, NEWINSTANCE_METHOD);
Type instance_type = Type.getType("L" + klass.get_instance_class_name().replace('.', '/') + ";");
ga.newInstance(instance_type);
ga.dup();
ga.invokeConstructor(instance_type, NOARG_CONSTRUCTOR);
ga.returnValue();
ga.endMethod();
runtime.loader.registerInstanceClass(klass);
}
private void gen_select_method(ClassWriter cw, Method select_method, Type selector_type) {
GeneratorAdapter ga = begin_method(cw, ACC_PUBLIC, SELECT_METHOD);
Label slow_version = ga.newLabel();
ga.loadArg(0);
ga.instanceOf(selector_type);
ga.ifZCmp(GeneratorAdapter.EQ, slow_version);
ga.loadArg(0);
ga.cast(SELECTOR_TYPE, selector_type);
ga.invokeInterface(selector_type, select_method);
ga.returnValue();
ga.mark(slow_version);
ga.loadThis();
ga.loadArg(0);
ga.push(selector_type.getClassName());
ga.invokeStatic(LOADED_RUBY_RUNTIME, RESOLVE_METHOD);
ga.returnValue();
ga.endMethod();
}
public Class<?> make_instance_class(MetaClass klass) {
klass.set_instance_class_compiled(true);
Type self_type = Type.getType("L" + klass.get_instance_class_name().replace('.', '/') + ";");
Type super_class_type = Type.getType("L" + klass.get_super_class().get_instance_class_name().replace('.', '/') + ";");
Type class_type = Type.getType("L" + klass.get_base_class_name().replace('.', '/') + ";");
ClassWriter cw = new ClassWriter(true);
cw.visit(Opcodes.V1_4, ACC_PUBLIC, self_type.getInternalName(), null,
super_class_type.getInternalName(), new String[0]);
add_default_constructor(cw, super_class_type);
add_fast_override(cw, klass.get_super_class().get_instance_class_name());
/*
* interface SelectKernel { RubyMethod get_RubyModuleKernel(); } public
* RubyMethod select(Selector sel) { if(sel instanceof SelectKernel) {
* return ((SelectKernel)sel).get_RubyModuleKernel(); } else { return
* LoadedRubyRuntime.resolve_method((RubyModuleKernel)this,sel,SelectKernel.class); } }
*
*/
gen_get_class(cw, class_type);
Method select_method = new Method("select_" + next_counter(),
RUBYMETHOD, new Type[0]);
Type selector_type = gen_selector_interface(self_type, select_method);
gen_select_method(cw, select_method, selector_type);
String[] compiled_ivars = klass.getCompiledIvars();
for (int i = 0; i < compiled_ivars.length; i++) {
FieldVisitor fv = cw.visitField(ACC_PUBLIC, compiled_ivars[i], IRUBYOBJECT.getDescriptor(), null, null);
fv.visitEnd();
}
cw.visitEnd();
byte[] data = cw.toByteArray();
debug_write_class(self_type, data);
Class instance_class = runtime.loader.doDefineClass(self_type
.getClassName(), data);
return instance_class;
}
private void add_fast_override(ClassWriter cw, String super_instance_name) {
Class super_instance;
try {
super_instance = runtime.loader.loadClass(super_instance_name, false);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new InternalError("cannot load super class");
}
Method[] fast_methods = get_fast_methods(super_instance);
for (int i = 0; i < fast_methods.length; i++) {
add_fast_override(cw, fast_methods[i]);
}
}
private void add_fast_override(ClassWriter cw, Method method) {
//System.out.println("should generate "+method);
GeneratorAdapter mg = begin_method(cw, ACC_PUBLIC, method);
mg.loadThis();
mg.loadArgs();
mg.invokeConstructor(RUBYOBJECT_TYPE, method);
mg.returnValue();
mg.endMethod();
}
private Method[] get_fast_methods(Class super_instance) {
Set<Method> methods = new HashSet<Method>();
for (Class c = super_instance; ! c.getName().equals(RUBYOBJECT.getClassName()); c = c.getSuperclass())
{
java.lang.reflect.Method[] m = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
java.lang.reflect.Method method = m[i];
Class<?>[] parms = method.getParameterTypes();
if (method.getName().startsWith("fast_") && parms.length>0 && parms[parms.length-1] == Selector.class) {
methods.add(reflect_to_asm(method));
}
}
}
return methods.toArray(new Method[methods.size()]);
}
private Method reflect_to_asm(java.lang.reflect.Method method) {
Type result = Type.getType(method.getReturnType());
Class[] reflect_parms = method.getParameterTypes();
Type[] parms = new Type[reflect_parms.length];
for (int i = 0; i < parms.length; i++) {
parms[i] = Type.getType(reflect_parms[i]);
}
return new Method(method.getName(), result, parms);
}
}
|
package net.powermatcher.mock;
import java.util.HashMap;
import java.util.Map;
import java.util.Observer;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import net.powermatcher.api.Agent;
import net.powermatcher.api.AgentRole;
import net.powermatcher.api.Session;
import net.powermatcher.api.data.Bid;
import net.powermatcher.api.data.Price;
import net.powermatcher.api.monitoring.AgentEvent;
import net.powermatcher.api.monitoring.AgentObserver;
import net.powermatcher.api.monitoring.ObservableAgent;
public class MockAgent implements Agent, AgentRole, ObservableAgent {
private Map<String, Object> agentProperties;
private Price lastPriceUpdate;
private Session session;
private String desiredParentId;
private String clusterId;
/**
* Collection of {@link Observer} services.
*/
private final Set<AgentObserver> observers = new CopyOnWriteArraySet<AgentObserver>();
public MockAgent(String agentId) {
this.agentProperties = new HashMap<String, Object>();
this.agentProperties.put("agentId", agentId);
}
@Override
public void connectToMatcher(Session session) {
this.session = session;
}
@Override
public void matcherRoleDisconnected(Session session) {
this.session = null;
}
@Override
public void updatePrice(Price newPrice) {
this.lastPriceUpdate = newPrice;
}
public void sendBid(Bid newBid) {
this.session.updateBid(newBid);
}
public Price getLastPriceUpdate() {
return lastPriceUpdate;
}
public Map<String, Object> getAgentProperties() {
return agentProperties;
}
@Override
public String getAgentId() {
return (String) agentProperties.get("agentId");
}
@Override
public String getClusterId() {
return clusterId;
}
@Override
public String getDesiredParentId() {
return desiredParentId;
}
public void setDesiredParentId(String desiredParentId) {
this.desiredParentId = desiredParentId;
}
@Override
public String getObserverId() {
return this.getAgentId();
}
@Override
public void addObserver(AgentObserver observer) {
observers.add(observer);
}
@Override
public void removeObserver(AgentObserver observer) {
observers.remove(observer);
}
public void publishEvent(AgentEvent event) {
for (AgentObserver observer : observers) {
observer.update(event);
}
}
}
|
package datastructures.stack;
import java.util.Iterator;
/**
*
* @author Denny Oommen Mathew <denny@dennymathew.com>
*
* @param <Item>
*/
public class ArrayStack<Item extends Object> implements Stack<Item>{
private Item[] stack_space;
private int size;
private int top;
private final static int SIZE = 10;
@Override
public Iterator<Item> iterator() {
return new ArrayStackIterator();
}
@Override
public Item pop() {
if(isEmpty()) {
return null;
}
Item item = stack_space[top];
stack_space[top--] = null;
//Optimal shrinking solution
if(top > 0 && top == stack_space.length / 4 ) {
resize(stack_space.length / 4);
}
return item;
}
@Override
public Item peek() {
return stack_space[top];
}
//Amortized O(1)
@Override
public void push(Item item) {
if(isFull()) {
resize(2*stack_space.length);
}
stack_space[++top] = item;
}
@Override
public boolean isEmpty() {
return (top == -1);
}
private boolean isFull() {
return (top == size - 1);
}
private void resize(int capacity) {
Item[] item = (Item[]) new Object[capacity];
System.arraycopy(stack_space, 0, item, 0, size);
stack_space = item;
size = capacity;
}
public ArrayStack(int size) {
this.stack_space = (Item[]) new Object[size];
this.size = size;
this.top = -1;
}
public ArrayStack() {
this(SIZE);
}
private class ArrayStackIterator implements Iterator<Item>{
private int ptr = top;
public ArrayStackIterator() {
}
@Override
public boolean hasNext() {
return (ptr >- 1);
}
@Override
public Item next() {
return stack_space[ptr
}
}
}
|
package com.phonegap;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.ArrayList;
import java.util.Stack;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Iterator;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.media.AudioManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.phonegap.api.LOG;
import com.phonegap.api.PhonegapActivity;
import com.phonegap.api.IPlugin;
import com.phonegap.api.PluginManager;
import org.xmlpull.v1.XmlPullParserException;
public class DroidGap extends PhonegapActivity {
public static String TAG = "DroidGap";
// The webview for our app
protected WebView appView;
protected WebViewClient webViewClient;
private ArrayList<Pattern> whiteList = new ArrayList<Pattern>();
private HashMap<String, Boolean> whiteListCache = new HashMap<String,Boolean>();
protected LinearLayout root;
public boolean bound = false;
public CallbackServer callbackServer;
protected PluginManager pluginManager;
protected boolean cancelLoadUrl = false;
protected ProgressDialog spinnerDialog = null;
// The initial URL for our app
// ie http://server/path/index.html#abc?query
private String url = null;
private Stack<String> urls = new Stack<String>();
// Url was specified from extras (activity was started programmatically)
private String initUrl = null;
private static int ACTIVITY_STARTING = 0;
private static int ACTIVITY_RUNNING = 1;
private static int ACTIVITY_EXITING = 2;
private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down
// The base of the initial URL for our app.
// Does not include file name. Ends with /
private String baseUrl = null;
// Plugin to call when activity result is received
protected IPlugin activityResultCallback = null;
protected boolean activityResultKeepRunning;
// Flag indicates that a loadUrl timeout occurred
private int loadUrlTimeout = 0;
// Default background color for activity
// (this is not the color for the webview, which is set in HTML)
private int backgroundColor = Color.BLACK;
/*
* The variables below are used to cache some of the activity properties.
*/
// Draw a splash screen using an image located in the drawable resource directory.
// This is not the same as calling super.loadSplashscreen(url)
protected int splashscreen = 0;
// LoadUrl timeout value in msec (default of 20 sec)
protected int loadUrlTimeoutValue = 20000;
// Keep app running when pause is received. (default = true)
// If true, then the JavaScript and native code continue to run in the background
// when another application (activity) is started.
protected boolean keepRunning = true;
/**
* Called when the activity is first created.
*
* @param savedInstanceState
*/
@Override
public void onCreate(Bundle savedInstanceState) {
LOG.d(TAG, "DroidGap.onCreate()");
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// This builds the view. We could probably get away with NOT having a LinearLayout, but I like having a bucket!
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
root = new LinearLayoutSoftKeyboardDetect(this, width, height);
root.setOrientation(LinearLayout.VERTICAL);
root.setBackgroundColor(this.backgroundColor);
root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT, 0.0F));
// Load PhoneGap configuration:
// white list of allowed URLs
// debug setting
this.loadConfiguration();
// If url was passed in to intent, then init webview, which will load the url
Bundle bundle = this.getIntent().getExtras();
if (bundle != null) {
String url = bundle.getString("url");
if (url != null) {
this.initUrl = url;
}
}
// Setup the hardware volume controls to handle volume control
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
/**
* Create and initialize web container.
*/
public void init() {
LOG.d(TAG, "DroidGap.init()");
// Create web container
this.appView = new WebView(DroidGap.this);
this.appView.setId(100);
this.appView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT,
1.0F));
WebViewReflect.checkCompatibility();
this.appView.setWebChromeClient(new GapClient(DroidGap.this));
this.setWebViewClient(this.appView, new GapViewClient(this));
this.appView.setInitialScale(100);
this.appView.setVerticalScrollBarEnabled(false);
this.appView.requestFocusFromTouch();
// Enable JavaScript
WebSettings settings = this.appView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
//Set the nav dump for HTC
settings.setNavDump(true);
// Enable database
settings.setDatabaseEnabled(true);
String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
// Enable DOM storage
WebViewReflect.setDomStorage(settings);
// Enable built-in geolocation
WebViewReflect.setGeolocationEnabled(settings, true);
// Add web view but make it invisible while loading URL
this.appView.setVisibility(View.INVISIBLE);
root.addView(this.appView);
setContentView(root);
// Clear cancel flag
this.cancelLoadUrl = false;
}
/**
* Set the WebViewClient.
*
* @param appView
* @param client
*/
protected void setWebViewClient(WebView appView, WebViewClient client) {
this.webViewClient = client;
appView.setWebViewClient(client);
}
/**
* Look at activity parameters and process them.
* This must be called from the main UI thread.
*/
private void handleActivityParameters() {
// If backgroundColor
this.backgroundColor = this.getIntegerProperty("backgroundColor", Color.BLACK);
this.root.setBackgroundColor(this.backgroundColor);
// If spashscreen
this.splashscreen = this.getIntegerProperty("splashscreen", 0);
if ((this.urls.size() == 0) && (this.splashscreen != 0)) {
root.setBackgroundResource(this.splashscreen);
}
// If loadUrlTimeoutValue
int timeout = this.getIntegerProperty("loadUrlTimeoutValue", 0);
if (timeout > 0) {
this.loadUrlTimeoutValue = timeout;
}
// If keepRunning
this.keepRunning = this.getBooleanProperty("keepRunning", true);
}
/**
* Load the url into the webview.
*
* @param url
*/
public void loadUrl(String url) {
// If first page of app, then set URL to load to be the one passed in
if (this.initUrl == null || (this.urls.size() > 0)) {
this.loadUrlIntoView(url);
}
// Otherwise use the URL specified in the activity's extras bundle
else {
this.loadUrlIntoView(this.initUrl);
}
}
/**
* Load the url into the webview.
*
* @param url
*/
private void loadUrlIntoView(final String url) {
if (!url.startsWith("javascript:")) {
LOG.d(TAG, "DroidGap.loadUrl(%s)", url);
}
// Init web view if not already done
if (this.appView == null) {
this.init();
}
this.url = url;
if (this.baseUrl == null) {
int i = url.lastIndexOf('/');
if (i > 0) {
this.baseUrl = url.substring(0, i+1);
}
else {
this.baseUrl = this.url + "/";
}
}
if (!url.startsWith("javascript:")) {
LOG.d(TAG, "DroidGap: url=%s baseUrl=%s", url, baseUrl);
}
// Load URL on UI thread
final DroidGap me = this;
this.runOnUiThread(new Runnable() {
public void run() {
// Handle activity parameters
me.handleActivityParameters();
// Track URLs loaded instead of using appView history
me.urls.push(url);
me.appView.clearHistory();
// Create callback server and plugin manager
if (me.callbackServer == null) {
me.callbackServer = new CallbackServer();
me.callbackServer.init(url);
}
else {
me.callbackServer.reinit(url);
}
if (me.pluginManager == null) {
me.pluginManager = new PluginManager(me.appView, me);
}
else {
me.pluginManager.reinit();
}
// If loadingDialog property, then show the App loading dialog for first page of app
String loading = null;
if (me.urls.size() == 0) {
loading = me.getStringProperty("loadingDialog", null);
}
else {
loading = me.getStringProperty("loadingPageDialog", null);
}
if (loading != null) {
String title = "";
String message = "Loading Application...";
if (loading.length() > 0) {
int comma = loading.indexOf(',');
if (comma > 0) {
title = loading.substring(0, comma);
message = loading.substring(comma+1);
}
else {
title = "";
message = loading;
}
}
me.spinnerStart(title, message);
}
// Create a timeout timer for loadUrl
final int currentLoadUrlTimeout = me.loadUrlTimeout;
Runnable runnable = new Runnable() {
public void run() {
try {
synchronized(this) {
wait(me.loadUrlTimeoutValue);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// If timeout, then stop loading and handle error
if (me.loadUrlTimeout == currentLoadUrlTimeout) {
me.appView.stopLoading();
LOG.e(TAG, "DroidGap: TIMEOUT ERROR! - calling webViewClient");
me.webViewClient.onReceivedError(me.appView, -6, "The connection to the server was unsuccessful.", url);
}
}
};
Thread thread = new Thread(runnable);
thread.start();
me.appView.loadUrl(url);
}
});
}
/**
* Load the url into the webview after waiting for period of time.
* This is used to display the splashscreen for certain amount of time.
*
* @param url
* @param time The number of ms to wait before loading webview
*/
public void loadUrl(final String url, int time) {
// If first page of app, then set URL to load to be the one passed in
if (this.initUrl == null || (this.urls.size() > 0)) {
this.loadUrlIntoView(url, time);
}
// Otherwise use the URL specified in the activity's extras bundle
else {
this.loadUrlIntoView(this.initUrl);
}
}
/**
* Load the url into the webview after waiting for period of time.
* This is used to display the splashscreen for certain amount of time.
*
* @param url
* @param time The number of ms to wait before loading webview
*/
private void loadUrlIntoView(final String url, final int time) {
// Clear cancel flag
this.cancelLoadUrl = false;
// If not first page of app, then load immediately
if (this.urls.size() > 0) {
this.loadUrlIntoView(url);
}
if (!url.startsWith("javascript:")) {
LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time);
}
final DroidGap me = this;
// Handle activity parameters
this.runOnUiThread(new Runnable() {
public void run() {
me.handleActivityParameters();
}
});
Runnable runnable = new Runnable() {
public void run() {
try {
synchronized(this) {
this.wait(time);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!me.cancelLoadUrl) {
me.loadUrlIntoView(url);
}
else{
me.cancelLoadUrl = false;
LOG.d(TAG, "Aborting loadUrl(%s): Another URL was loaded before timer expired.", url);
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
/**
* Cancel loadUrl before it has been loaded.
*/
public void cancelLoadUrl() {
this.cancelLoadUrl = true;
}
/**
* Clear the resource cache.
*/
public void clearCache() {
if (this.appView == null) {
this.init();
}
this.appView.clearCache(true);
}
/**
* Clear web history in this web view.
*/
public void clearHistory() {
this.urls.clear();
// Leave current url on history stack
if (this.url != null) {
this.urls.push(this.url);
}
}
/**
* Go to previous page in history. (We manage our own history)
*/
public void backHistory() {
if (this.urls.size() > 1) {
this.urls.pop(); // Pop current url
String url = this.urls.pop(); // Pop prev url that we want to load
this.loadUrl(url);
}
}
@Override
/**
* Called by the system when the device configuration changes while your activity is running.
*
* @param Configuration newConfig
*/
public void onConfigurationChanged(Configuration newConfig) {
//don't reload the current page when the orientation is changed
super.onConfigurationChanged(newConfig);
}
/**
* Get boolean property for activity.
*
* @param name
* @param defaultValue
* @return
*/
public boolean getBooleanProperty(String name, boolean defaultValue) {
Bundle bundle = this.getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
Boolean p = (Boolean)bundle.get(name);
if (p == null) {
return defaultValue;
}
return p.booleanValue();
}
/**
* Get int property for activity.
*
* @param name
* @param defaultValue
* @return
*/
public int getIntegerProperty(String name, int defaultValue) {
Bundle bundle = this.getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
Integer p = (Integer)bundle.get(name);
if (p == null) {
return defaultValue;
}
return p.intValue();
}
/**
* Get string property for activity.
*
* @param name
* @param defaultValue
* @return
*/
public String getStringProperty(String name, String defaultValue) {
Bundle bundle = this.getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
String p = bundle.getString(name);
if (p == null) {
return defaultValue;
}
return p;
}
/**
* Get double property for activity.
*
* @param name
* @param defaultValue
* @return
*/
public double getDoubleProperty(String name, double defaultValue) {
Bundle bundle = this.getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
Double p = (Double)bundle.get(name);
if (p == null) {
return defaultValue;
}
return p.doubleValue();
}
/**
* Set boolean property on activity.
*
* @param name
* @param value
*/
public void setBooleanProperty(String name, boolean value) {
this.getIntent().putExtra(name, value);
}
/**
* Set int property on activity.
*
* @param name
* @param value
*/
public void setIntegerProperty(String name, int value) {
this.getIntent().putExtra(name, value);
}
/**
* Set string property on activity.
*
* @param name
* @param value
*/
public void setStringProperty(String name, String value) {
this.getIntent().putExtra(name, value);
}
/**
* Set double property on activity.
*
* @param name
* @param value
*/
public void setDoubleProperty(String name, double value) {
this.getIntent().putExtra(name, value);
}
@Override
/**
* Called when the system is about to start resuming a previous activity.
*/
protected void onPause() {
super.onPause();
// Don't process pause if shutting down, since onDestroy() will be called
if (this.activityState == ACTIVITY_EXITING) {
return;
}
if (this.appView == null) {
return;
}
// Send pause event to JavaScript
this.appView.loadUrl("javascript:try{PhoneGap.onPause.fire();}catch(e){};");
// Forward to plugins
this.pluginManager.onPause(this.keepRunning);
// If app doesn't want to run in background
if (!this.keepRunning) {
// Pause JavaScript timers (including setInterval)
this.appView.pauseTimers();
}
}
@Override
/**
* Called when the activity receives a new intent
**/
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//Forward to plugins
this.pluginManager.onNewIntent(intent);
}
@Override
/**
* Called when the activity will start interacting with the user.
*/
protected void onResume() {
super.onResume();
if (this.activityState == ACTIVITY_STARTING) {
this.activityState = ACTIVITY_RUNNING;
return;
}
if (this.appView == null) {
return;
}
// Send resume event to JavaScript
this.appView.loadUrl("javascript:try{PhoneGap.onResume.fire();}catch(e){};");
// Forward to plugins
this.pluginManager.onResume(this.keepRunning || this.activityResultKeepRunning);
// If app doesn't want to run in background
if (!this.keepRunning || this.activityResultKeepRunning) {
// Restore multitasking state
if (this.activityResultKeepRunning) {
this.keepRunning = this.activityResultKeepRunning;
this.activityResultKeepRunning = false;
}
// Resume JavaScript timers (including setInterval)
this.appView.resumeTimers();
}
}
@Override
/**
* The final call you receive before your activity is destroyed.
*/
public void onDestroy() {
super.onDestroy();
if (this.appView != null) {
// Send destroy event to JavaScript
this.appView.loadUrl("javascript:try{PhoneGap.onDestroy.fire();}catch(e){};");
// Load blank page so that JavaScript onunload is called
this.appView.loadUrl("about:blank");
// Forward to plugins
this.pluginManager.onDestroy();
}
else {
this.endActivity();
}
}
/**
* Add a class that implements a service.
*
* @param serviceType
* @param className
*/
public void addService(String serviceType, String className) {
this.pluginManager.addService(serviceType, className);
}
/**
* Send JavaScript statement back to JavaScript.
* (This is a convenience method)
*
* @param message
*/
public void sendJavascript(String statement) {
this.callbackServer.sendJavascript(statement);
}
/**
* Load the specified URL in the PhoneGap webview or a new browser instance.
*
* NOTE: If openExternal is false, only URLs listed in whitelist can be loaded.
*
* @param url The url to load.
* @param openExternal Load url in browser instead of PhoneGap webview.
* @param clearHistory Clear the history stack, so new page becomes top of history
* @param params DroidGap parameters for new app
*/
public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException {
LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory);
// If clearing history
if (clearHistory) {
this.clearHistory();
}
// If loading into our webview
if (!openExternal) {
// Make sure url is in whitelist
if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) {
// TODO: What about params?
// Clear out current url from history, since it will be replacing it
if (clearHistory) {
this.urls.clear();
}
// Load new URL
this.loadUrl(url);
}
// Load in default viewer if not
else {
LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")");
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
// Load in default view intent
else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
/**
* Show the spinner. Must be called from the UI thread.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public void spinnerStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final DroidGap me = this;
this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true,
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
me.spinnerDialog = null;
}
});
}
/**
* Stop spinner.
*/
public void spinnerStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Set the chrome handler.
*/
public class GapClient extends WebChromeClient {
private String TAG = "PhoneGapLog";
private long MAX_QUOTA = 100 * 1024 * 1024;
private DroidGap ctx;
/**
* Constructor.
*
* @param ctx
*/
public GapClient(Context ctx) {
this.ctx = (DroidGap)ctx;
}
/**
* Tell the client to display a javascript alert dialog.
*
* @param view
* @param url
* @param message
* @param result
*/
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Alert");
//Don't let alerts break the back button
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.confirm();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.confirm();
return false;
}
else
return true;
}
});
dlg.create();
dlg.show();
return true;
}
/**
* Tell the client to display a confirm dialog to the user.
*
* @param view
* @param url
* @param message
* @param result
*/
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Confirm");
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.cancel();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.cancel();
return false;
}
else
return true;
}
});
dlg.create();
dlg.show();
return true;
}
/**
* Tell the client to display a prompt dialog to the user.
* If the client returns true, WebView will assume that the client will
* handle the prompt dialog and call the appropriate JsPromptResult method.
*
* Since we are hacking prompts for our own purposes, we should not be using them for
* this purpose, perhaps we should hack console.log to do this instead!
*
* @param view
* @param url
* @param message
* @param defaultValue
* @param result
*/
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
// Security check to make sure any requests are coming from the page initially
// loaded in webview and not another loaded in an iframe.
boolean reqOk = false;
if (url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) {
reqOk = true;
}
// Calling PluginManager.exec() to call a native service using
// prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true]));
if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) {
JSONArray array;
try {
array = new JSONArray(defaultValue.substring(4));
String service = array.getString(0);
String action = array.getString(1);
String callbackId = array.getString(2);
boolean async = array.getBoolean(3);
String r = pluginManager.exec(service, action, callbackId, message, async);
result.confirm(r);
} catch (JSONException e) {
e.printStackTrace();
}
}
// Polling for JavaScript messages
else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) {
String r = callbackServer.getJavascript();
result.confirm(r);
}
// Calling into CallbackServer
else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) {
String r = "";
if (message.equals("usePolling")) {
r = ""+callbackServer.usePolling();
}
else if (message.equals("restartServer")) {
callbackServer.restartServer();
}
else if (message.equals("getPort")) {
r = Integer.toString(callbackServer.getPort());
}
else if (message.equals("getToken")) {
r = callbackServer.getToken();
}
result.confirm(r);
}
// PhoneGap JS has initialized, so show webview
// (This solves white flash seen when rendering HTML)
else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) {
appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
result.confirm("OK");
}
// Show dialog
else {
final JsPromptResult res = result;
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
final EditText input = new EditText(this.ctx);
if (defaultValue != null) {
input.setText(defaultValue);
}
dlg.setView(input);
dlg.setCancelable(false);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String usertext = input.getText().toString();
res.confirm(usertext);
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
res.cancel();
}
});
dlg.create();
dlg.show();
}
return true;
}
/**
* Handle database quota exceeded notification.
*
* @param url
* @param databaseIdentifier
* @param currentQuota
* @param estimatedSize
* @param totalUsedQuota
* @param quotaUpdater
*/
@Override
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
{
LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
if( estimatedSize < MAX_QUOTA)
{
//increase for 1Mb
long newQuota = estimatedSize;
LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota);
quotaUpdater.updateQuota(newQuota);
}
else
{
// Set the quota to whatever it is and force an error
// TODO: get docs on how to handle this properly
quotaUpdater.updateQuota(currentQuota);
}
}
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID)
{
LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message);
super.onConsoleMessage(message, lineNumber, sourceID);
}
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{
LOG.d(TAG, consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
@Override
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
}
/**
* The webview client receives notifications about appView
*/
public class GapViewClient extends WebViewClient {
DroidGap ctx;
/**
* Constructor.
*
* @param ctx
*/
public GapViewClient(DroidGap ctx) {
this.ctx = ctx;
}
/**
* Give the host application a chance to take over the control when a new url
* is about to be loaded in the current WebView.
*
* @param view The WebView that is initiating the callback.
* @param url The url to be loaded.
* @return true to override, false for default behavior
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// First give any plugins the chance to handle the url themselves
if (this.ctx.pluginManager.onOverrideUrlLoading(url)) {
}
// If dialing phone (tel:5551212)
else if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error dialing "+url+": "+ e.toString());
}
}
// If displaying map (geo:0,0?q=address)
else if (url.startsWith("geo:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error showing map "+url+": "+ e.toString());
}
}
// If sending email (mailto:abc@corp.com)
else if (url.startsWith(WebView.SCHEME_MAILTO)) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending email "+url+": "+ e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
}
else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:"+address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending sms "+url+":"+ e.toString());
}
}
// All else
else {
// If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity.
// Our app continues to run. When BACK is pressed, our app is redisplayed.
if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) {
this.ctx.loadUrl(url);
}
// If not our application, let default viewer handle
else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Clear history so history.back() doesn't do anything.
// So we can reinit() native side CallbackServer & PluginManager.
view.clearHistory();
}
/**
* Notify the host application that a page has finished loading.
*
* @param view The webview initiating the callback.
* @param url The url of the page.
*/
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// Clear timeout flag
this.ctx.loadUrlTimeout++;
// Try firing the onNativeReady event in JS. If it fails because the JS is
// not loaded yet then just set a flag so that the onNativeReady can be fired
// from the JS side when the JS gets to that code.
if (!url.equals("about:blank")) {
appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}");
}
// Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly
if (appView.getVisibility() == View.INVISIBLE) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
ctx.runOnUiThread(new Runnable() {
public void run() {
appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
}
});
} catch (InterruptedException e) {
}
}
});
t.start();
}
// Shutdown if blank loaded
if (url.equals("about:blank")) {
if (this.ctx.callbackServer != null) {
this.ctx.callbackServer.destroy();
}
this.ctx.endActivity();
}
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param view The WebView that is initiating the callback.
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
// Clear timeout flag
this.ctx.loadUrlTimeout++;
// Stop "app loading" spinner if showing
this.ctx.spinnerStop();
// Handle error
this.ctx.onReceivedError(errorCode, description, failingUrl);
}
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
final String packageName = this.ctx.getPackageName();
final PackageManager pm = this.ctx.getPackageManager();
ApplicationInfo appInfo;
try {
appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
// debug = true
handler.proceed();
return;
} else {
// debug = false
super.onReceivedSslError(view, handler, error);
}
} catch (NameNotFoundException e) {
// When it doubt, lock it out!
super.onReceivedSslError(view, handler, error);
}
}
}
/**
* End this activity by calling finish for activity
*/
public void endActivity() {
this.finish();
}
/**
* Called when a key is pressed.
*
* @param keyCode
* @param event
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (this.appView == null) {
return super.onKeyDown(keyCode, event);
}
// If back key
if (keyCode == KeyEvent.KEYCODE_BACK) {
// If back key is bound, then send event to JavaScript
if (this.bound) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');");
return true;
}
// If not bound
else {
// Go to previous page in webview if it is possible to go back
if (this.urls.size() > 1) {
this.backHistory();
return true;
}
// If not, then invoke behavior of super class
else {
return super.onKeyDown(keyCode, event);
}
}
}
// If menu key
else if (keyCode == KeyEvent.KEYCODE_MENU) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');");
return true;
}
// If search key
else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');");
return true;
}
return false;
}
/**
* Any calls to Activity.startActivityForResult must use method below, so
* the result can be routed to them correctly.
*
* This is done to eliminate the need to modify DroidGap.java to receive activity results.
*
* @param intent The intent to start
* @param requestCode Identifies who to send the result to
*
* @throws RuntimeException
*/
@Override
public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException {
LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode);
super.startActivityForResult(intent, requestCode);
}
/**
* Launch an activity for which you would like a result when it finished. When this activity exits,
* your onActivityResult() method will be called.
*
* @param command The command object
* @param intent The intent to start
* @param requestCode The request code that is passed to callback to identify the activity
*/
public void startActivityForResult(IPlugin command, Intent intent, int requestCode) {
this.activityResultCallback = command;
this.activityResultKeepRunning = this.keepRunning;
// If multitasking turned on, then disable it for activities that return results
if (command != null) {
this.keepRunning = false;
}
// Start activity
super.startActivityForResult(intent, requestCode);
}
@Override
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
*
* @param requestCode The request code originally supplied to startActivityForResult(),
* allowing you to identify who this result came from.
* @param resultCode The integer result code returned by the child activity through its setResult().
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
IPlugin callback = this.activityResultCallback;
if (callback != null) {
callback.onActivityResult(requestCode, resultCode, intent);
}
}
@Override
public void setActivityResultCallback(IPlugin plugin) {
this.activityResultCallback = plugin;
}
/**
* Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable).
* The errorCode parameter corresponds to one of the ERROR_* constants.
*
* @param errorCode The error code corresponding to an ERROR_* value.
* @param description A String describing the error.
* @param failingUrl The url that failed to load.
*/
public void onReceivedError(int errorCode, String description, String failingUrl) {
final DroidGap me = this;
// If errorUrl specified, then load it
final String errorUrl = me.getStringProperty("errorUrl", null);
if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
public void run() {
me.showWebPage(errorUrl, true, true, null);
}
});
}
// If not, then display error dialog
else {
me.appView.setVisibility(View.GONE);
me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true);
}
}
/**
* Display an error dialog and optionally exit application.
*
* @param title
* @param message
* @param button
* @param exit
*/
public void displayError(final String title, final String message, final String button, final boolean exit) {
final DroidGap me = this;
me.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(me);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(button,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (exit) {
me.endActivity();
}
}
});
dlg.create();
dlg.show();
}
});
}
/**
* We are providing this class to detect when the soft keyboard is shown
* and hidden in the web view.
*/
class LinearLayoutSoftKeyboardDetect extends LinearLayout {
private static final String TAG = "SoftKeyboardDetect";
private int oldHeight = 0; // Need to save the old height as not to send redundant events
private int oldWidth = 0; // Need to save old width for orientation change
private int screenWidth = 0;
private int screenHeight = 0;
public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) {
super(context);
screenWidth = width;
screenHeight = height;
}
@Override
/**
* Start listening to new measurement events. Fire events when the height
* gets smaller fire a show keyboard event and when height gets bigger fire
* a hide keyboard event.
*
* Note: We are using callbackServer.sendJavascript() instead of
* this.appView.loadUrl() as changing the URL of the app would cause the
* soft keyboard to go away.
*
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
LOG.v(TAG, "We are in our onMeasure method");
// Get the current height of the visible part of the screen.
// This height will not included the status bar.
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
LOG.v(TAG, "Old Height = %d", oldHeight);
LOG.v(TAG, "Height = %d", height);
LOG.v(TAG, "Old Width = %d", oldWidth);
LOG.v(TAG, "Width = %d", width);
// If the oldHeight = 0 then this is the first measure event as the app starts up.
// If oldHeight == height then we got a measurement change that doesn't affect us.
if (oldHeight == 0 || oldHeight == height) {
LOG.d(TAG, "Ignore this event");
}
// Account for orientation change and ignore this event/Fire orientation change
else if(screenHeight == width)
{
int tmp_var = screenHeight;
screenHeight = screenWidth;
screenWidth = tmp_var;
LOG.v(TAG, "Orientation Change");
}
// If the height as gotten bigger then we will assume the soft keyboard has
// gone away.
else if (height > oldHeight) {
LOG.v(TAG, "Throw hide keyboard event");
callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');");
}
// If the height as gotten smaller then we will assume the soft keyboard has
// been displayed.
else if (height < oldHeight) {
LOG.v(TAG, "Throw show keyboard event");
callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');");
}
// Update the old height for the next event
oldHeight = height;
oldWidth = width;
}
}
private void loadConfiguration() {
int id = getResources().getIdentifier("phonegap", "xml", getPackageName());
if (id == 0) {
LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring...");
return;
}
XmlResourceParser xml = getResources().getXml(id);
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = xml.getName();
if (strNode.equals("access")) {
String origin = xml.getAttributeValue(null, "origin");
String subdomains = xml.getAttributeValue(null, "subdomains");
if (origin != null) {
this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
}
}
else if (strNode.equals("log")) {
String level = xml.getAttributeValue(null, "level");
LOG.i("PhoneGapLog", "Found log level %s", level);
if (level != null) {
LOG.setLogLevel(level);
}
}
}
try {
eventType = xml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Add entry to approved list of URLs (whitelist)
*
* @param origin URL regular expression to allow
* @param subdomains T=include all subdomains under origin
*/
public void addWhiteListEntry(String origin, boolean subdomains) {
try {
// Unlimited access to network resources
if(origin.compareTo("*") == 0) {
LOG.d(TAG, "Unlimited access to network resources");
whiteList.add(Pattern.compile("*"));
} else { // specific access
// check if subdomains should be included
// TODO: we should not add more domains if * has already been added
if (subdomains) {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if(origin.startsWith("http")) {
whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://.*")));
} else {
whiteList.add(Pattern.compile("^https{0,1}://.*"+origin));
}
LOG.d(TAG, "Origin to allow with subdomains: %s", origin);
} else {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if(origin.startsWith("http")) {
whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://")));
} else {
whiteList.add(Pattern.compile("^https{0,1}://"+origin));
}
LOG.d(TAG, "Origin to allow: %s", origin);
}
}
} catch(Exception e) {
LOG.d(TAG, "Failed to add origin %s", origin);
}
}
/**
* Determine if URL is in approved list of URLs to load.
*
* @param url
* @return
*/
private boolean isUrlWhiteListed(String url) {
// Check to see if we have matched url previously
if (whiteListCache.get(url) != null) {
return true;
}
// Look for match in white list
Iterator<Pattern> pit = whiteList.iterator();
while (pit.hasNext()) {
Pattern p = pit.next();
Matcher m = p.matcher(url);
// If match found, then cache it to speed up subsequent comparisons
if (m.find()) {
whiteListCache.put(url, true);
return true;
}
}
return false;
}
}
|
package team1100.season2010.robot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.DigitalInput;
public class RobotDriveController
{
private int back_pot_max = 461;
private int back_pot_center = 391;
private int back_pot_min = 318;
private int front_pot_max = 862;
private int front_pot_center = 790;
private int front_pot_min = 714;
private int drive_type;
private int joystick_type;
private int prev_drive_type;
private int diagnostic_state;
private int joystick_adjust_X;
private int joystick_adjust_Y;
public Joystick joystick_1;
public Joystick joystick_2;
private AdvJaguar front_right_motor;
private AdvJaguar front_left_motor;
private AdvJaguar back_right_motor;
private AdvJaguar back_left_motor;
private int motor_direction_adjust;
private int FRM_channel;
private int FLM_channel;
private int BRM_channel;
private int BLM_channel;
private DigitalInput limit_front_max;
private DigitalInput limit_front_min;
private DigitalInput limit_back_max;
private DigitalInput limit_back_min;
//private RobotDrive tank_drive;
private AverageController drive_motor_speed_setpoint;
private SteeringPID CRM_back;
private SteeringPID CRM_front;
private DSKnob frontCentering;
private DSKnob rearCentering;
private DSKnob steeringGain;
public RobotDriveController()
{
this(0,1,2,1,2,3,4,5,6,7,8,10);
}
public RobotDriveController(int type, int j1_channel, int j2_channel, int frm_channel,
int flm_channel, int brm_channel, int blm_channel, int CRM_front_channel, int CRM_back_channel,
int pot_front_channel, int pot_back_channel,int avgNum)
{
drive_type = type;
joystick_type = 0;
prev_drive_type = 1;
diagnostic_state = 0;
joystick_adjust_Y = 1; //JOYSTICK ADJUST LOCATION
joystick_adjust_X = -1;
joystick_1 = new Joystick(j1_channel);
joystick_2 = new Joystick(j2_channel);
front_right_motor = new AdvJaguar(frm_channel);
FRM_channel = frm_channel;
front_left_motor = new AdvJaguar(flm_channel);
FLM_channel = flm_channel;
back_right_motor = new AdvJaguar(brm_channel);
BRM_channel = brm_channel;
back_left_motor = new AdvJaguar(blm_channel);
BLM_channel = blm_channel;
drive_motor_speed_setpoint = new AverageController(avgNum);
CRM_back = new SteeringPID(pot_back_channel, CRM_back_channel, true);
CRM_front = new SteeringPID(pot_front_channel, CRM_front_channel, true);
frontCentering = new DSKnob(1);
rearCentering = new DSKnob(2);
steeringGain = new DSKnob(4);
CRM_back.setOperatingRangePct(15);
CRM_back.setCenterPct(49);
CRM_back.setLinearPct(steeringGain.getCurrentValue() * 20);
CRM_front.setOperatingRangePct(15);
CRM_front.setCenterPct(74);
CRM_front.setLinearPct(steeringGain.getCurrentValue() * 20);
limit_front_max = new DigitalInput(4,12);
limit_front_min = new DigitalInput(4,11);
limit_back_max = new DigitalInput(4,14);
limit_back_min = new DigitalInput(4,13);
}
/*Sets drive type (tank, swerve, car...)
* @param type : 0 = tank drive, 1 = car drive, 2 = swerve drive, 3 = swerve rotation, 4 = diagnostic
* */
public void setDriveType(int type)
{
drive_type = type;
if(drive_type == 2)
{
//translationInit();
}
if(drive_type == 3)
{
//rotationInit();
}
}
public int getDriveType ()
{
return drive_type;
}
//@param type: 0 = one joystick mode, 1 = two joystick mode
public void setJoystickType(int type)
{
joystick_type = type;
}
public int getJoystickType()
{
return joystick_type;
}
public void change90Mode()
{
if(drive_type == 22)
{
drive_type = prev_drive_type;
}
else
{
if(drive_type != 33)
prev_drive_type = drive_type;
drive_type = 22;
}
//translationInit();
}
/*public void change45Mode()
{
if(drive_type == 33)
drive_type = prev_drive_type;
else
{
if(drive_type != 22)
prev_drive_type = drive_type;
drive_type = 33;
}
rotationInit();
}*/
public void setInvertJoystickX()
{
joystick_adjust_X = joystick_adjust_X * -1;
System.out.println("X inverted");
}
public void setInvertJoystickY()
{
joystick_adjust_Y = joystick_adjust_Y * -1;
System.out.println("Y inverted");
}
public String getPotVals()
{
return "POT VALS: + CRM Front: " + CRM_front.getPot() +
"\tctr: " + CRM_front.getCtr() +
"\tCRM Back: " + CRM_back.getPot() +
"\tctr: " + CRM_back.getCtr() + "\n";
}
public String getPWMVals()
{
return "PWM VALS: \nCRM Front: ";//+ CRM_front.getPWM() + "\n\tCRM Back: " + CRM_back.getPWM() + "\n";
}
public String getJoystickVals()
{
if(joystick_type == 1)
return "JOYSTICK VALS: \n X:" + joystick_1.getX() + "\n\tY: " + joystick_2.getY() + "\n\n";
else return "JOYSTICK VALS: \n X:" + joystick_1.getX() + "\n\tY: " + joystick_1.getY() + "\n\n";
}
public void drive()
{
// System.out.println(getPotVals());
//if (drive_type == 0)
// tankDrive();
// the analog input ranges from about 0 to 3.2
CRM_front.setCenterPct(frontCentering.getCurrentValue()*30);
CRM_back.setCenterPct(rearCentering.getCurrentValue()*30);
CRM_front.setLinearPct(steeringGain.getCurrentValue() * 20);
CRM_back.setLinearPct(steeringGain.getCurrentValue() * 20);
if(joystick_type == 1) //2 Joystick
{
if(drive_type == 1)
carDrive();
else if(drive_type == 2)
swerveDrive();
else if(drive_type == 3)
swerveRotationDrive();
else if(drive_type == 4)
diagnostic();
else if(drive_type == 22)
translate90_TwoJoystick();
//else if(drive_type == 33)
//rotate45_TwoJoystick();
else if(drive_type == 5)
diagnosticLimitSwitches();
else if(drive_type == 6)
pitSetup();
else if(drive_type == 7)
setPCoeffsDriveSetup();
}
else //1 joystick
{
if(drive_type == 1)
carDriveOneJoystick();
else if(drive_type == 2)
swerveDriveOneJoystick();
else if(drive_type == 3)
swerveRotationDriveOneJoystick();
else if(drive_type == 4)
diagnostic();
else if(drive_type == 22)
translate90_OneJoystick();
//else if(drive_type == 33)
//rotate45_OneJoystick();
else if(drive_type == 5)
diagnosticLimitSwitches();
else if(drive_type == 6)
pitSetup();
else if(drive_type == 7)
setPCoeffsDriveSetup();
}
/*if(!limit_back_max.get() || !limit_back_min.get())
CRM_back.setDirect(0);
if(!limit_front_max.get() || !limit_front_min.get())
CRM_front.setDirect(0);*/
}
public void driveAutonomous(int driveType, double speed)
{
if(driveType == 1)
{
CRM_back.setDirection(0);
CRM_front.setDirection(0);
goTankDriveAutonomous(speed);
}
if(driveType == 2)
{
swerveDriveAutonomous(speed);
}
}
public void setSteeringCenter()
{
CRM_back.setCenterPct(rearCentering.getCurrentValue()*30);
CRM_back.setLinearPct(steeringGain.getCurrentValue() * 20);
CRM_front.setCenterPct(frontCentering.getCurrentValue()*30);
CRM_front.setLinearPct(steeringGain.getCurrentValue() * 20);
CRM_back.setDirection(0);
CRM_front.setDirection(0);
}
private void diagnostic()
{
System.out.println(getPotVals());
/*if(joystick_1.getX()>.4)
CRM_back.setDirect(.2);
else if(joystick_1.getX()<-.4)
CRM_back.setDirect(-.2);
else CRM_back.setDirect(0);
if(joystick_2.getX()>.4)
CRM_front.setDirect(.2);
else if(joystick_2.getX()<-.4)
CRM_front.setDirect(-.2);
else CRM_front.setDirect(0);*/
}
private void diagnosticLimitSwitches()
{
/*if(joystick_1.getTrigger())
{
if(diagnostic_state == 0) //find max
{
CRM_front.setDirect(.2);
if(!limit_front_max.get()) //hits limit switch
{
CRM_front.setDirect(0);
System.out.println("CRM_front pot_max: " + CRM_front.getPot());
CRM_front.setPotMax(CRM_front.getPot());
diagnostic_state++;
}
}
else if(diagnostic_state == 1) //find min
{
CRM_front.setDirect(-.2);
if(!limit_front_min.get()) //hits limit switch 2
{
CRM_front.setDirect(0);
System.out.println("CRM_front pot_min: " + CRM_front.getPot());
CRM_front.setPotMin(CRM_front.getPot());
diagnostic_state++;
}
}
else if(diagnostic_state == 2) //find max
{
CRM_back.setDirect(.2);
if(!limit_back_max.get()) //hits limit switch
{
CRM_back.setDirect(0);
System.out.println("CRM_back pot_max: " + CRM_back.getPot());
CRM_back.setPotMax(CRM_back.getPot());
diagnostic_state++;
}
}
else if(diagnostic_state == 3) //find min
{
CRM_back.setDirect(-.2);
if(!limit_back_min.get()) //hits limit switch 2
{
CRM_back.setDirect(0);
System.out.println("CRM_back pot_min: " + CRM_back.getPot());
CRM_back.setPotMin(CRM_back.getPot());
diagnostic_state++;
}
}
}*/
}
private void tankDrive()
{
CRM_back.setDirection(0);
CRM_front.setDirection(0);
goTankDrive();
}
private void goTankDrive()
{
front_right_motor.set(joystick_2.getY());
front_left_motor.set(joystick_1.getY());
back_right_motor.set(joystick_2.getY());
back_left_motor.set(joystick_1.getY());
}
private void goTankDriveAutonomous(double spd)
{
spd = -spd;
front_right_motor.set(spd);
front_left_motor.set(spd);
back_right_motor.set(spd);
back_left_motor.set(spd);
}
private void carDrive()
{
CRM_back.setDirection(0);
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_2.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_front.setDirection(-joystick_adjust_X * joystick_1.getX());
}
private void carDriveOneJoystick()
{
CRM_back.setDirection(0);
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y *joystick_1.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_front.setDirection(-joystick_adjust_X * joystick_1.getX());
}
private void swerveDrive()
{
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_2.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_back.setDirection(joystick_adjust_X * joystick_1.getX());
CRM_front.setDirection(-joystick_adjust_X * joystick_1.getX());
}
private void swerveDriveAutonomous(double spd)
{
drive_motor_speed_setpoint.addNewValue(spd);
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_back.setDirection(1);
CRM_front.setDirection(-1);
}
private void swerveDriveOneJoystick()
{
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_1.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_back.setDirection(joystick_adjust_X * joystick_1.getX());
CRM_front.setDirection(-joystick_adjust_X * joystick_1.getX());
}
private void translate90_TwoJoystick()
{
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_2.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_back.setDirection(joystick_adjust_X);
CRM_front.setDirection(-joystick_adjust_X);
}
private void translate90_OneJoystick()
{
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_1.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_back.setDirection(joystick_adjust_X);
CRM_front.setDirection(-joystick_adjust_X);
}
private void swerveRotationDrive()
{
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_2.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_back.setDirection(-joystick_adjust_X * joystick_1.getX() * 0.4);
CRM_front.setDirection(-joystick_adjust_X * joystick_1.getX() * 0.4);
}
private void swerveRotationDriveOneJoystick()
{
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_1.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_back.setDirection(-joystick_adjust_X * joystick_1.getX() * 0.4);
CRM_front.setDirection(-joystick_adjust_X * joystick_1.getX() * 0.4);
}
/*private void rotate45_TwoJoystick()
{
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_2.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
if(joystick_1.getX()<0)
{
CRM_back.setWheelDirection(joystick_adjust_X);
CRM_front.setWheelDirection(joystick_adjust_X);
}
else
{
CRM_back.setWheelDirection(-joystick_adjust_X);
CRM_front.setWheelDirection(-joystick_adjust_X);
}
}
private void rotate45_OneJoystick()
{
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_1.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
if(joystick_1.getX()<0)
{
CRM_back.setWheelDirection(joystick_adjust_X);
CRM_front.setWheelDirection(joystick_adjust_X);
}
else
{
CRM_back.setWheelDirection(-joystick_adjust_X);
CRM_front.setWheelDirection(-joystick_adjust_X);
}
}*/
public void pitSetup()
{
CRM_front.setDirection(0);
CRM_back.setDirection(0);
}
public void setPCoeffsDriveSetup()
{
//Z-Axis of joystick 1 controls the pCoeffs of the CRMs
//Z-Axis of joystick 2 controls the minSpeed of the CRMs
System.out.println("\t\t\t\tPCOEFF FRONT: "+(joystick_1.getZ()+1)/2);
System.out.println("\t\t\t\tPCOEFF BACK: " + (joystick_2.getZ()+1)/2);
//CRM_back.setPCoeff((joystick_2.getZ()+1)/2);
//CRM_front.setPCoeff((joystick_1.getZ()+1)/2);
//CRM_back.setMinSpeed((joystick_2.getZ()+1)/2);
//CRM_front.setMinSpeed((joystick_2.getZ()+1)/2);
drive_motor_speed_setpoint.addNewValue(joystick_adjust_Y * joystick_1.getY());
front_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
front_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_right_motor.set(drive_motor_speed_setpoint.getAverageValue());
back_left_motor.set(drive_motor_speed_setpoint.getAverageValue());
CRM_back.setDirection(joystick_adjust_X * joystick_1.getX());
CRM_front.setDirection(-joystick_adjust_X * joystick_1.getX());
}
public void setInvertedMotor(boolean m1, boolean m2, boolean m3, boolean m4)
{
front_right_motor.setInvertedMotor(m1);
front_left_motor.setInvertedMotor(m2);
back_right_motor.setInvertedMotor(m3);
back_left_motor.setInvertedMotor(m4);
}
/*private void translationInit()
{
CRM_back.setPotMax(back_pot_max);
CRM_back.setPotCenter(back_pot_center);
CRM_back.setPotMin(back_pot_min);
CRM_front.setPotCenter(front_pot_center);
CRM_front.setPotMax(front_pot_max);
CRM_front.setPotMin(front_pot_min);
}
private void rotationInit()
{
CRM_back.setPotMax((back_pot_max - back_pot_center)/2 + back_pot_center);
CRM_back.setPotCenter(back_pot_center);
CRM_back.setPotMin((back_pot_center - back_pot_min)/2 + back_pot_min);
CRM_front.setPotMax((front_pot_max - front_pot_center)/2 + front_pot_center);
CRM_front.setPotCenter(front_pot_center);
CRM_front.setPotMin((front_pot_center - front_pot_min)/2 + front_pot_min);
}*/
}
|
package org.openlca.app.editors.processes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.openlca.app.App;
import org.openlca.app.M;
import org.openlca.app.components.ContributionImage;
import org.openlca.app.db.Cache;
import org.openlca.app.db.Database;
import org.openlca.app.editors.ModelPage;
import org.openlca.app.rcp.images.Images;
import org.openlca.app.util.Controls;
import org.openlca.app.util.Labels;
import org.openlca.app.util.Numbers;
import org.openlca.app.util.UI;
import org.openlca.app.util.trees.Trees;
import org.openlca.app.util.viewers.Viewers;
import org.openlca.app.viewers.combo.ImpactMethodViewer;
import org.openlca.core.database.ImpactMethodDao;
import org.openlca.core.math.ReferenceAmount;
import org.openlca.core.matrix.DIndex;
import org.openlca.core.matrix.FlowIndex;
import org.openlca.core.matrix.ImpactTable;
import org.openlca.core.matrix.ParameterTable;
import org.openlca.core.matrix.format.IMatrix;
import org.openlca.core.model.Exchange;
import org.openlca.core.model.FlowType;
import org.openlca.core.model.ModelType;
import org.openlca.core.model.Process;
import org.openlca.core.model.descriptors.Descriptors;
import org.openlca.core.model.descriptors.FlowDescriptor;
import org.openlca.core.model.descriptors.ImpactCategoryDescriptor;
import org.openlca.core.model.descriptors.ImpactMethodDescriptor;
import org.openlca.expressions.FormulaInterpreter;
import org.openlca.io.CategoryPath;
import org.openlca.util.Strings;
class ImpactPage extends ModelPage<Process> {
private Button zeroCheck;
private TreeViewer tree;
ImpactPage(ProcessEditor editor) {
super(editor, "ProcessImpactPage", M.ImpactAnalysis);
}
@Override
protected void createFormContent(IManagedForm mform) {
ScrolledForm form = UI.formHeader(this);
FormToolkit tk = mform.getToolkit();
Composite body = UI.formBody(form, tk);
Composite comp = tk.createComposite(body);
UI.gridLayout(comp, 3);
UI.formLabel(comp, tk, M.ImpactAssessmentMethod);
ImpactMethodViewer combo = new ImpactMethodViewer(comp);
List<ImpactMethodDescriptor> list = new ImpactMethodDao(Database.get())
.getDescriptors()
.stream().sorted((m1, m2) -> Strings.compare(
m1.getName(), m2.getName()))
.collect(Collectors.toList());
combo.setInput(list);
combo.addSelectionChangedListener(m -> setTreeInput(m));
zeroCheck = tk.createButton(comp, M.ExcludeZeroValues, SWT.CHECK);
zeroCheck.setSelection(true);
Controls.onSelect(
zeroCheck, e -> setTreeInput(combo.getSelected()));
tree = Trees.createViewer(body,
M.Name, M.Category, M.Amount, M.Result);
UI.gridData(tree.getControl(), true, true);
tree.setContentProvider(new Content());
tree.setLabelProvider(new Label());
Trees.bindColumnWidths(tree.getTree(),
0.25, 0.25, 0.25, 0.25);
tree.getTree().getColumns()[2].setAlignment(SWT.RIGHT);
tree.getTree().getColumns()[3].setAlignment(SWT.RIGHT);
Trees.onDoubleClick(tree, e -> {
Node node = Viewers.getFirstSelected(tree);
if (node == null)
return;
if (node.exchange != null) {
App.openEditor(node.exchange.flow);
} else if (node.impact != null) {
App.openEditor(combo.getSelected());
}
});
if (!list.isEmpty()) {
ImpactMethodDescriptor m = list.get(0);
combo.select(m);
setTreeInput(m);
}
form.reflow(true);
}
private void setTreeInput(ImpactMethodDescriptor method) {
AtomicReference<List<Node>> ref = new AtomicReference<>();
boolean skipZeros = zeroCheck.getSelection();
App.runWithProgress("Load tree", () -> {
ref.set(buildTree(method, skipZeros));
}, () -> {
List<Node> nodes = ref.get();
if (nodes != null) {
tree.setInput(nodes);
}
});
}
private List<Node> buildTree(ImpactMethodDescriptor method,
boolean skipZeros) {
if (method == null)
return Collections.emptyList();
// index the elementary flows
List<Exchange> eList = getModel().getExchanges();
double[] values = new double[eList.size()];
Exchange[] exchanges = new Exchange[eList.size()];
FlowIndex flowIdx = new FlowIndex();
for (Exchange e : eList) {
if (e.flow == null ||
e.flow.getFlowType() != FlowType.ELEMENTARY_FLOW)
continue;
FlowDescriptor d = Descriptors.toDescriptor(e.flow);
int i = e.isInput
? flowIdx.putInput(d)
: flowIdx.putOutput(d);
exchanges[i] = e;
values[i] = ReferenceAmount.get(e);
}
// create the impact matrix
FormulaInterpreter interpreter = ParameterTable.interpreter(
Database.get(),
new HashSet<Long>(Arrays.asList(
getModel().getId(),
method.getId())),
Collections.emptySet());
ImpactTable iTable = ImpactTable.build(
Cache.getMatrixCache(), method.getId(), flowIdx);
IMatrix matrix = iTable.createMatrix(
App.getSolver(), interpreter);
// build the tree
List<Node> roots = new ArrayList<>();
DIndex<ImpactCategoryDescriptor> impactIdx = iTable.impactIndex;
for (int i = 0; i < impactIdx.size(); i++) {
Node root = new Node();
root.impact = impactIdx.at(i);
roots.add(root);
for (int j = 0; j < flowIdx.size(); j++) {
double factor = matrix.get(i, j);
if (exchanges[j].isInput) {
factor = -factor;
}
double result = values[j] * factor;
if (result == 0 && skipZeros)
continue;
root.result += result;
Node child = new Node();
child.result = result;
child.exchange = exchanges[j];
child.impact = root.impact;
if (root.childs == null) {
root.childs = new ArrayList<>();
}
root.childs.add(child);
}
}
sort(roots);
return roots;
}
private void sort(List<Node> roots) {
Collections.sort(roots, (n1, n2) -> {
String l1 = Labels.getDisplayName(n1.impact);
String l2 = Labels.getDisplayName(n2.impact);
return Strings.compare(l1, l2);
});
for (Node root : roots) {
if (root.childs == null)
continue;
if (root.result != 0) {
for (Node child : root.childs) {
child.share = child.result / root.result;
}
}
Collections.sort(root.childs, (n1, n2) -> {
int c = Double.compare(n2.share, n1.share);
if (c != 0)
return c;
if (n1.exchange == null || n2.exchange == null)
return c;
String l1 = Labels.getDisplayName(n1.exchange.flow);
String l2 = Labels.getDisplayName(n2.exchange.flow);
return Strings.compare(l1, l2);
});
}
}
private class Node {
ImpactCategoryDescriptor impact;
double share;
double result;
Exchange exchange;
List<Node> childs;
}
private class Content extends ArrayContentProvider
implements ITreeContentProvider {
@Override
public Object[] getChildren(Object parent) {
if (!(parent instanceof Node))
return null;
Node n = (Node) parent;
return n.childs == null ? null : n.childs.toArray();
}
@Override
public Object getParent(Object elem) {
return null;
}
@Override
public boolean hasChildren(Object elem) {
if (!(elem instanceof Node))
return false;
Node n = (Node) elem;
return n.childs != null && n.childs.size() > 0;
}
}
private class Label extends ColumnLabelProvider
implements ITableLabelProvider {
private ContributionImage img = new ContributionImage(Display.getCurrent());
@Override
public void dispose() {
img.dispose();
super.dispose();
}
@Override
public Image getColumnImage(Object obj, int col) {
if (!(obj instanceof Node))
return null;
Node n = (Node) obj;
if (col == 0) {
if (n.exchange == null)
return Images.get(ModelType.IMPACT_CATEGORY);
else
return Images.get(FlowType.ELEMENTARY_FLOW);
}
if (col != 3 || n.exchange == null)
return null;
return img.getForTable(n.share);
}
@Override
public String getColumnText(Object obj, int col) {
if (!(obj instanceof Node))
return null;
Node n = (Node) obj;
switch (col) {
case 0:
if (n.exchange == null)
return Labels.getDisplayName(n.impact);
else
return Labels.getDisplayName(n.exchange.flow);
case 1:
if (n.exchange == null)
return null;
else
return CategoryPath.getShort(
n.exchange.flow.getCategory());
case 2:
if (n.exchange == null)
return null;
if (n.exchange.unit == null)
return Numbers.format(n.exchange.amount);
else
return Numbers.format(n.exchange.amount)
+ " " + n.exchange.unit.getName();
case 3:
if (n.impact == null)
return null;
if (n.impact.getReferenceUnit() == null)
return Numbers.format(n.result);
else
return Numbers.format(n.result)
+ " " + n.impact.getReferenceUnit();
default:
return null;
}
}
}
}
|
package OpenRate.process;
import OpenRate.OpenRate;
import OpenRate.exception.InitializationException;
import OpenRate.exception.ProcessingException;
import static OpenRate.process.AbstractRUMTimeMatch.TIME_SPLITTING_CHECK_SPLITTING;
import static OpenRate.process.AbstractRUMTimeMatch.TIME_SPLITTING_CHECK_SPLITTING_BEAT_ROUNDING;
import static OpenRate.process.AbstractRUMTimeMatch.TIME_SPLITTING_NO_CHECK;
import OpenRate.record.ChargePacket;
import OpenRate.record.IRecord;
import OpenRate.record.TimePacket;
import OpenRate.utils.ConversionUtils;
import TestUtils.FrameworkUtils;
import TestUtils.TestRatingRecord;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Calendar;
import org.junit.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Test the splitting of a time based rating according to time zones.
*
* @author TGDSPIA1
*/
public class AbstractRUMTimeTest {
private static URL FQConfigFileName;
private static AbstractRUMTimeMatch instance;
// Used for logging and exception handling
private static String message;
@BeforeClass
public static void setUpClass() throws Exception {
FQConfigFileName = new URL("File:src/test/resources/TestRUMTime.properties.xml");
// Set up the OpenRate internal logger - this is normally done by app startup
OpenRate.getApplicationInstance();
// Load the properties into the OpenRate object
FrameworkUtils.loadProperties(FQConfigFileName);
// Get the loggers
FrameworkUtils.startupLoggers();
// Get the transaction manager
FrameworkUtils.startupTransactionManager();
// Get Data Sources
FrameworkUtils.startupDataSources();
// Get a connection
Connection JDBCChcon = FrameworkUtils.getDBConnection("RUMTimeTestCache");
try {
JDBCChcon.prepareStatement("DROP TABLE TEST_TIME_MODEL_MAP").execute();
} catch (SQLException ex) {
if ((ex.getMessage().startsWith("Unknown table")) || // Mysql
(ex.getMessage().startsWith("user lacks"))) // HSQL
{
// It's OK
} else {
// Not OK, fail the case
message = "Error dropping table TEST_TIME_MODEL_MAP in test <AbstractRUMTimeTest>.";
Assert.fail(message);
}
}
try {
JDBCChcon.prepareStatement("DROP TABLE TEST_TIME_MODEL_INTERVAL").execute();
} catch (SQLException ex) {
if ((ex.getMessage().startsWith("Unknown table")) || // Mysql
(ex.getMessage().startsWith("user lacks"))) // HSQL
{
// It's OK
} else {
// Not OK, fail the case
message = "Error dropping table TEST_TIME_MODEL_INTERVAL in test <AbstractRUMTimeTest>.";
Assert.fail(message);
}
}
// Create the test table
JDBCChcon.prepareStatement("CREATE TABLE TEST_TIME_MODEL_MAP (ID int, PRODUCT_NAME_IN varchar(24), TIME_MODEL_OUT varchar(24))").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_MAP (ID,PRODUCT_NAME_IN,TIME_MODEL_OUT) VALUES (1,'Default','Standard')").execute();
// Create the test table
JDBCChcon.prepareStatement("CREATE TABLE TEST_TIME_MODEL_INTERVAL (ID int, TIME_MODEL_NAME_IN varchar(24), DAY_IN varchar(24), FROM_IN varchar(24), TO_IN varchar(24), RESULT_OUT varchar(24))").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (1,'FLAT','0','00:00','23:59','FLAT')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (2,'FLAT','1','00:00','23:59','FLAT')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (3,'FLAT','2','00:00','23:59','FLAT')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (4,'FLAT','3','00:00','23:59','FLAT')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (5,'FLAT','4','00:00','23:59','FLAT')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (6,'FLAT','5','00:00','23:59','FLAT')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (7,'FLAT','6','00:00','23:59','FLAT')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (8,'Standard','1','00:00','07:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (9,'Standard','1','08:00','18:59','PEAK')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (10,'Standard','1','19:00','23:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (11,'Standard','2','00:00','07:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (12,'Standard','2','08:00','18:59','PEAK')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (13,'Standard','2','19:00','23:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (14,'Standard','3','00:00','07:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (15,'Standard','3','08:00','18:59','PEAK')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (16,'Standard','3','19:00','23:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (17,'Standard','4','00:00','07:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (18,'Standard','4','08:00','18:59','PEAK')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (19,'Standard','4','19:00','23:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (20,'Standard','5','00:00','07:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (21,'Standard','5','08:00','18:59','PEAK')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (22,'Standard','5','19:00','23:59','ECO')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (24,'Standard','0','00:00','23:59','WKD')").execute();
JDBCChcon.prepareStatement("INSERT INTO TEST_TIME_MODEL_INTERVAL (ID,TIME_MODEL_NAME_IN,DAY_IN,FROM_IN,TO_IN,RESULT_OUT) VALUES (23,'Standard','6','00:00','23:59','WKD')").execute();
// Get the caches that we are using
FrameworkUtils.startupCaches();
}
@AfterClass
public static void tearDownClass() throws Exception {
// Deallocate the resources
OpenRate.getApplicationInstance().cleanup();
}
@Before
public void setUp() {
getInstance();
}
@After
public void tearDown() {
releaseInstance();
}
/**
* Test the simple, non-crossing case.
*
* @throws java.lang.Exception
*/
@Test
public void testPerformRUMTImeMatchNonCrossing() throws Exception {
TestRatingRecord ratingRecord;
System.out.println("testPerformRUMTImeMatchNonCrossing");
ratingRecord = getNewRatingRecord("2010-01-23 00:00:00","2010-01-23 00:00:01", TIME_SPLITTING_NO_CHECK);
instance.performRUMTimeMatch(ratingRecord);
assertEquals(1, ratingRecord.getChargePacketCount());
assertEquals(1, ratingRecord.getChargePacket(0).getTimeZones().size());
TimePacket tmpTZ = ratingRecord.getChargePackets().get(0).getTimeZones().get(0);
assertEquals(1, tmpTZ.duration);
assertEquals(1, tmpTZ.totalDuration);
assertEquals("WKD", tmpTZ.timeResult);
}
/**
* Test the simple, crossing case, but with splitting turned off. In this case
* we create one charge packet with the time zone based on the start time.
*
* Note that because we do no splitting, the duration and total duration
* fields are not filled in.
*
* @throws java.lang.Exception
*/
@Test
public void testPerformRUMTImeMatchCrossingNoSplit() throws Exception {
TestRatingRecord ratingRecord;
System.out.println("testPerformRUMTImeMatchCrossingNoSplit");
ratingRecord = getNewRatingRecord("2010-01-20 07:50:00","2010-01-20 08:10:01", TIME_SPLITTING_NO_CHECK);
instance.performRUMTimeMatch(ratingRecord);
assertEquals(1, ratingRecord.getChargePacketCount());
assertEquals(1, ratingRecord.getChargePacket(0).getTimeZones().size());
TimePacket tmpTZ = ratingRecord.getChargePackets().get(0).getTimeZones().get(0);
assertEquals(1, tmpTZ.duration);
assertEquals(1, tmpTZ.totalDuration);
assertEquals("ECO", tmpTZ.timeResult);
}
/**
* Test the simple, crossing case, with splitting. In this case
* we create one charge packet with one time packet per time zone.
*
* @throws java.lang.Exception
*/
@Test
public void testPerformRUMTImeMatchCrossingSplit() throws Exception {
TestRatingRecord ratingRecord;
System.out.println("testPerformRUMTImeMatchCrossingSplit");
ratingRecord = getNewRatingRecord("2010-01-20 07:50:00","2010-01-20 08:10:01", TIME_SPLITTING_CHECK_SPLITTING);
instance.performRUMTimeMatch(ratingRecord);
assertEquals(1, ratingRecord.getChargePacketCount());
assertEquals(2, ratingRecord.getChargePacket(0).getTimeZones().size());
TimePacket tmpTZ1 = ratingRecord.getChargePackets().get(0).getTimeZones().get(0);
assertEquals(600, tmpTZ1.duration);
assertEquals(1201, tmpTZ1.totalDuration);
assertEquals("ECO", tmpTZ1.timeResult);
TimePacket tmpTZ2 = ratingRecord.getChargePackets().get(0).getTimeZones().get(1);
assertEquals(601, tmpTZ2.duration);
assertEquals(1201, tmpTZ2.totalDuration);
assertEquals("PEAK", tmpTZ2.timeResult);
}
/**
* Test the simple, crossing case, with splitting. In this case
* we create one charge packet with one time packet per time zone.
*
* At this point the "Beat Rounding" mode gives exactly the same results
* as the normal splitting. It however is treated differently during the
* rating that will follow.
*
* @throws java.lang.Exception
*/
@Test
public void testPerformRUMTImeMatchCrossingSplitBeatRounding() throws Exception {
TestRatingRecord ratingRecord;
System.out.println("testPerformRUMTImeMatchCrossingSplitBeatRounding");
ratingRecord = getNewRatingRecord("2010-01-20 07:50:00","2010-01-20 08:10:01", TIME_SPLITTING_CHECK_SPLITTING_BEAT_ROUNDING);
instance.performRUMTimeMatch(ratingRecord);
assertEquals(1, ratingRecord.getChargePacketCount());
assertEquals(2, ratingRecord.getChargePacket(0).getTimeZones().size());
TimePacket tmpTZ1 = ratingRecord.getChargePackets().get(0).getTimeZones().get(0);
assertEquals(600, tmpTZ1.duration);
assertEquals(1201, tmpTZ1.totalDuration);
assertEquals("ECO", tmpTZ1.timeResult);
TimePacket tmpTZ2 = ratingRecord.getChargePackets().get(0).getTimeZones().get(1);
assertEquals(601, tmpTZ2.duration);
assertEquals(1201, tmpTZ2.totalDuration);
assertEquals("PEAK", tmpTZ2.timeResult);
}
/**
* Test the multiple crossing case, with splitting. In this case
* we create one charge packet with one time packet per time zone.
*
* @throws java.lang.Exception
*/
@Test
public void testPerformRUMTimeMatchCrossingSplitLongCall() throws Exception {
TestRatingRecord ratingRecord;
System.out.println("testPerformRUMTimeMatchCrossingSplitLongCall");
ratingRecord = getNewRatingRecord("2010-01-20 07:50:00","2010-01-22 08:10:01", TIME_SPLITTING_CHECK_SPLITTING);
instance.performRUMTimeMatch(ratingRecord);
assertEquals(1, ratingRecord.getChargePacketCount());
assertEquals(8, ratingRecord.getChargePacket(0).getTimeZones().size());
int ourTotalDuration = 0;
TimePacket tmpTZ1 = ratingRecord.getChargePackets().get(0).getTimeZones().get(0);
assertEquals(600, tmpTZ1.duration);
assertEquals(174001, tmpTZ1.totalDuration);
assertEquals("ECO", tmpTZ1.timeResult);
ourTotalDuration += tmpTZ1.duration;
TimePacket tmpTZ2 = ratingRecord.getChargePackets().get(0).getTimeZones().get(1);
assertEquals(39600, tmpTZ2.duration);
assertEquals(174001, tmpTZ2.totalDuration);
assertEquals("PEAK", tmpTZ2.timeResult);
ourTotalDuration += tmpTZ2.duration;
TimePacket tmpTZ3 = ratingRecord.getChargePackets().get(0).getTimeZones().get(2);
assertEquals(18000, tmpTZ3.duration);
assertEquals(174001, tmpTZ3.totalDuration);
assertEquals("ECO", tmpTZ3.timeResult);
ourTotalDuration += tmpTZ3.duration;
TimePacket tmpTZ4 = ratingRecord.getChargePackets().get(0).getTimeZones().get(3);
assertEquals(28800, tmpTZ4.duration);
assertEquals(174001, tmpTZ4.totalDuration);
assertEquals("ECO", tmpTZ4.timeResult);
ourTotalDuration += tmpTZ4.duration;
TimePacket tmpTZ5 = ratingRecord.getChargePackets().get(0).getTimeZones().get(4);
assertEquals(39600, tmpTZ5.duration);
assertEquals(174001, tmpTZ5.totalDuration);
assertEquals("PEAK", tmpTZ5.timeResult);
ourTotalDuration += tmpTZ5.duration;
TimePacket tmpTZ6 = ratingRecord.getChargePackets().get(0).getTimeZones().get(5);
assertEquals(18000, tmpTZ6.duration);
assertEquals(174001, tmpTZ6.totalDuration);
assertEquals("ECO", tmpTZ6.timeResult);
ourTotalDuration += tmpTZ6.duration;
TimePacket tmpTZ7 = ratingRecord.getChargePackets().get(0).getTimeZones().get(6);
assertEquals(28800, tmpTZ7.duration);
assertEquals(174001, tmpTZ7.totalDuration);
assertEquals("ECO", tmpTZ7.timeResult);
ourTotalDuration += tmpTZ7.duration;
TimePacket tmpTZ8 = ratingRecord.getChargePackets().get(0).getTimeZones().get(7);
assertEquals(601, tmpTZ8.duration);
assertEquals(174001, tmpTZ8.totalDuration);
assertEquals("PEAK", tmpTZ8.timeResult);
ourTotalDuration += tmpTZ8.duration;
assertEquals(tmpTZ1.totalDuration, ourTotalDuration);
}
/**
* Test the performance with a standard case. We expect way more than 10,000
* per second.
*
* @throws java.lang.Exception
*/
@Test
public void testPerformRUMTimeMatchCrossingPerformance() throws Exception {
TestRatingRecord ratingRecord;
System.out.println("testPerformRUMTimeMatchCrossingPerformance");
// Test the result is right
ratingRecord = getNewRatingRecord("2010-01-20 07:50:00","2010-01-20 08:10:01", TIME_SPLITTING_CHECK_SPLITTING);
instance.performRUMTimeMatch(ratingRecord);
assertEquals(1, ratingRecord.getChargePacketCount());
assertEquals(2, ratingRecord.getChargePacket(0).getTimeZones().size());
long startMs = Calendar.getInstance().getTimeInMillis();
for (int i = 1; i < 10000; i++) {
ratingRecord = getNewRatingRecord("2010-01-20 07:50:00","2010-01-20 08:10:01", TIME_SPLITTING_CHECK_SPLITTING);
instance.performRUMTimeMatch(ratingRecord);
}
long duration = Calendar.getInstance().getTimeInMillis() - startMs;
// Dropped to 5000/s because of our crappy Jenkins
// TODO revert to 10k/s when we upgrade Jenkins (memory expansion)
System.out.println("10000 took " + duration + "mS");
assertTrue(duration < 2000);
}
public class AbstractRUMTimeMatchImpl extends AbstractRUMTimeMatch {
/**
* Override the unused event handling routines.
*
* @param r input record
* @return return record
* @throws ProcessingException
*/
@Override
public IRecord procValidRecord(IRecord r) throws ProcessingException {
return r;
}
/**
* Override the unused event handling routines.
*
* @param r input record
* @return return record
* @throws ProcessingException
*/
@Override
public IRecord procErrorRecord(IRecord r) throws ProcessingException {
return r;
}
}
/**
* Method to get an instance of the implementation. Done this way to allow
* tests to be executed individually.
*
* @throws InitializationException
*/
private void getInstance() {
if (instance == null) {
// Get an initialise the cache
instance = new AbstractRUMTimeTest.AbstractRUMTimeMatchImpl();
try {
// Get the instance
instance.init("DBTestPipe", "AbstractRUMTimeTest");
} catch (InitializationException ex) {
org.junit.Assert.fail();
}
} else {
org.junit.Assert.fail("Instance already allocated");
}
}
/**
* Method to release an instance of the implementation.
*/
private void releaseInstance() {
instance = null;
}
/**
* Create a rating record initialised with the information necessary for
* performing a rating.
*
* @param CDRDate Date of the CDR
* @param newPriceGroup The price group to use
* @param durationValue The duration value to use
* @return The record, ready to go
*/
private TestRatingRecord getNewRatingRecord(String CDRStartDate, String CDREndDate, int splittingType) throws ParseException {
TestRatingRecord ratingRecord = new TestRatingRecord();
ConversionUtils conv = ConversionUtils.getConversionUtilsObject();
conv.setInputDateFormat("yyyy-MM-dd hh:mm:ss");
long CDRDateUTC = conv.convertInputDateToUTC(CDRStartDate);
ratingRecord.UTCEventDate = CDRDateUTC;
ratingRecord.EventStartDate = conv.getDatefromLongFormat(CDRStartDate);
ratingRecord.EventEndDate = conv.getDatefromLongFormat(CDREndDate);
ChargePacket tmpCP = new ChargePacket();
tmpCP.timeModel = "Default";
tmpCP.timeSplitting = splittingType;
ratingRecord.addChargePacket(tmpCP);
return ratingRecord;
}
}
|
package org.onvif.client;
import de.onvif.discovery.OnvifDiscovery;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class calls OnvifDiscovery and for each device URL found, calls TestDevice This assumes all onvif
* devices on your network use the same username and password.
*
* @author Brad Lowe
*/
public class DiscoverAndTest {
private static final Logger LOG = LoggerFactory.getLogger(TestDevice.class);
public static String discoverAndTest(String user, String password) {
String sep = "\n";
StringBuffer out = new StringBuffer();
Collection<URL> urls = OnvifDiscovery.discoverOnvifURLs();
for (URL u : urls) {
out.append("Discovered URL:" + u.toString() + sep);
}
ArrayList<String> results = new ArrayList<>();
int good = 0, bad = 0;
for (URL u : urls) {
try {
String result = TestDevice.testCamera(u, user, password);
LOG.info(u + "->" + result);
good++;
results.add(u.toString() + ":" + result);
} catch (Throwable e) {
bad++;
LOG.error("error:" + u, e);
// This is a bit of a hack. When a camera is password protected (it should be!)
// and the password is not provided or wrong, a "Unable to Send Message" exception
// may be thrown. This is not clear-- buried in the stack track is the real cause.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String trace = sw.getBuffer().toString();
if (trace.contains("Unauthorized")) results.add(u + ":Unauthorized:");
else results.add(u + ":" + trace);
}
}
out.append("RESULTS: " + sep);
for (String s : results) out.append(s + sep);
out.append("cameras found:" + urls.size() + " good=" + good + ", bad=" + bad + sep);
return out.toString();
}
public static void main(String[] args) {
// get user and password.. we will ignore device host
String user = "";
String password = "";
if (args.length > 0) user = args[0];
if (args.length > 1) password = args[1];
if (password.isEmpty()) {
LOG.warn(
"Warning: No password for discover and test... run with common user password as arguments");
}
// OnvifDevice.setVerbose(true);
LOG.info(discoverAndTest(user, password));
}
}
|
package seedu.taskboss.testutil;
import java.util.List;
import com.google.common.collect.Lists;
import seedu.taskboss.commons.exceptions.IllegalValueException;
import seedu.taskboss.model.category.Category;
/**
* A mutable category object. For testing only.
*/
public class TestCategory extends Category {
private int taskCount;
private List<TestTask> taskList;
public TestCategory(String name, int taskCount) throws IllegalValueException {
super(name);
this.taskCount = taskCount;
}
public TestCategory(String name, TestTask... tasks) throws IllegalValueException {
super(name);
taskList = Lists.newArrayList(tasks);
}
public void setTaskCount(int count) {
taskCount = count;
}
public void setTaskList(TestTask...tasks) {
taskList = Lists.newArrayList(tasks);
}
public int getTaskCount() {
return taskCount;
}
public List<TestTask> getTaskList() {
return taskList;
}
}
|
package MWC.GUI.JFreeChart;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.DateTickUnitType;
import org.jfree.chart.axis.TickUnits;
import MWC.GUI.Properties.AbstractPropertyEditor;
public class DateAxisEditor extends AbstractPropertyEditor
{
public static class DatedRNFormatter extends RNFormatter
{
private static final long serialVersionUID = 1L;
/**
* cache the last date formatted. when this moves backwards, we know we're restarting - which
* helps us to detect the first item.
*/
private long _lastDate = Long.MIN_VALUE;
/**
* pattern for the on-the-day values. Note: we currently ignore this, since we just prepend the
* date value as a 2-digit value
*/
@SuppressWarnings("unused")
private final String _datePattern;
/**
* Construct a SimpleDateFormat using the given pattern in the default locale. <b>Note:</b> Not
* all locales support SimpleDateFormat; for full generality, use the factory methods in the
* DateFormat class.
*/
public DatedRNFormatter(final String pattern, final String datePattern)
{
super(pattern);
// store the date (even if we then choose to ignore it)
_datePattern = datePattern;
}
@SuppressWarnings("deprecation")
@Override
public StringBuffer format(final Date arg0, final StringBuffer arg1,
final FieldPosition arg2)
{
StringBuffer timeBit = super.format(arg0, arg1, arg2);
// see of we've moved back in time
long thisT = arg0.getTime();
// when in this special mode we show the date for the first item
final boolean firstOne = thisT < _lastDate;
// see if we're on the exact day (or if this is the first one)
if (((arg0.getHours() == 0) && (arg0.getMinutes() == 0) && (arg0
.getSeconds() == 0)) || firstOne)
{
// ok, use the suffix
final DecimalFormat df = new DecimalFormat("00");
final String prefix = df.format(arg0.getDate());
final StringBuffer res = new StringBuffer();
res.append(prefix);
res.append(timeBit);
timeBit = res;
}
// remember the date
_lastDate = thisT;
return timeBit;
}
}
public static class MWCDateTickUnitWrapper
{
public static MWCDateTickUnitWrapper getAutoScale()
{
return new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 0, null);
}
/**
* components of DateTickUnit
*/
protected DateTickUnitType _unit;
protected int _count;
protected String _formatter;
public MWCDateTickUnitWrapper(final DateTickUnitType unit, final int count,
final String formatter)
{
_unit = unit;
_count = count;
_formatter = formatter;
}
public DateTickUnit getUnit()
{
DateTickUnit res = null;
if (_formatter != DateAxisEditor.RELATIVE_DTG_FORMAT)
{
final SimpleDateFormat sdf = new SimpleDateFormat(_formatter);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
res = new OptimisedDateTickUnit(_unit, _count, sdf);
}
else
{
final SimpleDateFormat sdf = new SimpleDateFormat(_formatter);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
res = new OptimisedDateTickUnit(_unit, _count, sdf)
{
private static final long serialVersionUID = 1L;
/**
* Formats a date.
*
* @param date
* the date.
* @return the formatted date.
*/
@Override
public String dateToString(final Date date)
{
String res1 = null;
// how many secs?
final long secs = date.getTime() / 1000;
res1 = secs + "s";
return res1;
}
};
}
return res;
}
private String getUnitLabel()
{
switch (_unit.getCalendarField())
{
case (Calendar.YEAR):
return "Year";
case (Calendar.MONTH):
return "Month";
case (Calendar.DAY_OF_MONTH):
return "Day";
case (Calendar.HOUR):
case (Calendar.HOUR_OF_DAY):
return "Hour";
case (Calendar.MINUTE):
return "Min";
case (Calendar.SECOND):
return "Sec";
default:
return "Milli";
}
}
public boolean isAutoScale()
{
return (_formatter == null);
}
@Override
public String toString()
{
String res = null;
if (_formatter == null)
{
res = "Auto-scale";
}
else
{
res = _count + " " + getUnitLabel() + " " + _formatter;
}
return res;
}
}
public static class OptimisedDateTickUnit extends DateTickUnit
{
private static final long serialVersionUID = 1L;
/**
* static calendar instance, to reduce object allocation
*
*/
private static Calendar _myCal = null;
public OptimisedDateTickUnit(final DateTickUnitType unitType,
final int multiple)
{
super(unitType, multiple);
}
public OptimisedDateTickUnit(final DateTickUnitType unitType,
final int multiple, final DateFormat formatter)
{
super(unitType, multiple, formatter);
}
public OptimisedDateTickUnit(final DateTickUnitType unitType,
final int multiple, final DateTickUnitType rollUnitType,
final int rollMultiple, final DateFormat formatter)
{
super(unitType, multiple, rollUnitType, rollMultiple, formatter);
}
/**
* Overrides parent implementation, in order that we can use static Calendar instance rather
* than creating it lots of times.
*/
@Override
@SuppressWarnings("deprecation")
public Date addToDate(final Date base, final TimeZone zone)
{
// do we have a calenar already?
if (_myCal == null)
_myCal = Calendar.getInstance(zone);
_myCal.setTime(base);
_myCal.add(this.getUnitType().getCalendarField(), this.getCount());
return _myCal.getTime();
}
}
public static class RNFormatter extends SimpleDateFormat
{
private static final long serialVersionUID = 1L;
/**
* Construct a SimpleDateFormat using the given pattern in the default locale. <b>Note:</b> Not
* all locales support SimpleDateFormat; for full generality, use the factory methods in the
* DateFormat class.
*/
public RNFormatter(final String pattern)
{
super(pattern);
this.setTimeZone(TimeZone.getTimeZone("GMT"));
}
}
/**
* the string format used to denote a relative time description
*/
public static final String RELATIVE_DTG_FORMAT = "T+SSS";
// member methods
/**
* a list of strings representing the tick units
*/
private static String[] _theTags = null;
/**
* the actual tick units in use
*/
private static MWCDateTickUnitWrapper[] _theData = null;
/**
* Returns a collection of standard date tick units. This collection will be used by default, but
* you are free to create your own collection if you want to (see the setStandardTickUnits(...)
* method inherited from the ValueAxis class).
*
* @return a collection of standard date tick units.
*/
public static ArrayList<MWCDateTickUnitWrapper>
createStandardDateTickUnitsAsArrayList()
{
final ArrayList<MWCDateTickUnitWrapper> units =
new ArrayList<MWCDateTickUnitWrapper>();
units.add(MWCDateTickUnitWrapper.getAutoScale());
// milliseconds
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MILLISECOND, 500,
"HH:mm:ss.SSS"));
// seconds
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 1,
"HH:mm:ss"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 5,
"HH:mm:ss"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 10,
"HH:mm:ss"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 30,
"HH:mm:ss"));
// minutes
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 1, "HH:mm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 2, "HH:mm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 5, "HH:mm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 10, "HH:mm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 15, "HH:mm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 20, "HH:mm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.MINUTE, 30, "HH:mm"));
// hours
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 1, "HH:mm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 2, "HH:mm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 4, "HH:mm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 6, "ddHHmm"));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.HOUR, 12, "ddHHmm"));
// days
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.DAY, 1, "d-MMM"));
// absolute seconds
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 1,
RELATIVE_DTG_FORMAT));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 5,
RELATIVE_DTG_FORMAT));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 10,
RELATIVE_DTG_FORMAT));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 30,
RELATIVE_DTG_FORMAT));
units.add(new MWCDateTickUnitWrapper(DateTickUnitType.SECOND, 60,
RELATIVE_DTG_FORMAT));
return units;
}
public static TickUnits createStandardDateTickUnitsAsTickUnits()
{
final TickUnits units = new TickUnits();
// milliseconds
units.add(new OptimisedDateTickUnit(DateTickUnitType.MILLISECOND, 500,
new RNFormatter("HH:mm:ss.SSS")));
// seconds
units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 1,
new RNFormatter("HH:mm:ss")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 5,
new RNFormatter("HH:mm:ss")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 10,
new RNFormatter("HH:mm:ss")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.SECOND, 30,
new RNFormatter("HH:mm:ss")));
// minutes
units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 1,
new RNFormatter("HH:mm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 2,
new RNFormatter("HH:mm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 5,
new RNFormatter("HH:mm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 10,
new RNFormatter("HH:mm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 15,
new RNFormatter("HH:mm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 20,
new RNFormatter("HH:mm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.MINUTE, 30,
new RNFormatter("HH:mm")));
// hours
units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 1,
new RNFormatter("HH:mm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 2,
new RNFormatter("HH:mm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 4,
new RNFormatter("HH:mm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 6,
new RNFormatter("ddHHmm")));
units.add(new OptimisedDateTickUnit(DateTickUnitType.HOUR, 12,
new RNFormatter("ddHHmm")));
// days
units.add(new OptimisedDateTickUnit(DateTickUnitType.DAY, 1,
new RNFormatter("d-MMM")));
return units;
}
protected synchronized void checkCreated()
{
// have they been created?
if (_theData == null)
{
// create them
final ArrayList<MWCDateTickUnitWrapper> theList =
createStandardDateTickUnitsAsArrayList();
// _theDates = new TickUnits();
_theTags = new String[theList.size()];
_theData = new MWCDateTickUnitWrapper[theList.size()];
// work through the list
for (int i = 0; i < theList.size(); i++)
{
final MWCDateTickUnitWrapper unit = theList.get(i);
_theData[i] = unit;
// and create the strings
_theTags[i] = unit.toString();
}
}
}
public MWCDateTickUnitWrapper getDateTickUnit()
{
final Integer index = (Integer) this.getValue();
final MWCDateTickUnitWrapper theUnit = _theData[index.intValue()];
return theUnit;
}
/**
* retrieve the list of tags we display
*
* @return the list of options
*/
@Override
public String[] getTags()
{
// check we're ready
checkCreated();
return _theTags;
}
/**
* return the currently selected string
*
* @return
*/
@Override
public Object getValue()
{
// check we have the data
checkCreated();
final Integer theIndex = (Integer) super.getValue();
return _theData[theIndex.intValue()];
}
/**
* select this vlaue
*
* @param p1
*/
@Override
public void setValue(final Object p1)
{
// check we have the data
checkCreated();
if (p1 instanceof MWCDateTickUnitWrapper)
{
// pass through to match
for (int i = 0; i < _theData.length; i++)
{
final MWCDateTickUnitWrapper unit = _theData[i];
if (unit.equals(p1))
{
this.setValue(new Integer(i));
}
}
}
else
super.setValue(p1);
}
}
|
package org.osmdroid.views;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import microsoft.mappoint.TileSystem;
import net.wigle.wigleandroid.ZoomButtonsController;
import net.wigle.wigleandroid.ZoomButtonsController.OnZoomListener;
import org.metalev.multitouch.controller.MultiTouchController;
import org.metalev.multitouch.controller.MultiTouchController.MultiTouchObjectCanvas;
import org.metalev.multitouch.controller.MultiTouchController.PointInfo;
import org.metalev.multitouch.controller.MultiTouchController.PositionAndScale;
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IMapView;
import org.osmdroid.api.IProjection;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.MapTileProviderBase;
import org.osmdroid.tileprovider.MapTileProviderBasic;
import org.osmdroid.tileprovider.tilesource.IStyledTileSource;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.util.SimpleInvalidationHandler;
import org.osmdroid.util.BoundingBoxE6;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.constants.GeoConstants;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayManager;
import org.osmdroid.views.overlay.TilesOverlay;
import org.osmdroid.views.util.constants.MapViewConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Scroller;
public class MapView extends ViewGroup implements IMapView, MapViewConstants,
MultiTouchObjectCanvas<Object> {
// Constants
private static final Logger logger = LoggerFactory.getLogger(MapView.class);
private static final double ZOOM_SENSITIVITY = 1.3;
private static final double ZOOM_LOG_BASE_INV = 1.0 / Math.log(2.0 / ZOOM_SENSITIVITY);
// Fields
/** Current zoom level for map tiles. */
private int mZoomLevel = 0;
private final OverlayManager mOverlayManager;
private Projection mProjection;
private final TilesOverlay mMapOverlay;
private final GestureDetector mGestureDetector;
/** Handles map scrolling */
private final Scroller mScroller;
private final AtomicInteger mTargetZoomLevel = new AtomicInteger();
private final AtomicBoolean mIsAnimating = new AtomicBoolean(false);
private final ScaleAnimation mZoomInAnimation;
private final ScaleAnimation mZoomOutAnimation;
private final MapController mController;
// XXX we can use android.widget.ZoomButtonsController if we upgrade the
// dependency to Android 1.6
private final ZoomButtonsController mZoomController;
private boolean mEnableZoomController = false;
private final ResourceProxy mResourceProxy;
private MultiTouchController<Object> mMultiTouchController;
private float mMultiTouchScale = 1.0f;
protected MapListener mListener;
// for speed (avoiding allocations)
private final Matrix mMatrix = new Matrix();
private final MapTileProviderBase mTileProvider;
private final Handler mTileRequestCompleteHandler;
/* a point that will be reused to design added views */
private final Point mPoint = new Point();
// Constructors
protected MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy, MapTileProviderBase tileProvider,
final Handler tileRequestCompleteHandler, final AttributeSet attrs) {
super(context, attrs);
mResourceProxy = resourceProxy;
this.mController = new MapController(this);
this.mScroller = new Scroller(context);
TileSystem.setTileSize(tileSizePixels);
if (tileProvider == null) {
final ITileSource tileSource = getTileSourceFromAttributes(attrs);
tileProvider = new MapTileProviderBasic(context, tileSource);
}
mTileRequestCompleteHandler = tileRequestCompleteHandler == null ? new SimpleInvalidationHandler(
this) : tileRequestCompleteHandler;
mTileProvider = tileProvider;
mTileProvider.setTileRequestCompleteHandler(mTileRequestCompleteHandler);
this.mMapOverlay = new TilesOverlay(mTileProvider, mResourceProxy);
mOverlayManager = new OverlayManager(mMapOverlay);
this.mZoomController = new ZoomButtonsController(this);
this.mZoomController.setOnZoomListener(new MapViewZoomListener());
mZoomInAnimation = new ScaleAnimation(1, 2, 1, 2, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mZoomOutAnimation = new ScaleAnimation(1, 0.5f, 1, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mZoomInAnimation.setDuration(ANIMATION_DURATION_SHORT);
mZoomOutAnimation.setDuration(ANIMATION_DURATION_SHORT);
mGestureDetector = new GestureDetector(context, new MapViewGestureDetectorListener());
mGestureDetector.setOnDoubleTapListener(new MapViewDoubleClickListener());
}
/**
* Constructor used by XML layout resource (uses default tile source).
*/
public MapView(final Context context, final AttributeSet attrs) {
this(context, 256, new DefaultResourceProxyImpl(context), null, null, attrs);
}
/**
* Standard Constructor.
*/
public MapView(final Context context, final int tileSizePixels) {
this(context, tileSizePixels, new DefaultResourceProxyImpl(context));
}
public MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy) {
this(context, tileSizePixels, resourceProxy, null);
}
public MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider) {
this(context, tileSizePixels, resourceProxy, aTileProvider, null);
}
public MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider,
final Handler tileRequestCompleteHandler) {
this(context, tileSizePixels, resourceProxy, aTileProvider, tileRequestCompleteHandler,
null);
}
// Getter & Setter
@Override
public MapController getController() {
return this.mController;
}
/**
* You can add/remove/reorder your Overlays using the List of {@link Overlay}. The first (index
* 0) Overlay gets drawn first, the one with the highest as the last one.
*/
public List<Overlay> getOverlays() {
return this.getOverlayManager();
}
public OverlayManager getOverlayManager() {
return mOverlayManager;
}
public MapTileProviderBase getTileProvider() {
return mTileProvider;
}
public Scroller getScroller() {
return mScroller;
}
public Handler getTileRequestCompleteHandler() {
return mTileRequestCompleteHandler;
}
@Override
public int getLatitudeSpan() {
return this.getBoundingBox().getLatitudeSpanE6();
}
@Override
public int getLongitudeSpan() {
return this.getBoundingBox().getLongitudeSpanE6();
}
public BoundingBoxE6 getBoundingBox() {
return getBoundingBox(getWidth(), getHeight());
}
public BoundingBoxE6 getBoundingBox(final int pViewWidth, final int pViewHeight) {
final int world_2 = TileSystem.MapSize(mZoomLevel) / 2;
final Rect screenRect = getScreenRect(null);
screenRect.offset(world_2, world_2);
final IGeoPoint neGeoPoint = TileSystem.PixelXYToLatLong(screenRect.right, screenRect.top,
mZoomLevel, null);
final IGeoPoint swGeoPoint = TileSystem.PixelXYToLatLong(screenRect.left,
screenRect.bottom, mZoomLevel, null);
return new BoundingBoxE6(neGeoPoint.getLatitudeE6(), neGeoPoint.getLongitudeE6(),
swGeoPoint.getLatitudeE6(), swGeoPoint.getLongitudeE6());
}
/**
* Gets the current bounds of the screen in <I>screen coordinates</I>.
*/
public Rect getScreenRect(final Rect reuse) {
final Rect out = reuse == null ? new Rect() : reuse;
out.set(getScrollX() - getWidth() / 2, getScrollY() - getHeight() / 2, getScrollX()
+ getWidth() / 2, getScrollY() + getHeight() / 2);
return out;
}
/**
* Get a projection for converting between screen-pixel coordinates and latitude/longitude
* coordinates. You should not hold on to this object for more than one draw, since the
* projection of the map could change.
*
* @return The Projection of the map in its current state. You should not hold on to this object
* for more than one draw, since the projection of the map could change.
*/
@Override
public Projection getProjection() {
if (mProjection == null) {
mProjection = new Projection();
}
return mProjection;
}
void setMapCenter(final IGeoPoint aCenter) {
this.setMapCenter(aCenter.getLatitudeE6(), aCenter.getLongitudeE6());
}
void setMapCenter(final int aLatitudeE6, final int aLongitudeE6) {
final Point coords = TileSystem.LatLongToPixelXY(aLatitudeE6 / 1E6, aLongitudeE6 / 1E6,
getZoomLevel(), null);
final int worldSize_2 = TileSystem.MapSize(this.getZoomLevel(false)) / 2;
if (getAnimation() == null || getAnimation().hasEnded()) {
logger.debug("StartScroll");
mScroller.startScroll(getScrollX(), getScrollY(),
coords.x - worldSize_2 - getScrollX(), coords.y - worldSize_2 - getScrollY(),
500);
postInvalidate();
}
}
public void setTileSource(final ITileSource aTileSource) {
mTileProvider.setTileSource(aTileSource);
TileSystem.setTileSize(aTileSource.getTileSizePixels());
this.checkZoomButtons();
this.setZoomLevel(mZoomLevel); // revalidate zoom level
postInvalidate();
}
/**
* @param aZoomLevel
* the zoom level bound by the tile source
*/
int setZoomLevel(final int aZoomLevel) {
final int minZoomLevel = getMinZoomLevel();
final int maxZoomLevel = getMaxZoomLevel();
final int newZoomLevel = Math.max(minZoomLevel, Math.min(maxZoomLevel, aZoomLevel));
final int curZoomLevel = this.mZoomLevel;
if (newZoomLevel != curZoomLevel) {
mScroller.forceFinished(true);
}
this.mZoomLevel = newZoomLevel;
this.checkZoomButtons();
if (newZoomLevel > curZoomLevel) {
// We are going from a lower-resolution plane to a higher-resolution plane, so we have
// to do it the hard way.
final int worldSize_current_2 = TileSystem.MapSize(curZoomLevel) / 2;
final int worldSize_new_2 = TileSystem.MapSize(newZoomLevel) / 2;
final IGeoPoint centerGeoPoint = TileSystem.PixelXYToLatLong(getScrollX()
+ worldSize_current_2, getScrollY() + worldSize_current_2, curZoomLevel, null);
final Point centerPoint = TileSystem.LatLongToPixelXY(
centerGeoPoint.getLatitudeE6() / 1E6, centerGeoPoint.getLongitudeE6() / 1E6,
newZoomLevel, null);
scrollTo(centerPoint.x - worldSize_new_2, centerPoint.y - worldSize_new_2);
} else if (newZoomLevel < curZoomLevel) {
// We are going from a higher-resolution plane to a lower-resolution plane, so we can do
// it the easy way.
scrollTo(getScrollX() >> curZoomLevel - newZoomLevel,
getScrollY() >> curZoomLevel - newZoomLevel);
}
// snap for all snappables
final Point snapPoint = new Point();
mProjection = new Projection();
if (this.getOverlayManager().onSnapToItem(getScrollX(), getScrollY(), snapPoint, this)) {
scrollTo(snapPoint.x, snapPoint.y);
}
mTileProvider.rescaleCache(newZoomLevel, curZoomLevel, getScreenRect(null));
// do callback on listener
if (newZoomLevel != curZoomLevel && mListener != null) {
final ZoomEvent event = new ZoomEvent(this, newZoomLevel);
mListener.onZoom(event);
}
// Allows any views fixed to a Location in the MapView to adjust
this.requestLayout();
return this.mZoomLevel;
}
/**
* Zoom the map to enclose the specified bounding box, as closely as possible.
* Must be called after display layout is complete, or screen dimensions are not known, and
* will always zoom to center of zoom level 0.
* Suggestion: Check getScreenRect(null).getHeight() > 0
*/
public void zoomToBoundingBox(final BoundingBoxE6 boundingBox) {
final BoundingBoxE6 currentBox = getBoundingBox();
// Calculated required zoom based on latitude span
final double maxZoomLatitudeSpan = mZoomLevel == getMaxZoomLevel() ?
currentBox.getLatitudeSpanE6() :
currentBox.getLatitudeSpanE6() / Math.pow(2, getMaxZoomLevel() - mZoomLevel);
final double requiredLatitudeZoom =
getMaxZoomLevel() -
Math.ceil(Math.log(boundingBox.getLatitudeSpanE6() / maxZoomLatitudeSpan) / Math.log(2));
// Calculated required zoom based on longitude span
final double maxZoomLongitudeSpan = mZoomLevel == getMaxZoomLevel() ?
currentBox.getLongitudeSpanE6() :
currentBox.getLongitudeSpanE6() / Math.pow(2, getMaxZoomLevel() - mZoomLevel);
final double requiredLongitudeZoom =
getMaxZoomLevel() -
Math.ceil(Math.log(boundingBox.getLongitudeSpanE6() / maxZoomLongitudeSpan) / Math.log(2));
// Zoom to boundingBox center, at calculated maximum allowed zoom level
getController().setZoom((int)(
requiredLatitudeZoom < requiredLongitudeZoom ?
requiredLatitudeZoom : requiredLongitudeZoom));
getController().setCenter(
new GeoPoint(
boundingBox.getCenter().getLatitudeE6()/1000000.0,
boundingBox.getCenter().getLongitudeE6()/1000000.0
));
}
/**
* Get the current ZoomLevel for the map tiles.
*
* @return the current ZoomLevel between 0 (equator) and 18/19(closest), depending on the tile
* source chosen.
*/
@Override
public int getZoomLevel() {
return getZoomLevel(true);
}
/**
* Get the current ZoomLevel for the map tiles.
*
* @param aPending
* if true and we're animating then return the zoom level that we're animating
* towards, otherwise return the current zoom level
* @return the zoom level
*/
public int getZoomLevel(final boolean aPending) {
if (aPending && isAnimating()) {
return mTargetZoomLevel.get();
} else {
return mZoomLevel;
}
}
/**
* Returns the minimum zoom level for the point currently at the center.
*
* @return The minimum zoom level for the map's current center.
*/
public int getMinZoomLevel() {
return mMapOverlay.getMinimumZoomLevel();
}
/**
* Returns the maximum zoom level for the point currently at the center.
*
* @return The maximum zoom level for the map's current center.
*/
@Override
public int getMaxZoomLevel() {
return mMapOverlay.getMaximumZoomLevel();
}
public boolean canZoomIn() {
final int maxZoomLevel = getMaxZoomLevel();
if (mZoomLevel >= maxZoomLevel) {
return false;
}
if (mIsAnimating.get() & mTargetZoomLevel.get() >= maxZoomLevel) {
return false;
}
return true;
}
public boolean canZoomOut() {
final int minZoomLevel = getMinZoomLevel();
if (mZoomLevel <= minZoomLevel) {
return false;
}
if (mIsAnimating.get() && mTargetZoomLevel.get() <= minZoomLevel) {
return false;
}
return true;
}
/**
* Zoom in by one zoom level.
*/
boolean zoomIn() {
if (canZoomIn()) {
if (mIsAnimating.get()) {
// TODO extend zoom (and return true)
return false;
} else {
mTargetZoomLevel.set(mZoomLevel + 1);
mIsAnimating.set(true);
startAnimation(mZoomInAnimation);
return true;
}
} else {
return false;
}
}
boolean zoomInFixing(final IGeoPoint point) {
setMapCenter(point); // TODO should fix on point, not center on it
return zoomIn();
}
boolean zoomInFixing(final int xPixel, final int yPixel) {
setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it
return zoomIn();
}
/**
* Zoom out by one zoom level.
*/
boolean zoomOut() {
if (canZoomOut()) {
if (mIsAnimating.get()) {
// TODO extend zoom (and return true)
return false;
} else {
mTargetZoomLevel.set(mZoomLevel - 1);
mIsAnimating.set(true);
startAnimation(mZoomOutAnimation);
return true;
}
} else {
return false;
}
}
boolean zoomOutFixing(final IGeoPoint point) {
setMapCenter(point); // TODO should fix on point, not center on it
return zoomOut();
}
boolean zoomOutFixing(final int xPixel, final int yPixel) {
setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it
return zoomOut();
}
/**
* Returns the current center-point position of the map, as a GeoPoint (latitude and longitude).
*
* @return A GeoPoint of the map's center-point.
*/
@Override
public IGeoPoint getMapCenter() {
final int world_2 = TileSystem.MapSize(mZoomLevel) / 2;
final Rect screenRect = getScreenRect(null);
screenRect.offset(world_2, world_2);
return TileSystem.PixelXYToLatLong(screenRect.centerX(), screenRect.centerY(), mZoomLevel,
null);
}
public ResourceProxy getResourceProxy() {
return mResourceProxy;
}
/**
* Whether to use the network connection if it's available.
*/
public boolean useDataConnection() {
return mMapOverlay.useDataConnection();
}
/**
* Set whether to use the network connection if it's available.
*
* @param aMode
* if true use the network connection if it's available. if false don't use the
* network connection even if it's available.
*/
public void setUseDataConnection(final boolean aMode) {
mMapOverlay.setUseDataConnection(aMode);
}
// Methods from SuperClass/Interfaces
/**
* Returns a set of layout parameters with a width of
* {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, a height of
* {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} at the {@link GeoPoint} (0, 0) align
* with {@link MapView.LayoutParams#BOTTOM_CENTER}.
*/
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, null, MapView.LayoutParams.BOTTOM_CENTER, 0, 0);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(final AttributeSet attrs) {
return new MapView.LayoutParams(getContext(), attrs);
}
// Override to allow type-checking of LayoutParams.
@Override
protected boolean checkLayoutParams(final ViewGroup.LayoutParams p) {
return p instanceof MapView.LayoutParams;
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(final ViewGroup.LayoutParams p) {
return new MapView.LayoutParams(p);
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final int count = getChildCount();
int maxHeight = 0;
int maxWidth = 0;
// Find out how big everyone wants to be
measureChildren(widthMeasureSpec, heightMeasureSpec);
// Find rightmost and bottom-most child
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int childWidth = child.getMeasuredWidth();
getProjection().toMapPixels(lp.geoPoint, mPoint);
final int x = mPoint.x + getWidth() / 2;
final int y = mPoint.y + getHeight() / 2;
int childRight = x;
int childBottom = y;
switch (lp.alignment) {
case MapView.LayoutParams.TOP_LEFT:
childRight = x + childWidth;
childBottom = y;
break;
case MapView.LayoutParams.TOP_CENTER:
childRight = x + childWidth / 2;
childBottom = y;
break;
case MapView.LayoutParams.TOP_RIGHT:
childRight = x;
childBottom = y;
break;
case MapView.LayoutParams.CENTER_LEFT:
childRight = x + childWidth;
childBottom = y + childHeight / 2;
break;
case MapView.LayoutParams.CENTER:
childRight = x + childWidth / 2;
childBottom = y + childHeight / 2;
break;
case MapView.LayoutParams.CENTER_RIGHT:
childRight = x;
childBottom = y + childHeight / 2;
break;
case MapView.LayoutParams.BOTTOM_LEFT:
childRight = x + childWidth;
childBottom = y + childHeight;
break;
case MapView.LayoutParams.BOTTOM_CENTER:
childRight = x + childWidth / 2;
childBottom = y + childHeight;
break;
case MapView.LayoutParams.BOTTOM_RIGHT:
childRight = x;
childBottom = y + childHeight;
break;
}
childRight += lp.offsetX;
childBottom += lp.offsetY;
maxWidth = Math.max(maxWidth, childRight);
maxHeight = Math.max(maxHeight, childBottom);
}
}
// Account for padding too
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Check against minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
resolveSize(maxHeight, heightMeasureSpec));
}
@Override
protected void onLayout(final boolean changed, final int l, final int t, final int r,
final int b) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int childWidth = child.getMeasuredWidth();
getProjection().toMapPixels(lp.geoPoint, mPoint);
final int x = mPoint.x + getWidth() / 2;
final int y = mPoint.y + getHeight() / 2;
int childLeft = x;
int childTop = y;
switch (lp.alignment) {
case MapView.LayoutParams.TOP_LEFT:
childLeft = getPaddingLeft() + x;
childTop = getPaddingTop() + y;
break;
case MapView.LayoutParams.TOP_CENTER:
childLeft = getPaddingLeft() + x - childWidth / 2;
childTop = getPaddingTop() + y;
break;
case MapView.LayoutParams.TOP_RIGHT:
childLeft = getPaddingLeft() + x - childWidth;
childTop = getPaddingTop() + y;
break;
case MapView.LayoutParams.CENTER_LEFT:
childLeft = getPaddingLeft() + x;
childTop = getPaddingTop() + y - childHeight / 2;
break;
case MapView.LayoutParams.CENTER:
childLeft = getPaddingLeft() + x - childWidth / 2;
childTop = getPaddingTop() + y - childHeight / 2;
break;
case MapView.LayoutParams.CENTER_RIGHT:
childLeft = getPaddingLeft() + x - childWidth;
childTop = getPaddingTop() + y - childHeight / 2;
break;
case MapView.LayoutParams.BOTTOM_LEFT:
childLeft = getPaddingLeft() + x;
childTop = getPaddingTop() + y - childHeight;
break;
case MapView.LayoutParams.BOTTOM_CENTER:
childLeft = getPaddingLeft() + x - childWidth / 2;
childTop = getPaddingTop() + y - childHeight;
break;
case MapView.LayoutParams.BOTTOM_RIGHT:
childLeft = getPaddingLeft() + x - childWidth;
childTop = getPaddingTop() + y - childHeight;
break;
}
childLeft += lp.offsetX;
childTop += lp.offsetY;
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
}
}
}
public void onDetach() {
this.getOverlayManager().onDetach(this);
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
final boolean result = this.getOverlayManager().onKeyDown(keyCode, event, this);
return result || super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(final int keyCode, final KeyEvent event) {
final boolean result = this.getOverlayManager().onKeyUp(keyCode, event, this);
return result || super.onKeyUp(keyCode, event);
}
@Override
public boolean onTrackballEvent(final MotionEvent event) {
if (this.getOverlayManager().onTrackballEvent(event, this)) {
return true;
}
scrollBy((int) (event.getX() * 25), (int) (event.getY() * 25));
return super.onTrackballEvent(event);
}
@Override
public boolean dispatchTouchEvent(final MotionEvent event) {
if (DEBUGMODE) {
logger.debug("dispatchTouchEvent(" + event + ")");
}
if (mZoomController.isVisible() && mZoomController.onTouch(this, event)) {
return true;
}
if (this.getOverlayManager().onTouchEvent(event, this)) {
return true;
}
if (mMultiTouchController != null && mMultiTouchController.onTouchEvent(event)) {
if (DEBUGMODE) {
logger.debug("mMultiTouchController handled onTouchEvent");
}
return true;
}
if (super.dispatchTouchEvent(event)) {
if (DEBUGMODE) {
logger.debug("super handled onTouchEvent");
}
return true;
}
if (mGestureDetector.onTouchEvent(event)) {
if (DEBUGMODE) {
logger.debug("mGestureDetector handled onTouchEvent");
}
return true;
}
if (DEBUGMODE) {
logger.debug("no-one handled onTouchEvent");
}
return false;
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
if (mScroller.isFinished()) {
// This will facilitate snapping-to any Snappable points.
setZoomLevel(mZoomLevel);
} else {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
}
postInvalidate(); // Keep on drawing until the animation has
// finished.
}
}
@Override
public void scrollTo(int x, int y) {
final int worldSize_2 = TileSystem.MapSize(this.getZoomLevel(false)) / 2;
while (x < -worldSize_2) {
x += worldSize_2 * 2;
}
while (x > worldSize_2) {
x -= worldSize_2 * 2;
}
while (y < -worldSize_2) {
y += worldSize_2 * 2;
}
while (y > worldSize_2) {
y -= worldSize_2 * 2;
}
super.scrollTo(x, y);
// do callback on listener
if (mListener != null) {
final ScrollEvent event = new ScrollEvent(this, x, y);
mListener.onScroll(event);
}
}
@Override
public void setBackgroundColor(final int pColor) {
mMapOverlay.setLoadingBackgroundColor(pColor);
invalidate();
}
@Override
protected void dispatchDraw(final Canvas c) {
final long startMs = System.currentTimeMillis();
mProjection = new Projection();
// Save the current canvas matrix
c.save();
if (mMultiTouchScale == 1.0f) {
c.translate(getWidth() / 2, getHeight() / 2);
} else {
c.getMatrix(mMatrix);
mMatrix.postTranslate(getWidth() / 2, getHeight() / 2);
mMatrix.preScale(mMultiTouchScale, mMultiTouchScale, getScrollX(), getScrollY());
c.setMatrix(mMatrix);
}
/* Draw background */
// c.drawColor(mBackgroundColor);
/* Draw all Overlays. */
this.getOverlayManager().onDraw(c, this);
// Restore the canvas matrix
c.restore();
super.dispatchDraw(c);
if (DEBUGMODE) {
final long endMs = System.currentTimeMillis();
logger.debug("Rendering overall: " + (endMs - startMs) + "ms");
}
}
@Override
protected void onDetachedFromWindow() {
this.mZoomController.setVisible(false);
this.onDetach();
super.onDetachedFromWindow();
}
// Animation
@Override
protected void onAnimationStart() {
mIsAnimating.set(true);
super.onAnimationStart();
}
@Override
protected void onAnimationEnd() {
mIsAnimating.set(false);
clearAnimation();
setZoomLevel(mTargetZoomLevel.get());
super.onAnimationEnd();
}
/**
* Check mAnimationListener.isAnimating() to determine if view is animating. Useful for overlays
* to avoid recalculating during an animation sequence.
*
* @return boolean indicating whether view is animating.
*/
public boolean isAnimating() {
return mIsAnimating.get();
}
// Implementation of MultiTouchObjectCanvas
@Override
public Object getDraggableObjectAtPoint(final PointInfo pt) {
return this;
}
@Override
public void getPositionAndScale(final Object obj, final PositionAndScale objPosAndScaleOut) {
objPosAndScaleOut.set(0, 0, true, mMultiTouchScale, false, 0, 0, false, 0);
}
@Override
public void selectObject(final Object obj, final PointInfo pt) {
// if obj is null it means we released the pointers
// if scale is not 1 it means we pinched
if (obj == null && mMultiTouchScale != 1.0f) {
final float scaleDiffFloat = (float) (Math.log(mMultiTouchScale) * ZOOM_LOG_BASE_INV);
final int scaleDiffInt = Math.round(scaleDiffFloat);
setZoomLevel(mZoomLevel + scaleDiffInt);
// XXX maybe zoom in/out instead of zooming direct to zoom level
// - probably not a good idea because you'll repeat the animation
}
// reset scale
mMultiTouchScale = 1.0f;
}
@Override
public boolean setPositionAndScale(final Object obj, final PositionAndScale aNewObjPosAndScale,
final PointInfo aTouchPoint) {
float multiTouchScale = aNewObjPosAndScale.getScale();
// If we are at the first or last zoom level, prevent pinching/expanding
if (multiTouchScale > 1 && !canZoomIn()) {
multiTouchScale = 1;
}
if (multiTouchScale < 1 && !canZoomOut()) {
multiTouchScale = 1;
}
mMultiTouchScale = multiTouchScale;
invalidate(); // redraw
return true;
}
/*
* Set the MapListener for this view
*/
public void setMapListener(final MapListener ml) {
mListener = ml;
}
// Methods
private void checkZoomButtons() {
this.mZoomController.setZoomInEnabled(canZoomIn());
this.mZoomController.setZoomOutEnabled(canZoomOut());
}
public void setBuiltInZoomControls(final boolean on) {
this.mEnableZoomController = on;
this.checkZoomButtons();
}
public void setMultiTouchControls(final boolean on) {
mMultiTouchController = on ? new MultiTouchController<Object>(this, false) : null;
}
private ITileSource getTileSourceFromAttributes(final AttributeSet aAttributeSet) {
ITileSource tileSource = TileSourceFactory.DEFAULT_TILE_SOURCE;
if (aAttributeSet != null) {
final String tileSourceAttr = aAttributeSet.getAttributeValue(null, "tilesource");
if (tileSourceAttr != null) {
try {
final ITileSource r = TileSourceFactory.getTileSource(tileSourceAttr);
logger.info("Using tile source specified in layout attributes: " + r);
tileSource = r;
} catch (final IllegalArgumentException e) {
logger.warn("Invalid tile souce specified in layout attributes: " + tileSource);
}
}
}
if (aAttributeSet != null && tileSource instanceof IStyledTileSource) {
final String style = aAttributeSet.getAttributeValue(null, "style");
if (style == null) {
logger.info("Using default style: 1");
} else {
logger.info("Using style specified in layout attributes: " + style);
((IStyledTileSource<?>) tileSource).setStyle(style);
}
}
logger.info("Using tile source: " + tileSource);
return tileSource;
}
// Inner and Anonymous Classes
/**
* A Projection serves to translate between the coordinate system of x/y on-screen pixel
* coordinates and that of latitude/longitude points on the surface of the earth. You obtain a
* Projection from MapView.getProjection(). You should not hold on to this object for more than
* one draw, since the projection of the map could change. <br />
* <br />
* <I>Screen coordinates</I> are in the coordinate system of the screen's Canvas. The origin is
* in the center of the plane. <I>Screen coordinates</I> are appropriate for using to draw to
* the screen.<br />
* <br />
* <I>Map coordinates</I> are in the coordinate system of the standard Mercator projection. The
* origin is in the upper-left corner of the plane. <I>Map coordinates</I> are appropriate for
* use in the TileSystem class.<br />
* <br />
* <I>Intermediate coordinates</I> are used to cache the computationally heavy part of the
* projection. They aren't suitable for use until translated into <I>screen coordinates</I> or
* <I>map coordinates</I>.
*
* @author Nicolas Gramlich
* @author Manuel Stahl
*/
public class Projection implements IProjection, GeoConstants {
private final int viewWidth_2 = getWidth() / 2;
private final int viewHeight_2 = getHeight() / 2;
private final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2;
private final int offsetX = -worldSize_2;
private final int offsetY = -worldSize_2;
private final BoundingBoxE6 mBoundingBoxProjection;
private final int mZoomLevelProjection;
private final Rect mScreenRectProjection;
private Projection() {
/*
* Do some calculations and drag attributes to local variables to save some performance.
*/
mZoomLevelProjection = MapView.this.mZoomLevel;
mBoundingBoxProjection = MapView.this.getBoundingBox();
mScreenRectProjection = MapView.this.getScreenRect(null);
}
public int getZoomLevel() {
return mZoomLevelProjection;
}
public BoundingBoxE6 getBoundingBox() {
return mBoundingBoxProjection;
}
public Rect getScreenRect() {
return mScreenRectProjection;
}
/**
* @deprecated Use TileSystem.getTileSize() instead.
*/
@Deprecated
public int getTileSizePixels() {
return TileSystem.getTileSize();
}
/**
* @deprecated Use
* <code>Point out = TileSystem.PixelXYToTileXY(screenRect.centerX(), screenRect.centerY(), null);</code>
* instead.
*/
@Deprecated
public Point getCenterMapTileCoords() {
final Rect rect = getScreenRect();
return TileSystem.PixelXYToTileXY(rect.centerX(), rect.centerY(), null);
}
/**
* @deprecated Use
* <code>final Point out = TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null);</code>
* instead.
*/
@Deprecated
public Point getUpperLeftCornerOfCenterMapTile() {
final Point centerMapTileCoords = getCenterMapTileCoords();
return TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null);
}
/**
* Converts <I>screen coordinates</I> to the underlying GeoPoint.
*
* @param x
* @param y
* @return GeoPoint under x/y.
*/
public IGeoPoint fromPixels(final float x, final float y) {
final Rect screenRect = getScreenRect();
return TileSystem.PixelXYToLatLong(screenRect.left + (int) x + worldSize_2,
screenRect.top + (int) y + worldSize_2, mZoomLevelProjection, null);
}
public Point fromMapPixels(final int x, final int y, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
out.set(x - viewWidth_2, y - viewHeight_2);
out.offset(getScrollX(), getScrollY());
return out;
}
/**
* Converts a GeoPoint to its <I>screen coordinates</I>.
*
* @param in
* the GeoPoint you want the <I>screen coordinates</I> of
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
* @return the Point containing the <I>screen coordinates</I> of the GeoPoint passed.
*/
public Point toMapPixels(final IGeoPoint in, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
TileSystem.LatLongToPixelXY(
in.getLatitudeE6() / 1E6,
in.getLongitudeE6() / 1E6,
getZoomLevel(), out);
out.offset(offsetX, offsetY);
if (Math.abs(out.x - getScrollX()) >
Math.abs(out.x - TileSystem.MapSize(getZoomLevel()) - getScrollX())) {
out.x -= TileSystem.MapSize(getZoomLevel());
}
if (Math.abs(out.y - getScrollY()) >
Math.abs(out.y - TileSystem.MapSize(getZoomLevel()) - getScrollY())) {
out.y -= TileSystem.MapSize(getZoomLevel());
}
return out;
}
/**
* Performs only the first computationally heavy part of the projection. Call
* toMapPixelsTranslated to get the final position.
*
* @param latituteE6
* the latitute of the point
* @param longitudeE6
* the longitude of the point
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
* @return intermediate value to be stored and passed to toMapPixelsTranslated.
*/
public Point toMapPixelsProjected(final int latituteE6, final int longitudeE6,
final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
TileSystem
.LatLongToPixelXY(latituteE6 / 1E6, longitudeE6 / 1E6, MAXIMUM_ZOOMLEVEL, out);
return out;
}
/**
* Performs the second computationally light part of the projection. Returns results in
* <I>screen coordinates</I>.
*
* @param in
* the Point calculated by the toMapPixelsProjected
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
* @return the Point containing the <I>Screen coordinates</I> of the initial GeoPoint passed
* to the toMapPixelsProjected.
*/
public Point toMapPixelsTranslated(final Point in, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel();
out.set((in.x >> zoomDifference) + offsetX, (in.y >> zoomDifference) + offsetY);
return out;
}
/**
* Translates a rectangle from <I>screen coordinates</I> to <I>intermediate coordinates</I>.
*
* @param in
* the rectangle in <I>screen coordinates</I>
* @return a rectangle in </I>intermediate coordindates</I>.
*/
public Rect fromPixelsToProjected(final Rect in) {
final Rect result = new Rect();
final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel();
final int x0 = in.left - offsetX << zoomDifference;
final int x1 = in.right - offsetX << zoomDifference;
final int y0 = in.bottom - offsetY << zoomDifference;
final int y1 = in.top - offsetY << zoomDifference;
result.set(Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1));
return result;
}
/**
* @deprecated Use TileSystem.TileXYToPixelXY
*/
@Deprecated
public Point toPixels(final Point tileCoords, final Point reuse) {
return toPixels(tileCoords.x, tileCoords.y, reuse);
}
/**
* @deprecated Use TileSystem.TileXYToPixelXY
*/
@Deprecated
public Point toPixels(final int tileX, final int tileY, final Point reuse) {
return TileSystem.TileXYToPixelXY(tileX, tileY, reuse);
}
// not presently used
public Rect toPixels(final BoundingBoxE6 pBoundingBoxE6) {
final Rect rect = new Rect();
final Point reuse = new Point();
toMapPixels(
new GeoPoint(pBoundingBoxE6.getLatNorthE6(), pBoundingBoxE6.getLonWestE6()),
reuse);
rect.left = reuse.x;
rect.top = reuse.y;
toMapPixels(
new GeoPoint(pBoundingBoxE6.getLatSouthE6(), pBoundingBoxE6.getLonEastE6()),
reuse);
rect.right = reuse.x;
rect.bottom = reuse.y;
return rect;
}
@Override
public float metersToEquatorPixels(final float meters) {
return meters / (float) TileSystem.GroundResolution(0, mZoomLevelProjection);
}
@Override
public Point toPixels(final IGeoPoint in, final Point out) {
return toMapPixels(in, out);
}
@Override
public IGeoPoint fromPixels(final int x, final int y) {
return fromPixels((float) x, (float) y);
}
}
private class MapViewGestureDetectorListener implements OnGestureListener {
@Override
public boolean onDown(final MotionEvent e) {
if (MapView.this.getOverlayManager().onDown(e, MapView.this)) {
return true;
}
mZoomController.setVisible(mEnableZoomController);
return true;
}
@Override
public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX,
final float velocityY) {
if (MapView.this.getOverlayManager()
.onFling(e1, e2, velocityX, velocityY, MapView.this)) {
return true;
}
final int worldSize = TileSystem.MapSize(MapView.this.getZoomLevel(false));
mScroller.fling(getScrollX(), getScrollY(), (int) -velocityX, (int) -velocityY,
-worldSize, worldSize, -worldSize, worldSize);
return true;
}
@Override
public void onLongPress(final MotionEvent e) {
if (mMultiTouchController != null && mMultiTouchController.isPinching()) {
return;
}
MapView.this.getOverlayManager().onLongPress(e, MapView.this);
}
@Override
public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX,
final float distanceY) {
if (MapView.this.getOverlayManager().onScroll(e1, e2, distanceX, distanceY,
MapView.this)) {
return true;
}
scrollBy((int) distanceX, (int) distanceY);
return true;
}
@Override
public void onShowPress(final MotionEvent e) {
MapView.this.getOverlayManager().onShowPress(e, MapView.this);
}
@Override
public boolean onSingleTapUp(final MotionEvent e) {
if (MapView.this.getOverlayManager().onSingleTapUp(e, MapView.this)) {
return true;
}
return false;
}
}
private class MapViewDoubleClickListener implements GestureDetector.OnDoubleTapListener {
@Override
public boolean onDoubleTap(final MotionEvent e) {
if (MapView.this.getOverlayManager().onDoubleTap(e, MapView.this)) {
return true;
}
final IGeoPoint center = getProjection().fromPixels(e.getX(), e.getY());
return zoomInFixing(center);
}
@Override
public boolean onDoubleTapEvent(final MotionEvent e) {
if (MapView.this.getOverlayManager().onDoubleTapEvent(e, MapView.this)) {
return true;
}
return false;
}
@Override
public boolean onSingleTapConfirmed(final MotionEvent e) {
if (MapView.this.getOverlayManager().onSingleTapConfirmed(e, MapView.this)) {
return true;
}
return false;
}
}
private class MapViewZoomListener implements OnZoomListener {
@Override
public void onZoom(final boolean zoomIn) {
if (zoomIn) {
getController().zoomIn();
} else {
getController().zoomOut();
}
}
@Override
public void onVisibilityChanged(final boolean visible) {
}
}
// Public Classes
/**
* Per-child layout information associated with OpenStreetMapView.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* Special value for the alignment requested by a View. TOP_LEFT means that the location
* will at the top left the View.
*/
public static final int TOP_LEFT = 1;
/**
* Special value for the alignment requested by a View. TOP_RIGHT means that the location
* will be centered at the top of the View.
*/
public static final int TOP_CENTER = 2;
/**
* Special value for the alignment requested by a View. TOP_RIGHT means that the location
* will at the top right the View.
*/
public static final int TOP_RIGHT = 3;
/**
* Special value for the alignment requested by a View. CENTER_LEFT means that the location
* will at the center left the View.
*/
public static final int CENTER_LEFT = 4;
/**
* Special value for the alignment requested by a View. CENTER means that the location will
* be centered at the center of the View.
*/
public static final int CENTER = 5;
/**
* Special value for the alignment requested by a View. CENTER_RIGHT means that the location
* will at the center right the View.
*/
public static final int CENTER_RIGHT = 6;
/**
* Special value for the alignment requested by a View. BOTTOM_LEFT means that the location
* will be at the bottom left of the View.
*/
public static final int BOTTOM_LEFT = 7;
/**
* Special value for the alignment requested by a View. BOTTOM_CENTER means that the
* location will be centered at the bottom of the view.
*/
public static final int BOTTOM_CENTER = 8;
/**
* Special value for the alignment requested by a View. BOTTOM_RIGHT means that the location
* will be at the bottom right of the View.
*/
public static final int BOTTOM_RIGHT = 9;
/**
* The location of the child within the map view.
*/
public IGeoPoint geoPoint;
/**
* The alignment the alignment of the view compared to the location.
*/
public int alignment;
public int offsetX;
public int offsetY;
/**
* Creates a new set of layout parameters with the specified width, height and location.
*
* @param width
* the width, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size
* in pixels
* @param height
* the height, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size
* in pixels
* @param geoPoint
* the location of the child within the map view
* @param alignment
* the alignment of the view compared to the location {@link #BOTTOM_CENTER},
* {@link #BOTTOM_LEFT}, {@link #BOTTOM_RIGHT} {@link #TOP_CENTER},
* {@link #TOP_LEFT}, {@link #TOP_RIGHT}
* @param offsetX
* the additional X offset from the alignment location to draw the child within
* the map view
* @param offsetY
* the additional Y offset from the alignment location to draw the child within
* the map view
*/
public LayoutParams(final int width, final int height, final IGeoPoint geoPoint,
final int alignment, final int offsetX, final int offsetY) {
super(width, height);
if (geoPoint != null) {
this.geoPoint = geoPoint;
} else {
this.geoPoint = new GeoPoint(0, 0);
}
this.alignment = alignment;
this.offsetX = offsetX;
this.offsetY = offsetY;
}
/**
* Since we cannot use XML files in this project this constructor is useless. Creates a new
* set of layout parameters. The values are extracted from the supplied attributes set and
* context.
*
* @param c
* the application environment
* @param attrs
* the set of attributes fom which to extract the layout parameters values
*/
public LayoutParams(final Context c, final AttributeSet attrs) {
super(c, attrs);
this.geoPoint = new GeoPoint(0, 0);
this.alignment = BOTTOM_CENTER;
}
/**
* {@inheritDoc}
*/
public LayoutParams(final ViewGroup.LayoutParams source) {
super(source);
}
}
}
|
package us.kbase.workspace.database.mongo;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import us.kbase.auth.AuthException;
import us.kbase.auth.AuthService;
import us.kbase.auth.AuthToken;
import us.kbase.auth.AuthUser;
import us.kbase.auth.TokenExpiredException;
import us.kbase.shock.client.BasicShockClient;
import us.kbase.shock.client.ShockNode;
import us.kbase.shock.client.ShockNodeId;
import us.kbase.shock.client.exceptions.InvalidShockUrlException;
import us.kbase.shock.client.exceptions.ShockHttpException;
import us.kbase.typedobj.core.MD5;
import us.kbase.typedobj.core.Writable;
import us.kbase.workspace.database.ByteArrayFileCacheManager;
import us.kbase.workspace.database.ByteArrayFileCacheManager.ByteArrayFileCache;
import us.kbase.workspace.database.exceptions.FileCacheIOException;
import us.kbase.workspace.database.exceptions.FileCacheLimitExceededException;
import us.kbase.workspace.database.mongo.exceptions.BlobStoreAuthorizationException;
import us.kbase.workspace.database.mongo.exceptions.BlobStoreCommunicationException;
import us.kbase.workspace.database.mongo.exceptions.BlobStoreException;
import us.kbase.workspace.database.mongo.exceptions.NoSuchBlobException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.gc.iotools.stream.base.ExecutionModel;
import com.gc.iotools.stream.base.ExecutorServiceFactory;
import com.gc.iotools.stream.os.OutputStreamToInputStream;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
public class ShockBackend implements BlobStore {
private static final String nodeMap = "nodeMap";
private String user;
private String password;
private BasicShockClient client;
private DBCollection mongoCol;
private static final String IDX_UNIQ = "unique";
public ShockBackend(final DB mongoDB, final String collectionPrefix,
final URL url, final String user, final String password)
throws BlobStoreAuthorizationException,
BlobStoreException {
if (collectionPrefix == null || mongoDB == null) {
throw new IllegalArgumentException(
"mongoDB and collectionPrefix cannot be null");
}
this.mongoCol = mongoDB.getCollection(collectionPrefix + nodeMap);
final DBObject dbo = new BasicDBObject();
dbo.put(Fields.SHOCK_CHKSUM, 1);
final DBObject opts = new BasicDBObject();
opts.put(IDX_UNIQ, 1);
mongoCol.ensureIndex(dbo, opts);
this.user = user;
this.password = password;
try {
client = new BasicShockClient(url, getToken());
} catch (InvalidShockUrlException isue) {
throw new BlobStoreException(
"The shock url " + url + " is invalid", isue);
} catch (ShockHttpException she) {
throw new BlobStoreException(
"Shock appears to be misconfigured - the client could not initialize",
she);
} catch (TokenExpiredException ete) {
throw new BlobStoreException( //uh... this should never happen
"The token retrieved from the auth service is already " +
"expired", ete);
} catch (IOException ioe) {
throw new BlobStoreCommunicationException(
"Could not connect to the shock backend: " +
ioe.getLocalizedMessage(), ioe);
}
}
private AuthToken getToken() throws BlobStoreAuthorizationException,
BlobStoreCommunicationException {
final AuthUser u;
try {
u = AuthService.login(user, password);
} catch (AuthException ae) {
throw new BlobStoreAuthorizationException(
"Could not authenticate backend user", ae);
} catch (IOException ioe) {
throw new BlobStoreCommunicationException(
"Could not connect to the shock backend auth provider: " +
ioe.getLocalizedMessage(), ioe);
}
return u.getToken();
}
private void checkAuth() throws BlobStoreAuthorizationException,
BlobStoreCommunicationException {
if(client.isTokenExpired()) {
try {
client.updateToken(getToken());
} catch (TokenExpiredException ete) {
throw new RuntimeException(
"Auth service is handing out expired tokens", ete);
}
}
}
@Override
public void saveBlob(final MD5 md5, final Writable data)
throws BlobStoreAuthorizationException,
BlobStoreCommunicationException {
if (data == null) {
throw new IllegalArgumentException("data cannot be null");
}
try {
getNode(md5);
return; //already saved
} catch (NoSuchBlobException nb) {
//go ahead, need to save
}
checkAuth();
final ShockNode sn;
final OutputStreamToInputStream<ShockNode> osis =
new OutputStreamToInputStream<ShockNode>() {
@Override
protected ShockNode doRead(InputStream is) throws Exception {
final ShockNode sn;
try {
sn = client.addNode(is, "workspace_" + md5.getMD5(),
"JSON");
} catch (TokenExpiredException ete) {
//this should be impossible
throw new RuntimeException("Token magically expired: "
+ ete.getLocalizedMessage(), ete);
} catch (JsonProcessingException jpe) {
//this should be impossible
throw new RuntimeException("JsonNode serialization failed: "
+ jpe.getLocalizedMessage(), jpe);
} catch (IOException ioe) {
throw new BlobStoreCommunicationException(
"Could not connect to the shock backend: " +
ioe.getLocalizedMessage(), ioe);
} catch (ShockHttpException she) {
throw new BlobStoreCommunicationException(
"Failed to create shock node: " +
she.getLocalizedMessage(), she);
}
// is.close(); closing the stream has caused deadlocks in other applications
return sn;
}
};
try {
//writes in UTF8
data.write(osis);
data.releaseResources();
} catch (IOException ioe) {
//no way to test this easily, manually tested for now.
//be sure to test manually if making changes
if (ioe.getCause().getClass().equals(
BlobStoreCommunicationException.class)) {
throw (BlobStoreCommunicationException) ioe.getCause();
}
throw new RuntimeException("IO Error during streaming of data to Shock: "
+ ioe.getLocalizedMessage(), ioe);
} finally {
try {
osis.close();
} catch (IOException ioe) {
//no way to test this easily, manually tested for now.
//be sure to test manually if making changes
if (ioe.getCause().getClass().equals(
BlobStoreCommunicationException.class)) {
throw (BlobStoreCommunicationException) ioe.getCause();
}
throw new RuntimeException(
"Couldn't close Shock output stream: " +
ioe.getLocalizedMessage(), ioe);
}
}
try {
sn = osis.getResult();
} catch (InterruptedException ie) {
throw new RuntimeException(
"Interrupt trying to retrieve ShockNode from EasyStream instance: "
+ ie.getLocalizedMessage(), ie);
} catch (ExecutionException ee) {
throw new RuntimeException(
"Excecution error trying to retrieve ShockNode from EasyStream instance: "
+ ee.getLocalizedMessage(), ee);
}
final DBObject dbo = new BasicDBObject();
dbo.put(Fields.SHOCK_CHKSUM, md5.getMD5());
dbo.put(Fields.SHOCK_NODE, sn.getId().getId());
dbo.put(Fields.SHOCK_VER, sn.getVersion().getVersion());
final DBObject query = new BasicDBObject();
query.put(Fields.SHOCK_CHKSUM, md5.getMD5());
try {
//possible that this was inserted just prior to saving the object
//so do update vs. insert since the data must be the same
mongoCol.update(query, dbo, true, false);
} catch (MongoException me) {
throw new BlobStoreCommunicationException(
"Could not write to the mongo database", me);
}
}
private String getNode(final MD5 md5) throws
BlobStoreCommunicationException, NoSuchBlobException {
final DBObject query = new BasicDBObject();
query.put(Fields.SHOCK_CHKSUM, md5.getMD5());
final DBObject ret;
try {
ret = mongoCol.findOne(query);
} catch (MongoException me) {
throw new BlobStoreCommunicationException(
"Could not read from the mongo database", me);
}
if (ret == null) {
throw new NoSuchBlobException("No blob saved with chksum "
+ md5.getMD5());
}
return (String) ret.get(Fields.SHOCK_NODE);
}
@Override
public ByteArrayFileCache getBlob(final MD5 md5,
final ByteArrayFileCacheManager bafcMan)
throws BlobStoreAuthorizationException,
BlobStoreCommunicationException, NoSuchBlobException,
FileCacheLimitExceededException, FileCacheIOException {
checkAuth();
final String node = getNode(md5);
final OutputStreamToInputStream<ByteArrayFileCache> osis =
new OutputStreamToInputStream<ByteArrayFileCache>(true,
ExecutorServiceFactory.getExecutor(
ExecutionModel.THREAD_PER_INSTANCE), 10000000) { //speeds up by 2-3x
@Override
protected ByteArrayFileCache doRead(InputStream is) throws Exception {
return bafcMan.createBAFC(is);
}
};
try {
client.getFile(new ShockNodeId(node), osis);
} catch (TokenExpiredException ete) {
//this should be impossible
throw new RuntimeException("Things are broke", ete);
} catch (IOException ioe) {
if (ioe.getCause() instanceof FileCacheLimitExceededException) {
throw (FileCacheLimitExceededException) ioe.getCause();
}
if (ioe.getCause() instanceof FileCacheIOException) {
throw (FileCacheIOException) ioe.getCause();
}
throw new BlobStoreCommunicationException(
"Could not connect to the shock backend: " +
ioe.getLocalizedMessage(), ioe);
} catch (ShockHttpException she) {
throw new BlobStoreCommunicationException(
"Failed to retrieve shock node: " +
she.getLocalizedMessage(), she);
}
try {
osis.close();
} catch (IOException ioe) {
throw new RuntimeException("Something is broken", ioe);
}
try {
return osis.getResult();
} catch (InterruptedException ie) {
throw new RuntimeException("Something is broken", ie);
} catch (ExecutionException ee) {
throw new RuntimeException("Something is broken", ee);
}
}
@Override
public void removeBlob(final MD5 md5)
throws BlobStoreAuthorizationException,
BlobStoreCommunicationException {
checkAuth();
final String node;
try {
node = getNode(md5);
} catch (NoSuchBlobException nb) {
return; //already gone
}
try {
client.deleteNode(new ShockNodeId(node));
} catch (TokenExpiredException ete) {
//this should be impossible
throw new RuntimeException("Things are broke", ete);
} catch (IOException ioe) {
throw new BlobStoreCommunicationException(
"Could not connect to the shock backend: " +
ioe.getLocalizedMessage(), ioe);
} catch (ShockHttpException she) {
throw new BlobStoreCommunicationException(
"Failed to delete shock node: " +
she.getLocalizedMessage(), she);
}
final DBObject query = new BasicDBObject();
query.put(Fields.SHOCK_CHKSUM, md5.getMD5());
mongoCol.remove(query);
}
/**
* this is for testing purposes only - leave Shock in the state we found it
*/
public void removeAllBlobs() throws BlobStoreCommunicationException,
BlobStoreAuthorizationException {
final DBCursor ret;
try {
ret = mongoCol.find();
} catch (MongoException me) {
throw new BlobStoreCommunicationException(
"Could not read from the mongo database", me);
}
for (final DBObject o: ret) {
removeBlob(new MD5((String) o.get(Fields.SHOCK_CHKSUM)));
}
}
@Override
public String getExternalIdentifier(final MD5 md5) throws
BlobStoreCommunicationException, NoSuchBlobException {
return getNode(md5);
}
@Override
public String getStoreType() {
return "Shock";
}
}
|
package com.std.sort;
import com.std.util.ArrayUtil;
public class MergeSort {
private int[] arr;
/**
*
* @param arrs
*/
public MergeSort(int[] arrs){
this.arr = arrs;
int[] ws = new int[arrs.length];
doMergeSort(ws,0,arr.length-1);
ArrayUtil.printArray(this.arr, ",");
}
public void doMergeSort(int[] arr,int lowerBound,int upBound){
if(lowerBound>=upBound){
return;
}
int partition = (int)Math.ceil((upBound+lowerBound)/2*1.0);
doMergeSort(arr,lowerBound,partition);
doMergeSort(arr,partition+1,upBound);
//partition+1 0-96
merge(arr,lowerBound,partition+1,upBound);
}
private void merge (int[] arr ,int lowerBound,int partition,int upBound) {
int j = 0;
int lowerPar = lowerBound;
int mid = partition-1;
while(lowerBound<=mid && partition<=upBound ){
if(this.arr[lowerBound]<this.arr[partition]){
arr[j++] = this.arr[lowerBound++];
}else{
arr[j++]=this.arr[partition++];
}
}
while(lowerBound<=mid){
arr[j++] = this.arr[lowerBound++];
}
while(partition<=upBound){
arr[j++] = this.arr[partition++];
}
for(int i=0;i<j;i++){
this.arr[lowerPar++] = arr[i];
}
}
}
|
package org.genericsystem.ir.app;
import org.genericsystem.common.Root;
import org.genericsystem.cv.model.Doc;
import org.genericsystem.cv.model.Doc.DocFilename;
import org.genericsystem.cv.model.Doc.DocTimestamp;
import org.genericsystem.cv.model.Doc.RefreshTimestamp;
import org.genericsystem.cv.model.DocClass;
import org.genericsystem.cv.model.ImgFilter;
import org.genericsystem.cv.model.LevDistance;
import org.genericsystem.cv.model.MeanLevenshtein;
import org.genericsystem.cv.model.Score;
import org.genericsystem.cv.model.ZoneGeneric;
import org.genericsystem.cv.model.ZoneText;
import org.genericsystem.cv.model.ZoneText.ZoneTimestamp;
import org.genericsystem.ir.OcrEngineHolderVerticle;
import org.genericsystem.ir.app.gui.pages.FiltersStatisticsPage;
import org.genericsystem.ir.app.gui.pages.HomePage;
import org.genericsystem.ir.app.gui.utils.PageSwitcher;
import org.genericsystem.reactor.annotations.Children;
import org.genericsystem.reactor.annotations.DependsOnModel;
import org.genericsystem.reactor.appserver.ApplicationServer;
import org.genericsystem.reactor.gscomponents.RootTagImpl;
import org.genericsystem.security.model.Role;
import org.genericsystem.security.model.User;
import org.genericsystem.security.model.UserRole;
/**
* This application can be used to deploy the verticles of gs-watch to automatically process the documents sent to a specific email address.
* <p>
* The main view shows a list of documents for each document's class. Each record can be visualized, and supervised (provided that it was OCR'r first).
*
* @author Pierrik Lassalas
*/
@DependsOnModel({ Role.class, User.class, UserRole.class, Doc.class, RefreshTimestamp.class, DocTimestamp.class, DocFilename.class, DocClass.class, ZoneGeneric.class, ZoneText.class, ZoneTimestamp.class, ImgFilter.class, LevDistance.class,
MeanLevenshtein.class, Score.class })
@Children({ HomePage.class, FiltersStatisticsPage.class })
public class WatchApp extends RootTagImpl {
private static final String gsPath = "/gs-cv_model3";
@Override
public void init() {
createNewInitializedProperty(PageSwitcher.PAGE, c -> PageSwitcher.HOME_PAGE);
}
public static void main(String[] mainArgs) {
ApplicationServer server = ApplicationServer.startSimpleGenericApp(mainArgs, WatchApp.class, gsPath);
Root root = server.getRoots().get(System.getenv("HOME") + "/genericsystem/" + gsPath);
deployVerticles(root);
}
private static void deployVerticles(Root root) {
OcrEngineHolderVerticle deployer = new OcrEngineHolderVerticle(root);
deployer.doDeploy();
}
}
|
package roart.util;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import roart.action.Action;
import roart.action.FindProfitAction;
import roart.action.ImproveProfitAction;
import roart.action.WebData;
import roart.action.UpdateDBAction;
import roart.iclij.config.IclijConfig;
import roart.common.config.MyConfig;
import roart.common.constants.Constants;
import roart.common.pipeline.PipelineConstants;
import roart.common.util.TimeUtil;
import roart.component.Component;
import roart.component.model.ComponentInput;
import roart.component.model.ComponentData;
import roart.config.IclijXMLConfig;
import roart.config.Market;
import roart.config.MarketFilter;
import roart.constants.IclijConstants;
import roart.constants.IclijPipelineConstants;
import roart.iclij.model.ConfigItem;
import roart.iclij.model.IncDecItem;
import roart.iclij.model.MapList;
import roart.iclij.model.MemoryItem;
import roart.iclij.model.TimingItem;
import roart.iclij.model.Trend;
import roart.iclij.service.IclijServiceList;
import roart.iclij.service.IclijServiceResult;
import roart.service.ControlService;
import roart.service.model.ProfitData;
public class ServiceUtil {
private static Logger log = LoggerFactory.getLogger(ServiceUtil.class);
public static double median(Set<Double> set) {
Double[] scores = set.toArray(new Double[set.size()]);
Arrays.sort(scores);
//System.out.print("Sorted Scores: ");
for (double x : scores) {
//System.out.print(x + " ");
}
//System.out.println("");
// Calculate median (middle number)
double median = 0;
double pos1 = Math.floor((scores.length - 1.0) / 2.0);
double pos2 = Math.ceil((scores.length - 1.0) / 2.0);
if (pos1 == pos2 ) {
median = scores[(int)pos1];
} else {
median = (scores[(int)pos1] + scores[(int)pos2]) / 2.0 ;
}
return median;
}
private static double median2(Set<Double> set) {
Double[] numArray = set.toArray(new Double[set.size()]);
Arrays.sort(numArray);
Arrays.sort(numArray);
int middle = numArray.length/2;
double medianValue = 0; //declare variable
if (numArray.length%2 == 1) {
medianValue = numArray[middle];
} else {
medianValue = (numArray[middle-1] + numArray[middle]) / 2;
}
return medianValue;
}
@Deprecated
public static String getWantedCategory(Map<String, Map<String, Object>> maps, String type) throws Exception {
List<String> wantedList = new ArrayList<>();
wantedList.add(Constants.PRICE);
wantedList.add(Constants.INDEX);
//wantedList.add("cy");
String cat = null;
for (String wanted : wantedList) {
Map<String, Object> map = maps.get(wanted);
if (map != null) {
if (map.containsKey(type)) {
LinkedHashMap<String, Object> tmpMap = (LinkedHashMap<String, Object>) map.get(type);
if (tmpMap.get(PipelineConstants.RESULT) != null) {
return wanted;
}
}
}
}
return cat;
}
public static String getWantedCategory2(Map<String, Map<String, Object>> maps, String type) throws Exception {
System.out.println(maps.keySet());
List<String> wantedList = new ArrayList<>();
wantedList.add(Constants.PRICE);
wantedList.add(Constants.INDEX);
//wantedList.add("cy");
String cat = null;
for (String wanted : wantedList) {
Map<String, Object> map = maps.get(wanted + " " + type.toUpperCase());
if (map != null) {
return wanted;
}
}
for (String key : maps.keySet()) {
if (key.endsWith(" " + type.toUpperCase())) {
return key.substring(0, key.length() - 1 - type.length());
}
}
return cat;
}
public static IclijServiceResult getConfig() throws Exception {
IclijXMLConfig conf = IclijXMLConfig.instance();
IclijConfig instance = IclijXMLConfig.getConfigInstance();
IclijServiceResult result = new IclijServiceResult();
result.setIclijConfig(instance);
return result;
}
public static IclijServiceResult getContent(ComponentInput componentInput) throws Exception {
IclijServiceResult result = new IclijServiceResult();
LocalDate date = componentInput.getEnddate();
IclijXMLConfig i = new IclijXMLConfig();
IclijXMLConfig conf = IclijXMLConfig.instance();
IclijConfig instance = IclijXMLConfig.getConfigInstance();
List<IncDecItem> listAll = IncDecItem.getAll();
List<IclijServiceList> lists = new ArrayList<>();
lists.add(getHeader("Content"));
Map<String, Object> trendMap = new HashMap<>();
List<Market> markets = conf.getMarkets(instance);
for (Market market : markets) {
ComponentData param = null;
try {
param = ServiceUtil.getParam(componentInput, 0);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
param.setAction(IclijConstants.FINDPROFIT);
ControlService srv = new ControlService();
//srv.getConfig();
param.setService(srv);
//param.setOffset(0);
srv.conf.setMarket(market.getConfig().getMarket());
// the market may be incomplete, the exception and skip
try {
Short mystartoffset = market.getConfig().getStartoffset();
short startoffset = mystartoffset != null ? mystartoffset : 0;
Trend trend = new FindProfitAction().getTrend(instance.verificationDays(), date, param.getService(), startoffset);
trendMap.put(market.getConfig().getMarket(), trend);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
}
List<IncDecItem> currentIncDecs = getCurrentIncDecs(date, listAll, market, market.getConfig().getFindtime());
List<IncDecItem> listInc = currentIncDecs.stream().filter(m -> m.isIncrease()).collect(Collectors.toList());
List<IncDecItem> listDec = currentIncDecs.stream().filter(m -> !m.isIncrease()).collect(Collectors.toList());
List<IncDecItem> listIncDec = moveAndGetCommon(listInc, listDec);
List<IclijServiceList> subLists = getServiceList(market.getConfig().getMarket(), listInc, listDec, listIncDec);
lists.addAll(subLists);
}
List<TimingItem> listAllTimings = TimingItem.getAll();
for (Market market : markets) {
List<TimingItem> currentTimings = getCurrentTimings(date, listAllTimings, market, IclijConstants.FINDPROFIT, market.getConfig().getFindtime());
List<IclijServiceList> subLists = getServiceList(market.getConfig().getMarket(), currentTimings);
lists.addAll(subLists);
}
result.setLists(lists);
ComponentData param = null;
try {
param = getParam(componentInput, 0);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
return result;
}
Map<String, Map<String, Object>> updateMarketMap = new HashMap<>();
Map<String, Object> updateMap = new HashMap<>();
FindProfitAction findProfitAction = new FindProfitAction();
//Market market = findProfitAction.findMarket(param);
//String marketName = market.getConfig().getMarket();
List<String> componentList = getFindProfitComponents(componentInput.getConfig());
for (Market market : findProfitAction.getMarkets()) {
updateMarketMap.put(market.getConfig().getMarket(), new HashMap<>());
Map<String, Component> componentMap = findProfitAction.getComponentMap(componentList, null);
for (Component component : componentMap.values()) {
Map<String, Object> anUpdateMap = loadConfig(param, market, market.getConfig().getMarket(), IclijConstants.FINDPROFIT, component.getPipeline(), false, null);
updateMarketMap.get(market.getConfig().getMarket()).putAll(anUpdateMap);
updateMap.putAll(anUpdateMap);
}
}
Map<String, Map<String, Object>> mapmaps = new HashMap<>();
mapmaps.put("ml", updateMap);
result.setMaps(mapmaps);
for (Market market : findProfitAction.getMarkets()) {
//for (Entry<String, Map<String, Object>> entry : updateMarketMap.entrySet()) {
String marketName = market.getConfig().getMarket();
Map<String, Object> anUpdateMap = updateMarketMap.get(marketName);
IclijServiceList updates = convert(marketName, anUpdateMap);
lists.add(updates);
List<MemoryItem> marketMemory = findProfitAction.getMarketMemory(market.getConfig().getMarket());
List<MemoryItem> currentList = findProfitAction.filterKeepRecent(marketMemory, componentInput.getEnddate(), market.getConfig().getFindtime());
IclijServiceList memories = new IclijServiceList();
memories.setTitle("Memories " + marketName);
memories.setList(currentList);
lists.add(memories);
}
IclijServiceList trends = convert(trendMap);
lists.add(trends);
addRelations(componentInput, lists, new ArrayList<>());
print(result);
return result;
}
private static void addRelations(ComponentInput componentInput, List<IclijServiceList> lists, List<IncDecItem> listIncDecs) throws Exception {
List[] objects = new RelationUtil().method(componentInput, listIncDecs);
IclijServiceList incdecs = new IclijServiceList();
incdecs.setTitle("Incdecs with relations");
incdecs.setList(objects[0]);
IclijServiceList relations = new IclijServiceList();
relations.setTitle("Relations");
relations.setList(objects[1]);
lists.add(incdecs);
lists.add(relations);
}
public static IclijServiceResult getContentImprove(ComponentInput componentInput) throws Exception {
LocalDate date = componentInput.getEnddate();
IclijXMLConfig i = new IclijXMLConfig();
IclijXMLConfig conf = IclijXMLConfig.instance();
IclijConfig instance = IclijXMLConfig.getConfigInstance();
List<IncDecItem> listAll = IncDecItem.getAll();
List<IclijServiceList> lists = new ArrayList<>();
lists.add(getHeader("Content"));
List<Market> markets = conf.getMarkets(instance);
/*
for (Market market : markets) {
List<IncDecItem> currentIncDecs = getCurrentIncDecs(date, listAll, market);
List<IncDecItem> listInc = currentIncDecs.stream().filter(m -> m.isIncrease()).collect(Collectors.toList());
List<IncDecItem> listDec = currentIncDecs.stream().filter(m -> !m.isIncrease()).collect(Collectors.toList());
List<IncDecItem> listIncDec = moveAndGetCommon(listInc, listDec);
List<IclijServiceList> subLists = getServiceList(market.getConfig().getMarket(), listInc, listDec, listIncDec);
lists.addAll(subLists);
}
*/
List<TimingItem> listAllTimings = TimingItem.getAll();
for (Market market : markets) {
List<TimingItem> currentTimings = getCurrentTimings(date, listAllTimings, market, IclijConstants.IMPROVEPROFIT, market.getConfig().getImprovetime());
List<IclijServiceList> subLists = getServiceList(market.getConfig().getMarket(), currentTimings);
lists.addAll(subLists);
}
IclijServiceResult result = new IclijServiceResult();
result.setLists(lists);
ComponentData param = null;
try {
param = getParam(componentInput, 0);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
return result;
}
Map<String, Map<String, Object>> updateMarketMap = new HashMap<>();
Map<String, Object> updateMap = new HashMap<>();
FindProfitAction findProfitAction = new FindProfitAction();
//Market market = findProfitAction.findMarket(param);
//String marketName = market.getConfig().getMarket();
List<String> componentList = getFindProfitComponents(componentInput.getConfig());
for (Market market : findProfitAction.getMarkets()) {
updateMarketMap.put(market.getConfig().getMarket(), new HashMap<>());
updateMarketMap.put(market.getConfig().getMarket() + " sell", new HashMap<>());
Map<String, Component> componentMap = findProfitAction.getComponentMap(componentList, null);
for (Component component : componentMap.values()) {
Map<String, Object> anUpdateMap = loadConfig(param, market, market.getConfig().getMarket(), IclijConstants.IMPROVEPROFIT, component.getPipeline(), false, true);
updateMarketMap.get(market.getConfig().getMarket()).putAll(anUpdateMap);
updateMap.putAll(anUpdateMap);
Map<String, Object> anUpdateMap2 = loadConfig(param, market, market.getConfig().getMarket(), IclijConstants.IMPROVEPROFIT, component.getPipeline(), false, false);
updateMarketMap.get(market.getConfig().getMarket() + " sell").putAll(anUpdateMap2);
}
}
Map<String, Map<String, Object>> mapmaps = new HashMap<>();
mapmaps.put("ml", updateMap);
result.setMaps(mapmaps);
for (Market market : findProfitAction.getMarkets()) {
//for (Entry<String, Map<String, Object>> entry : updateMarketMap.entrySet()) {
String marketName = market.getConfig().getMarket();
Map<String, Object> anUpdateMap = updateMarketMap.get(marketName);
IclijServiceList updates = convert(marketName, anUpdateMap);
lists.add(updates);
Map<String, Object> anUpdateMap2 = updateMarketMap.get(marketName + " sell");
IclijServiceList updates2 = convert(marketName + " sell", anUpdateMap2);
lists.add(updates2);
List<MemoryItem> marketMemory = findProfitAction.getMarketMemory(market.getConfig().getMarket());
List<MemoryItem> currentList = findProfitAction.filterKeepRecent(marketMemory, componentInput.getEnddate(), market.getConfig().getImprovetime());
IclijServiceList memories = new IclijServiceList();
memories.setTitle("Memories " + marketName);
memories.setList(currentList);
lists.add(memories);
}
print(result);
return result;
}
public static List<TimingItem> getCurrentTimings(LocalDate date, List<TimingItem> listAll, Market market, String action, int days) {
if (date == null) {
date = LocalDate.now();
}
LocalDate newdate = date;
LocalDate olddate = date.minusDays(days);
List<TimingItem> filterListAll = listAll.stream().filter(m -> m.getDate() != null).collect(Collectors.toList());
filterListAll = filterListAll.stream().filter(m -> action.equals(m.getAction())).collect(Collectors.toList());
List<TimingItem> currentIncDecs = filterListAll.stream().filter(m -> olddate.compareTo(m.getDate()) <= 0).collect(Collectors.toList());
currentIncDecs = currentIncDecs.stream().filter(m -> newdate.compareTo(m.getDate()) >= 0).collect(Collectors.toList());
currentIncDecs = currentIncDecs.stream().filter(m -> market.getConfig().getMarket().equals(m.getMarket())).collect(Collectors.toList());
return currentIncDecs;
}
public static List<IncDecItem> getCurrentIncDecs(LocalDate date, List<IncDecItem> listAll, Market market, int days) {
if (date == null) {
date = LocalDate.now();
}
LocalDate newdate = date;
LocalDate olddate = date.minusDays(days);
List<IncDecItem> filterListAll = listAll.stream().filter(m -> m.getDate() != null).collect(Collectors.toList());
List<IncDecItem> currentIncDecs = filterListAll.stream().filter(m -> olddate.compareTo(m.getDate()) <= 0).collect(Collectors.toList());
currentIncDecs = currentIncDecs.stream().filter(m -> newdate.compareTo(m.getDate()) >= 0).collect(Collectors.toList());
currentIncDecs = currentIncDecs.stream().filter(m -> market.getConfig().getMarket().equals(m.getMarket())).collect(Collectors.toList());
return currentIncDecs;
}
static IclijServiceList getHeader(String title) {
IclijServiceList header = new IclijServiceList();
header.setTitle(title);
return header;
}
private static List<IclijServiceList> getServiceList(String market, List<TimingItem> listIncDec) {
List<IclijServiceList> subLists = new ArrayList<>();
if (!listIncDec.isEmpty()) {
IclijServiceList incDec = new IclijServiceList();
incDec.setTitle(market + " " + "timing");
incDec.setList(listIncDec);
subLists.add(incDec);
}
return subLists;
}
static List<IclijServiceList> getServiceList(String market, List<IncDecItem> listInc, List<IncDecItem> listDec,
List<IncDecItem> listIncDec) {
List<IclijServiceList> subLists = new ArrayList<>();
if (!listInc.isEmpty()) {
List<Boolean> listIncBoolean = listInc.stream().map(IncDecItem::getVerified).filter(Objects::nonNull).collect(Collectors.toList());
long count = listIncBoolean.stream().filter(i -> i).count();
IclijServiceList inc = new IclijServiceList();
String trendStr = "";
inc.setTitle(market + " " + "Increase ( verified " + count + " / " + listIncBoolean.size() + " )" + trendStr);
inc.setList(listInc);
subLists.add(inc);
}
if (!listDec.isEmpty()) {
List<Boolean> listDecBoolean = listDec.stream().map(IncDecItem::getVerified).filter(Objects::nonNull).collect(Collectors.toList());
long count = listDecBoolean.stream().filter(i -> i).count();
IclijServiceList dec = new IclijServiceList();
dec.setTitle(market + " " + "Decrease ( verified " + count + " / " + listDecBoolean.size() + " )");
dec.setList(listDec);
subLists.add(dec);
}
if (!listIncDec.isEmpty()) {
IclijServiceList incDec = new IclijServiceList();
incDec.setTitle(market + " " + "Increase and decrease");
incDec.setList(listIncDec);
subLists.add(incDec);
}
return subLists;
}
public static List<IncDecItem> moveAndGetCommon(List<IncDecItem> listInc, List<IncDecItem> listDec) {
// and a new list for common items
//List<String> incIds = listInc.stream().map(IncDecItem::getId).collect(Collectors.toList());
//List<String> decIds = listDec.stream().map(IncDecItem::getId).collect(Collectors.toList());
//List<IncDecItem> listIncDec = listInc.stream().filter(m -> decIds.contains(m.getId())).collect(Collectors.toList());
//List<IncDecItem> listDecInc = listDec.stream().filter(m -> incIds.contains(m.getId())).collect(Collectors.toList());
List<IncDecItem> common = new ArrayList<>(listInc);
common.retainAll(listDec);
listInc.removeAll(common);
listDec.removeAll(common);
//listIncDec.addAll(listDecInc);
return common;
}
public static IclijServiceResult getVerify(ComponentInput componentInput) throws Exception {
String type = "Verify";
componentInput.setDoSave(componentInput.getConfig().wantVerificationSave());
int verificationdays = componentInput.getConfig().verificationDays();
IclijServiceResult result = getFindProfitVerify(componentInput, type, verificationdays);
print(result);
return result;
}
private static IclijServiceResult getFindProfitVerify(ComponentInput componentInput, String type, int verificationdays) throws Exception {
IclijServiceResult result = new IclijServiceResult();
result.setLists(new ArrayList<>());
List<IclijServiceList> retLists = result.getLists();
ComponentData param = null;
try {
param = getParam(componentInput, verificationdays);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
return result;
}
FindProfitAction findProfitAction = new FindProfitAction();
// this calculates, does not read from db
List<MemoryItem> allMemoryItems = new ArrayList<>();
//ProfitData picks = findProfitAction.getPicks(param, allMemoryItems);
//getMemoryItems(componentInput.getConfig(), param, verificationdays, getFindProfitComponents(componentInput.getConfig()));
IclijServiceList memories = new IclijServiceList();
memories.setTitle("Memories");
memories.setList(allMemoryItems);
Map<String, Object> updateMap = new HashMap<>();
//param.setUpdateMap(updateMap);
Market market = findProfitAction.findMarket(param);
boolean evolve = getEvolve(verificationdays, param);
WebData myData = findProfitAction.getMarket(null, param, market, evolve);
ProfitData buysells = myData.profitData; // findProfitAction.getPicks(param, allMemoryItems);
updateMap = myData.updateMap;
allMemoryItems.addAll(myData.memoryItems);
List<IncDecItem> listInc = new ArrayList<>(buysells.getBuys().values());
List<IncDecItem> listDec = new ArrayList<>(buysells.getSells().values());
List<IncDecItem> listIncDec = moveAndGetCommon(listInc, listDec);
Map<String, Object> trendMap = new HashMap<>();
Short mystartoffset = market.getConfig().getStartoffset();
short startoffset = mystartoffset != null ? mystartoffset : 0;
Trend trend = findProfitAction.getTrend(param.getInput().getConfig().verificationDays(), param.getInput().getEnddate(), param.getService(), startoffset);
trendMap.put(market.getConfig().getMarket(), trend);
if (verificationdays > 0) {
try {
param.setFuturedays(0);
param.setOffset(0);
param.setDates(0, 0, TimeUtil.convertDate2(param.getInput().getEnddate()));
} catch (ParseException e) {
log.error(Constants.EXCEPTION, e);
}
findProfitAction.getVerifyProfit(verificationdays, param.getFutureDate(), param.getService(), param.getBaseDate(), listInc, listDec, startoffset);
/*
List<MapList> inc = new ArrayList<>();
List<MapList> dec = new ArrayList<>();
IclijServiceList incMap = new IclijServiceList();
incMap.setTitle("Increase verify");
incMap.setList(inc);
IclijServiceList decMap = new IclijServiceList();
decMap.setTitle("Decrease verify");
decMap.setList(dec);
retLists.add(incMap);
retLists.add(decMap);
*/
}
addHeader(componentInput, type, result, param);
List<IclijServiceList> subLists = getServiceList(param.getMarket(), listInc, listDec, listIncDec);
retLists.addAll(subLists);
retLists.add(memories);
{
List<TimingItem> currentTimings = (List<TimingItem>) myData.timingMap.get(market.getConfig().getMarket());
List<IclijServiceList> subLists2 = getServiceList(market.getConfig().getMarket(), currentTimings);
retLists.addAll(subLists2);
}
Map<String, Map<String, Object>> mapmaps = new HashMap<>();
mapmaps.put("ml", updateMap);
result.setMaps(mapmaps);
IclijServiceList updates = convert(market.getConfig().getMarket(), updateMap);
retLists.add(updates);
IclijServiceList trends = convert(trendMap);
retLists.add(trends);
List<IncDecItem> listIncDecs = new ArrayList<>(buysells.getBuys().values());
listIncDecs.addAll(buysells.getSells().values());
addRelations(componentInput, retLists, listIncDecs);
return result;
}
public static boolean getEvolve(int verificationdays, ComponentData param) {
Boolean evolvefirst;
if (verificationdays > 0) {
evolvefirst = param.getInput().getConfig().verificationEvolveFirstOnly();
} else {
evolvefirst = param.getInput().getConfig().singlemarketEvolveFirstOnly();
}
boolean evolve = true;
if (evolvefirst && param.getInput().getLoopoffset() > 0) {
evolve = false;
}
return evolve;
}
private static void addHeader(ComponentInput componentInput, String type, IclijServiceResult result,
ComponentData param) {
IclijServiceList header = new IclijServiceList();
result.getLists().add(header);
header.setTitle(type + " " + "Market: " + componentInput.getConfig().getMarket() + " Date: " + componentInput.getConfig().getDate() + " Offset: " + componentInput.getLoopoffset());
List<MapList> aList = new ArrayList<>();
header.setList(aList);
MapList mapList = new MapList();
mapList.setKey("Dates");
mapList.setValue("Base " + param.getBaseDate() + " Future " + param.getFutureDate());
aList.add(mapList);
}
public static ComponentData getParam(ComponentInput input, int days) throws Exception {
ComponentData param = new ComponentData(input);
param.setAction(IclijConstants.FINDPROFIT);
String market = input.getConfig().getMarket();
/*
if (market == null) {
throw new Exception("Market null");
}
*/
//LocalDate date = input.getConfig().getDate();
ControlService srv = new ControlService();
param.setService(srv);
if (market != null) {
srv.conf.setMarket(market);
param.getInput().setMarket(market);
}
// verification days, 0 or something
param.setOffset(days);
//srv.getConfig();
/*
List<String> stockdates = srv.getDates(market);
if (date == null) {
date = TimeUtil.convertDate(stockdates.get(stockdates.size() - 1));
}
if (input.getLoopoffset() != null) {
int index = getDateIndex(date, stockdates);
index = index - input.getLoopoffset();
if (index <= 0) {
throw new Exception("Index <= 0");
}
date = getDateIndex(stockdates, index);
}
int dateoffset = getDateOffset(date, stockdates);
if (date == null) {
date = getLastDate(stockdates);
}
log.info("Stock size {} ", stockdates.size());
log.info("Main date {} ", date);
String baseDateStr = stockdates.get(stockdates.size() - 1 - dateoffset - days);
LocalDate baseDate = TimeUtil.convertDate(baseDateStr);
log.info("Old date {} ", baseDate);
param.setBaseDate(baseDate);
param.setFutureDate(date);
param.setOffset(dateoffset);
*/
//param.setDates(days, input.getLoopoffset(), TimeUtil.convertDate2(input.getEnddate()));
return param;
}
/*
if (config.wantsImproveProfit()) {
ImproveProfitAction improveProfitAction = new ImproveProfitAction();
getImprovements(retLists, market, date, save, improveProfitAction, allMemoryItems);
}
*/
private static void print(IclijServiceResult result) {
Path path = Paths.get("" + System.currentTimeMillis() + ".txt");
BufferedWriter writer = null;
try {
writer = Files.newBufferedWriter(path);
} catch (IOException e) {
log.error(Constants.EXCEPTION, e);
}
for (IclijServiceList item : result.getLists()) {
listWriter(writer, item, item.getList());
}
try {
writer.flush();
writer.close();
} catch (IOException e) {
log.error(Constants.EXCEPTION, e);
}
}
private static void listWriter(BufferedWriter writer, IclijServiceList item, List mylist) {
try {
writer.write(item.getTitle());
writer.write("\n");
if (mylist == null) {
return;
}
for (Object object : mylist) {
writer.write(object.toString());
}
writer.write("\n");
} catch (IOException e) {
log.error(Constants.EXCEPTION, e);
}
}
private static IclijServiceList convert(String marketName, Map<String, Object> updateMap) {
IclijServiceList list = new IclijServiceList();
list.setTitle("Updates for " + marketName);
List<MapList> aList = new ArrayList<>();
for (Entry<String, Object> map : updateMap.entrySet()) {
MapList m = new MapList();
m.setKey(map.getKey());
m.setValue((String) map.getValue().toString());
aList.add(m);
}
list.setList(aList);
return list;
}
private static IclijServiceList convert(Map<String, Object> map) {
IclijServiceList list = new IclijServiceList();
list.setTitle("Trends");
List<MapList> aList = new ArrayList<>();
for (Entry<String, Object> entry : map.entrySet()) {
MapList m = new MapList();
m.setKey(entry.getKey());
m.setValue(entry.getValue().toString());
aList.add(m);
}
list.setList(aList);
return list;
}
private static LocalDate getDateIndex(List<String> stocks, int index) throws ParseException {
String newDate = stocks.get(index);
return TimeUtil.convertDate(newDate);
}
/*
@Deprecated
private static void getImprovements(List<IclijServiceList> retLists, ComponentData param,
ImproveProfitAction improveProfitAction, List<MemoryItem> allMemoryItems) throws Exception {
Map<String, String> map = improveProfitAction.getMarket(param, allMemoryItems);
List<MapList> mapList = improveProfitAction.getList(map);
IclijServiceList resultMap = new IclijServiceList();
resultMap.setTitle("Improve Profit Info");
resultMap.setList(mapList);
retLists.add(resultMap);
}
*/
public static IclijServiceResult getFindProfit(ComponentInput componentInput) throws Exception {
String type = "FindProfit";
int days = 0; // config.verificationDays();
IclijServiceResult result = getFindProfitVerify(componentInput, type, days);
print(result);
return result;
}
public static List<String> getFindProfitComponents(IclijConfig config) {
List<String> components = new ArrayList<>();
if (config.wantsFindProfitRecommender()) {
components.add(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
}
if (config.wantsFindProfitPredictor()) {
components.add(PipelineConstants.PREDICTORSLSTM);
}
if (config.wantsFindProfitMLMACD()) {
components.add(PipelineConstants.MLMACD);
}
if (config.wantsFindProfitMLRSI()) {
components.add(PipelineConstants.MLRSI);
}
if (config.wantsFindProfitMLIndicator()) {
components.add(PipelineConstants.MLINDICATOR);
}
return components;
}
public static IclijServiceResult getImproveProfit(ComponentInput componentInput) throws Exception {
try {
int loopOffset = 0;
int days = 0; // config.verificationDays();
IclijServiceResult result = new IclijServiceResult();
result.setLists(new ArrayList<>());
List<IclijServiceList> retLists = result.getLists();
ComponentData param = null;
try {
param = getParam(componentInput, days);
} catch (Exception e) {
log.error(Constants.EXCEPTION, e);
return result;
}
param.getInput().setDoSave(false);
//FindProfitAction findProfitAction = new FindProfitAction();
ImproveProfitAction improveProfitAction = new ImproveProfitAction();
List<MemoryItem> allMemoryItems = new ArrayList<>(); // getMemoryItems(componentInput.getConfig(), param, days, getImproveProfitComponents(componentInput.getConfig()));
//IclijServiceList memories = new IclijServiceList();
//memories.setTitle("Memories");
//memories.setList(allMemoryItems);
Map<String, Object> updateMap = new HashMap<>();
Market market = improveProfitAction.findMarket(param);
WebData webData = improveProfitAction.getMarket(null, param, market);
List<MapList> mapList = improveProfitAction.getList(webData.updateMap);
IclijServiceList resultMap = new IclijServiceList();
resultMap.setTitle("Improve Profit Info");
resultMap.setList(mapList);
retLists.add(resultMap);
//retLists.add(memories);
List<IclijServiceList> lists = new ArrayList<>();
Map<String, Object> timingMap = webData.timingMap;
for (Entry<String, Object> entry : timingMap.entrySet()) {
String marketName = entry.getKey();
List<TimingItem> list = (List<TimingItem>) entry.getValue();
List<IclijServiceList> subLists = getServiceList(marketName, list);
lists.addAll(subLists);
}
Map<String, Object> timingMap2 = webData.timingMap2;
for (Entry<String, Object> entry : timingMap2.entrySet()) {
String marketName = entry.getKey();
List<TimingItem> list = (List<TimingItem>) entry.getValue();
List<IclijServiceList> subLists = getServiceList(marketName + " sell", list);
lists.addAll(subLists);
}
result.setLists(lists);
updateMap = webData.updateMap;
Map<String, Map<String, Object>> mapmaps = new HashMap<>();
mapmaps.put("ml", updateMap);
result.setMaps(mapmaps);
IclijServiceList updates = convert(null, updateMap);
lists.add(updates);
updateMap = webData.updateMap2;
updates = convert(null, updateMap);
lists.add(updates);
return result;
} catch (Exception e) {
log.error("Ex", e);
}
return null;
}
public static List<String> getImproveProfitComponents(IclijConfig config) {
List<String> components = new ArrayList<>();
if (config.wantsImproveProfitRecommender()) {
components.add(PipelineConstants.AGGREGATORRECOMMENDERINDICATOR);
}
if (config.wantsImproveProfitPredictor()) {
components.add(PipelineConstants.PREDICTORSLSTM);
}
if (config.wantsImproveProfitMLMACD()) {
components.add(PipelineConstants.MLMACD);
}
if (config.wantsImproveProfitMLRSI()) {
components.add(PipelineConstants.MLRSI);
}
if (config.wantsImproveProfitMLIndicator()) {
components.add(PipelineConstants.MLINDICATOR);
}
return components;
}
private static LocalDate getLastDate(List<String> stocks) throws ParseException {
String aDate = stocks.get(stocks.size() - 1);
return TimeUtil.convertDate(aDate);
}
private static int getDateIndex(LocalDate date, List<String> stocks) {
int index;
if (date == null) {
index = stocks.size() - 1;
} else {
String aDate = TimeUtil.convertDate2(date);
index = stocks.indexOf(aDate);
}
return index;
}
private static int getDateOffset(LocalDate date, List<String> stocks) {
int offset = 0;
if (date != null) {
String aDate = TimeUtil.convertDate2(date);
int index = stocks.indexOf(aDate);
if (index >= 0) {
offset = stocks.size() - 1 - index;
}
}
return offset;
}
public static List<MemoryItem> getMemoryItems(IclijConfig config, ComponentData param, int days, List<String> components) throws InterruptedException {
List<MemoryItem> allMemoryItems = new ArrayList<>();
UpdateDBAction updateDbAction = new UpdateDBAction();
Queue<Action> serviceActions = updateDbAction.findAllMarketComponentsToCheck(param, days, config, components);
for (Action serviceAction : serviceActions) {
serviceAction.goal(null, param);
Map<String, Object> resultMap = serviceAction.getLocalResultMap();
List<MemoryItem> memoryItems = (List<MemoryItem>) resultMap.get(IclijPipelineConstants.MEMORY);
if (memoryItems != null) {
allMemoryItems.addAll(memoryItems);
} else {
log.error("Memory null");
}
}
return allMemoryItems;
}
public static Map<String, Object> loadConfig(ComponentData param, Market market, String marketName, String action, String component, boolean evolve, Boolean buy) throws Exception {
LocalDate date = param.getInput().getEnddate();
LocalDate olddate = date.minusDays(market.getFilter().getRecordage());
List<ConfigItem> filterConfigs = new ArrayList<>();
List<ConfigItem> configs = ConfigItem.getAll();
List<ConfigItem> currentConfigs = configs.stream().filter(m -> olddate.compareTo(m.getDate()) <= 0).collect(Collectors.toList());
currentConfigs = currentConfigs.stream().filter(m -> date.compareTo(m.getDate()) >= 0).collect(Collectors.toList());
for (ConfigItem config : currentConfigs) {
if (marketName.equals(config.getMarket()) && action.equals(config.getAction()) && component.equals(config.getComponent())) {
if (buy != null && config.getBuy() != null && buy != config.getBuy()) {
continue;
}
filterConfigs.add(config);
}
}
Collections.sort(filterConfigs, (o1, o2) -> (o2.getDate().compareTo(o1.getDate())));
Map<String, Class> type = param.getService().conf.getType();
Map<String, Object> updateMap = new HashMap<>();
for (ConfigItem config : filterConfigs) {
Object value = config.getValue();
String string = config.getValue();
Class myclass = type.get(config.getId());
if (myclass == null) {
log.error("No class for {}", config.getId());
myclass = String.class;
}
log.info("Trying {} {}", config.getId(), myclass.getName());
switch (myclass.getName()) {
case "java.lang.String":
break;
case "java.lang.Integer":
value = Integer.valueOf(string);
break;
case "java.lang.Double":
value = Double.valueOf(string);
break;
case "java.lang.Boolean":
value = Boolean.valueOf(string);
break;
default:
log.info("unknown {}", myclass.getName());
}
updateMap.put(config.getId(), value);
}
return updateMap;
}
}
|
package org.zstack.image;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.Platform;
import org.zstack.core.cloudbus.*;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.config.GlobalConfig;
import org.zstack.core.config.GlobalConfigUpdateExtensionPoint;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.defer.Defer;
import org.zstack.core.defer.Deferred;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.CancelablePeriodicTask;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.AbstractService;
import org.zstack.header.apimediator.ApiMessageInterceptionException;
import org.zstack.header.core.AsyncLatch;
import org.zstack.header.core.NoErrorCompletion;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.ErrorCodeList;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.identity.*;
import org.zstack.header.image.*;
import org.zstack.header.image.APICreateRootVolumeTemplateFromVolumeSnapshotEvent.Failure;
import org.zstack.header.image.ImageConstant.ImageMediaType;
import org.zstack.header.image.ImageDeletionPolicyManager.ImageDeletionPolicy;
import org.zstack.header.managementnode.ManagementNodeReadyExtensionPoint;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.search.SearchOp;
import org.zstack.header.storage.backup.*;
import org.zstack.header.storage.primary.PrimaryStorageVO;
import org.zstack.header.storage.primary.PrimaryStorageVO_;
import org.zstack.header.storage.snapshot.*;
import org.zstack.header.vm.CreateTemplateFromVmRootVolumeMsg;
import org.zstack.header.vm.CreateTemplateFromVmRootVolumeReply;
import org.zstack.header.vm.VmInstanceConstant;
import org.zstack.header.volume.*;
import org.zstack.identity.AccountManager;
import org.zstack.search.SearchQuery;
import org.zstack.tag.TagManager;
import org.zstack.utils.CollectionUtils;
import org.zstack.utils.ObjectUtils;
import org.zstack.utils.RunOnce;
import org.zstack.utils.Utils;
import org.zstack.utils.data.SizeUnit;
import org.zstack.utils.function.ForEachFunction;
import org.zstack.utils.function.Function;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.zstack.utils.CollectionDSL.list;
public class ImageManagerImpl extends AbstractService implements ImageManager, ManagementNodeReadyExtensionPoint,
ReportQuotaExtensionPoint {
private static final CLogger logger = Utils.getLogger(ImageManagerImpl.class);
@Autowired
private CloudBus bus;
@Autowired
private PluginRegistry pluginRgty;
@Autowired
private DatabaseFacade dbf;
@Autowired
private AccountManager acntMgr;
@Autowired
private ErrorFacade errf;
@Autowired
private TagManager tagMgr;
@Autowired
private ThreadFacade thdf;
@Autowired
private ResourceDestinationMaker destMaker;
@Autowired
private ImageDeletionPolicyManager deletionPolicyMgr;
@Autowired
protected RESTFacade restf;
private Map<String, ImageFactory> imageFactories = Collections.synchronizedMap(new HashMap<String, ImageFactory>());
private static final Set<Class> allowedMessageAfterDeletion = new HashSet<Class>();
private Future<Void> expungeTask;
static {
allowedMessageAfterDeletion.add(ImageDeletionMsg.class);
}
@Override
@MessageSafe
public void handleMessage(Message msg) {
if (msg instanceof ImageMessage) {
passThrough((ImageMessage) msg);
} else if (msg instanceof APIMessage) {
handleApiMessage(msg);
} else {
handleLocalMessage(msg);
}
}
private void handleLocalMessage(Message msg) {
bus.dealWithUnknownMessage(msg);
}
private void handleApiMessage(Message msg) {
if (msg instanceof APIAddImageMsg) {
handle((APIAddImageMsg) msg);
} else if (msg instanceof APIListImageMsg) {
handle((APIListImageMsg) msg);
} else if (msg instanceof APISearchImageMsg) {
handle((APISearchImageMsg) msg);
} else if (msg instanceof APIGetImageMsg) {
handle((APIGetImageMsg) msg);
} else if (msg instanceof APICreateRootVolumeTemplateFromRootVolumeMsg) {
handle((APICreateRootVolumeTemplateFromRootVolumeMsg) msg);
} else if (msg instanceof APICreateRootVolumeTemplateFromVolumeSnapshotMsg) {
handle((APICreateRootVolumeTemplateFromVolumeSnapshotMsg) msg);
} else if (msg instanceof APICreateDataVolumeTemplateFromVolumeMsg) {
handle((APICreateDataVolumeTemplateFromVolumeMsg) msg);
} else {
bus.dealWithUnknownMessage(msg);
}
}
private void handle(final APICreateDataVolumeTemplateFromVolumeMsg msg) {
final APICreateDataVolumeTemplateFromVolumeEvent evt = new APICreateDataVolumeTemplateFromVolumeEvent(msg.getId());
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("create-data-volume-template-from-volume-%s", msg.getVolumeUuid()));
chain.then(new ShareFlow() {
List<BackupStorageInventory> backupStorage = new ArrayList<BackupStorageInventory>();
ImageVO image;
long actualSize;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-actual-size-of-data-volume";
@Override
public void run(final FlowTrigger trigger, Map data) {
SyncVolumeSizeMsg smsg = new SyncVolumeSizeMsg();
smsg.setVolumeUuid(msg.getVolumeUuid());
bus.makeTargetServiceIdByResourceUuid(smsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid());
bus.send(smsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
SyncVolumeSizeReply sr = reply.castReply();
actualSize = sr.getActualSize();
trigger.next();
}
});
}
});
flow(new Flow() {
String __name__ = "create-image-in-database";
@Override
public void run(FlowTrigger trigger, Map data) {
SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class);
q.select(VolumeVO_.format, VolumeVO_.size);
q.add(VolumeVO_.uuid, Op.EQ, msg.getVolumeUuid());
Tuple t = q.findTuple();
String format = t.get(0, String.class);
long size = t.get(1, Long.class);
final ImageVO vo = new ImageVO();
vo.setUuid(msg.getResourceUuid() == null ? Platform.getUuid() : msg.getResourceUuid());
vo.setName(msg.getName());
vo.setDescription(msg.getDescription());
vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE);
vo.setMediaType(ImageMediaType.DataVolumeTemplate);
vo.setSize(size);
vo.setActualSize(actualSize);
vo.setState(ImageState.Enabled);
vo.setStatus(ImageStatus.Creating);
vo.setFormat(format);
vo.setUrl(String.format("volume://%s", msg.getVolumeUuid()));
image = dbf.persistAndRefresh(vo);
acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class);
tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName());
trigger.next();
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (image != null) {
dbf.remove(image);
}
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = "select-backup-storage";
@Override
public void run(final FlowTrigger trigger, Map data) {
final String zoneUuid = new Callable<String>() {
@Override
@Transactional(readOnly = true)
public String call() {
String sql = "select ps.zoneUuid from PrimaryStorageVO ps, VolumeVO vol where vol.primaryStorageUuid = ps.uuid and vol.uuid = :volUuid";
TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
q.setParameter("volUuid", msg.getVolumeUuid());
return q.getSingleResult();
}
}.call();
if (msg.getBackupStorageUuids() == null) {
AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg();
amsg.setRequiredZoneUuid(zoneUuid);
amsg.setSize(actualSize);
bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID);
bus.send(amsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
backupStorage.add(((AllocateBackupStorageReply) reply).getInventory());
trigger.next();
} else {
trigger.fail(errf.stringToOperationError("cannot find proper backup storage", reply.getError()));
}
}
});
} else {
List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() {
@Override
public AllocateBackupStorageMsg call(String arg) {
AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg();
amsg.setRequiredZoneUuid(zoneUuid);
amsg.setSize(actualSize);
amsg.setBackupStorageUuid(arg);
bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID);
return amsg;
}
});
bus.send(amsgs, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
List<ErrorCode> errs = new ArrayList<ErrorCode>();
for (MessageReply r : replies) {
if (r.isSuccess()) {
backupStorage.add(((AllocateBackupStorageReply) r).getInventory());
} else {
errs.add(r.getError());
}
}
if (backupStorage.isEmpty()) {
trigger.fail(errf.stringToOperationError(String.format("failed to allocate all backup storage[uuid:%s], a list of error: %s",
msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))));
} else {
trigger.next();
}
}
});
}
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (!backupStorage.isEmpty()) {
List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(backupStorage, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() {
@Override
public ReturnBackupStorageMsg call(BackupStorageInventory arg) {
ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg();
rmsg.setBackupStorageUuid(arg.getUuid());
rmsg.setSize(actualSize);
bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID);
return rmsg;
}
});
bus.send(rmsgs, new CloudBusListCallBack() {
@Override
public void run(List<MessageReply> replies) {
for (MessageReply r : replies) {
BackupStorageInventory bs = backupStorage.get(replies.indexOf(r));
logger.warn(String.format("failed to return %s bytes to backup storage[uuid:%s]", acntMgr, bs.getUuid()));
}
}
});
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "create-data-volume-template-from-volume";
@Override
public void run(final FlowTrigger trigger, Map data) {
List<CreateDataVolumeTemplateFromDataVolumeMsg> cmsgs = CollectionUtils.transformToList(backupStorage, new Function<CreateDataVolumeTemplateFromDataVolumeMsg, BackupStorageInventory>() {
@Override
public CreateDataVolumeTemplateFromDataVolumeMsg call(BackupStorageInventory bs) {
CreateDataVolumeTemplateFromDataVolumeMsg cmsg = new CreateDataVolumeTemplateFromDataVolumeMsg();
cmsg.setVolumeUuid(msg.getVolumeUuid());
cmsg.setBackupStorageUuid(bs.getUuid());
cmsg.setImageUuid(image.getUuid());
bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid());
return cmsg;
}
});
bus.send(cmsgs, new CloudBusListCallBack(msg) {
@Override
public void run(List<MessageReply> replies) {
int fail = 0;
String mdsum = null;
ErrorCode err = null;
String format = null;
for (MessageReply r : replies) {
BackupStorageInventory bs = backupStorage.get(replies.indexOf(r));
if (!r.isSuccess()) {
logger.warn(String.format("failed to create data volume template from volume[uuid:%s] on backup storage[uuid:%s], %s",
msg.getVolumeUuid(), bs.getUuid(), r.getError()));
fail++;
err = r.getError();
continue;
}
CreateDataVolumeTemplateFromDataVolumeReply reply = r.castReply();
ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO();
ref.setBackupStorageUuid(bs.getUuid());
ref.setStatus(ImageStatus.Ready);
ref.setImageUuid(image.getUuid());
ref.setInstallPath(reply.getInstallPath());
dbf.persist(ref);
if (mdsum == null) {
mdsum = reply.getMd5sum();
}
if (reply.getFormat() != null) {
format = reply.getFormat();
}
}
int backupStorageNum = msg.getBackupStorageUuids() == null ? 1 : msg.getBackupStorageUuids().size();
if (fail == backupStorageNum) {
ErrorCode errCode = errf.instantiateErrorCode(SysErrors.OPERATION_ERROR,
String.format("failed to create data volume template from volume[uuid:%s] on all backup storage%s. See cause for one of errors",
msg.getVolumeUuid(), msg.getBackupStorageUuids()),
err
);
trigger.fail(errCode);
} else {
image = dbf.reload(image);
if (format != null) {
image.setFormat(format);
}
image.setMd5Sum(mdsum);
image.setStatus(ImageStatus.Ready);
image = dbf.updateAndRefresh(image);
trigger.next();
}
}
});
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
evt.setInventory(ImageInventory.valueOf(image));
bus.publish(evt);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
evt.setErrorCode(errCode);
bus.publish(evt);
}
});
}
}).start();
}
private void handle(final APICreateRootVolumeTemplateFromVolumeSnapshotMsg msg) {
final APICreateRootVolumeTemplateFromVolumeSnapshotEvent evt = new APICreateRootVolumeTemplateFromVolumeSnapshotEvent(msg.getId());
SimpleQuery<VolumeSnapshotVO> q = dbf.createQuery(VolumeSnapshotVO.class);
q.select(VolumeSnapshotVO_.format);
q.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid());
String format = q.findValue();
final ImageVO vo = new ImageVO();
if (msg.getResourceUuid() != null) {
vo.setUuid(msg.getResourceUuid());
} else {
vo.setUuid(Platform.getUuid());
}
vo.setName(msg.getName());
vo.setSystem(msg.isSystem());
vo.setDescription(msg.getDescription());
vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform()));
vo.setGuestOsType(vo.getGuestOsType());
vo.setStatus(ImageStatus.Creating);
vo.setState(ImageState.Enabled);
vo.setFormat(format);
vo.setMediaType(ImageMediaType.RootVolumeTemplate);
vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE);
vo.setUrl(String.format("volumeSnapshot://%s", msg.getSnapshotUuid()));
dbf.persist(vo);
acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class);
tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName());
SimpleQuery<VolumeSnapshotVO> sq = dbf.createQuery(VolumeSnapshotVO.class);
sq.select(VolumeSnapshotVO_.volumeUuid, VolumeSnapshotVO_.treeUuid);
sq.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid());
Tuple t = sq.findTuple();
String volumeUuid = t.get(0, String.class);
String treeUuid = t.get(1, String.class);
List<CreateTemplateFromVolumeSnapshotMsg> cmsgs = msg.getBackupStorageUuids().stream().map(bsUuid -> {
CreateTemplateFromVolumeSnapshotMsg cmsg = new CreateTemplateFromVolumeSnapshotMsg();
cmsg.setSnapshotUuid(msg.getSnapshotUuid());
cmsg.setImageUuid(vo.getUuid());
cmsg.setVolumeUuid(volumeUuid);
cmsg.setTreeUuid(treeUuid);
cmsg.setBackupStorageUuid(bsUuid);
String resourceUuid = volumeUuid != null ? volumeUuid : treeUuid;
bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeSnapshotConstant.SERVICE_ID, resourceUuid);
return cmsg;
}).collect(Collectors.toList());
List<Failure> failures = new ArrayList<>();
AsyncLatch latch = new AsyncLatch(cmsgs.size(), new NoErrorCompletion(msg) {
@Override
public void done() {
if (failures.size() == cmsgs.size()) {
// failed on all
ErrorCodeList error = errf.stringToOperationError(String.format("failed to create template from" +
" the volume snapshot[uuid:%s] on backup storage[uuids:%s]", msg.getSnapshotUuid(),
msg.getBackupStorageUuids()), failures.stream().map(f -> f.error).collect(Collectors.toList()));
evt.setErrorCode(error);
dbf.remove(vo);
} else {
ImageVO imvo = dbf.reload(vo);
evt.setInventory(ImageInventory.valueOf(imvo));
logger.debug(String.format("successfully created image[uuid:%s, name:%s] from volume snapshot[uuid:%s]",
imvo.getUuid(), imvo.getName(), msg.getSnapshotUuid()));
}
if (!failures.isEmpty()) {
evt.setFailuresOnBackupStorage(failures);
}
bus.publish(evt);
}
});
RunOnce once = new RunOnce();
for (CreateTemplateFromVolumeSnapshotMsg cmsg : cmsgs) {
bus.send(cmsg, new CloudBusCallBack(latch) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
synchronized (failures) {
Failure failure = new Failure();
failure.error = reply.getError();
failure.backupStorageUuid = cmsg.getBackupStorageUuid();
failures.add(failure);
}
} else {
CreateTemplateFromVolumeSnapshotReply cr = reply.castReply();
ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO();
ref.setBackupStorageUuid(cr.getBackupStorageUuid());
ref.setInstallPath(cr.getBackupStorageInstallPath());
ref.setStatus(ImageStatus.Ready);
ref.setImageUuid(vo.getUuid());
dbf.persist(ref);
once.run(() -> {
vo.setSize(cr.getSize());
vo.setActualSize(cr.getActualSize());
vo.setStatus(ImageStatus.Ready);
dbf.update(vo);
});
}
latch.ack();
}
});
}
}
private void passThrough(ImageMessage msg) {
ImageVO vo = dbf.findByUuid(msg.getImageUuid(), ImageVO.class);
if (vo == null && allowedMessageAfterDeletion.contains(msg.getClass())) {
ImageEO eo = dbf.findByUuid(msg.getImageUuid(), ImageEO.class);
vo = ObjectUtils.newAndCopy(eo, ImageVO.class);
}
if (vo == null) {
String err = String.format("Cannot find image[uuid:%s], it may have been deleted", msg.getImageUuid());
logger.warn(err);
bus.replyErrorByMessageType((Message) msg, errf.instantiateErrorCode(SysErrors.RESOURCE_NOT_FOUND, err));
return;
}
ImageFactory factory = getImageFacotry(ImageType.valueOf(vo.getType()));
Image img = factory.getImage(vo);
img.handleMessage((Message) msg);
}
private void handle(final APICreateRootVolumeTemplateFromRootVolumeMsg msg) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("create-template-from-root-volume-%s", msg.getRootVolumeUuid()));
chain.then(new ShareFlow() {
ImageVO imageVO;
VolumeInventory rootVolume;
Long imageActualSize;
List<BackupStorageInventory> targetBackupStorages = new ArrayList<BackupStorageInventory>();
String zoneUuid;
{
VolumeVO rootvo = dbf.findByUuid(msg.getRootVolumeUuid(), VolumeVO.class);
rootVolume = VolumeInventory.valueOf(rootvo);
SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class);
q.select(PrimaryStorageVO_.zoneUuid);
q.add(PrimaryStorageVO_.uuid, Op.EQ, rootVolume.getPrimaryStorageUuid());
zoneUuid = q.findValue();
}
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-volume-actual-size";
@Override
public void run(final FlowTrigger trigger, Map data) {
SyncVolumeSizeMsg msg = new SyncVolumeSizeMsg();
msg.setVolumeUuid(rootVolume.getUuid());
bus.makeTargetServiceIdByResourceUuid(msg, VolumeConstant.SERVICE_ID, rootVolume.getPrimaryStorageUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
SyncVolumeSizeReply sr = reply.castReply();
imageActualSize = sr.getActualSize();
trigger.next();
}
});
}
});
flow(new Flow() {
String __name__ = "create-image-in-database";
public void run(FlowTrigger trigger, Map data) {
SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class);
q.add(VolumeVO_.uuid, Op.EQ, msg.getRootVolumeUuid());
final VolumeVO volvo = q.find();
String accountUuid = acntMgr.getOwnerAccountUuidOfResource(volvo.getUuid());
final ImageVO imvo = new ImageVO();
if (msg.getResourceUuid() != null) {
imvo.setUuid(msg.getResourceUuid());
} else {
imvo.setUuid(Platform.getUuid());
}
imvo.setDescription(msg.getDescription());
imvo.setMediaType(ImageMediaType.RootVolumeTemplate);
imvo.setState(ImageState.Enabled);
imvo.setGuestOsType(msg.getGuestOsType());
imvo.setFormat(volvo.getFormat());
imvo.setName(msg.getName());
imvo.setSystem(msg.isSystem());
imvo.setPlatform(ImagePlatform.valueOf(msg.getPlatform()));
imvo.setStatus(ImageStatus.Downloading);
imvo.setType(ImageConstant.ZSTACK_IMAGE_TYPE);
imvo.setUrl(String.format("volume://%s", msg.getRootVolumeUuid()));
imvo.setSize(volvo.getSize());
imvo.setActualSize(imageActualSize);
dbf.persist(imvo);
acntMgr.createAccountResourceRef(accountUuid, imvo.getUuid(), ImageVO.class);
tagMgr.createTagsFromAPICreateMessage(msg, imvo.getUuid(), ImageVO.class.getSimpleName());
imageVO = imvo;
trigger.next();
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (imageVO != null) {
dbf.remove(imageVO);
}
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = String.format("select-backup-storage");
@Override
public void run(final FlowTrigger trigger, Map data) {
if (msg.getBackupStorageUuids() == null) {
AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg();
abmsg.setRequiredZoneUuid(zoneUuid);
abmsg.setSize(imageActualSize);
bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID);
bus.send(abmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
targetBackupStorages.add(((AllocateBackupStorageReply) reply).getInventory());
trigger.next();
} else {
trigger.fail(reply.getError());
}
}
});
} else {
List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() {
@Override
public AllocateBackupStorageMsg call(String arg) {
AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg();
abmsg.setSize(imageActualSize);
abmsg.setBackupStorageUuid(arg);
bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID);
return abmsg;
}
});
bus.send(amsgs, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
List<ErrorCode> errs = new ArrayList<ErrorCode>();
for (MessageReply r : replies) {
if (r.isSuccess()) {
targetBackupStorages.add(((AllocateBackupStorageReply) r).getInventory());
} else {
errs.add(r.getError());
}
}
if (targetBackupStorages.isEmpty()) {
trigger.fail(errf.stringToOperationError(String.format("unable to allocate backup storage specified by uuids%s, list errors are: %s",
msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs))));
} else {
trigger.next();
}
}
});
}
}
@Override
public void rollback(final FlowRollback trigger, Map data) {
if (targetBackupStorages.isEmpty()) {
trigger.rollback();
return;
}
List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() {
@Override
public ReturnBackupStorageMsg call(BackupStorageInventory arg) {
ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg();
rmsg.setBackupStorageUuid(arg.getUuid());
rmsg.setSize(imageActualSize);
bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID);
return rmsg;
}
});
bus.send(rmsgs, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
for (MessageReply r : replies) {
if (!r.isSuccess()) {
BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r));
logger.warn(String.format("failed to return capacity[%s] to backup storage[uuid:%s], because %s",
imageActualSize, bs.getUuid(), r.getError()));
}
}
trigger.rollback();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = String.format("start-creating-template");
@Override
public void run(final FlowTrigger trigger, Map data) {
List<CreateTemplateFromVmRootVolumeMsg> cmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<CreateTemplateFromVmRootVolumeMsg, BackupStorageInventory>() {
@Override
public CreateTemplateFromVmRootVolumeMsg call(BackupStorageInventory arg) {
CreateTemplateFromVmRootVolumeMsg cmsg = new CreateTemplateFromVmRootVolumeMsg();
cmsg.setRootVolumeInventory(rootVolume);
cmsg.setBackupStorageUuid(arg.getUuid());
cmsg.setImageInventory(ImageInventory.valueOf(imageVO));
bus.makeTargetServiceIdByResourceUuid(cmsg, VmInstanceConstant.SERVICE_ID, rootVolume.getVmInstanceUuid());
return cmsg;
}
});
bus.send(cmsgs, new CloudBusListCallBack(trigger) {
@Override
public void run(List<MessageReply> replies) {
boolean success = false;
ErrorCode err = null;
for (MessageReply r : replies) {
BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r));
if (!r.isSuccess()) {
logger.warn(String.format("failed to create image from root volume[uuid:%s] on backup storage[uuid:%s], because %s",
msg.getRootVolumeUuid(), bs.getUuid(), r.getError()));
err = r.getError();
continue;
}
CreateTemplateFromVmRootVolumeReply reply = (CreateTemplateFromVmRootVolumeReply) r;
ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO();
ref.setBackupStorageUuid(bs.getUuid());
ref.setStatus(ImageStatus.Ready);
ref.setImageUuid(imageVO.getUuid());
ref.setInstallPath(reply.getInstallPath());
dbf.persist(ref);
imageVO.setStatus(ImageStatus.Ready);
if (reply.getFormat() != null) {
imageVO.setFormat(reply.getFormat());
}
dbf.update(imageVO);
imageVO = dbf.reload(imageVO);
success = true;
logger.debug(String.format("successfully created image[uuid:%s] from root volume[uuid:%s] on backup storage[uuid:%s]",
imageVO.getUuid(), msg.getRootVolumeUuid(), bs.getUuid()));
}
if (success) {
trigger.next();
} else {
trigger.fail(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, String.format("failed to create image from root volume[uuid:%s] on all backup storage, see cause for one of errors",
msg.getRootVolumeUuid()), err));
}
}
});
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId());
imageVO = dbf.reload(imageVO);
ImageInventory iinv = ImageInventory.valueOf(imageVO);
evt.setInventory(iinv);
logger.warn(String.format("successfully create template[uuid:%s] from root volume[uuid:%s]", iinv.getUuid(), msg.getRootVolumeUuid()));
bus.publish(evt);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId());
evt.setErrorCode(errCode);
logger.warn(String.format("failed to create template from root volume[uuid:%s], because %s", msg.getRootVolumeUuid(), errCode));
bus.publish(evt);
}
});
}
}).start();
}
private void handle(APIGetImageMsg msg) {
SearchQuery<ImageInventory> sq = new SearchQuery(ImageInventory.class);
sq.addAccountAsAnd(msg);
sq.add("uuid", SearchOp.AND_EQ, msg.getUuid());
List<ImageInventory> invs = sq.list();
APIGetImageReply reply = new APIGetImageReply();
if (!invs.isEmpty()) {
reply.setInventory(JSONObjectUtil.toJsonString(invs.get(0)));
}
bus.reply(msg, reply);
}
private void handle(APISearchImageMsg msg) {
SearchQuery<ImageInventory> sq = SearchQuery.create(msg, ImageInventory.class);
sq.addAccountAsAnd(msg);
String content = sq.listAsString();
APISearchImageReply reply = new APISearchImageReply();
reply.setContent(content);
bus.reply(msg, reply);
}
private void handle(APIListImageMsg msg) {
List<ImageVO> vos = dbf.listAll(ImageVO.class);
List<ImageInventory> invs = ImageInventory.valueOf(vos);
APIListImageReply reply = new APIListImageReply();
reply.setInventories(invs);
bus.reply(msg, reply);
}
@Deferred
private void handle(final APIAddImageMsg msg) {
String imageType = msg.getType();
imageType = imageType == null ? DefaultImageFactory.type.toString() : imageType;
final APIAddImageEvent evt = new APIAddImageEvent(msg.getId());
ImageVO vo = new ImageVO();
if (msg.getResourceUuid() != null) {
vo.setUuid(msg.getResourceUuid());
} else {
vo.setUuid(Platform.getUuid());
}
vo.setName(msg.getName());
vo.setDescription(msg.getDescription());
if (msg.getFormat().equals(ImageConstant.ISO_FORMAT_STRING)) {
vo.setMediaType(ImageMediaType.ISO);
} else {
vo.setMediaType(ImageMediaType.valueOf(msg.getMediaType()));
}
vo.setType(imageType);
vo.setSystem(msg.isSystem());
vo.setGuestOsType(msg.getGuestOsType());
vo.setFormat(msg.getFormat());
vo.setStatus(ImageStatus.Downloading);
vo.setState(ImageState.Enabled);
vo.setUrl(msg.getUrl());
vo.setDescription(msg.getDescription());
vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform()));
ImageFactory factory = getImageFacotry(ImageType.valueOf(imageType));
final ImageVO ivo = factory.createImage(vo, msg);
acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class);
tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName());
Defer.guard(new Runnable() {
@Override
public void run() {
dbf.remove(ivo);
}
});
final ImageInventory inv = ImageInventory.valueOf(ivo);
for (AddImageExtensionPoint ext : pluginRgty.getExtensionList(AddImageExtensionPoint.class)) {
ext.preAddImage(inv);
}
final List<DownloadImageMsg> dmsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<DownloadImageMsg, String>() {
@Override
public DownloadImageMsg call(String arg) {
DownloadImageMsg dmsg = new DownloadImageMsg(inv);
dmsg.setBackupStorageUuid(arg);
dmsg.setFormat(msg.getFormat());
bus.makeTargetServiceIdByResourceUuid(dmsg, BackupStorageConstant.SERVICE_ID, arg);
return dmsg;
}
});
CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() {
@Override
public void run(AddImageExtensionPoint ext) {
ext.beforeAddImage(inv);
}
});
bus.send(dmsgs, new CloudBusListCallBack(msg) {
@Override
public void run(List<MessageReply> replies) {
//TODO: check if the database still has the record of the image
// if there is no record, that means user delete the image during the downloading,
// then we need to cleanup
boolean success = false;
StringBuilder sb = new StringBuilder();
for (MessageReply r : replies) {
String bsUuid = msg.getBackupStorageUuids().get(replies.indexOf(r));
if (!r.isSuccess()) {
logger.warn(String.format("failed to download image[uuid:%s, name:%s] to backup storage[uuid:%s], %s", inv.getUuid(), inv.getName(), bsUuid, r.getError()));
sb.append(String.format("\nerror code for backup storage[uuid:%s]: %s", bsUuid, r.getError()));
} else {
DownloadImageReply re = (DownloadImageReply) r;
ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO();
ref.setImageUuid(ivo.getUuid());
ref.setInstallPath(re.getInstallPath());
ref.setBackupStorageUuid(bsUuid);
ref.setStatus(ImageStatus.Ready);
dbf.persist(ref);
if (!success) {
ivo.setMd5Sum(re.getMd5sum());
ivo.setSize(re.getSize());
ivo.setActualSize(re.getActualSize());
ivo.setStatus(ImageStatus.Ready);
ivo.setFormat(re.getFormat());
dbf.update(ivo);
success = true;
}
logger.debug(String.format("successfully downloaded image[uuid:%s, name:%s] to backup storage[uuid:%s]", inv.getUuid(), inv.getName(), bsUuid));
}
}
if (success) {
ImageVO vo = dbf.reload(ivo);
final ImageInventory einv = ImageInventory.valueOf(vo);
CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() {
@Override
public void run(AddImageExtensionPoint ext) {
ext.afterAddImage(einv);
}
});
evt.setInventory(einv);
} else {
final ErrorCode err = errf.instantiateErrorCode(SysErrors.CREATE_RESOURCE_ERROR, String.format("Failed to download image[name:%s] on all backup storage%s. %s",
inv.getName(), msg.getBackupStorageUuids(), sb.toString()));
CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() {
@Override
public void run(AddImageExtensionPoint ext) {
ext.failedToAddImage(inv, err);
}
});
dbf.remove(ivo);
evt.setErrorCode(err);
}
bus.publish(evt);
}
});
}
@Override
public String getId() {
return bus.makeLocalServiceId(ImageConstant.SERVICE_ID);
}
private void populateExtensions() {
for (ImageFactory f : pluginRgty.getExtensionList(ImageFactory.class)) {
ImageFactory old = imageFactories.get(f.getType().toString());
if (old != null) {
throw new CloudRuntimeException(String.format("duplicate ImageFactory[%s, %s] for type[%s]",
f.getClass().getName(), old.getClass().getName(), f.getType()));
}
imageFactories.put(f.getType().toString(), f);
}
}
@Override
public boolean start() {
populateExtensions();
installGlobalConfigUpdater();
return true;
}
private void installGlobalConfigUpdater() {
ImageGlobalConfig.DELETION_POLICY.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() {
@Override
public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) {
startExpungeTask();
}
});
ImageGlobalConfig.EXPUNGE_INTERVAL.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() {
@Override
public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) {
startExpungeTask();
}
});
ImageGlobalConfig.EXPUNGE_PERIOD.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() {
@Override
public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) {
startExpungeTask();
}
});
}
private void startExpungeTask() {
if (expungeTask != null) {
expungeTask.cancel(true);
}
expungeTask = thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask() {
private List<Tuple> getDeletedImageManagedByUs() {
int qun = 1000;
SimpleQuery q = dbf.createQuery(ImageBackupStorageRefVO.class);
q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted);
long amount = q.count();
int times = (int) (amount / qun) + (amount % qun != 0 ? 1 : 0);
int start = 0;
List<Tuple> ret = new ArrayList<Tuple>();
for (int i = 0; i < times; i++) {
q = dbf.createQuery(ImageBackupStorageRefVO.class);
q.select(ImageBackupStorageRefVO_.imageUuid, ImageBackupStorageRefVO_.lastOpDate, ImageBackupStorageRefVO_.backupStorageUuid);
q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted);
q.setLimit(qun);
q.setStart(start);
List<Tuple> ts = q.listTuple();
start += qun;
for (Tuple t : ts) {
String imageUuid = t.get(0, String.class);
if (!destMaker.isManagedByUs(imageUuid)) {
continue;
}
ret.add(t);
}
}
return ret;
}
@Override
public boolean run() {
final List<Tuple> images = getDeletedImageManagedByUs();
if (images.isEmpty()) {
logger.debug("[Image Expunge Task]: no images to expunge");
return false;
}
for (Tuple t : images) {
String imageUuid = t.get(0, String.class);
Timestamp date = t.get(1, Timestamp.class);
String bsUuid = t.get(2, String.class);
final Timestamp current = dbf.getCurrentSqlTime();
if (current.getTime() >= date.getTime() + TimeUnit.SECONDS.toMillis(ImageGlobalConfig.EXPUNGE_PERIOD.value(Long.class))) {
ImageDeletionPolicy deletionPolicy = deletionPolicyMgr.getDeletionPolicy(imageUuid);
if (ImageDeletionPolicy.Never == deletionPolicy) {
logger.debug(String.format("the deletion policy[Never] is set for the image[uuid:%s] on the backup storage[uuid:%s]," +
"don't expunge it", images, bsUuid));
continue;
}
ExpungeImageMsg msg = new ExpungeImageMsg();
msg.setImageUuid(imageUuid);
msg.setBackupStorageUuid(bsUuid);
bus.makeTargetServiceIdByResourceUuid(msg, ImageConstant.SERVICE_ID, imageUuid);
bus.send(msg, new CloudBusCallBack() {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
//TODO
logger.warn(String.format("failed to expunge the image[uuid:%s], %s", images, reply.getError()));
}
}
});
}
}
return false;
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return ImageGlobalConfig.EXPUNGE_INTERVAL.value(Long.class);
}
@Override
public String getName() {
return "expunge-image";
}
});
}
@Override
public boolean stop() {
return true;
}
private ImageFactory getImageFacotry(ImageType type) {
ImageFactory factory = imageFactories.get(type.toString());
if (factory == null) {
throw new CloudRuntimeException(String.format("Unable to find ImageFactory with type[%s]", type));
}
return factory;
}
@Override
public void managementNodeReady() {
startExpungeTask();
}
@Override
public List<Quota> reportQuota() {
Quota.QuotaOperator checker = new Quota.QuotaOperator() {
class ImageQuota {
long imageNum;
long imageSize;
}
@Override
public void checkQuota(APIMessage msg, Map<String, Quota.QuotaPair> pairs) {
SimpleQuery<AccountVO> q = dbf.createQuery(AccountVO.class);
q.select(AccountVO_.type);
q.add(AccountVO_.uuid, Op.EQ, msg.getSession().getAccountUuid());
AccountType type = q.findValue();
if (type != AccountType.SystemAdmin) {
if (msg instanceof APIAddImageMsg) {
check((APIAddImageMsg) msg, pairs);
} else if (msg instanceof APIRecoverImageMsg) {
check((APIRecoverImageMsg) msg, pairs);
} else if (msg instanceof APIChangeResourceOwnerMsg) {
check((APIChangeResourceOwnerMsg) msg, pairs);
}
} else {
if (msg instanceof APIChangeResourceOwnerMsg) {
check((APIChangeResourceOwnerMsg) msg, pairs);
}
}
}
@Override
public List<Quota.QuotaUsage> getQuotaUsageByAccount(String accountUuid) {
List<Quota.QuotaUsage> usages = new ArrayList<Quota.QuotaUsage>();
ImageQuota imageQuota = getUsed(accountUuid);
Quota.QuotaUsage usage = new Quota.QuotaUsage();
usage.setName(ImageConstant.QUOTA_IMAGE_NUM);
usage.setUsed(imageQuota.imageNum);
usages.add(usage);
usage = new Quota.QuotaUsage();
usage.setName(ImageConstant.QUOTA_IMAGE_SIZE);
usage.setUsed(imageQuota.imageSize);
usages.add(usage);
return usages;
}
@Transactional(readOnly = true)
private ImageQuota getUsed(String accountUUid) {
ImageQuota quota = new ImageQuota();
quota.imageSize = getUsedImageSize(accountUUid);
quota.imageNum = getUsedImageNum(accountUUid);
return quota;
}
@Transactional(readOnly = true)
private long getUsedImageNum(String accountUuid) {
String sql = "select count(image) " +
" from ImageVO image, AccountResourceRefVO ref " +
" where image.uuid = ref.resourceUuid " +
" and ref.accountUuid = :auuid " +
" and ref.resourceType = :rtype ";
TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class);
q.setParameter("auuid", accountUuid);
q.setParameter("rtype", ImageVO.class.getSimpleName());
Long imageNum = q.getSingleResult();
imageNum = imageNum == null ? 0 : imageNum;
return imageNum;
}
@Transactional(readOnly = true)
private long getUsedImageSize(String accountUuid) {
String sql = "select sum(image.size) " +
" from ImageVO image, AccountResourceRefVO ref " +
" where image.uuid = ref.resourceUuid " +
" and ref.accountUuid = :auuid " +
" and ref.resourceType = :rtype ";
TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class);
q.setParameter("auuid", accountUuid);
q.setParameter("rtype", ImageVO.class.getSimpleName());
Long imageSize = q.getSingleResult();
imageSize = imageSize == null ? 0 : imageSize;
return imageSize;
}
@Transactional(readOnly = true)
private void check(APIChangeResourceOwnerMsg msg, Map<String, Quota.QuotaPair> pairs) {
SimpleQuery<AccountVO> q1 = dbf.createQuery(AccountVO.class);
q1.select(AccountVO_.type);
q1.add(AccountVO_.uuid, Op.EQ, msg.getSession().getAccountUuid());
AccountType type = q1.findValue();
if (type == AccountType.SystemAdmin && (pairs == null || pairs.size() == 0)) {
logger.debug("APIChangeResourceOwnerMsg:(pairs == null || pairs.size() == 0)." +
"Skip quota check for being called by QuotaChecker with admin account session." +
"Another quota check would be executed by message interceptor.");
return;
}
SimpleQuery<AccountResourceRefVO> q = dbf.createQuery(AccountResourceRefVO.class);
q.add(AccountResourceRefVO_.resourceUuid, Op.EQ, msg.getResourceUuid());
AccountResourceRefVO accResRefVO = q.find();
String resourceOriginalOwnerAccountUuid = accResRefVO.getOwnerAccountUuid();
String currentAccountUuid = msg.getSession().getAccountUuid();
String resourceTargetOwnerAccountUuid = msg.getAccountUuid();
if (resourceTargetOwnerAccountUuid.equals(resourceOriginalOwnerAccountUuid)) {
throw new ApiMessageInterceptionException(errf.instantiateErrorCode(IdentityErrors.QUOTA_INVALID_OP,
String.format("Invalid ChangerResourceOwner operation." +
"Original owner is the same as target owner." +
"Current account is [uuid: %s]." +
"The resource target owner account[uuid: %s]." +
"The resource original owner account[uuid:%s].",
currentAccountUuid, resourceTargetOwnerAccountUuid, resourceOriginalOwnerAccountUuid)
));
}
if (accResRefVO.getResourceType().equals(ImageVO.class.getSimpleName())) {
long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue();
long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue();
long imageNumUsed = getUsedImageNum(resourceTargetOwnerAccountUuid);
long imageSizeUsed = getUsedImageSize(resourceTargetOwnerAccountUuid);
ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getResourceUuid());
long imageSizeAsked = image.getSize();
if (imageNumUsed + 1 > imageNumQuota) {
throw new ApiMessageInterceptionException(errf.instantiateErrorCode(IdentityErrors.QUOTA_EXCEEDING,
String.format("quota exceeding. The account[uuid: %s] exceeds a quota[name: %s, value: %s]",
resourceTargetOwnerAccountUuid, ImageConstant.QUOTA_IMAGE_NUM, imageNumQuota)
));
}
if (imageSizeUsed + imageSizeAsked > imageSizeQuota) {
throw new ApiMessageInterceptionException(errf.instantiateErrorCode(IdentityErrors.QUOTA_EXCEEDING,
String.format("quota exceeding. The account[uuid: %s] exceeds a quota[name: %s, value: %s]",
resourceTargetOwnerAccountUuid, ImageConstant.QUOTA_IMAGE_SIZE, imageSizeQuota)
));
}
}
}
@Transactional(readOnly = true)
private void check(APIRecoverImageMsg msg, Map<String, Quota.QuotaPair> pairs) {
long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue();
long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue();
long imageNumUsed = getUsedImageNum(msg.getSession().getAccountUuid());
long imageSizeUsed = getUsedImageSize(msg.getSession().getAccountUuid());
ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getImageUuid());
long imageSizeAsked = image.getSize();
if (imageNumUsed + 1 > imageNumQuota) {
throw new ApiMessageInterceptionException(errf.instantiateErrorCode(IdentityErrors.QUOTA_EXCEEDING,
String.format("quota exceeding. The account[uuid: %s] exceeds a quota[name: %s, value: %s]",
msg.getSession().getAccountUuid(), ImageConstant.QUOTA_IMAGE_NUM, imageNumQuota)
));
}
if (imageSizeUsed + imageSizeAsked > imageSizeQuota) {
throw new ApiMessageInterceptionException(errf.instantiateErrorCode(IdentityErrors.QUOTA_EXCEEDING,
String.format("quota exceeding. The account[uuid: %s] exceeds a quota[name: %s, value: %s]",
msg.getSession().getAccountUuid(), ImageConstant.QUOTA_IMAGE_SIZE, imageSizeQuota)
));
}
}
private void checkImageSize(APIAddImageMsg msg, long imageSizeQuota, long imageSizeUsed) {
long imageSizeAsked;
String url = msg.getUrl().trim();
if (url.startsWith("http") || url.startsWith("https")) {
String len;
try {
HttpHeaders header = restf.getRESTTemplate().headForHeaders(url);
len = header.getFirst("Content-Length");
} catch (Exception e) {
logger.warn(String.format("cannot get image. The image url : %s. description: %s.name: %s",
url, msg.getDescription(), msg.getName()));
return;
}
if (len == null) {
imageSizeAsked = 0;
} else {
imageSizeAsked = Long.valueOf(len);
}
} else if (url.startsWith("file:
GetImageSizeOnBackupStorageMsg cmsg = new GetImageSizeOnBackupStorageMsg();
cmsg.setBackupStorageUuid(msg.getBackupStorageUuids().get(0));
cmsg.setImageUrl(url);
cmsg.setImageUuid(msg.getResourceUuid());
bus.makeTargetServiceIdByResourceUuid(cmsg, BackupStorageConstant.SERVICE_ID,
msg.getBackupStorageUuids().get(0));
GetImageSizeOnBackupStorageReply reply = (GetImageSizeOnBackupStorageReply) bus.call(cmsg);
if (!reply.isSuccess()) {
throw new CloudRuntimeException("Cannot get local image size.");
} else {
imageSizeAsked = reply.getSize();
}
} else {
logger.info("not check quota for mismatched scheme:" + url);
return;
}
if ((imageSizeQuota == 0) || (imageSizeUsed + imageSizeAsked > imageSizeQuota)) {
throw new ApiMessageInterceptionException(errf.instantiateErrorCode(IdentityErrors.QUOTA_EXCEEDING,
String.format("quota exceeding. The account[uuid: %s] exceeds a quota[name: %s, value: %s]",
msg.getSession().getAccountUuid(), ImageConstant.QUOTA_IMAGE_SIZE, imageSizeQuota)
));
}
}
@Transactional(readOnly = true)
private void check(APIAddImageMsg msg, Map<String, Quota.QuotaPair> pairs) {
long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue();
long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue();
long imageNumUsed = getUsedImageNum(msg.getSession().getAccountUuid());
long imageSizeUsed = getUsedImageSize(msg.getSession().getAccountUuid());
// check image num quota
if (imageNumUsed + 1 > imageNumQuota) {
throw new ApiMessageInterceptionException(errf.instantiateErrorCode(IdentityErrors.QUOTA_EXCEEDING,
String.format("quota exceeding. The account[uuid: %s] exceeds a quota[name: %s, value: %s]",
msg.getSession().getAccountUuid(), ImageConstant.QUOTA_IMAGE_NUM, imageNumQuota)
));
}
// check image amount size quota
if (!CoreGlobalProperty.UNIT_TEST_ON) {
checkImageSize(msg, imageSizeQuota, imageSizeUsed);
} else {
logger.debug("CoreGlobalProperty.UNIT_TEST_ON is true. Skip the image size quota check.");
}
}
};
Quota quota = new Quota();
quota.setOperator(checker);
quota.addMessageNeedValidation(APIAddImageMsg.class);
quota.addMessageNeedValidation(APIRecoverImageMsg.class);
quota.addMessageNeedValidation(APIChangeResourceOwnerMsg.class);
Quota.QuotaPair p = new Quota.QuotaPair();
p.setName(ImageConstant.QUOTA_IMAGE_NUM);
p.setValue(20);
quota.addPair(p);
p = new Quota.QuotaPair();
p.setName(ImageConstant.QUOTA_IMAGE_SIZE);
p.setValue(SizeUnit.TERABYTE.toByte(10));
quota.addPair(p);
return list(quota);
}
}
|
package org.broadinstitute.sting.gatk.refdata;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.GenomeLocParser;
import org.broadinstitute.sting.utils.StingException;
import org.broadinstitute.sting.utils.Utils;
import org.broadinstitute.sting.utils.genotype.BasicGenotype;
import org.broadinstitute.sting.utils.genotype.DiploidGenotype;
import org.broadinstitute.sting.utils.genotype.Genotype;
import org.broadinstitute.sting.utils.genotype.VariantBackedByGenotype;
import org.broadinstitute.sting.utils.genotype.vcf.VCFGenotypeEncoding;
import org.broadinstitute.sting.utils.genotype.vcf.VCFGenotypeRecord;
import org.broadinstitute.sting.utils.genotype.vcf.VCFReader;
import org.broadinstitute.sting.utils.genotype.vcf.VCFRecord;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* @author aaron
* <p/>
* Class RodVCF
* <p/>
* An implementation of the ROD for VCF.
*/
public class RodVCF extends BasicReferenceOrderedDatum implements VariationRod, VariantBackedByGenotype, Iterator<RodVCF> {
// our VCF related information
private VCFReader mReader;
public VCFRecord mCurrentRecord;
public RodVCF(String name) {
super(name);
}
private RodVCF(String name, VCFRecord currentRecord, VCFReader reader) {
super(name);
mCurrentRecord = currentRecord;
mReader = reader;
}
public void assertNotNull() {
if (mCurrentRecord == null) {
throw new UnsupportedOperationException("The current Record is null");
}
}
@Override
public boolean parseLine(Object header, String[] parts) throws IOException {
throw new UnsupportedOperationException("We don't support the parse line");
}
public Object initialize(final File source) throws FileNotFoundException {
if (mReader == null) mReader = new VCFReader(source);
return mReader.getHeader();
}
@Override
public String toString() {
if (this.mCurrentRecord != null)
return this.mCurrentRecord.toStringRepresentation(mReader.getHeader());
else
return "";
}
public static RodVCF createIterator(String name, File file) {
RodVCF vcf = new RodVCF(name);
try {
vcf.initialize(file);
} catch (FileNotFoundException e) {
throw new StingException("Unable to find file " + file);
}
return vcf;
}
public void assertMultiAllelic() {
if (this.getAlternateBaseList().size() < 1)
throw new StingException("We're not multi-allelic.");
}
/**
* get the frequency of this variant
*
* @return VariantFrequency with the stored frequency
*/
@Override
public double getNonRefAlleleFrequency() {
assertNotNull();
if (this.mCurrentRecord.getInfoValues().containsKey("AF")) {
return Double.valueOf(this.mCurrentRecord.getInfoValues().get("AF"));
} else {
// this is the poor man's AF
if (this.mCurrentRecord.getInfoValues().containsKey("AC") && this.mCurrentRecord.getInfoValues().containsKey("AN")) {
String splt[] = mCurrentRecord.getInfoValues().get("AC").split(",");
if (splt.length > 0) {
return (Double.valueOf(splt[0]) / Double.valueOf(mCurrentRecord.getInfoValues().get("AN")));
}
}
}
return 0.0;
}
/** @return the VARIANT_TYPE of the current variant */
@Override
public VARIANT_TYPE getType() {
if (this.isSNP()) return VARIANT_TYPE.SNP;
else if (this.isIndel()) return VARIANT_TYPE.INDEL;
return VARIANT_TYPE.REFERENCE;
}
/**
* are we a SNP? If not we're a Indel/deletion
*
* @return true if we're a SNP
*/
@Override
public boolean isSNP() {
this.assertNotNull();
assertMultiAllelic();
for (VCFGenotypeEncoding alt : this.mCurrentRecord.getAlternateAlleles()) {
if (alt.getType() != VCFGenotypeEncoding.TYPE.SINGLE_BASE)
return false;
}
return true;
}
/**
* are we an insertion?
*
* @return true if we are, false otherwise
*/
@Override
public boolean isInsertion() {
this.assertNotNull();
assertMultiAllelic();
if (!mCurrentRecord.hasAlternateAllele())
return false;
for (VCFGenotypeEncoding alt : this.mCurrentRecord.getAlternateAlleles()) {
if (alt.getType() == VCFGenotypeEncoding.TYPE.INSERTION)
return true;
}
return false;
}
/**
* are we an insertion?
*
* @return true if we are, false otherwise
*/
@Override
public boolean isDeletion() {
this.assertNotNull();
assertMultiAllelic();
if (!mCurrentRecord.hasAlternateAllele())
return false;
for (VCFGenotypeEncoding alt : this.mCurrentRecord.getAlternateAlleles()) {
if (alt.getType() == VCFGenotypeEncoding.TYPE.DELETION)
return true;
}
return false;
}
@Override
public GenomeLoc getLocation() {
this.assertNotNull();
return GenomeLocParser.createGenomeLoc(mCurrentRecord.getChromosome(), mCurrentRecord.getPosition(), mCurrentRecord.getPosition());
}
/**
* get the reference base(s) at this position
*
* @return the reference base or bases, as a string
*/
@Override
public String getReference() {
return String.valueOf(mCurrentRecord.getReferenceBase());
}
/** are we bi-allelic? */
@Override
public boolean isBiallelic() {
return (this.getAlternateBaseList().size() == 1);
}
/**
* get the -1 * (log 10 of the error value)
*
* @return the log based error estimate
*/
@Override
public double getNegLog10PError() {
// we're -10 log(error), we have to divide by 10
return mCurrentRecord.getQual() / 10.0;
}
/**
* are we truely a variant, given a reference
*
* @return false if we're a variant(indel, delete, SNP, etc), true if we're not
*/
@Override
public boolean isReference() {
return (!mCurrentRecord.hasAlternateAllele());
}
/**
* gets the alternate bases. If this is homref, throws an UnsupportedOperationException
*
* @return
*/
@Override
public String getAlternateBases() {
if (!this.isBiallelic())
throw new UnsupportedOperationException("We're not biallelic, so please call getAlternateBaseList instead");
return this.mCurrentRecord.getAlternateAlleles().get(0).toString();
}
/**
* gets the alternate bases. If this is homref, throws an UnsupportedOperationException
*
* @return
*/
@Override
public List<String> getAlternateBaseList() {
List<String> list = new ArrayList<String>();
for (VCFGenotypeEncoding enc : mCurrentRecord.getAlternateAlleles())
list.add(enc.toString());
return list;
}
/**
* are we an insertion or a deletion? yes, then return true. No? Well, false then.
*
* @return true if we're an insertion or deletion
*/
@Override
public boolean isIndel() {
return (!isSNP());
}
@Override
public char getAlternativeBaseForSNP() {
if (!isSNP()) throw new IllegalStateException("we're not a SNP");
if (mCurrentRecord.getAlternateAlleles().size() != 1) throw new UnsupportedOperationException("We're not a biallelic VCF site");
return (mCurrentRecord.getAlternateAlleles().get(0).toString()).charAt(0);
}
@Override
public char getReferenceForSNP() {
if (!isSNP()) throw new IllegalStateException("we're not a SNP");
return mCurrentRecord.getReferenceBase();
}
/**
* get the genotype
*
* @return a map in lexigraphical order of the genotypes
*/
@Override
public Genotype getCalledGenotype() {
double refQual = (this.getNegLog10PError());
if (this.mCurrentRecord != null && this.mCurrentRecord.hasGenotypeData()) {
List<VCFGenotypeRecord> lst = this.mCurrentRecord.getVCFGenotypeRecords();
if (lst.size() != 1) {
throw new IllegalStateException("VCF object does not have one and only one genotype record");
}
double qual = 0;
if (lst.get(0).getAlleles().equals(this.getReference()))
qual = refQual;
else if (lst.get(0).getFields().containsKey("GQ"))
qual = Double.valueOf(lst.get(0).getFields().get("GQ")) / 10.0;
return new BasicGenotype(this.getLocation(), Utils.join("", lst.get(0).getAlleles()), this.getReference().charAt(0), qual);
}
return null;
}
/**
* get the genotypes
*
* @return a list of the genotypes
*/
@Override
public List<Genotype> getGenotypes() {
List<Genotype> genotypes = new ArrayList<Genotype>();
if (!this.mCurrentRecord.hasGenotypeData()) {
return genotypes;
}
double refQual = (this.getNegLog10PError());
// add the reference
for (VCFGenotypeRecord rec : mCurrentRecord.getVCFGenotypeRecords()) {
double qual = 0;
if (rec.getAlleles().equals(this.getReference()))
qual = refQual;
else if (rec.getFields().containsKey("GQ"))
qual = Double.valueOf(rec.getFields().get("GQ")) / 10.0;
genotypes.add(new BasicGenotype(this.getLocation(), Utils.join("", rec.getAlleles()), this.getReference().charAt(0), qual));
}
return genotypes;
}
/**
* a private helper method
*
* @return an array in lexigraphical order of the likelihoods
*/
private Genotype getGenotype(DiploidGenotype x) {
if (x.toString().equals(getReference()))
return new BasicGenotype(this.getLocation(), getReference(), this.getReference().charAt(0), 0);
for (VCFGenotypeRecord record : mCurrentRecord.getVCFGenotypeRecords()) {
if (Utils.join("", record.getAlleles()).equals(x.toString())) {
double qual = 0.0;
if (record.getAlleles().equals(this.getReference()))
qual = this.getNegLog10PError();
else if (record.getFields().containsKey("GQ"))
qual = Double.valueOf(record.getFields().get("GQ")) / 10.0;
return new BasicGenotype(this.getLocation(), Utils.join("", record.getAlleles()), this.getReference().charAt(0), qual);
}
}
return null;
}
/**
* do we have the specified genotype? not all backedByGenotypes
* have all the genotype data.
*
* @param x the genotype
*
* @return true if available, false otherwise
*/
@Override
public boolean hasGenotype(DiploidGenotype x) {
if (getGenotype(x) != null)
return true;
return false;
}
@Override
public boolean hasNext() {
return (mReader.hasNext());
}
@Override
public RodVCF next() {
mCurrentRecord = mReader.next();
return new RodVCF(this.name, mCurrentRecord, mReader);
}
@Override
public void remove() {
throw new UnsupportedOperationException("You cannot remove from a VCF rod");
}
}
|
package ab.j3d.awt.view.jogl;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.concurrent.*;
import ab.j3d.*;
import ab.j3d.appearance.*;
import com.jogamp.opengl.*;
import com.jogamp.opengl.glu.*;
import com.jogamp.opengl.util.texture.*;
import com.jogamp.opengl.util.texture.awt.*;
import org.jetbrains.annotations.*;
/**
* Provides access to a {@link Texture} in such a way that it can be loaded
* asynchronously. Typical usage involves submitting an object of this class to
* an {@link ExecutorService} and passing the resulting future back using {@link
* #setTextureData(Future)}.
*
* @author G. Meinders
*/
public class TextureProxy
implements Callable<TextureData>
{
/**
* Name of the texture image.
*/
protected final TextureMap _textureMap;
/**
* Texture cache.
*/
protected final TextureCache _textureCache;
/**
* Future that will provide texture data, when it becomes available.
*/
private Future<TextureData> _textureData;
/**
* Texture, when available.
*/
protected Texture _texture;
/**
* Construct new texture proxy for a texture that is already loaded.
*
* @param texture Texture to be wrapped.
*/
public TextureProxy( @NotNull final Texture texture )
{
_textureMap = null;
_textureCache = null;
_textureData = null;
_texture = texture;
}
/**
* Construct new texture proxy.
*
* @param textureMap Texture map.
* @param textureCache Texture cache.
*/
public TextureProxy( @NotNull final TextureMap textureMap, final TextureCache textureCache )
{
_textureMap = textureMap;
_textureCache = textureCache;
_textureData = null;
_texture = null;
}
/**
* Construct new texture proxy.
*
* @param textureCache Texture cache.
*/
protected TextureProxy( final TextureCache textureCache )
{
_textureMap = null;
_textureCache = textureCache;
_textureData = null;
_texture = null;
}
/**
* Returns whether the proxy has access to texture data to create a texture
* from when needed.
*
* @return <code>true</code> if texture data is available/accessible.
*/
public boolean isTextureDataSet()
{
return ( _textureData != null );
}
/**
* Returns the texture, if available. Must be called on the OpenGL thread.
*
* @return Texture.
*
* @throws GLException if there is no current OpenGL context.
*/
@Nullable
public Texture getTexture()
{
Texture texture = _texture;
if ( texture == null )
{
final Future<TextureData> textureDataFuture = _textureData;
if ( ( textureDataFuture != null ) && textureDataFuture.isDone() )
{
final TextureData textureData = getTextureData();
if ( textureData != null )
{
texture = createTexture( textureData );
_textureData = null;
textureData.flush();
_texture = texture;
}
}
}
return texture;
}
/**
* Creates a texture from the given texture data.
*
* @param textureData Texture data.
*
* @return Created texture.
*/
protected Texture createTexture( final TextureData textureData )
{
final Texture result = TextureIO.newTexture( textureData );
final GL gl = GLU.getCurrentGL();
setTextureParameters( gl, result );
return result;
}
/**
* Returns the texture data, if available.
*
* @return Texture data.
*/
@Nullable
public TextureData getTextureData()
{
TextureData result = null;
final Future<TextureData> textureData = _textureData;
if ( ( textureData != null ) && textureData.isDone() )
{
try
{
result = textureData.get();
}
catch ( InterruptedException e )
{
System.err.println( "getTextureData( " + _textureMap.getName() + " ) => " + e );
}
catch ( ExecutionException e )
{
System.err.println( "getTextureData( " + _textureMap.getName() + " ) => " + e.getCause() );
_textureData = null;
}
}
return result;
}
/**
* Sets a future that will provide texture data when it becomes available.
*
* @param textureData Future providing texture data.
*/
public void setTextureData( @NotNull final Future<TextureData> textureData )
{
_textureData = textureData;
}
/**
* Loads and returns the texture data for the texture.
*
* @return Texture data.
*/
@Override
@Nullable
public TextureData call()
throws IOException
{
return createTextureData( _textureCache.loadImage( _textureMap ) );
}
/**
* Creates texture data from the given buffered image, if not {@code null}.
* The image is automatically converted to a compatible size using {@link
* #createCompatibleTextureImage(BufferedImage)}.
*
* @param image Texture image.
*
* @return Compatible texture data.
*/
@Nullable
protected TextureData createTextureData( @Nullable final BufferedImage image )
{
TextureData result = null;
if ( image != null )
{
final BufferedImage compatibleImage = createCompatibleTextureImage( image );
result = AWTTextureIO.newTextureData( GLProfile.get( GLProfile.GL2 ), compatibleImage, true );
}
return result;
}
protected BufferedImage createCompatibleTextureImage( final BufferedImage image )
{
final BufferedImage result;
final int imageWidth = image.getWidth();
final int imageHeight = image.getHeight();
final TextureCache textureCache = _textureCache;
int scaledWidth = Math.min( textureCache.getMaximumTextureSize(), imageWidth );
int scaledHeight = Math.min( textureCache.getMaximumTextureSize(), imageHeight );
/*
* Texture sizes may need to be powers of two.
*/
if ( !textureCache.isNonPowerOfTwo() )
{
scaledWidth = MathTools.nearestPowerOfTwo( scaledWidth );
scaledHeight = MathTools.nearestPowerOfTwo( scaledHeight );
}
if ( ( imageWidth == scaledWidth ) && ( imageHeight == scaledHeight ) )
{
result = image;
}
else
{
result = createScaledInstance( image, scaledWidth, scaledHeight );
}
return result;
}
public static BufferedImage createScaledInstance( final BufferedImage source, final int targetWidth, final int targetHeight )
{
/*
* Determine appropriate image type.
*/
final ColorModel sourceColorModel = source.getColorModel();
final int scaledType = sourceColorModel.hasAlpha() ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
int currentWidth = source.getWidth();
int currentHeight = source.getHeight();
/*
* Choose interpolation method.
*/
final Object interpolation;
if ( ( targetWidth < currentWidth ) || ( targetHeight < currentHeight ) )
{
interpolation = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
}
else
{
interpolation = RenderingHints.VALUE_INTERPOLATION_BICUBIC;
}
/*
* Perform scaling, using multiple steps when reducing to less than 50%.
*/
BufferedImage result = source;
while ( ( targetWidth != currentWidth ) || ( targetHeight != currentHeight ) )
{
currentWidth = Math.max( currentWidth / 2, targetWidth );
currentHeight = Math.max( currentHeight / 2, targetHeight );
/*
* Use specified target size instead of the aspect-correct size in
* the final scaling step.
*/
final boolean finalStep = ( currentWidth == targetWidth ) && ( currentHeight == targetHeight );
final int scaledCanvasWidth = finalStep ? targetWidth : currentWidth;
final int scaledCanvasHeight = finalStep ? targetHeight : currentHeight;
/*
* Perform the scaling step.
*/
final BufferedImage scaledImage = new BufferedImage( scaledCanvasWidth, scaledCanvasHeight, scaledType );
final Graphics2D g2 = scaledImage.createGraphics();
g2.setRenderingHint( RenderingHints.KEY_INTERPOLATION, interpolation );
g2.drawImage( result, 0, 0, scaledCanvasWidth, scaledCanvasHeight, null );
g2.dispose();
result = scaledImage;
}
return result;
}
/**
* Sets common texture parameters for wrapping and mipmapping.
*
* @param gl OpenGL pipeline.
* @param texture Texture to set parameters for.
*/
private static void setTextureParameters( @NotNull final GL gl, @NotNull final Texture texture )
{
final boolean rectangle = ( texture.getTarget() == GL2.GL_TEXTURE_RECTANGLE );
texture.setTexParameteri( gl, GL.GL_TEXTURE_WRAP_S, rectangle ? GL.GL_CLAMP_TO_EDGE : GL.GL_REPEAT );
texture.setTexParameteri( gl, GL.GL_TEXTURE_WRAP_T, rectangle ? GL.GL_CLAMP_TO_EDGE : GL.GL_REPEAT );
if ( hasAutoMipMapGenerationSupport( gl ) )
{
try
{
/*
* Generate mip maps to avoid 'noise' on far-away textures.
*/
texture.setTexParameteri( gl, GL2.GL_GENERATE_MIPMAP, GL.GL_TRUE );
/*
* Use linear texture filtering.
*/
texture.setTexParameteri( gl, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR );
texture.setTexParameteri( gl, GL.GL_TEXTURE_MIN_FILTER, rectangle ? GL.GL_LINEAR : GL.GL_LINEAR_MIPMAP_NEAREST );
}
catch ( GLException e )
{
/*
* If setting texture parameters fails, it's no
* severe problem. Catch any exception so the view
* doesn't crash.
*/
e.printStackTrace();
}
}
}
/**
* Test if OpenGL supports auto-generated mipmaps.
*
* @param gl OpenGL pipeline.
*
* @return <code>true</code> if OpenGL supports auto-generated mipmaps;
* <code>false</code> otherwise.
*/
private static boolean hasAutoMipMapGenerationSupport( final GL gl )
{
return ( gl.isExtensionAvailable( "GL_VERSION_1_4" ) || gl.isExtensionAvailable( "GL_SGIS_generate_mipmap" ) );
}
@Override
public String toString()
{
return super.toString() + "[textureMap=" + _textureMap + "]";
}
}
|
package com.fsck.k9.activity;
import java.util.Collection;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import timber.log.Timber;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.Account.SortType;
import com.fsck.k9.K9;
import com.fsck.k9.K9.SplitViewMode;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.compose.MessageActions;
import com.fsck.k9.activity.misc.SwipeGestureDetector.OnSwipeGestureListener;
import com.fsck.k9.activity.setup.AccountSettings;
import com.fsck.k9.activity.setup.FolderSettings;
import com.fsck.k9.activity.setup.Prefs;
import com.fsck.k9.fragment.MessageListFragment;
import com.fsck.k9.fragment.MessageListFragment.MessageListFragmentListener;
import com.fsck.k9.helper.ParcelableUtil;
import com.fsck.k9.mailstore.StorageManager;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.search.LocalSearch;
import com.fsck.k9.search.SearchAccount;
import com.fsck.k9.search.SearchSpecification;
import com.fsck.k9.search.SearchSpecification.Attribute;
import com.fsck.k9.search.SearchSpecification.SearchCondition;
import com.fsck.k9.search.SearchSpecification.SearchField;
import com.fsck.k9.ui.messageview.MessageViewFragment;
import com.fsck.k9.ui.messageview.MessageViewFragment.MessageViewFragmentListener;
import com.fsck.k9.view.MessageHeader;
import com.fsck.k9.view.MessageTitleView;
import com.fsck.k9.view.ViewSwitcher;
import com.fsck.k9.view.ViewSwitcher.OnSwitchCompleteListener;
import de.cketti.library.changelog.ChangeLog;
/**
* MessageList is the primary user interface for the program. This Activity
* shows a list of messages.
* From this Activity the user can perform all standard message operations.
*/
public class MessageList extends K9Activity implements MessageListFragmentListener,
MessageViewFragmentListener, OnBackStackChangedListener, OnSwipeGestureListener,
OnSwitchCompleteListener {
@Deprecated
//TODO: Remove after 2017-09-11
private static final String EXTRA_SEARCH_OLD = "search";
private static final String EXTRA_SEARCH = "search_bytes";
private static final String EXTRA_NO_THREADING = "no_threading";
private static final String ACTION_SHORTCUT = "shortcut";
private static final String EXTRA_SPECIAL_FOLDER = "special_folder";
private static final String EXTRA_MESSAGE_REFERENCE = "message_reference";
// used for remote search
public static final String EXTRA_SEARCH_ACCOUNT = "com.fsck.k9.search_account";
private static final String EXTRA_SEARCH_FOLDER = "com.fsck.k9.search_folder";
private static final String STATE_DISPLAY_MODE = "displayMode";
private static final String STATE_MESSAGE_LIST_WAS_DISPLAYED = "messageListWasDisplayed";
private static final String STATE_FIRST_BACK_STACK_ID = "firstBackstackId";
// Used for navigating to next/previous message
private static final int PREVIOUS = 1;
private static final int NEXT = 2;
public static final int REQUEST_MASK_PENDING_INTENT = 1 << 16;
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask) {
actionDisplaySearch(context, search, noThreading, newTask, true);
}
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
context.startActivity(
intentDisplaySearch(context, search, noThreading, newTask, clearTop));
}
public static Intent intentDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
Intent intent = new Intent(context, MessageList.class);
intent.putExtra(EXTRA_SEARCH, ParcelableUtil.marshall(search));
intent.putExtra(EXTRA_NO_THREADING, noThreading);
if (clearTop) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
if (newTask) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
return intent;
}
public static Intent shortcutIntent(Context context, String specialFolder) {
Intent intent = new Intent(context, MessageList.class);
intent.setAction(ACTION_SHORTCUT);
intent.putExtra(EXTRA_SPECIAL_FOLDER, specialFolder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
public static Intent actionDisplayMessageIntent(Context context,
MessageReference messageReference) {
Intent intent = new Intent(context, MessageList.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference.toIdentityString());
return intent;
}
private enum DisplayMode {
MESSAGE_LIST,
MESSAGE_VIEW,
SPLIT_VIEW
}
private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation();
private ActionBar mActionBar;
private View mActionBarMessageList;
private View mActionBarMessageView;
private MessageTitleView mActionBarSubject;
private TextView mActionBarTitle;
private TextView mActionBarSubTitle;
private TextView mActionBarUnread;
private Menu mMenu;
private ViewGroup mMessageViewContainer;
private View mMessageViewPlaceHolder;
private MessageListFragment mMessageListFragment;
private MessageViewFragment mMessageViewFragment;
private int mFirstBackStackId = -1;
private Account mAccount;
private String mFolderName;
private LocalSearch mSearch;
private boolean mSingleFolderMode;
private boolean mSingleAccountMode;
private ProgressBar mActionBarProgress;
private MenuItem mMenuButtonCheckMail;
private View mActionButtonIndeterminateProgress;
private int mLastDirection = (K9.messageViewShowNext()) ? NEXT : PREVIOUS;
/**
* {@code true} if the message list should be displayed as flat list (i.e. no threading)
* regardless whether or not message threading was enabled in the settings. This is used for
* filtered views, e.g. when only displaying the unread messages in a folder.
*/
private boolean mNoThreading;
private DisplayMode mDisplayMode;
private MessageReference mMessageReference;
/**
* {@code true} when the message list was displayed once. This is used in
* {@link #onBackPressed()} to decide whether to go from the message view to the message list or
* finish the activity.
*/
private boolean mMessageListWasDisplayed = false;
private ViewSwitcher mViewSwitcher;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) {
finish();
return;
}
if (useSplitView()) {
setContentView(R.layout.split_message_list);
} else {
setContentView(R.layout.message_list);
mViewSwitcher = (ViewSwitcher) findViewById(R.id.container);
mViewSwitcher.setFirstInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_left));
mViewSwitcher.setFirstOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_right));
mViewSwitcher.setSecondInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right));
mViewSwitcher.setSecondOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_left));
mViewSwitcher.setOnSwitchCompleteListener(this);
}
initializeActionBar();
// Enable gesture detection for MessageLists
setupGestureDetector(this);
if (!decodeExtras(getIntent())) {
return;
}
findFragments();
initializeDisplayMode(savedInstanceState);
initializeLayout();
initializeFragments();
displayViews();
ChangeLog cl = new ChangeLog(this);
if (cl.isFirstRun()) {
cl.getLogDialog().show();
}
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (isFinishing()) {
return;
}
setIntent(intent);
if (mFirstBackStackId >= 0) {
getFragmentManager().popBackStackImmediate(mFirstBackStackId,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
mFirstBackStackId = -1;
}
removeMessageListFragment();
removeMessageViewFragment();
mMessageReference = null;
mSearch = null;
mFolderName = null;
if (!decodeExtras(intent)) {
return;
}
initializeDisplayMode(null);
initializeFragments();
displayViews();
}
/**
* Get references to existing fragments if the activity was restarted.
*/
private void findFragments() {
FragmentManager fragmentManager = getFragmentManager();
mMessageListFragment = (MessageListFragment) fragmentManager.findFragmentById(
R.id.message_list_container);
mMessageViewFragment = (MessageViewFragment) fragmentManager.findFragmentById(
R.id.message_view_container);
}
/**
* Create fragment instances if necessary.
*
* @see #findFragments()
*/
private void initializeFragments() {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
boolean hasMessageListFragment = (mMessageListFragment != null);
if (!hasMessageListFragment) {
FragmentTransaction ft = fragmentManager.beginTransaction();
mMessageListFragment = MessageListFragment.newInstance(mSearch, false,
(K9.isThreadedViewEnabled() && !mNoThreading));
ft.add(R.id.message_list_container, mMessageListFragment);
ft.commit();
}
// Check if the fragment wasn't restarted and has a MessageReference in the arguments. If
// so, open the referenced message.
if (!hasMessageListFragment && mMessageViewFragment == null &&
mMessageReference != null) {
openMessage(mMessageReference);
}
}
/**
* Set the initial display mode (message list, message view, or split view).
*
* <p><strong>Note:</strong>
* This method has to be called after {@link #findFragments()} because the result depends on
* the availability of a {@link MessageViewFragment} instance.
* </p>
*
* @param savedInstanceState
* The saved instance state that was passed to the activity as argument to
* {@link #onCreate(Bundle)}. May be {@code null}.
*/
private void initializeDisplayMode(Bundle savedInstanceState) {
if (useSplitView()) {
mDisplayMode = DisplayMode.SPLIT_VIEW;
return;
}
if (savedInstanceState != null) {
DisplayMode savedDisplayMode =
(DisplayMode) savedInstanceState.getSerializable(STATE_DISPLAY_MODE);
if (savedDisplayMode != DisplayMode.SPLIT_VIEW) {
mDisplayMode = savedDisplayMode;
return;
}
}
if (mMessageViewFragment != null || mMessageReference != null) {
mDisplayMode = DisplayMode.MESSAGE_VIEW;
} else {
mDisplayMode = DisplayMode.MESSAGE_LIST;
}
}
private boolean useSplitView() {
SplitViewMode splitViewMode = K9.getSplitViewMode();
int orientation = getResources().getConfiguration().orientation;
return (splitViewMode == SplitViewMode.ALWAYS ||
(splitViewMode == SplitViewMode.WHEN_IN_LANDSCAPE &&
orientation == Configuration.ORIENTATION_LANDSCAPE));
}
private void initializeLayout() {
mMessageViewContainer = (ViewGroup) findViewById(R.id.message_view_container);
LayoutInflater layoutInflater = getLayoutInflater();
mMessageViewPlaceHolder = layoutInflater.inflate(R.layout.empty_message_view, mMessageViewContainer, false);
}
private void displayViews() {
switch (mDisplayMode) {
case MESSAGE_LIST: {
showMessageList();
break;
}
case MESSAGE_VIEW: {
showMessageView();
break;
}
case SPLIT_VIEW: {
mMessageListWasDisplayed = true;
if (mMessageViewFragment == null) {
showMessageViewPlaceHolder();
} else {
MessageReference activeMessage = mMessageViewFragment.getMessageReference();
if (activeMessage != null) {
mMessageListFragment.setActiveMessage(activeMessage);
}
}
break;
}
}
}
private boolean decodeExtras(Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action) && intent.getData() != null) {
Uri uri = intent.getData();
List<String> segmentList = uri.getPathSegments();
String accountId = segmentList.get(0);
Collection<Account> accounts = Preferences.getPreferences(this).getAvailableAccounts();
for (Account account : accounts) {
if (String.valueOf(account.getAccountNumber()).equals(accountId)) {
String folderName = segmentList.get(1);
String messageUid = segmentList.get(2);
mMessageReference = new MessageReference(account.getUuid(), folderName, messageUid, null);
break;
}
}
} else if (ACTION_SHORTCUT.equals(action)) {
// Handle shortcut intents
String specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER);
if (SearchAccount.UNIFIED_INBOX.equals(specialFolder)) {
mSearch = SearchAccount.createUnifiedInboxAccount(this).getRelatedSearch();
} else if (SearchAccount.ALL_MESSAGES.equals(specialFolder)) {
mSearch = SearchAccount.createAllMessagesAccount(this).getRelatedSearch();
}
} else if (intent.getStringExtra(SearchManager.QUERY) != null) {
// check if this intent comes from the system search ( remote )
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
//Query was received from Search Dialog
String query = intent.getStringExtra(SearchManager.QUERY).trim();
mSearch = new LocalSearch(getString(R.string.search_results));
mSearch.setManualSearch(true);
mNoThreading = true;
mSearch.or(new SearchCondition(SearchField.SENDER, Attribute.CONTAINS, query));
mSearch.or(new SearchCondition(SearchField.SUBJECT, Attribute.CONTAINS, query));
mSearch.or(new SearchCondition(SearchField.MESSAGE_CONTENTS, Attribute.CONTAINS, query));
Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
mSearch.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT));
// searches started from a folder list activity will provide an account, but no folder
if (appData.getString(EXTRA_SEARCH_FOLDER) != null) {
mSearch.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER));
}
} else {
mSearch.addAccountUuid(LocalSearch.ALL_ACCOUNTS);
}
}
} else if (intent.hasExtra(EXTRA_SEARCH_OLD)) {
mSearch = intent.getParcelableExtra(EXTRA_SEARCH_OLD);
mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false);
} else {
// regular LocalSearch object was passed
mSearch = intent.hasExtra(EXTRA_SEARCH) ?
ParcelableUtil.unmarshall(intent.getByteArrayExtra(EXTRA_SEARCH), LocalSearch.CREATOR) : null;
mNoThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false);
}
if (mMessageReference == null) {
String messageReferenceString = intent.getStringExtra(EXTRA_MESSAGE_REFERENCE);
mMessageReference = MessageReference.parse(messageReferenceString);
}
if (mMessageReference != null) {
mSearch = new LocalSearch();
mSearch.addAccountUuid(mMessageReference.getAccountUuid());
mSearch.addAllowedFolder(mMessageReference.getFolderName());
}
if (mSearch == null) {
// We've most likely been started by an old unread widget
String accountUuid = intent.getStringExtra("account");
String folderName = intent.getStringExtra("folder");
mSearch = new LocalSearch(folderName);
mSearch.addAccountUuid((accountUuid == null) ? "invalid" : accountUuid);
if (folderName != null) {
mSearch.addAllowedFolder(folderName);
}
}
Preferences prefs = Preferences.getPreferences(getApplicationContext());
String[] accountUuids = mSearch.getAccountUuids();
if (mSearch.searchAllAccounts()) {
List<Account> accounts = prefs.getAccounts();
mSingleAccountMode = (accounts.size() == 1);
if (mSingleAccountMode) {
mAccount = accounts.get(0);
}
} else {
mSingleAccountMode = (accountUuids.length == 1);
if (mSingleAccountMode) {
mAccount = prefs.getAccount(accountUuids[0]);
}
}
mSingleFolderMode = mSingleAccountMode && (mSearch.getFolderNames().size() == 1);
if (mSingleAccountMode && (mAccount == null || !mAccount.isAvailable(this))) {
Timber.i("not opening MessageList of unavailable account");
onAccountUnavailable();
return false;
}
if (mSingleFolderMode) {
mFolderName = mSearch.getFolderNames().get(0);
}
// now we know if we are in single account mode and need a subtitle
mActionBarSubTitle.setVisibility((!mSingleFolderMode) ? View.GONE : View.VISIBLE);
return true;
}
@Override
public void onPause() {
super.onPause();
StorageManager.getInstance(getApplication()).removeListener(mStorageListener);
}
@Override
public void onResume() {
super.onResume();
if (!(this instanceof Search)) {
//necessary b/c no guarantee Search.onStop will be called before MessageList.onResume
//when returning from search results
Search.setActive(false);
}
if (mAccount != null && !mAccount.isAvailable(this)) {
onAccountUnavailable();
return;
}
StorageManager.getInstance(getApplication()).addListener(mStorageListener);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_DISPLAY_MODE, mDisplayMode);
outState.putBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED, mMessageListWasDisplayed);
outState.putInt(STATE_FIRST_BACK_STACK_ID, mFirstBackStackId);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mMessageListWasDisplayed = savedInstanceState.getBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED);
mFirstBackStackId = savedInstanceState.getInt(STATE_FIRST_BACK_STACK_ID);
}
private void initializeActionBar() {
mActionBar = getActionBar();
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setCustomView(R.layout.actionbar_custom);
View customView = mActionBar.getCustomView();
mActionBarMessageList = customView.findViewById(R.id.actionbar_message_list);
mActionBarMessageView = customView.findViewById(R.id.actionbar_message_view);
mActionBarSubject = (MessageTitleView) customView.findViewById(R.id.message_title_view);
mActionBarTitle = (TextView) customView.findViewById(R.id.actionbar_title_first);
mActionBarSubTitle = (TextView) customView.findViewById(R.id.actionbar_title_sub);
mActionBarUnread = (TextView) customView.findViewById(R.id.actionbar_unread_count);
mActionBarProgress = (ProgressBar) customView.findViewById(R.id.actionbar_progress);
mActionButtonIndeterminateProgress = getActionButtonIndeterminateProgress();
mActionBar.setDisplayHomeAsUpEnabled(true);
}
@SuppressLint("InflateParams")
private View getActionButtonIndeterminateProgress() {
return getLayoutInflater().inflate(R.layout.actionbar_indeterminate_progress_actionview, null);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean ret = false;
if (KeyEvent.ACTION_DOWN == event.getAction()) {
ret = onCustomKeyDown(event.getKeyCode(), event);
}
if (!ret) {
ret = super.dispatchKeyEvent(event);
}
return ret;
}
@Override
public void onBackPressed() {
if (mDisplayMode == DisplayMode.MESSAGE_VIEW && mMessageListWasDisplayed) {
showMessageList();
} else {
super.onBackPressed();
}
}
/**
* Handle hotkeys
*
* <p>
* This method is called by {@link #dispatchKeyEvent(KeyEvent)} before any view had the chance
* to consume this key event.
* </p>
*
* @param keyCode
* The value in {@code event.getKeyCode()}.
* @param event
* Description of the key event.
*
* @return {@code true} if this event was consumed.
*/
public boolean onCustomKeyDown(final int keyCode, final KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP: {
if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST &&
K9.useVolumeKeysForNavigationEnabled()) {
showPreviousMessage();
return true;
} else if (mDisplayMode != DisplayMode.MESSAGE_VIEW &&
K9.useVolumeKeysForListNavigationEnabled()) {
mMessageListFragment.onMoveUp();
return true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_DOWN: {
if (mMessageViewFragment != null && mDisplayMode != DisplayMode.MESSAGE_LIST &&
K9.useVolumeKeysForNavigationEnabled()) {
showNextMessage();
return true;
} else if (mDisplayMode != DisplayMode.MESSAGE_VIEW &&
K9.useVolumeKeysForListNavigationEnabled()) {
mMessageListFragment.onMoveDown();
return true;
}
break;
}
case KeyEvent.KEYCODE_C: {
mMessageListFragment.onCompose();
return true;
}
case KeyEvent.KEYCODE_Q: {
if (mMessageListFragment != null && mMessageListFragment.isSingleAccountMode()) {
onShowFolderList();
}
return true;
}
case KeyEvent.KEYCODE_O: {
mMessageListFragment.onCycleSort();
return true;
}
case KeyEvent.KEYCODE_I: {
mMessageListFragment.onReverseSort();
return true;
}
case KeyEvent.KEYCODE_DEL:
case KeyEvent.KEYCODE_D: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onDelete();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onDelete();
}
return true;
}
case KeyEvent.KEYCODE_S: {
mMessageListFragment.toggleMessageSelect();
return true;
}
case KeyEvent.KEYCODE_G: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onToggleFlagged();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onToggleFlagged();
}
return true;
}
case KeyEvent.KEYCODE_M: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onMove();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onMove();
}
return true;
}
case KeyEvent.KEYCODE_V: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onArchive();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onArchive();
}
return true;
}
case KeyEvent.KEYCODE_Y: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onCopy();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onCopy();
}
return true;
}
case KeyEvent.KEYCODE_Z: {
if (mDisplayMode == DisplayMode.MESSAGE_LIST) {
mMessageListFragment.onToggleRead();
} else if (mMessageViewFragment != null) {
mMessageViewFragment.onToggleRead();
}
return true;
}
case KeyEvent.KEYCODE_F: {
if (mMessageViewFragment != null) {
mMessageViewFragment.onForward();
}
return true;
}
case KeyEvent.KEYCODE_A: {
if (mMessageViewFragment != null) {
mMessageViewFragment.onReplyAll();
}
return true;
}
case KeyEvent.KEYCODE_R: {
if (mMessageViewFragment != null) {
mMessageViewFragment.onReply();
}
return true;
}
case KeyEvent.KEYCODE_J:
case KeyEvent.KEYCODE_P: {
if (mMessageViewFragment != null) {
showPreviousMessage();
}
return true;
}
case KeyEvent.KEYCODE_N:
case KeyEvent.KEYCODE_K: {
if (mMessageViewFragment != null) {
showNextMessage();
}
return true;
}
/* FIXME
case KeyEvent.KEYCODE_Z: {
mMessageViewFragment.zoom(event);
return true;
}*/
case KeyEvent.KEYCODE_H: {
Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG);
toast.show();
return true;
}
case KeyEvent.KEYCODE_DPAD_LEFT: {
if (mMessageViewFragment != null && mDisplayMode == DisplayMode.MESSAGE_VIEW) {
return showPreviousMessage();
}
return false;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
if (mMessageViewFragment != null && mDisplayMode == DisplayMode.MESSAGE_VIEW) {
return showNextMessage();
}
return false;
}
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// Swallow these events too to avoid the audible notification of a volume change
if (K9.useVolumeKeysForListNavigationEnabled()) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
Timber.v("Swallowed key up.");
return true;
}
}
return super.onKeyUp(keyCode, event);
}
private void onAccounts() {
Accounts.listAccounts(this);
finish();
}
private void onShowFolderList() {
FolderList.actionHandleAccount(this, mAccount);
finish();
}
private void onEditPrefs() {
Prefs.actionPrefs(this);
}
private void onEditAccount() {
AccountSettings.actionSettings(this, mAccount);
}
@Override
public boolean onSearchRequested() {
return mMessageListFragment.onSearchRequested();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home: {
goBack();
return true;
}
case R.id.compose: {
mMessageListFragment.onCompose();
return true;
}
case R.id.toggle_message_view_theme: {
onToggleTheme();
return true;
}
// MessageList
case R.id.check_mail: {
mMessageListFragment.checkMail();
return true;
}
case R.id.set_sort_date: {
mMessageListFragment.changeSort(SortType.SORT_DATE);
return true;
}
case R.id.set_sort_arrival: {
mMessageListFragment.changeSort(SortType.SORT_ARRIVAL);
return true;
}
case R.id.set_sort_subject: {
mMessageListFragment.changeSort(SortType.SORT_SUBJECT);
return true;
}
case R.id.set_sort_sender: {
mMessageListFragment.changeSort(SortType.SORT_SENDER);
return true;
}
case R.id.set_sort_flag: {
mMessageListFragment.changeSort(SortType.SORT_FLAGGED);
return true;
}
case R.id.set_sort_unread: {
mMessageListFragment.changeSort(SortType.SORT_UNREAD);
return true;
}
case R.id.set_sort_attach: {
mMessageListFragment.changeSort(SortType.SORT_ATTACHMENT);
return true;
}
case R.id.select_all: {
mMessageListFragment.selectAll();
return true;
}
case R.id.app_settings: {
onEditPrefs();
return true;
}
case R.id.account_settings: {
onEditAccount();
return true;
}
case R.id.search: {
mMessageListFragment.onSearchRequested();
return true;
}
case R.id.search_remote: {
mMessageListFragment.onRemoteSearch();
return true;
}
case R.id.mark_all_as_read: {
mMessageListFragment.confirmMarkAllAsRead();
return true;
}
case R.id.show_folder_list: {
onShowFolderList();
return true;
}
// MessageView
case R.id.next_message: {
showNextMessage();
return true;
}
case R.id.previous_message: {
showPreviousMessage();
return true;
}
case R.id.delete: {
mMessageViewFragment.onDelete();
return true;
}
case R.id.reply: {
mMessageViewFragment.onReply();
return true;
}
case R.id.reply_all: {
mMessageViewFragment.onReplyAll();
return true;
}
case R.id.forward: {
mMessageViewFragment.onForward();
return true;
}
case R.id.share: {
mMessageViewFragment.onSendAlternate();
return true;
}
case R.id.toggle_unread: {
mMessageViewFragment.onToggleRead();
return true;
}
case R.id.archive:
case R.id.refile_archive: {
mMessageViewFragment.onArchive();
return true;
}
case R.id.spam:
case R.id.refile_spam: {
mMessageViewFragment.onSpam();
return true;
}
case R.id.move:
case R.id.refile_move: {
mMessageViewFragment.onMove();
return true;
}
case R.id.copy:
case R.id.refile_copy: {
mMessageViewFragment.onCopy();
return true;
}
case R.id.select_text: {
mMessageViewFragment.onSelectText();
return true;
}
case R.id.show_headers:
case R.id.hide_headers: {
mMessageViewFragment.onToggleAllHeadersView();
updateMenu();
return true;
}
}
if (!mSingleFolderMode) {
// None of the options after this point are "safe" for search results
//TODO: This is not true for "unread" and "starred" searches in regular folders
return false;
}
switch (itemId) {
case R.id.send_messages: {
mMessageListFragment.onSendPendingMessages();
return true;
}
case R.id.folder_settings: {
if (mFolderName != null) {
FolderSettings.actionSettings(this, mAccount, mFolderName);
}
return true;
}
case R.id.expunge: {
mMessageListFragment.onExpunge();
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.message_list_option, menu);
mMenu = menu;
mMenuButtonCheckMail= menu.findItem(R.id.check_mail);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
configureMenu(menu);
return true;
}
/**
* Hide menu items not appropriate for the current context.
*
* <p><strong>Note:</strong>
* Please adjust the comments in {@code res/menu/message_list_option.xml} if you change the
* visibility of a menu item in this method.
* </p>
*
* @param menu
* The {@link Menu} instance that should be modified. May be {@code null}; in that case
* the method does nothing and immediately returns.
*/
private void configureMenu(Menu menu) {
if (menu == null) {
return;
}
// Set visibility of account/folder settings menu items
if (mMessageListFragment == null) {
menu.findItem(R.id.account_settings).setVisible(false);
menu.findItem(R.id.folder_settings).setVisible(false);
} else {
menu.findItem(R.id.account_settings).setVisible(
mMessageListFragment.isSingleAccountMode());
menu.findItem(R.id.folder_settings).setVisible(
mMessageListFragment.isSingleFolderMode());
}
/*
* Set visibility of menu items related to the message view
*/
if (mDisplayMode == DisplayMode.MESSAGE_LIST
|| mMessageViewFragment == null
|| !mMessageViewFragment.isInitialized()) {
menu.findItem(R.id.next_message).setVisible(false);
menu.findItem(R.id.previous_message).setVisible(false);
menu.findItem(R.id.single_message_options).setVisible(false);
menu.findItem(R.id.delete).setVisible(false);
menu.findItem(R.id.compose).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.copy).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
menu.findItem(R.id.refile).setVisible(false);
menu.findItem(R.id.toggle_unread).setVisible(false);
menu.findItem(R.id.select_text).setVisible(false);
menu.findItem(R.id.toggle_message_view_theme).setVisible(false);
menu.findItem(R.id.show_headers).setVisible(false);
menu.findItem(R.id.hide_headers).setVisible(false);
} else {
// hide prev/next buttons in split mode
if (mDisplayMode != DisplayMode.MESSAGE_VIEW) {
menu.findItem(R.id.next_message).setVisible(false);
menu.findItem(R.id.previous_message).setVisible(false);
} else {
MessageReference ref = mMessageViewFragment.getMessageReference();
boolean initialized = (mMessageListFragment != null &&
mMessageListFragment.isLoadFinished());
boolean canDoPrev = (initialized && !mMessageListFragment.isFirst(ref));
boolean canDoNext = (initialized && !mMessageListFragment.isLast(ref));
MenuItem prev = menu.findItem(R.id.previous_message);
prev.setEnabled(canDoPrev);
prev.getIcon().setAlpha(canDoPrev ? 255 : 127);
MenuItem next = menu.findItem(R.id.next_message);
next.setEnabled(canDoNext);
next.getIcon().setAlpha(canDoNext ? 255 : 127);
}
MenuItem toggleTheme = menu.findItem(R.id.toggle_message_view_theme);
if (K9.useFixedMessageViewTheme()) {
toggleTheme.setVisible(false);
} else {
// Set title of menu item to switch to dark/light theme
if (K9.getK9MessageViewTheme() == K9.Theme.DARK) {
toggleTheme.setTitle(R.string.message_view_theme_action_light);
} else {
toggleTheme.setTitle(R.string.message_view_theme_action_dark);
}
toggleTheme.setVisible(true);
}
// Set title of menu item to toggle the read state of the currently displayed message
if (mMessageViewFragment.isMessageRead()) {
menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_unread_action);
} else {
menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_read_action);
}
// Jellybean has built-in long press selection support
menu.findItem(R.id.select_text).setVisible(Build.VERSION.SDK_INT < 16);
menu.findItem(R.id.delete).setVisible(K9.isMessageViewDeleteActionVisible());
/*
* Set visibility of copy, move, archive, spam in action bar and refile submenu
*/
if (mMessageViewFragment.isCopyCapable()) {
menu.findItem(R.id.copy).setVisible(K9.isMessageViewCopyActionVisible());
menu.findItem(R.id.refile_copy).setVisible(true);
} else {
menu.findItem(R.id.copy).setVisible(false);
menu.findItem(R.id.refile_copy).setVisible(false);
}
if (mMessageViewFragment.isMoveCapable()) {
boolean canMessageBeArchived = mMessageViewFragment.canMessageBeArchived();
boolean canMessageBeMovedToSpam = mMessageViewFragment.canMessageBeMovedToSpam();
menu.findItem(R.id.move).setVisible(K9.isMessageViewMoveActionVisible());
menu.findItem(R.id.archive).setVisible(canMessageBeArchived &&
K9.isMessageViewArchiveActionVisible());
menu.findItem(R.id.spam).setVisible(canMessageBeMovedToSpam &&
K9.isMessageViewSpamActionVisible());
menu.findItem(R.id.refile_move).setVisible(true);
menu.findItem(R.id.refile_archive).setVisible(canMessageBeArchived);
menu.findItem(R.id.refile_spam).setVisible(canMessageBeMovedToSpam);
} else {
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
menu.findItem(R.id.refile).setVisible(false);
}
if (mMessageViewFragment.allHeadersVisible()) {
menu.findItem(R.id.show_headers).setVisible(false);
} else {
menu.findItem(R.id.hide_headers).setVisible(false);
}
}
/*
* Set visibility of menu items related to the message list
*/
// Hide both search menu items by default and enable one when appropriate
menu.findItem(R.id.search).setVisible(false);
menu.findItem(R.id.search_remote).setVisible(false);
if (mDisplayMode == DisplayMode.MESSAGE_VIEW || mMessageListFragment == null ||
!mMessageListFragment.isInitialized()) {
menu.findItem(R.id.check_mail).setVisible(false);
menu.findItem(R.id.set_sort).setVisible(false);
menu.findItem(R.id.select_all).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.mark_all_as_read).setVisible(false);
menu.findItem(R.id.show_folder_list).setVisible(false);
} else {
menu.findItem(R.id.set_sort).setVisible(true);
menu.findItem(R.id.select_all).setVisible(true);
menu.findItem(R.id.compose).setVisible(true);
menu.findItem(R.id.mark_all_as_read).setVisible(
mMessageListFragment.isMarkAllAsReadSupported());
if (!mMessageListFragment.isSingleAccountMode()) {
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.show_folder_list).setVisible(false);
} else {
menu.findItem(R.id.send_messages).setVisible(mMessageListFragment.isOutbox());
menu.findItem(R.id.expunge).setVisible(mMessageListFragment.isRemoteFolder() &&
mMessageListFragment.isAccountExpungeCapable());
menu.findItem(R.id.show_folder_list).setVisible(true);
}
menu.findItem(R.id.check_mail).setVisible(mMessageListFragment.isCheckMailSupported());
// If this is an explicit local search, show the option to search on the server
if (!mMessageListFragment.isRemoteSearch() &&
mMessageListFragment.isRemoteSearchAllowed()) {
menu.findItem(R.id.search_remote).setVisible(true);
} else if (!mMessageListFragment.isManualSearch()) {
menu.findItem(R.id.search).setVisible(true);
}
}
}
protected void onAccountUnavailable() {
finish();
// TODO inform user about account unavailability using Toast
Accounts.listAccounts(this);
}
public void setActionBarTitle(String title) {
mActionBarTitle.setText(title);
}
public void setActionBarSubTitle(String subTitle) {
mActionBarSubTitle.setText(subTitle);
}
public void setActionBarUnread(int unread) {
if (unread == 0) {
mActionBarUnread.setVisibility(View.GONE);
} else {
mActionBarUnread.setVisibility(View.VISIBLE);
mActionBarUnread.setText(String.format("%d", unread));
}
}
@Override
public void setMessageListTitle(String title) {
setActionBarTitle(title);
}
@Override
public void setMessageListSubTitle(String subTitle) {
setActionBarSubTitle(subTitle);
}
@Override
public void setUnreadCount(int unread) {
setActionBarUnread(unread);
}
@Override
public void setMessageListProgress(int progress) {
setProgress(progress);
}
@Override
public void openMessage(MessageReference messageReference) {
Preferences prefs = Preferences.getPreferences(getApplicationContext());
Account account = prefs.getAccount(messageReference.getAccountUuid());
String folderName = messageReference.getFolderName();
if (folderName.equals(account.getDraftsFolderName())) {
MessageActions.actionEditDraft(this, messageReference);
} else {
mMessageViewContainer.removeView(mMessageViewPlaceHolder);
if (mMessageListFragment != null) {
mMessageListFragment.setActiveMessage(messageReference);
}
MessageViewFragment fragment = MessageViewFragment.newInstance(messageReference);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.message_view_container, fragment);
mMessageViewFragment = fragment;
ft.commit();
if (mDisplayMode != DisplayMode.SPLIT_VIEW) {
showMessageView();
}
}
}
@Override
public void onResendMessage(MessageReference messageReference) {
MessageActions.actionEditDraft(this, messageReference);
}
@Override
public void onForward(MessageReference messageReference) {
onForward(messageReference, null);
}
@Override
public void onForward(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionForward(this, messageReference, decryptionResultForReply);
}
@Override
public void onReply(MessageReference messageReference) {
onReply(messageReference, null);
}
@Override
public void onReply(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionReply(this, messageReference, false, decryptionResultForReply);
}
@Override
public void onReplyAll(MessageReference messageReference) {
onReplyAll(messageReference, null);
}
@Override
public void onReplyAll(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionReply(this, messageReference, true, decryptionResultForReply);
}
@Override
public void onCompose(Account account) {
MessageActions.actionCompose(this, account);
}
@Override
public void showMoreFromSameSender(String senderAddress) {
LocalSearch tmpSearch = new LocalSearch("From " + senderAddress);
tmpSearch.addAccountUuids(mSearch.getAccountUuids());
tmpSearch.and(SearchField.SENDER, senderAddress, Attribute.CONTAINS);
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, false, false);
addMessageListFragment(fragment, true);
}
@Override
public void onBackStackChanged() {
findFragments();
if (mDisplayMode == DisplayMode.SPLIT_VIEW) {
showMessageViewPlaceHolder();
}
configureMenu(mMenu);
}
@Override
public void onSwipeRightToLeft(MotionEvent e1, MotionEvent e2) {
if (mMessageListFragment != null && mDisplayMode != DisplayMode.MESSAGE_VIEW) {
mMessageListFragment.onSwipeRightToLeft(e1, e2);
}
}
@Override
public void onSwipeLeftToRight(MotionEvent e1, MotionEvent e2) {
if (mMessageListFragment != null && mDisplayMode != DisplayMode.MESSAGE_VIEW) {
mMessageListFragment.onSwipeLeftToRight(e1, e2);
}
}
private final class StorageListenerImplementation implements StorageManager.StorageListener {
@Override
public void onUnmount(String providerId) {
if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) {
runOnUiThread(new Runnable() {
@Override
public void run() {
onAccountUnavailable();
}
});
}
}
@Override
public void onMount(String providerId) {
// no-op
}
}
private void addMessageListFragment(MessageListFragment fragment, boolean addToBackStack) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.message_list_container, fragment);
if (addToBackStack)
ft.addToBackStack(null);
mMessageListFragment = fragment;
int transactionId = ft.commit();
if (transactionId >= 0 && mFirstBackStackId < 0) {
mFirstBackStackId = transactionId;
}
}
@Override
public boolean startSearch(Account account, String folderName) {
// If this search was started from a MessageList of a single folder, pass along that folder info
// so that we can enable remote search.
if (account != null && folderName != null) {
final Bundle appData = new Bundle();
appData.putString(EXTRA_SEARCH_ACCOUNT, account.getUuid());
appData.putString(EXTRA_SEARCH_FOLDER, folderName);
startSearch(null, false, appData, false);
} else {
// TODO Handle the case where we're searching from within a search result.
startSearch(null, false, null, false);
}
return true;
}
@Override
public void showThread(Account account, String folderName, long threadRootId) {
showMessageViewPlaceHolder();
LocalSearch tmpSearch = new LocalSearch();
tmpSearch.addAccountUuid(account.getUuid());
tmpSearch.and(SearchField.THREAD_ID, String.valueOf(threadRootId), Attribute.EQUALS);
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, true, false);
addMessageListFragment(fragment, true);
}
private void showMessageViewPlaceHolder() {
removeMessageViewFragment();
// Add placeholder view if necessary
if (mMessageViewPlaceHolder.getParent() == null) {
mMessageViewContainer.addView(mMessageViewPlaceHolder);
}
mMessageListFragment.setActiveMessage(null);
}
/**
* Remove MessageViewFragment if necessary.
*/
private void removeMessageViewFragment() {
if (mMessageViewFragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(mMessageViewFragment);
mMessageViewFragment = null;
ft.commit();
showDefaultTitleView();
}
}
private void removeMessageListFragment() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(mMessageListFragment);
mMessageListFragment = null;
ft.commit();
}
@Override
public void remoteSearchStarted() {
// Remove action button for remote search
configureMenu(mMenu);
}
@Override
public void goBack() {
FragmentManager fragmentManager = getFragmentManager();
if (mDisplayMode == DisplayMode.MESSAGE_VIEW) {
showMessageList();
} else if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
} else if (mMessageListFragment.isManualSearch()) {
finish();
} else if (!mSingleFolderMode) {
onAccounts();
} else {
onShowFolderList();
}
}
@Override
public void enableActionBarProgress(boolean enable) {
if (mMenuButtonCheckMail != null && mMenuButtonCheckMail.isVisible()) {
mActionBarProgress.setVisibility(ProgressBar.GONE);
if (enable) {
mMenuButtonCheckMail
.setActionView(mActionButtonIndeterminateProgress);
} else {
mMenuButtonCheckMail.setActionView(null);
}
} else {
if (mMenuButtonCheckMail != null)
mMenuButtonCheckMail.setActionView(null);
if (enable) {
mActionBarProgress.setVisibility(ProgressBar.VISIBLE);
} else {
mActionBarProgress.setVisibility(ProgressBar.GONE);
}
}
}
@Override
public void displayMessageSubject(String subject) {
if (mDisplayMode == DisplayMode.MESSAGE_VIEW) {
mActionBarSubject.setText(subject);
} else {
mActionBarSubject.showSubjectInMessageHeader();
}
}
@Override
public void showNextMessageOrReturn() {
if (K9.messageViewReturnToList() || !showLogicalNextMessage()) {
if (mDisplayMode == DisplayMode.SPLIT_VIEW) {
showMessageViewPlaceHolder();
} else {
showMessageList();
}
}
}
/**
* Shows the next message in the direction the user was displaying messages.
*
* @return {@code true}
*/
private boolean showLogicalNextMessage() {
boolean result = false;
if (mLastDirection == NEXT) {
result = showNextMessage();
} else if (mLastDirection == PREVIOUS) {
result = showPreviousMessage();
}
if (!result) {
result = showNextMessage() || showPreviousMessage();
}
return result;
}
@Override
public void setProgress(boolean enable) {
setProgressBarIndeterminateVisibility(enable);
}
@Override
public void messageHeaderViewAvailable(MessageHeader header) {
mActionBarSubject.setMessageHeader(header);
}
private boolean showNextMessage() {
MessageReference ref = mMessageViewFragment.getMessageReference();
if (ref != null) {
if (mMessageListFragment.openNext(ref)) {
mLastDirection = NEXT;
return true;
}
}
return false;
}
private boolean showPreviousMessage() {
MessageReference ref = mMessageViewFragment.getMessageReference();
if (ref != null) {
if (mMessageListFragment.openPrevious(ref)) {
mLastDirection = PREVIOUS;
return true;
}
}
return false;
}
private void showMessageList() {
mMessageListWasDisplayed = true;
mDisplayMode = DisplayMode.MESSAGE_LIST;
mViewSwitcher.showFirstView();
mMessageListFragment.setActiveMessage(null);
showDefaultTitleView();
configureMenu(mMenu);
}
private void showMessageView() {
mDisplayMode = DisplayMode.MESSAGE_VIEW;
if (!mMessageListWasDisplayed) {
mViewSwitcher.setAnimateFirstView(false);
}
mViewSwitcher.showSecondView();
showMessageTitleView();
configureMenu(mMenu);
}
@Override
public void updateMenu() {
invalidateOptionsMenu();
}
@Override
public void disableDeleteAction() {
mMenu.findItem(R.id.delete).setEnabled(false);
}
private void onToggleTheme() {
if (K9.getK9MessageViewTheme() == K9.Theme.DARK) {
K9.setK9MessageViewThemeSetting(K9.Theme.LIGHT);
} else {
K9.setK9MessageViewThemeSetting(K9.Theme.DARK);
}
new Thread(new Runnable() {
@Override
public void run() {
Context appContext = getApplicationContext();
Preferences prefs = Preferences.getPreferences(appContext);
StorageEditor editor = prefs.getStorage().edit();
K9.save(editor);
editor.commit();
}
}).start();
recreate();
}
private void showDefaultTitleView() {
mActionBarMessageView.setVisibility(View.GONE);
mActionBarMessageList.setVisibility(View.VISIBLE);
if (mMessageListFragment != null) {
mMessageListFragment.updateTitle();
}
mActionBarSubject.setMessageHeader(null);
}
private void showMessageTitleView() {
mActionBarMessageList.setVisibility(View.GONE);
mActionBarMessageView.setVisibility(View.VISIBLE);
if (mMessageViewFragment != null) {
displayMessageSubject(null);
mMessageViewFragment.updateTitle();
}
}
@Override
public void onSwitchComplete(int displayedChild) {
if (displayedChild == 0) {
removeMessageViewFragment();
}
}
@Override
public void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags) throws SendIntentException {
requestCode |= REQUEST_MASK_PENDING_INTENT;
super.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode & REQUEST_MASK_PENDING_INTENT) == REQUEST_MASK_PENDING_INTENT) {
requestCode ^= REQUEST_MASK_PENDING_INTENT;
if (mMessageViewFragment != null) {
mMessageViewFragment.onPendingIntentResult(requestCode, resultCode, data);
}
}
}
}
|
package aspectMatlab;
import natlab.DecIntNumericLiteralValue;
import natlab.toolkits.analysis.varorfun.FunctionVFDatum;
import natlab.toolkits.analysis.varorfun.VFFlowset;
import natlab.toolkits.analysis.varorfun.VFPreorderAnalysis;
import natlab.toolkits.analysis.varorfun.ValueDatumPair;
import ast.*;
import ast.List;
import ast.Properties;
import java.util.*;
public class AspectsEngine {
static Map<ASTNode, VFFlowset<String, FunctionVFDatum>> vfaMap;
static LinkedList<action> actionsList = new LinkedList<action>();
static LinkedList<pattern> patternsList = new LinkedList<pattern>();
static ArrayList<String> aspectList = new ArrayList<String>();
//Advice
static final public String AFTER = "after";
static final public String BEFORE = "before";
static final public String AROUND = "around";
//Patterns
static final public String SET = "set";
static final public String GET = "get";
static final public String CALL = "call";
static final public String EXECUTION = "execution";
static final public String LOOP = "loop";
static final public String LOOPBODY = "loopbody";
static final public String LOOPHEAD = "loophead";
//Selectors
static final public String ARGS = "args";
static final public String DIMS = "dims";
static final public String NEWVAL = "newVal";
static final public String OBJ = "obj";
static final public String THIS = "this";
static final public String NAME = "name";
static final public String LINE = "line";
static final public String COUNTER = "counter";
static final public String LOC = "loc";
//Misc.
static final public String PROCEED_FUN_NAME = "proceed";
static final public String GLOBAL_STRUCTURE = "AM_GLOBAL";
static final public String LOCAL_CHECK = "AM_EntryPoint_";
static final public String AM_CF_SCRIPT = "AM_CF_Script_";
static final public String AM_CF_VAR = "AM_CVar_";
//Around Advice Arguments
static final public Name CF_OUTPUT = new Name("varargout");
static final public Name CF_INPUT_CASE = new Name("AM_caseNum");
static final public Name CF_INPUT_OBJ = new Name("AM_obj");
static final public Name CF_INPUT_AGRS = new Name("AM_args");
static public int correspondingCount = 0;
public static int getCorrespondingCount() { return correspondingCount; }
private static String generateCorrespondingFunctionName(){
return AM_CF_SCRIPT + correspondingCount++;
}
private static String generateCorrespondingVariableName(){
return AM_CF_VAR + correspondingCount++;
}
static public int entrypointCount = 0;
private static String generateEntrypointCountVariableName(){
return LOCAL_CHECK + entrypointCount++;
}
public static void analysis(ASTNode cu){
VFPreorderAnalysis vfa = new VFPreorderAnalysis(cu);
vfa.analyze();
vfaMap = vfa.getFlowSets();
System.out.println(vfa.getCurrentSet().toString());
}
public static FunctionVFDatum checkVarOrFun(ASTNode node, String target){
java.util.List<ValueDatumPair<String, FunctionVFDatum>> fset = vfaMap.get(node).toList();
for(ValueDatumPair<String, FunctionVFDatum> vdp : fset){
if(vdp.getValue().compareTo(target) == 0)
return vdp.getDatum();
}
return new FunctionVFDatum();
}
private static String generateActionName(String aspect, String action){
return aspect + "_" + action;
}
public static void fetchAspectInfo(Program prog)
{
Aspect aspect = (Aspect) prog;
aspectList.add(aspect.getName());
for(Patterns patterns : aspect.getPatterns())
for(Pattern pattern : patterns.getPatterns())
{
String name = pattern.getName();
PatternDesignator pd = (PatternDesignator) pattern.getPD();
String type = pd.getName();
String variable = "";
if(pd.getArgs().getNumChild() > 0) {
variable = pd.getArgs().getChild(pd.getArgs().getNumChild()-1).getID();
variable = variable.substring(variable.lastIndexOf('.')+1);
}
String target = variable;
String dims = "-1";
boolean more = false;
if(variable.contains("$")) {
target = variable.substring(0, variable.lastIndexOf('$'));
dims = variable.substring(variable.lastIndexOf('$')+1);
if(dims.contains("+")) {
more = true;
dims = dims.substring(0, dims.lastIndexOf('+'));
}
}
patternsList.add(new pattern(name, type, target, Integer.valueOf(dims), more));
}
for(Actions lst : aspect.getActions())
for(AspectAction action : lst.getAspectActions())
{
String name = action.getName();
String type = action.getType();
String pattern = action.getPattern();
String modifiedName = generateActionName(aspect.getName(), name);
pattern pat = null;
for(int i = 0; i<patternsList.size(); i++) {
pattern tmp = patternsList.get(i);
if(tmp.getName().compareTo(pattern) == 0) {
pat = tmp;
break;
}
}
Function fun = new Function();
if(type.compareTo(AROUND) != 0)
fun = new Function(new ast.List<Name>(), modifiedName, action.getSelectors(), new ast.List<HelpComment>(), action.getStmts(), action.getNestedFunctions());
else
fun = createAroundFunction(modifiedName, action, true);
actionsList.add(new action(modifiedName, type, pat, fun, aspect.getName()));
}
}
public static ClassDef convertToClass(Program prog)
{
Aspect aspect = (Aspect) prog;
ClassDef out = new ClassDef();
out.setName(aspect.getName());
SuperClass sc = new SuperClass();
sc.setName("handle");
out.setSuperClass(sc, 0);
for(Properties propertys : aspect.getPropertys())
out.addProperty(propertys);
for(Methods methods : aspect.getMethods())
out.addMethod(methods);
Methods methods = new Methods();
for(Actions actions : aspect.getActions())
for(AspectAction action : actions.getAspectActions())
{
String name = action.getName();
String type = action.getType();
String modifiedName = generateActionName(aspect.getName(), name);
if(type.compareTo(AROUND) != 0) {
ast.List<Name> input = action.getSelectors();
input.insertChild(new Name(THIS), 0);
methods.addFunction(new Function(new ast.List<Name>(), modifiedName, input, new ast.List<HelpComment>(), action.getStmts(), action.getNestedFunctions()));
} else
methods.addFunction(createAroundFunction(modifiedName, action, false));
}
out.addMethod(methods);
return out;
}
public static void generateCorrespondingStmt(Expr pe) {
if(pe.getWeavability() && !pe.getCFStmtDone()) {
String target = pe.FetchTargetExpr();
for(pattern pat : patternsList) {
if((pat.getType().compareTo(GET) == 0 || pat.getType().compareTo(CALL) == 0)
&& (pat.getTarget().compareTo(target) == 0 || pat.getTarget().compareTo("*") == 0)
) {
ASTNode node = pe;
while(node != null && !(node instanceof Stmt))
node = node.getParent();
//No need for ExprStmt
if(pe.getParent() instanceof ExprStmt)
return;
//Multiple values return from function
if(pe.getParent() instanceof AssignStmt){
Expr exp = ((AssignStmt)node).getLHS();
if(exp instanceof MatrixExpr){
//TODO: how to weave
exp.setWeavability(false);
return;
}
}
//AssignStmt inside ForStmt header
if(node != null)
if(node instanceof AssignStmt && node.getParent() instanceof ForStmt)
node = node.getParent();
if(node != null) {
String var = generateCorrespondingVariableName();
Expr lhs = new NameExpr(new Name(var));
lhs.setWeavability(false);
pe.setCFStmtDone(true);
AssignStmt stmt = new AssignStmt((Expr) lhs.copy(), (Expr) pe.copy());
stmt.setOutputSuppressed(true);
int ind = pe.getParent().getIndexOfChild(pe);
pe.getParent().setChild(lhs, ind);
ind = node.getParent().getIndexOfChild(node);
node.getParent().insertChild(stmt, ind);
//Condition of WhileStmt
if(node instanceof WhileStmt){
WhileStmt ws = (WhileStmt)node;
ws.getStmts().add(stmt);
ws.WeaveLoopStmts(stmt, true);
}
}
return;
}
}
//No match
pe.setWeavability(false);
}
}
public static void generateCorrespondingStmt(List<Stmt> stmts, List<Name> input) {
for(int i = input.getNumChild()-1; i>= 0; i
Name pe = input.getChild(i);
String target = pe.getID();
for(pattern pat : patternsList) {
if(pat.getType().compareTo(SET) == 0 &&
(pat.getTarget().compareTo(target) == 0 || pat.getTarget().compareTo("*") == 0)) {
String var = generateCorrespondingVariableName();
Expr rhs = new NameExpr(new Name(var));
rhs.setWeavability(false);
AssignStmt stmt = new AssignStmt(new NameExpr(pe), rhs);
stmt.setOutputSuppressed(true);
stmts.insertChild(stmt, 0);
input.setChild(new Name(var), i);
break;
}
}
}
}
/*
public static void generateCorrespondingFunction(Expr pe) {
if(pe.getWeavability()) {
String target = pe.FetchTargetExpr();
for(pattern pat : patternsList) {
if((pat.getType().compareTo(GET) == 0 || pat.getType().compareTo(CALL) == 0) &&
(pat.getTarget().compareTo(target) == 0 || pat.getTarget().compareTo("*") == 0)) {
ASTNode node = pe;
while(node != null && !(node instanceof Function || node instanceof PropertyAccess || node instanceof Script))
node = node.getParent();
if(node != null) {
Function corFun = null;
IntLiteralExpr ile = null;
if(node instanceof Function) {
Function prog = (Function)node;
corFun = prog.getCorrespondingFunction();
if(corFun == null) {
String funName = "AM_CF_" + prog.getName();
corFun = createCorrespondingFunction(funName, false);
prog.addNestedFunction(corFun);
prog.setCorrespondingFunction(corFun);
}
ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(prog.getCorrespondingCount())));
prog.incCorrespondingCount();
addSwitchCaseToCorrespondingFunction(pe, corFun, ile, false);
insertCallToCorrespondingFunction(pe, corFun, ile, false);
} else if(node instanceof PropertyAccess) {
PropertyAccess prog = (PropertyAccess)node;
corFun = prog.getCorrespondingFunction();
if(corFun == null) {
String funName = "AM_CF_" + prog.getAccess() + "_" + prog.getName();
corFun = createCorrespondingFunction(funName, false);
prog.addNestedFunction(corFun);
prog.setCorrespondingFunction(corFun);
}
ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(prog.getCorrespondingCount())));
prog.incCorrespondingCount();
addSwitchCaseToCorrespondingFunction(pe, corFun, ile, false);
insertCallToCorrespondingFunction(pe, corFun, ile, false);
} else if(node instanceof Script) {
Script prog = (Script)node;
corFun = prog.getCorrespondingFunction();
if(corFun == null) {
String funName = generateCorrespondingFunctionName();
corFun = createCorrespondingFunction(funName, true);
prog.getParent().addChild(new FunctionList(new ast.List<Function>().add(corFun)));
prog.setCorrespondingFunction(corFun);
}
ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(prog.getCorrespondingCount())));
prog.incCorrespondingCount();
addSwitchCaseToCorrespondingFunction(pe, corFun, ile, true);
insertCallToCorrespondingFunction(pe, corFun, ile, true);
}
}
return;
}
}
}
}
private static void addSwitchCaseToCorrespondingFunction(Expr pe, Function corFun, IntLiteralExpr ile, boolean isScript){
Expr exp = (Expr) pe.copy();
Expr tmp = (Expr) pe.copy();
ast.List<Expr> input = new ast.List<Expr>();
if(exp instanceof ParameterizedExpr || exp instanceof CellIndexExpr) {
int size = 0;
if(exp instanceof ParameterizedExpr) {
size = ((ParameterizedExpr)exp).getArgs().getNumChild();
tmp = ((ParameterizedExpr)exp).getTarget();
} else if(exp instanceof CellIndexExpr) {
size = ((CellIndexExpr)exp).getArgs().getNumChild();
tmp = ((CellIndexExpr)exp).getTarget();
}
for(int i=1; i<=size; i++)
input.add(new CellIndexExpr(new NameExpr(CF_INPUT_AGRS), new ast.List<Expr>().add(new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(i))))));
if(exp instanceof ParameterizedExpr)
exp = new ParameterizedExpr(((ParameterizedExpr)exp).getTarget(), input);
else if(exp instanceof CellIndexExpr)
exp = new CellIndexExpr(((CellIndexExpr)exp).getTarget(), input);
}
ast.List<Stmt> scsl = new ast.List<Stmt>();
AssignStmt tmpStmt = new AssignStmt();
if(isScript) {
Expr exp1 = new NameExpr(new Name("AM_tmp_" + tmp.FetchTargetExpr()));
tmpStmt = new AssignStmt(exp1, new NameExpr(CF_INPUT_OBJ));
tmpStmt.setOutputSuppressed(true);
tmpStmt.setWeavability(false, true);
scsl.add(tmpStmt);
if(exp instanceof ParameterizedExpr)
exp = new ParameterizedExpr(exp1, input);
else if(exp instanceof CellIndexExpr)
exp = new CellIndexExpr(exp1, input);
else
exp = exp1;
}
Expr lhs = new NameExpr(CF_OUTPUT);
lhs.setWeavability(false);
exp.setWeavability(true);
AssignStmt stmt = new AssignStmt(lhs, exp);
stmt.setOutputSuppressed(true);
scsl.add(stmt);
SwitchCaseBlock scb = new SwitchCaseBlock(ile, scsl);
SwitchStmt ss = (SwitchStmt) corFun.getStmt(0);
ss.addSwitchCaseBlock(scb);
}
private static void insertCallToCorrespondingFunction(Expr pe, Function corFun, IntLiteralExpr ile, boolean isScript){
ast.List<Expr> input = new ast.List<Expr>().add(ile);
ast.List<Expr> args = new ast.List<Expr>();
Expr tmp = (Expr) pe.copy();
if(pe instanceof ParameterizedExpr) {
args = ((ParameterizedExpr)pe).getArgs();
tmp = ((ParameterizedExpr)pe).getTarget();
} else if(pe instanceof CellIndexExpr) {
args = ((CellIndexExpr)pe).getArgs();
tmp = ((CellIndexExpr)pe).getTarget();
}
IfStmt ifstmt = new IfStmt();
if(isScript) {
ast.List<Expr> lst = new ast.List<Expr>().add(new StringLiteralExpr(tmp.FetchTargetExpr()));
lst.add(new StringLiteralExpr("var"));
ParameterizedExpr exist = new ParameterizedExpr(new NameExpr(new Name("exist")), lst);
BinaryExpr cond = new NEExpr(exist, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
AssignStmt eas = new AssignStmt(tmp, new StringLiteralExpr("AM_tmp_" + tmp.FetchTargetExpr()));
eas.setOutputSuppressed(true);
eas.setWeavability(false, true);
IfBlock ib = new IfBlock(cond, new ast.List<Stmt>().add(eas));
ifstmt = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>());
ASTNode node = pe;
while(node != null && !(node instanceof Stmt))
node = node.getParent();
if(node != null) {
int ind = node.getParent().getIndexOfChild(node);
node.getParent().insertChild(ifstmt, ind);
}
input.add(tmp);
}
CellArrayExpr values = new CellArrayExpr();
values.addRow(new Row(args));
input.add(values);
ParameterizedExpr call = new ParameterizedExpr(new NameExpr(new Name(corFun.getName())), input);
call.setWeavability(false);
int ind = pe.getParent().getIndexOfChild(pe);
pe.getParent().setChild(call, ind);
}
*/
private static Function createAroundFunction(String modifiedName, AspectAction action, boolean isConvertProceed){
ast.List<Name> output = new ast.List<Name>();
output.add(CF_OUTPUT);
ast.List<Name> input = action.getSelectors();
ast.List<Function> nf = action.getNestedFunctions();
if(isConvertProceed) {
input.add(CF_INPUT_CASE);
input.add(CF_INPUT_OBJ);
input.add(CF_INPUT_AGRS);
convertProceedCalls(action.getStmts());
Function pf = createCorrespondingFunction(PROCEED_FUN_NAME, true);
pf.setOutputParamList(new List<Name>());
nf.add(pf);
} else
input.insertChild(new Name(THIS), 0);
return new Function(output, modifiedName, input, new ast.List<HelpComment>(), action.getStmts(), nf);
}
private static Function createCorrespondingFunction(String funName, boolean isScript){
ast.List<Name> output = new ast.List<Name>();
output.add(CF_OUTPUT);
ast.List<Name> input = new ast.List<Name>();
input.add(CF_INPUT_CASE);
if(isScript)
input.add(CF_INPUT_OBJ);
input.add(CF_INPUT_AGRS);
SwitchStmt ss = new SwitchStmt(new NameExpr(CF_INPUT_CASE), new ast.List<SwitchCaseBlock>(), new Opt<DefaultCaseBlock>());
ast.List<Stmt> sl = new ast.List<Stmt>();
sl.add(ss);
return new Function(output, funName, input, new ast.List<HelpComment>(), sl, new ast.List<Function>());
}
private static void convertProceedCalls(ast.List<Stmt> stmts){
for(Stmt stmt : stmts) {
stmt.ProceedTransformation();
}
}
public static void transformProceedCall(Expr pe){
if(pe.FetchTargetExpr().compareTo("proceed") == 0) {
ast.List<Expr> input = new ast.List<Expr>();
input.add(new NameExpr(CF_INPUT_CASE));
input.add(new NameExpr(CF_INPUT_OBJ));
input.add(new NameExpr(CF_INPUT_AGRS));
ParameterizedExpr call = new ParameterizedExpr(new NameExpr(new Name(PROCEED_FUN_NAME)), input);
int ind = pe.getParent().getIndexOfChild(pe);
pe.getParent().setChild(call, ind);
}
}
/*
private static int matchAndWeave(ast.List<Stmt> stmts, int s, String type, String target, AssignStmt context) {
Expr rhs = context.getRHS();
Expr lhs = context.getLHS();
int count = 0;
for(int j=0; j<actionsList.size(); j++)
{
action act = actionsList.get(j);
pattern pat = act.getPattern();
if(pat.getType().compareTo(type) == 0 && pat.getTarget().compareTo(target) == 0){
Function fun = act.getFunction();
NameExpr funcName = new NameExpr(new Name(act.getName()));
ast.List<Expr> lstExpr = new ast.List<Expr>();
for(Name param : fun.getInputParams()) {
if(param.getID().compareTo(NEWVAL) == 0) {
lstExpr.add(getNewVal(rhs));
} else if(param.getID().compareTo(ARGS) == 0) {
if(pat.getType().compareTo(CALL) == 0)
lstExpr.add(getDims(rhs));
else
lstExpr.add(new CellArrayExpr());
} else if(param.getID().compareTo(DIMS) == 0) {
if(pat.getType().compareTo(SET) == 0)
lstExpr.add(getDims(lhs));
else if(pat.getType().compareTo(GET) == 0)
lstExpr.add(getDims(rhs));
else
lstExpr.add(new CellArrayExpr());
} else if(param.getID().compareTo(CF_INPUT_CASE.getID()) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
lstExpr.add(ile);
} else if(param.getID().compareTo(CF_INPUT_OBJ.getID()) == 0) {
lstExpr.add(new NameExpr(new Name(target)));
} else if(param.getID().compareTo(CF_INPUT_AGRS.getID()) == 0) {
if(pat.getType().compareTo(SET) == 0)
lstExpr.add(rhs);
else //get, call
lstExpr.add(getDims(rhs));
} else
lstExpr.add(new CellArrayExpr());
}
ParameterizedExpr pe = new ParameterizedExpr(funcName, lstExpr);
Stmt action;
if(act.getType().compareTo(AROUND) == 0)
action = new AssignStmt(lhs, pe);
else
action = new ExprStmt(pe);
Stmt call = action;
action.setOutputSuppressed(true);
if(!(pat.getDims().compareTo("0") == 0)) {
BinaryExpr cond = null;
if(!pat.getDimsAndMore())
cond = new EQExpr(new NameExpr(new Name("numel("+target+")")), new NameExpr(new Name(pat.getDims())));
else
cond = new GEExpr(new NameExpr(new Name("numel("+target+")")), new NameExpr(new Name(pat.getDims())));
IfBlock ib = new IfBlock(cond, new ast.List<Stmt>().add(action));
call = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>());
if(act.getType().compareTo(AROUND) == 0) {
AssignStmt eas = new AssignStmt(lhs, rhs);
eas.setOutputSuppressed(true);
ElseBlock eb = new ElseBlock(new ast.List<Stmt>().add(eas));
call = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>(eb));
}
}
if(act.getType().compareTo(BEFORE) == 0) {
stmts.insertChild(call, s);
count += 1;
} else if(act.getType().compareTo(AFTER) == 0) {
stmts.insertChild(call, s+1);
count += 1;
} else if(act.getType().compareTo(AROUND) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
addSwitchCaseToAroundCorrespondingFunction(rhs, fun.getNestedFunction(0), ile, type);
fun.incCorrespondingCount();
//context.setRHS(pe);
stmts.setChild(call, s);
}
}
}
return count;
}
*/
private static int setMatchAndWeave(ast.List<Stmt> stmts, int s, String target, AssignStmt context) {
Expr rhs = context.getRHS();
Expr lhs = context.getLHS();
int args = lhs.FetchArgsCount();
int acount = 0, bcount = 0, tcount= 0;
for(int j=0; j<actionsList.size(); j++)
{
action act = actionsList.get(j);
pattern pat = act.getPattern();
if(pat.getType().compareTo(SET) == 0 && (pat.getTarget().compareTo(target) == 0 || pat.getTarget().compareTo("*") == 0)
&& (pat.getDims() == -1 || (!pat.getDimsAndMore() && pat.getDims() == args) || (pat.getDimsAndMore() && pat.getDims() <= args))
){
Function fun = act.getFunction();
ast.List<Expr> lstExpr = new ast.List<Expr>();
Expr nv = null;
boolean objExist = false;
for(Name param : fun.getInputParams()) {
if(param.getID().compareTo(NEWVAL) == 0 || param.getID().compareTo(CF_INPUT_AGRS.getID()) == 0) {
if(nv == null){
if(rhs instanceof IntLiteralExpr || rhs instanceof FPLiteralExpr || rhs instanceof StringLiteralExpr) {
nv = rhs;
} else if(rhs.getWeavability() && !rhs.getCFStmtDone()) {
String var = generateCorrespondingVariableName();
Expr tmp = new NameExpr(new Name(var));
AssignStmt stmt = new AssignStmt((Expr) tmp.copy(), (Expr) rhs.copy());
stmt.setOutputSuppressed(true);
tmp.setWeavability(false);
rhs.setWeavability(false);
rhs.setCFStmtDone(true);
int ind = context.getIndexOfChild(rhs);
context.setChild(tmp, ind);
ind = context.getParent().getIndexOfChild(context);
context.getParent().insertChild(stmt, ind);
nv = tmp;
tcount = 1;
} else if(!rhs.getWeavability()){
nv = rhs;
}
}
if(param.getID().compareTo(CF_INPUT_AGRS.getID()) == 0){
CellArrayExpr cae = new CellArrayExpr();
Row row = new Row();
row.addElement(nv);
cae.addRow(row);
lstExpr.add(cae);
} else
lstExpr.add(nv);
} else if(param.getID().compareTo(ARGS) == 0) {
lstExpr.add(getDims(lhs));
} else if(param.getID().compareTo(CF_INPUT_CASE.getID()) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
lstExpr.add(ile);
} else if(param.getID().compareTo(OBJ) == 0 || param.getID().compareTo(CF_INPUT_OBJ.getID()) == 0) {
objExist = true;
lstExpr.add(new NameExpr(new Name(target)));
} else if(param.getID().compareTo(THIS) == 0) {
//do nothing
} else if(param.getID().compareTo(NAME) == 0) {
lstExpr.add(new StringLiteralExpr(target));
} else if(param.getID().compareTo(LINE) == 0) {
lstExpr.add(new IntLiteralExpr(new DecIntNumericLiteralValue(String.valueOf(context.getLine(context.getStart())))));
} else if(param.getID().compareTo(LOC) == 0) {
lstExpr.add(new StringLiteralExpr(getLocation(context)));
} else
lstExpr.add(new CellArrayExpr());
}
Expr de1 = new DotExpr(new NameExpr(new Name(GLOBAL_STRUCTURE)), new Name(act.getClassName()));
Expr de2 = new DotExpr(de1, new Name(act.getName()));
ParameterizedExpr pe = new ParameterizedExpr(de2, lstExpr);
Stmt action;
if(act.getType().compareTo(AROUND) == 0)
action = new AssignStmt(lhs, pe);
else
action = new ExprStmt(pe);
Stmt call = action;
action.setOutputSuppressed(true);
Stmt existCheck = null;
if(objExist){
ast.List<Expr> elst = new ast.List<Expr>().add(new StringLiteralExpr(target));
elst.add(new StringLiteralExpr("var"));
ParameterizedExpr exist = new ParameterizedExpr(new NameExpr(new Name("exist")), elst);
BinaryExpr cond = new NEExpr(exist, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
AssignStmt tmp = new AssignStmt(new NameExpr(new Name(target)), new MatrixExpr());
tmp.setWeavability(false, true);
tmp.setOutputSuppressed(true);
IfBlock ib = new IfBlock(cond, new ast.List<Stmt>().add(tmp));
existCheck = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>());
}
if(act.getType().compareTo(BEFORE) == 0) {
stmts.insertChild(call, s+tcount);
if(existCheck != null){
stmts.insertChild(existCheck, s+tcount);
tcount += 1;
}
bcount += 1;
} else if(act.getType().compareTo(AFTER) == 0) {
stmts.insertChild(call, s+acount+bcount+tcount+1);
acount += 1;
} else if(act.getType().compareTo(AROUND) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
addSwitchCaseToAroundCorrespondingFunction(lhs, rhs, fun.getNestedFunction(0), ile, SET);
fun.incCorrespondingCount();
stmts.setChild(call, s+bcount+tcount);
if(existCheck != null){
stmts.insertChild(existCheck, s+bcount+tcount);
tcount += 1;
}
}
}
}
return acount + bcount + tcount;
}
private static int getOrCallMatchAndWeave(ast.List<Stmt> stmts, int s, String target, AssignStmt context, FunctionVFDatum varOrFun) {
Expr rhs = context.getRHS();
Expr lhs = context.getLHS();
int acount = 0, bcount = 0;
int args = rhs.FetchArgsCount();
for(int j=0; j<actionsList.size(); j++)
{
action act = actionsList.get(j);
pattern pat = act.getPattern();
if((pat.getType().compareTo(GET) == 0 || pat.getType().compareTo(CALL) == 0)
&& (pat.getTarget().compareTo(target) == 0 || pat.getTarget().compareTo("*") == 0)
&& (pat.getDims() == -1 || (!pat.getDimsAndMore() && pat.getDims() == args) || (pat.getDimsAndMore() && pat.getDims() <= args))
){
Function fun = act.getFunction();
ast.List<Expr> lstExpr = new ast.List<Expr>();
for(Name param : fun.getInputParams()) {
if(param.getID().compareTo(ARGS) == 0) {
lstExpr.add(getDims(rhs));
} else if(param.getID().compareTo(CF_INPUT_CASE.getID()) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
lstExpr.add(ile);
} else if(param.getID().compareTo(CF_INPUT_OBJ.getID()) == 0) {
if(pat.getType().compareTo(CALL) == 0){
if(varOrFun != null && (varOrFun.isFunction() || varOrFun.isBottom())) //inside function
lstExpr.add(new FunctionHandleExpr(new Name(target)));
else if(varOrFun == null) //inside script
lstExpr.add(new ParameterizedExpr(new NameExpr(new Name("eval")), new List<Expr>().add(new StringLiteralExpr("@"+target))));
else
lstExpr.add(new CellArrayExpr());
}
else
lstExpr.add(new NameExpr(new Name(target)));
} else if(param.getID().compareTo(CF_INPUT_AGRS.getID()) == 0) {
lstExpr.add(getDims(rhs));
} else if(param.getID().compareTo(THIS) == 0) {
//do nothing
} else if(param.getID().compareTo(NAME) == 0) {
lstExpr.add(new StringLiteralExpr(target));
} else if(param.getID().compareTo(OBJ) == 0) {
if(pat.getType().compareTo(GET) == 0)
lstExpr.add(new NameExpr(new Name(target)));
//lstExpr.add(new ParameterizedExpr(new NameExpr(new Name("eval")), new List<Expr>().add(new StringLiteralExpr(target))));
else
lstExpr.add(new MatrixExpr());
} else if(param.getID().compareTo(LINE) == 0) {
lstExpr.add(new IntLiteralExpr(new DecIntNumericLiteralValue(String.valueOf(context.getLine(context.getStart())))));
} else if(param.getID().compareTo(LOC) == 0) {
lstExpr.add(new StringLiteralExpr(getLocation(context)));
} else
lstExpr.add(new CellArrayExpr());
}
Expr de1 = new DotExpr(new NameExpr(new Name(GLOBAL_STRUCTURE)), new Name(act.getClassName()));
Expr de2 = new DotExpr(de1, new Name(act.getName()));
ParameterizedExpr pe = new ParameterizedExpr(de2, lstExpr);
Stmt action;
if(act.getType().compareTo(AROUND) == 0)
action = new AssignStmt(lhs, pe);
else
action = new ExprStmt(pe);
action.setOutputSuppressed(true);
Stmt call;
if(varOrFun != null){ //function
call = action;
} else { //script
BinaryExpr cond;
ast.List<Expr> elst = new ast.List<Expr>().add(new StringLiteralExpr(target));
elst.add(new StringLiteralExpr("var"));
ParameterizedExpr exist = new ParameterizedExpr(new NameExpr(new Name("exist")), elst);
if(pat.getType().compareTo(GET) == 0)
cond = new EQExpr(exist, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
else
cond = new NEExpr(exist, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
IfBlock ib = new IfBlock(cond, new ast.List<Stmt>().add(action));
Stmt outerIf = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>());
if(act.getType().compareTo(AROUND) == 0) {
AssignStmt eas = new AssignStmt(lhs, rhs);
eas.setOutputSuppressed(true);
ElseBlock eb = new ElseBlock(new ast.List<Stmt>().add(eas));
outerIf = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>(eb));
}
call = outerIf;
}
if(varOrFun == null || (varOrFun != null && (((varOrFun.isFunction() || varOrFun.isBottom()) && pat.getType().compareTo(CALL) == 0) || (varOrFun.isVariable() && pat.getType().compareTo(GET) == 0)))){
if(act.getType().compareTo(BEFORE) == 0) {
stmts.insertChild(call, s);
bcount += 1;
} else if(act.getType().compareTo(AFTER) == 0) {
stmts.insertChild(call, s+bcount+acount+1);
acount += 1;
} else if(act.getType().compareTo(AROUND) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
addSwitchCaseToAroundCorrespondingFunction(lhs, rhs, fun.getNestedFunction(0), ile, pat.getType());
fun.incCorrespondingCount();
stmts.setChild(call, s+bcount);
}
}
}
}
return acount + bcount;
}
/* private static int getOrCallMatchAndWeave(ast.List<Stmt> stmts, int s, String target, AssignStmt context) {
Expr rhs = context.getRHS();
Expr lhs = context.getLHS();
int acount = 0, bcount = 0;
for(int j=0; j<actionsList.size(); j++)
{
action act = actionsList.get(j);
pattern pat = act.getPattern();
if((pat.getType().compareTo(GET) == 0 || pat.getType().compareTo(CALL) == 0)
&& (pat.getTarget().compareTo(target) == 0 || pat.getTarget().compareTo("*") == 0)){
Function fun = act.getFunction();
ast.List<Expr> lstExpr = new ast.List<Expr>();
for(Name param : fun.getInputParams()) {
if(param.getID().compareTo(ARGS) == 0) {
//if(pat.getType().compareTo(CALL) == 0)
lstExpr.add(getDims(rhs));
//else
//lstExpr.add(new CellArrayExpr());
} else if(param.getID().compareTo(DIMS) == 0) {
//if(pat.getType().compareTo(GET) == 0)
// lstExpr.add(getDims(rhs));
//else
lstExpr.add(new CellArrayExpr());
} else if(param.getID().compareTo(CF_INPUT_CASE.getID()) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
lstExpr.add(ile);
} else if(param.getID().compareTo(CF_INPUT_OBJ.getID()) == 0) {
if(pat.getType().compareTo(CALL) == 0)
lstExpr.add(new FunctionHandleExpr(new Name(target)));
else
lstExpr.add(new NameExpr(new Name(target)));
} else if(param.getID().compareTo(CF_INPUT_AGRS.getID()) == 0) {
lstExpr.add(getDims(rhs));
} else if(param.getID().compareTo(THIS) == 0) {
//do nothing
} else if(param.getID().compareTo(NAME) == 0) {
lstExpr.add(new StringLiteralExpr(target));
} else if(param.getID().compareTo(OBJ) == 0) {
if(pat.getType().compareTo(GET) == 0)
lstExpr.add(new NameExpr(new Name(target)));
else
lstExpr.add(new CellArrayExpr());
} else if(param.getID().compareTo(LINE) == 0) {
lstExpr.add(new IntLiteralExpr(new DecIntNumericLiteralValue(String.valueOf(context.getLine(context.getStart())))));
} else if(param.getID().compareTo(LOC) == 0) {
lstExpr.add(new StringLiteralExpr(getLocation(context)));
} else
lstExpr.add(new CellArrayExpr());
}
Expr de1 = new DotExpr(new NameExpr(new Name(GLOBAL_STRUCTURE)), new Name(act.getClassName()));
Expr de2 = new DotExpr(de1, new Name(act.getName()));
ParameterizedExpr pe = new ParameterizedExpr(de2, lstExpr);
Stmt action;
if(act.getType().compareTo(AROUND) == 0)
action = new AssignStmt(lhs, pe);
else
action = new ExprStmt(pe);
Stmt call = action;
action.setOutputSuppressed(true);
BinaryExpr cond;
// ASTNode node = stmts;
// while(node != null && !(node instanceof Function))
// node = node.getParent();
// boolean isScriptCF = false;
// ParameterizedExpr strcmp = new ParameterizedExpr();
//
// if(node != null && ((Function)node).getName().startsWith(AM_CF_SCRIPT)) {
// isScriptCF = true;
// ast.List<Expr> lst = new ast.List<Expr>().add(new NameExpr(CF_INPUT_OBJ));
// lst.add(new StringLiteralExpr("AM_tmp_" + target));
// strcmp = new ParameterizedExpr(new NameExpr(new Name("strcmp")), lst);
// }
//ast.List<Expr> nlst = new ast.List<Expr>().add(new NameExpr(new Name(target)));
//ParameterizedExpr numel = new ParameterizedExpr(new NameExpr(new Name("numel")), nlst);
ast.List<Expr> elst = new ast.List<Expr>().add(new StringLiteralExpr(target));
elst.add(new StringLiteralExpr("var"));
ParameterizedExpr exist = new ParameterizedExpr(new NameExpr(new Name("exist")), elst);
if(pat.getType().compareTo(GET) == 0) {
// if(!(pat.getDims().compareTo("0") == 0)) {
// BinaryExpr cond2;
//
// if(!pat.getDimsAndMore())
// cond2 = new EQExpr(numel, new NameExpr(new Name(pat.getDims())));
// else
// cond2 = new EQExpr(numel, new NameExpr(new Name(pat.getDims())));
//
// IfBlock ib = new IfBlock(cond2, new ast.List<Stmt>().add(action));
// call = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>());
//
// if(act.getType().compareTo(AROUND) == 0) {
// AssignStmt eas = new AssignStmt(lhs, rhs);
// eas.setOutputSuppressed(true);
// ElseBlock eb = new ElseBlock(new ast.List<Stmt>().add(eas));
// call = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>(eb));
// }
// }
//if(isScriptCF)
// cond = new NEExpr(strcmp, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
//else
cond = new EQExpr(exist, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
} else {
//if(isScriptCF)
// cond = new EQExpr(strcmp, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
//else
cond = new NEExpr(exist, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
}
IfBlock ib = new IfBlock(cond, new ast.List<Stmt>().add(call));
Stmt outerIf = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>());
if(act.getType().compareTo(AROUND) == 0) {
AssignStmt eas = new AssignStmt(lhs, rhs);
eas.setOutputSuppressed(true);
ElseBlock eb = new ElseBlock(new ast.List<Stmt>().add(eas));
outerIf = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>(eb));
}
if(act.getType().compareTo(BEFORE) == 0) {
stmts.insertChild(outerIf, s);
bcount += 1;
} else if(act.getType().compareTo(AFTER) == 0) {
stmts.insertChild(outerIf, s+bcount+acount+1);
acount += 1;
} else if(act.getType().compareTo(AROUND) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
addSwitchCaseToAroundCorrespondingFunction(lhs, rhs, fun.getNestedFunction(0), ile, pat.getType());
fun.incCorrespondingCount();
stmts.setChild(outerIf, s+bcount);
}
}
}
return acount + bcount;
}*/
private static int exprMatchAndWeave(ast.List<Stmt> stmts, int s, String target, ExprStmt context, FunctionVFDatum varOrFun) {
Expr rhs = context.getExpr();
int acount = 0, bcount = 0;
int args = rhs.FetchArgsCount();
for(int j=0; j<actionsList.size(); j++)
{
action act = actionsList.get(j);
pattern pat = act.getPattern();
if((pat.getType().compareTo(GET) == 0 || pat.getType().compareTo(CALL) == 0)
&& (pat.getTarget().compareTo(target) == 0 || pat.getTarget().compareTo("*") == 0)
&& (pat.getDims() == -1 || (!pat.getDimsAndMore() && pat.getDims() == args) || (pat.getDimsAndMore() && pat.getDims() <= args))
){
Function fun = act.getFunction();
ast.List<Expr> lstExpr = new ast.List<Expr>();
for(Name param : fun.getInputParams()) {
if(param.getID().compareTo(ARGS) == 0) {
lstExpr.add(getDims(rhs));
} else if(param.getID().compareTo(CF_INPUT_CASE.getID()) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
lstExpr.add(ile);
} else if(param.getID().compareTo(CF_INPUT_OBJ.getID()) == 0) {
if(pat.getType().compareTo(CALL) == 0){
if(varOrFun != null && (varOrFun.isFunction() || varOrFun.isBottom())) //inside function
lstExpr.add(new FunctionHandleExpr(new Name(target)));
else if(varOrFun == null) //inside script
lstExpr.add(new ParameterizedExpr(new NameExpr(new Name("eval")), new List<Expr>().add(new StringLiteralExpr("@"+target))));
else
lstExpr.add(new CellArrayExpr());
}
else
lstExpr.add(new NameExpr(new Name(target)));
} else if(param.getID().compareTo(CF_INPUT_AGRS.getID()) == 0) {
lstExpr.add(getDims(rhs));
} else if(param.getID().compareTo(THIS) == 0) {
//do nothing
} else if(param.getID().compareTo(NAME) == 0) {
lstExpr.add(new StringLiteralExpr(target));
} else if(param.getID().compareTo(OBJ) == 0) {
if(pat.getType().compareTo(GET) == 0)
lstExpr.add(new NameExpr(new Name(target)));
//lstExpr.add(new ParameterizedExpr(new NameExpr(new Name("eval")), new List<Expr>().add(new StringLiteralExpr(target))));
else
lstExpr.add(new MatrixExpr());
} else if(param.getID().compareTo(LINE) == 0) {
lstExpr.add(new IntLiteralExpr(new DecIntNumericLiteralValue(String.valueOf(context.getLine(context.getStart())))));
} else if(param.getID().compareTo(LOC) == 0) {
lstExpr.add(new StringLiteralExpr(getLocation(context)));
} else
lstExpr.add(new CellArrayExpr());
}
Expr de1 = new DotExpr(new NameExpr(new Name(GLOBAL_STRUCTURE)), new Name(act.getClassName()));
Expr de2 = new DotExpr(de1, new Name(act.getName()));
ParameterizedExpr pe = new ParameterizedExpr(de2, lstExpr);
Stmt action = new ExprStmt(pe);
action.setOutputSuppressed(true);
Stmt call;
if(varOrFun != null){ //function
call = action;
} else { //script
BinaryExpr cond;
ast.List<Expr> elst = new ast.List<Expr>().add(new StringLiteralExpr(target));
elst.add(new StringLiteralExpr("var"));
ParameterizedExpr exist = new ParameterizedExpr(new NameExpr(new Name("exist")), elst);
if(pat.getType().compareTo(GET) == 0)
cond = new EQExpr(exist, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
else
cond = new NEExpr(exist, new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1))));
IfBlock ib = new IfBlock(cond, new ast.List<Stmt>().add(action));
Stmt outerIf = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>());
call = outerIf;
}
if(varOrFun == null || (varOrFun != null && (((varOrFun.isFunction() || varOrFun.isBottom()) && pat.getType().compareTo(CALL) == 0) || (varOrFun.isVariable() && pat.getType().compareTo(GET) == 0)))){
if(act.getType().compareTo(BEFORE) == 0) {
stmts.insertChild(call, s);
bcount += 1;
} else if(act.getType().compareTo(AFTER) == 0) {
stmts.insertChild(call, s+bcount+acount+1);
acount += 1;
} else if(act.getType().compareTo(AROUND) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
addSwitchCaseToAroundCorrespondingFunction(null, rhs, fun.getNestedFunction(0), ile, pat.getType());
fun.incCorrespondingCount();
stmts.setChild(call, s+bcount);
}
}
}
}
return acount + bcount;
}
private static void addSwitchCaseToAroundCorrespondingFunction(Expr lhs, Expr pe, Function corFun, IntLiteralExpr ile, String type){
Expr exp = (Expr) pe.copy();
Expr tmp = (Expr) pe.copy();
ast.List<Expr> input = new ast.List<Expr>();
if(exp instanceof ParameterizedExpr || exp instanceof CellIndexExpr) {
int size = 0;
if(exp instanceof ParameterizedExpr) {
size = ((ParameterizedExpr)exp).getArgs().getNumChild();
tmp = ((ParameterizedExpr)exp).getTarget();
} else if(exp instanceof CellIndexExpr) {
size = ((CellIndexExpr)exp).getArgs().getNumChild();
tmp = ((CellIndexExpr)exp).getTarget();
}
for(int i=1; i<=size; i++)
input.add(new CellIndexExpr(new NameExpr(CF_INPUT_AGRS), new ast.List<Expr>().add(new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(i))))));
if(exp instanceof ParameterizedExpr)
exp = new ParameterizedExpr(((ParameterizedExpr)exp).getTarget(), input);
else if(exp instanceof CellIndexExpr)
exp = new CellIndexExpr(((CellIndexExpr)exp).getTarget(), input);
}
ast.List<Stmt> scsl = new ast.List<Stmt>();
AssignStmt tmpStmt = new AssignStmt();
if(type.compareTo(SET) == 0 || type.compareTo(LOOPHEAD) == 0) {
exp = new CellIndexExpr(new NameExpr(CF_INPUT_AGRS), new ast.List<Expr>().add(new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1)))));
} else if(type.compareTo(EXECUTION) == 0 || type.compareTo(CALL) == 0) {
exp = new ParameterizedExpr(new NameExpr(CF_INPUT_OBJ), input);
} else {
tmpStmt = new AssignStmt(tmp, new NameExpr(CF_INPUT_OBJ));
tmpStmt.setOutputSuppressed(true);
tmpStmt.setWeavability(false, true);
scsl.add(tmpStmt);
}
Expr out = null;
if(lhs instanceof MatrixExpr){
MatrixExpr me = (MatrixExpr)lhs;
int size = me.getRow(0).getNumElement();
List<Expr> lst = new List<Expr>();
for(int i=1; i<=size; i++)
lst.add(new CellIndexExpr(new NameExpr(CF_OUTPUT), new ast.List<Expr>().add(new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(i))))));
out = new MatrixExpr(new List<Row>().add(new Row(lst)));
} else {
out = new CellIndexExpr(new NameExpr(CF_OUTPUT), new ast.List<Expr>().add(new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(1)))));
}
Stmt stmt = new AssignStmt(out, exp);
if(lhs == null) //ExprStmt case
stmt = new ExprStmt(exp);
stmt.setOutputSuppressed(true);
scsl.add(stmt);
SwitchCaseBlock scb = new SwitchCaseBlock(ile, scsl);
SwitchStmt ss = (SwitchStmt) corFun.getStmt(0);
ss.addSwitchCaseBlock(scb);
}
private static void transformForStmt(ast.List<Stmt> stmts)
{
int stmtCount = stmts.getNumChild();
for(int s=0; s<stmtCount; s++)
{
if(stmts.getChild(s) instanceof ForStmt) {
ForStmt fs = (ForStmt) stmts.getChild(s);
if( !fs.isAspectTransformed() ) {
AssignStmt as_old = fs.getAssignStmt();
Expr lhs = as_old.getLHS();
String tmpAS = "AM_" + "tmpAS_";
String tmpFS = "AM_" + "tmpFS_";
if(lhs instanceof NameExpr){
NameExpr ne = (NameExpr) lhs;
tmpAS += ne.getName().getID();
tmpFS += ne.getName().getID();
}
AssignStmt as_out = new AssignStmt();
as_out.setRHS(as_old.getRHS());
as_out.setLHS(new NameExpr(new Name(tmpAS)));
as_out.setOutputSuppressed(true);
as_out.getLHS().setWeavability(false);
AssignStmt as_for = new AssignStmt();
as_for.setRHS(new RangeExpr(new IntLiteralExpr(new DecIntNumericLiteralValue("1")), new Opt<Expr>(), new ParameterizedExpr(new NameExpr(new Name("numel")), new ast.List<Expr>().add(as_out.getLHS()))));
as_for.setLHS(new NameExpr(new Name(tmpFS)));
as_for.setWeavability(false, true);
AssignStmt as_in = new AssignStmt();
as_in.setRHS(new ParameterizedExpr(new NameExpr(new Name(tmpAS)), new ast.List<Expr>().add(new NameExpr(new Name(tmpFS)))));
as_in.setLHS(as_old.getLHS());
as_in.setOutputSuppressed(true);
as_in.getRHS().setWeavability(false);
ast.List<Stmt> lstFor = new ast.List<Stmt>();
lstFor.add(as_in);
for(Stmt stmt : fs.getStmts())
lstFor.add(stmt);
ForStmt fs_new = new ForStmt();
fs_new.setAssignStmt(as_for);
fs_new.setStmtList(lstFor);
fs_new.setAspectTransformed(true);
fs_new.setLoopVar(lhs.FetchTargetExpr());
fs_new.setLoopHead(as_out);
stmts.removeChild(s);
stmts.insertChild(as_out, s);
stmts.insertChild(fs_new, s+1);
s++;
stmtCount++;
}
}
}
}
public static void transformWhileStmt(ast.List<Stmt> stmts)
{
int stmtCount = stmts.getNumChild();
for(int s=0; s<stmtCount; s++)
{
if(stmts.getChild(s) instanceof WhileStmt) {
WhileStmt ws = (WhileStmt) stmts.getChild(s);
if( !ws.isAspectTransformed() ) {
String var = generateCorrespondingVariableName();
Expr rhs = ws.getExpr();
Expr lhs = new NameExpr(new Name(var));
ws.setLoopVars(rhs.FetchTargetExpr());
rhs.aspectsCorrespondingFunctions();
AssignStmt as = new AssignStmt(lhs, rhs);
as.setOutputSuppressed(true);
lhs.setWeavability(false);
ws.setExpr(lhs);
stmts.insertChild(as, stmts.getIndexOfChild(ws));
//AssignStmt tmp = as.copy();
//ws.getStmtList().add(tmp);
//ws.WeaveLoopStmts(tmp, true);
ws.setLoopHead(as);
ws.setAspectTransformed(true);
s++;
stmtCount++;
}
}
}
}
public static void weaveGlobalStructure(CompilationUnits cu) {
for(int i=0; i < cu.getNumProgram(); i++) {
ast.List<Stmt> stmts = new ast.List<Stmt>();
GlobalStmt gs = new GlobalStmt(new ast.List<Name>().add(new Name(GLOBAL_STRUCTURE)));
gs.setOutputSuppressed(true);
stmts.add(gs);
//TODO: checkif it is first file?
String var = generateEntrypointCountVariableName();
Expr oirhs = new IntLiteralExpr(new DecIntNumericLiteralValue("0"));
Expr oerhs = new IntLiteralExpr(new DecIntNumericLiteralValue("1"));
Expr olhs = new NameExpr(new Name(var));
AssignStmt oias = new AssignStmt(olhs, oirhs);
AssignStmt oeas = new AssignStmt(olhs, oerhs);
oias.setOutputSuppressed(true);
oias.setWeavability(false, true);
oeas.setOutputSuppressed(true);
oeas.setWeavability(false, true);
UnaryExpr ocond = new NotExpr(new NameExpr(new Name("isempty("+GLOBAL_STRUCTURE+")")));
IfBlock oib = new IfBlock(ocond, new ast.List<Stmt>().add(oias));
ElseBlock oeb = new ElseBlock(new ast.List<Stmt>().add(oeas));
Stmt ois = new IfStmt(new ast.List<IfBlock>().add(oib), new Opt<ElseBlock>(oeb));
stmts.add(ois);
for(String s : aspectList){
Expr rhs = new NameExpr(new Name(s));
Expr lhs = new DotExpr(new NameExpr(new Name(GLOBAL_STRUCTURE)), new Name(s));
AssignStmt as = new AssignStmt(lhs, rhs);
as.setOutputSuppressed(true);
as.setWeavability(false, true);
UnaryExpr cond = new NotExpr(new NameExpr(new Name("isfield("+GLOBAL_STRUCTURE+", '"+s+"')")));
IfBlock ib = new IfBlock(cond, new ast.List<Stmt>().add(as));
Stmt is = new IfStmt(new ast.List<IfBlock>().add(ib), new Opt<ElseBlock>());
stmts.add(is);
}
Expr nrhs = new MatrixExpr();
Expr nlhs = new NameExpr(new Name(GLOBAL_STRUCTURE));
AssignStmt nas = new AssignStmt(nlhs, nrhs);
nas.setOutputSuppressed(true);
nas.setWeavability(false, true);
Expr ncond = new NameExpr(new Name(var));
IfBlock nib = new IfBlock(ncond, new ast.List<Stmt>().add(nas));
Stmt nis = new IfStmt(new ast.List<IfBlock>().add(nib), new Opt<ElseBlock>());
Program p = cu.getProgram(i);
p.weaveGlobalStructure(stmts, nis);
}
}
public static void weaveStmts(ast.List<Stmt> stmts)
{
transformForStmt(stmts);
transformWhileStmt(stmts);
ASTNode node = stmts;
while(node != null && !(node instanceof Function))
node = node.getParent();
int stmtCount = stmts.getNumChild();
for(int s=0; s<stmtCount; s++)
{
Stmt stmt = stmts.getChild(s);
if(stmt instanceof ExprStmt) {
ExprStmt es = ((ExprStmt)stmt);
Expr rhs = es.getExpr();
int count = 0;
String varName = "";
if(rhs.getWeavability()) {
varName = rhs.FetchTargetExpr();
if(varName.compareTo("") != 0) {
StringTokenizer st = new StringTokenizer(varName, ",");
while (st.hasMoreTokens()) {
String target = st.nextToken();
FunctionVFDatum varOrFun = null;
if(node != null)
varOrFun = checkVarOrFun(node, target);
count += exprMatchAndWeave(stmts, stmts.getIndexOfChild(stmt), target, es, varOrFun);
}
}
}
s += count;
stmtCount += count;
} else if(stmt instanceof AssignStmt) {
AssignStmt as = (AssignStmt) stmt;
if(as.getWeavability()) {
Expr lhs = as.getLHS();
Expr rhs = as.getRHS();
int count = 0;
String varName = "";
if(lhs.getWeavability()) {
varName = lhs.FetchTargetExpr();
if(varName.compareTo("") != 0) {
StringTokenizer st = new StringTokenizer(varName, ",");
while (st.hasMoreTokens()) {
count += setMatchAndWeave(stmts, stmts.getIndexOfChild(as), st.nextToken(), as);
}
}
}
//TODO: ???
s += count;
stmtCount += count;
count = 0;
if(rhs.getWeavability()) {
varName = rhs.FetchTargetExpr();
if(varName.compareTo("") != 0) {
StringTokenizer st = new StringTokenizer(varName, ",");
while (st.hasMoreTokens()) {
String target = st.nextToken();
FunctionVFDatum varOrFun = null;
if(node != null)
varOrFun = checkVarOrFun(node, target);
count += getOrCallMatchAndWeave(stmts, stmts.getIndexOfChild(as), target, as, varOrFun);
}
}
}
s += count;
stmtCount += count;
}
} else if(stmt instanceof ForStmt || stmt instanceof WhileStmt){
int count = weaveLoops(stmt);
//other heads of while
if(stmt instanceof WhileStmt){
WhileStmt ws = (WhileStmt)stmt;
ws.getStmtList().add(ws.getLoopHead());
ws.WeaveLoopStmts(ws.getLoopHead(), true);
}
s += count;
stmtCount += count;
stmt.aspectsWeave();
} else {
stmt.aspectsWeave();
}
}
}
private static String fetchLoopVariables(Stmt loop)
{
String loopVar = "";
if(loop instanceof ForStmt){
ForStmt fstmt = (ForStmt) loop;
loopVar = fstmt.getLoopVar();
} if(loop instanceof WhileStmt){
WhileStmt wstmt = (WhileStmt) loop;
loopVar = wstmt.getLoopVars();
}
return loopVar+",";
}
private static AssignStmt fetchLoopHeads(Stmt loop)
{
AssignStmt loopHead = null;
if(loop instanceof ForStmt){
ForStmt fstmt = (ForStmt) loop;
loopHead = fstmt.getLoopHead();
} if(loop instanceof WhileStmt){
WhileStmt wstmt = (WhileStmt) loop;
loopHead = wstmt.getLoopHead();
}
return loopHead;
}
public static int weaveLoops(Stmt loop)
{
String loopVar = fetchLoopVariables(loop);
AssignStmt head = fetchLoopHeads(loop);
int acount = 0, bcount = 0, tcount = 0;
ASTNode parent = loop.getParent();
for(int j=0; j<actionsList.size(); j++)
{
action act = actionsList.get(j);
pattern pat = act.getPattern();
if((pat.getType().compareTo(LOOP) == 0 || pat.getType().compareTo(LOOPBODY) == 0 || pat.getType().compareTo(LOOPHEAD) == 0)
&& (loopVar.contains(pat.getTarget()+",") || pat.getTarget().compareTo("*") == 0)){
Function fun = act.getFunction();
ast.List<Expr> lstExpr = new ast.List<Expr>();
Expr nv = null;
for(Name param : fun.getInputParams()) {
if(param.getID().compareTo(ARGS) == 0) {
if(loop instanceof ForStmt && !(pat.getType().compareTo(LOOPHEAD) == 0 && (act.getType().compareTo(BEFORE) == 0 || act.getType().compareTo(AROUND) == 0))){
CellArrayExpr cae = new CellArrayExpr();
Row row = new Row();
row.addElement(new NameExpr(new Name("AM_tmpAS_" + loopVar.replace(",", ""))));
cae.addRow(row);
lstExpr.add(cae);
//lstExpr.add(new NameExpr(new Name("AM_tmpAS_" + loopVar.replace(",", ""))));
} else
lstExpr.add(new CellArrayExpr());
} else if(param.getID().compareTo(CF_INPUT_CASE.getID()) == 0) {
if(pat.getType().compareTo(LOOPHEAD) == 0){
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
lstExpr.add(ile);
} else
lstExpr.add(new CellArrayExpr());
}
else if(param.getID().compareTo(NEWVAL) == 0 || param.getID().compareTo(CF_INPUT_AGRS.getID()) == 0) {
if(pat.getType().compareTo(LOOPHEAD) == 0){
if(nv == null){
//Expr nv = new CellArrayExpr();
Expr rhs = head.getRHS();
if(rhs.getWeavability() && !rhs.getCFStmtDone()) {
String var = generateCorrespondingVariableName();
Expr tmp = new NameExpr(new Name(var));
tmp.setWeavability(false);
rhs.setCFStmtDone(true);
AssignStmt stmt = new AssignStmt((Expr) tmp.copy(), (Expr) rhs.copy());
stmt.setOutputSuppressed(true);
int ind = head.getIndexOfChild(rhs);
head.setChild(tmp, ind);
ind = head.getParent().getIndexOfChild(head);
head.getParent().insertChild(stmt, ind);
nv = tmp;
tcount = 1;
//other heads of while
if(loop instanceof WhileStmt){
WhileStmt ws = (WhileStmt)loop;
ws.getStmtList().add(stmt);
ws.WeaveLoopStmts(stmt, true);
}
} else if(!rhs.getWeavability()){
nv = rhs;
}
}
if(param.getID().compareTo(CF_INPUT_AGRS.getID()) == 0){
CellArrayExpr cae = new CellArrayExpr();
Row row = new Row();
row.addElement(nv);
cae.addRow(row);
lstExpr.add(cae);
} else
lstExpr.add(nv);
} else
lstExpr.add(new CellArrayExpr());
}
else if(param.getID().compareTo(COUNTER) == 0) {
if(loop instanceof ForStmt && pat.getType().compareTo(LOOPBODY) == 0)
lstExpr.add(new NameExpr(new Name(loopVar.replace(",", ""))));
else
lstExpr.add(new CellArrayExpr());
} else if(param.getID().compareTo(THIS) == 0) {
//do nothing
} else if(param.getID().compareTo(LINE) == 0) {
lstExpr.add(new IntLiteralExpr(new DecIntNumericLiteralValue(String.valueOf(loop.getLine(loop.getStart())))));
} else if(param.getID().compareTo(LOC) == 0) {
lstExpr.add(new StringLiteralExpr(getLocation(loop)));
} else
lstExpr.add(new CellArrayExpr());
}
Expr de1 = new DotExpr(new NameExpr(new Name(GLOBAL_STRUCTURE)), new Name(act.getClassName()));
Expr de2 = new DotExpr(de1, new Name(act.getName()));
ParameterizedExpr pe = new ParameterizedExpr(de2, lstExpr);
Stmt call = new ExprStmt(pe);
call.setOutputSuppressed(true);
if(pat.getType().compareTo(LOOP) == 0){
//ASTNode parent = loop.getParent();
if(act.getType().compareTo(BEFORE) == 0) {
parent.insertChild(call, parent.getIndexOfChild(loop));
bcount += 1;
} else if(act.getType().compareTo(AFTER) == 0) {
parent.insertChild(call, parent.getIndexOfChild(loop)+1);
acount += 1;
} else if(act.getType().compareTo(AROUND) == 0) {
//TODO
}
} else if(pat.getType().compareTo(LOOPBODY) == 0){
if(act.getType().compareTo(BEFORE) == 0) {
if(loop instanceof ForStmt)
loop.getChild(1).insertChild(call, 1);
else
loop.getChild(1).insertChild(call, 0);
} else if(act.getType().compareTo(AFTER) == 0) {
loop.getChild(1).addChild(call);
//continue, break, return
loop.WeaveLoopStmts(call, false);
} else if(act.getType().compareTo(AROUND) == 0) {
//TODO
}
} else if(pat.getType().compareTo(LOOPHEAD) == 0){
if(act.getType().compareTo(BEFORE) == 0) {
parent.insertChild(call, parent.getIndexOfChild(head));
bcount += 1;
//other heads of while
if(loop instanceof WhileStmt){
WhileStmt ws = (WhileStmt)loop;
ws.getStmtList().add(call);
ws.WeaveLoopStmts(call, true);
}
} else if(act.getType().compareTo(AFTER) == 0) {
parent.insertChild(call, parent.getIndexOfChild(head)+1);
acount += 1;
//other heads of while
if(loop instanceof WhileStmt){
WhileStmt ws = (WhileStmt)loop;
ws.getStmtList().add(call);
ws.WeaveLoopStmts(call, true);
}
} else if(act.getType().compareTo(AROUND) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
addSwitchCaseToAroundCorrespondingFunction(head.getLHS(), head.getRHS(), fun.getNestedFunction(0), ile, LOOPHEAD);
fun.incCorrespondingCount();
head.setRHS(pe);
}
}
}
}
return acount + bcount + tcount;
}
public static void WeaveLoopStmts(ast.List<Stmt> stmts, Stmt call, boolean onlyContinue){
int count = stmts.getNumChild();
for(int i=0; i<count; i++) {
Stmt stmt = stmts.getChild(i);
if(stmt instanceof BreakStmt || stmt instanceof ContinueStmt || stmt instanceof ReturnStmt){
if((!onlyContinue && (stmt instanceof BreakStmt || stmt instanceof ReturnStmt)) || stmt instanceof ContinueStmt){
ASTNode<ASTNode> parent = stmt.getParent();
parent.insertChild(call, parent.getIndexOfChild(stmt));
i++; count++;
}
} else
stmt.WeaveLoopStmts(call, onlyContinue);
}
}
public static void weaveFunction(Function func)
{
for(int j=0; j<actionsList.size(); j++)
{
action act = actionsList.get(j);
pattern pat = act.getPattern();
if(pat.getType().compareTo(EXECUTION) == 0 && (pat.getTarget().compareTo(func.getName()) == 0 || pat.getTarget().compareTo("*") == 0)){
Function fun = act.getFunction();
NameExpr funcName = new NameExpr(new Name(act.getName()));
ast.List<Expr> lstExpr = new ast.List<Expr>();
for(Name param : fun.getInputParams()) {
if(param.getID().compareTo(ARGS) == 0 || param.getID().compareTo(CF_INPUT_AGRS.getID()) == 0) {
CellArrayExpr args = new CellArrayExpr();
Row row = new Row();
for(Name arg : func.getInputParams()) {
row.addElement(new NameExpr(arg));
}
args.addRow(row);
lstExpr.add(args);
} else if(param.getID().compareTo(CF_INPUT_CASE.getID()) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
lstExpr.add(ile);
} else if(param.getID().compareTo(CF_INPUT_OBJ.getID()) == 0) {
lstExpr.add(new FunctionHandleExpr(new Name(generateHandleName(func.getName()))));
} else if(param.getID().compareTo(THIS) == 0) {
//do nothing
} else if(param.getID().compareTo(NAME) == 0) {
lstExpr.add(new StringLiteralExpr(func.getName()));
} else if(param.getID().compareTo(OBJ) == 0) {
//TODO: ???
//lstExpr.add(new FunctionHandleExpr(new Name(func.getName())));
lstExpr.add(new CellArrayExpr());
} else if(param.getID().compareTo(LINE) == 0) {
lstExpr.add(new IntLiteralExpr(new DecIntNumericLiteralValue(String.valueOf(func.getLine(func.getStart())))));
} else if(param.getID().compareTo(LOC) == 0) {
lstExpr.add(new StringLiteralExpr(func.getName()));
} else
lstExpr.add(new CellArrayExpr());
}
Expr de1 = new DotExpr(new NameExpr(new Name(GLOBAL_STRUCTURE)), new Name(act.getClassName()));
Expr de2 = new DotExpr(de1, new Name(act.getName()));
ParameterizedExpr pe = new ParameterizedExpr(de2, lstExpr);
List<Expr> lst = new List<Expr>();
for(Name arg : func.getOutputParams())
lst.add((new NameExpr(arg)));
Expr out = new MatrixExpr(new List<Row>().add(new Row(lst)));
Stmt call;
if(act.getType().compareTo(AROUND) == 0)
call = new AssignStmt(out, pe);
else
call = new ExprStmt(pe);
call.setOutputSuppressed(true);
if(act.getType().compareTo(BEFORE) == 0) {
func.getStmts().insertChild(call, 0);
} else if(act.getType().compareTo(AFTER) == 0) {
func.getStmts().addChild(call);
} else if(act.getType().compareTo(AROUND) == 0) {
IntLiteralExpr ile = new IntLiteralExpr(new DecIntNumericLiteralValue(Integer.toString(fun.getCorrespondingCount())));
convertToHandleFunction(func);
ast.List<Expr> tmp = new ast.List<Expr>();
for(Name arg : func.getInputParams()) {
tmp.add(new NameExpr(arg));
}
ParameterizedExpr tmp_pe = new ParameterizedExpr(funcName, tmp);
addSwitchCaseToAroundCorrespondingFunction(out, tmp_pe, fun.getNestedFunction(0), ile, EXECUTION);
fun.incCorrespondingCount();
func.getStmts().addChild(call);
}
}
}
}
private static String generateHandleName(String func){
return "AM_Handle_" + func;
}
private static void convertToHandleFunction(Function func){
Function handle = new Function(func.getOutputParams(), generateHandleName(func.getName()), func.getInputParams(), new ast.List<HelpComment>(), func.getStmts(), func.getNestedFunctions());
func.setStmtList(new ast.List<Stmt>());
func.setNestedFunctionList(new ast.List<Function>());
func.addNestedFunction(handle);
}
/*
private static CellArrayExpr getNewVal(Expr exp){
CellArrayExpr nv = new CellArrayExpr();
if(exp instanceof IntLiteralExpr || exp instanceof FPLiteralExpr || exp instanceof StringLiteralExpr) {
nv.addRow(new Row(new ast.List<Expr>().add(exp)));
}
return nv;
}
*/
private static CellArrayExpr getDims(Expr exp){
CellArrayExpr dims = new CellArrayExpr();
if(exp instanceof ParameterizedExpr) {
ParameterizedExpr pe = (ParameterizedExpr) exp;
dims.addRow(new Row(pe.getArgs()));
}
return dims;
}
private static String getLocation(ASTNode exp){
String loc = "";
ASTNode node = exp;
while(node != null && !(node instanceof Function || node instanceof Script))
node = node.getParent();
if(node != null){
if(node instanceof Script)
loc = "Script";
else
loc = ((Function)node).getName();
}
return loc;
}
}
class pattern {
private String name;
private String type; //TODO: complicated patterns
private String target;
private int dims;
private boolean dimsAndMore;
public pattern(String nam, String typ, String tar, int dim, boolean mor) {
name = nam;
type = typ;
target = tar;
dims = dim;
dimsAndMore = mor;
}
public void setName(String nam) { name = nam; }
public void setType(String typ) { type = typ; }
public void setTarget(String tar) { target = tar; }
public void setDims(int dim) { dims = dim; }
public void setDimsAndMore(boolean mor) { dimsAndMore = mor; }
public String getName() { return name; }
public String getType() { return type; }
public String getTarget() { return target; }
public int getDims() { return dims; }
public boolean getDimsAndMore() { return dimsAndMore; }
}
class action {
private String name;
private String type;
private pattern patt;
private Function func;
private String className;
public action(String nam, String typ, pattern pat, Function fun, String cName) {
name = nam;
type = typ;
patt = pat;
func = fun;
className = cName;
}
public void setName(String nam) { name = nam; }
public void setType(String typ) { type = typ; }
public void setPattern(pattern pat) { patt = pat; }
public void setFunction(Function fun) { func = fun; }
public void setClassName(String name) { className = name; }
public String getName() { return name; }
public String getType() { return type; }
public pattern getPattern() { return patt; }
public Function getFunction() { return func; }
public String getClassName() { return className; }
}
|
package com.alamkanak.weekview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.widget.OverScroller;
import android.widget.Scroller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class WeekView extends View {
@Deprecated
public static final int LENGTH_SHORT = 1;
@Deprecated
public static final int LENGTH_LONG = 2;
private final Context mContext;
private Calendar mHomeDate;
private Calendar mMinDate;
private Calendar mMaxDate;
private Paint mTimeTextPaint;
private float mTimeTextWidth;
private float mTimeTextHeight;
private Paint mHeaderTextPaint;
private float mHeaderTextHeight;
private GestureDetectorCompat mGestureDetector;
private OverScroller mScroller;
private PointF mCurrentOrigin = new PointF(0f, 0f);
private Direction mCurrentScrollDirection = Direction.NONE;
private Paint mHeaderBackgroundPaint;
private float mWidthPerDay;
private Paint mDayBackgroundPaint;
private Paint mHourSeparatorPaint;
private float mHeaderMarginBottom;
private Paint mTodayBackgroundPaint;
private Paint mTodayHeaderTextPaint;
private Paint mEventBackgroundPaint;
private float mHeaderColumnWidth;
private List<EventRect> mEventRects;
private TextPaint mEventTextPaint;
private Paint mHeaderColumnBackgroundPaint;
private Scroller mStickyScroller;
private int mFetchedMonths[] = new int[3];
private boolean mRefreshEvents = false;
private float mDistanceY = 0;
private float mDistanceX = 0;
private Direction mCurrentFlingDirection = Direction.NONE;
// Attributes and their default values.
private int mHourHeight = 50;
private int mColumnGap = 10;
private int mFirstDayOfWeek = Calendar.MONDAY;
private int mTextSize = 12;
private int mHeaderColumnPadding = 10;
private int mHeaderColumnTextColor = Color.BLACK;
private int mNumberOfVisibleDays = 3;
private int mHeaderRowPadding = 10;
private int mHeaderRowBackgroundColor = Color.WHITE;
private int mDayBackgroundColor = Color.rgb(245, 245, 245);
private int mHourSeparatorColor = Color.rgb(230, 230, 230);
private int mTodayBackgroundColor = Color.rgb(239, 247, 254);
private int mHourSeparatorHeight = 2;
private int mTodayHeaderTextColor = Color.rgb(39, 137, 228);
private int mEventTextSize = 12;
private int mEventTextColor = Color.BLACK;
private int mEventPadding = 8;
private int mHeaderColumnBackgroundColor = Color.WHITE;
private int mDefaultEventColor;
private boolean mIsFirstDraw = true;
private boolean mAreDimensionsInvalid = true;
@Deprecated private int mDayNameLength = LENGTH_LONG;
private int mOverlappingEventGap = 0;
private int mEventMarginVertical = 0;
private float mXScrollingSpeed = 1f;
private Calendar mFirstVisibleDay;
private Calendar mLastVisibleDay;
private Calendar mScrollToDay = null;
private double mScrollToHour = -1;
// Listeners.
private EventClickListener mEventClickListener;
private EventLongPressListener mEventLongPressListener;
private MonthChangeListener mMonthChangeListener;
private EmptyViewClickListener mEmptyViewClickListener;
private EmptyViewLongPressListener mEmptyViewLongPressListener;
private DateTimeInterpreter mDateTimeInterpreter;
private ScrollListener mScrollListener;
private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (mCurrentScrollDirection == Direction.NONE) {
if (Math.abs(distanceX) > Math.abs(distanceY)){
mCurrentScrollDirection = Direction.HORIZONTAL;
mCurrentFlingDirection = Direction.HORIZONTAL;
}
else {
mCurrentFlingDirection = Direction.VERTICAL;
mCurrentScrollDirection = Direction.VERTICAL;
}
}
mDistanceX = distanceX * mXScrollingSpeed;
mDistanceY = distanceY;
// Update the origin, enforcing the scroll limits
if (mCurrentScrollDirection == Direction.HORIZONTAL) {
float minX = getXMinLimit(), maxX = getXMaxLimit();
if (mCurrentOrigin.x - mDistanceX > maxX)
mCurrentOrigin.x = maxX;
else if (mCurrentOrigin.x - mDistanceX < minX)
mCurrentOrigin.x = minX;
else
mCurrentOrigin.x -= mDistanceX;
} else if (mCurrentScrollDirection == Direction.VERTICAL) {
float minY = getYMinLimit(), maxY = getYMaxLimit();
if (mCurrentOrigin.y - mDistanceY > maxY)
mCurrentOrigin.y = maxY;
else if (mCurrentOrigin.y - mDistanceY < minY)
mCurrentOrigin.y = minY;
else
mCurrentOrigin.y -= mDistanceY;
}
invalidate();
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
if (mCurrentFlingDirection == Direction.HORIZONTAL){
mScroller.fling((int) mCurrentOrigin.x, 0, (int) (velocityX * mXScrollingSpeed), 0, (int) getXMinLimit(), (int) getXMaxLimit(), 0, 0);
}
else if (mCurrentFlingDirection == Direction.VERTICAL){
mScroller.fling(0, (int) mCurrentOrigin.y, 0, (int) velocityY, 0, 0, (int) getYMinLimit(), (int) getYMaxLimit());
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// If the tap was on an event then trigger the callback.
if (mEventRects != null && mEventClickListener != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
return super.onSingleTapConfirmed(e);
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewClickListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mEmptyViewClickListener.onEmptyViewClicked(selectedTime);
}
}
return super.onSingleTapConfirmed(e);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mEventLongPressListener != null && mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return;
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewLongPressListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
mEmptyViewLongPressListener.onEmptyViewLongPress(selectedTime);
}
}
}
};
private enum Direction {
NONE, HORIZONTAL, VERTICAL
}
public WeekView(Context context) {
this(context, null);
}
public WeekView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WeekView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Hold references.
mContext = context;
// Get the attribute values (if any).
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0);
try {
mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek);
mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight);
mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics()));
mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding);
mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap);
mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor);
mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays);
mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding);
mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor);
mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor);
mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor);
mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor);
mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight);
mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor);
mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics()));
mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor);
mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mEventPadding);
mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor);
mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength);
mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap);
mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical);
mXScrollingSpeed = a.getFloat(R.styleable.WeekView_xScrollingSpeed, mXScrollingSpeed);
} finally {
a.recycle();
}
init();
}
private void init() {
// Initialize the home date, which will be day zero for layout purposes (other days have a
// positive or negative offset relative to the home date)
resetHomeDate();
// Scrolling initialization.
mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener);
mScroller = new OverScroller(mContext);
mStickyScroller = new Scroller(mContext);
// Measure settings for time column.
mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTimeTextPaint.setTextAlign(Paint.Align.RIGHT);
mTimeTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
Rect rect = new Rect();
mTimeTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mTimeTextWidth = mTimeTextPaint.measureText("00 PM");
mTimeTextHeight = rect.height();
mHeaderMarginBottom = mTimeTextHeight / 2;
// Measure settings for header row.
mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mHeaderTextHeight = rect.height();
mHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
// Prepare header background paint.
mHeaderBackgroundPaint = new Paint();
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
// Prepare day background color paint.
mDayBackgroundPaint = new Paint();
mDayBackgroundPaint.setColor(mDayBackgroundColor);
// Prepare hour separator color paint.
mHourSeparatorPaint = new Paint();
mHourSeparatorPaint.setStyle(Paint.Style.STROKE);
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
mHourSeparatorPaint.setColor(mHourSeparatorColor);
// Prepare today background color paint.
mTodayBackgroundPaint = new Paint();
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
// Prepare today header text color paint.
mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mTodayHeaderTextPaint.setTextSize(mTextSize);
mTodayHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
// Prepare event background color.
mEventBackgroundPaint = new Paint();
mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238));
// Prepare header column background color.
mHeaderColumnBackgroundPaint = new Paint();
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
// Prepare event text size and color.
mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
mEventTextPaint.setStyle(Paint.Style.FILL);
mEventTextPaint.setColor(mEventTextColor);
mEventTextPaint.setTextSize(mEventTextSize);
// Set default event color.
mDefaultEventColor = Color.parseColor("#9fc6e7");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the header row.
drawHeaderRowAndEvents(canvas);
// Draw the time column and all the axes/separators.
drawTimeColumnAndAxes(canvas);
// Hide everything in the first cell (top left corner).
canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Hide anything that is in the bottom margin of the header row.
canvas.drawRect(mHeaderColumnWidth, mHeaderTextHeight + mHeaderRowPadding * 2, getWidth(), mHeaderRowPadding * 2 + mHeaderTextHeight + mHeaderMarginBottom + mTimeTextHeight/2 - mHourSeparatorHeight / 2, mHeaderColumnBackgroundPaint);
}
private void drawTimeColumnAndAxes(Canvas canvas) {
// Draw the background color for the header column.
canvas.drawRect(0, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint);
for (int i = 0; i < 24; i++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * i + mHeaderMarginBottom;
// Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner.
String time = getDateTimeInterpreter().interpretTime(i);
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
if (top < getHeight()) canvas.drawText(time, mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint);
}
}
private void drawHeaderRowAndEvents(Canvas canvas) {
// Calculate the available width for each day.
mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding *2;
mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (mNumberOfVisibleDays - 1);
mWidthPerDay = mWidthPerDay/mNumberOfVisibleDays;
if (mAreDimensionsInvalid) {
mAreDimensionsInvalid = false;
if(mScrollToDay != null)
goToDate(mScrollToDay);
mAreDimensionsInvalid = false;
if(mScrollToHour >= 0)
goToHour(mScrollToHour);
mScrollToDay = null;
mScrollToHour = -1;
mAreDimensionsInvalid = false;
}
if (mIsFirstDraw){
mIsFirstDraw = false;
// If the week view is being drawn for the first time, then consider the first day of the week.
if(mNumberOfVisibleDays >= 7 && mHomeDate.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) {
int difference = (7 + (mHomeDate.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek)) % 7;
mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference;
}
}
// Consider scroll offset.
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startFromPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
float startPixel = startFromPixel;
// Get today's date for highlighting purposes
Calendar today = Calendar.getInstance();
// Prepare to iterate for each hour to draw the hour lines.
int lineCount = (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 -
mHeaderMarginBottom) / mHourHeight) + 1;
lineCount = (lineCount) * (mNumberOfVisibleDays+1);
float[] hourLines = new float[lineCount * 4];
// Clear the cache for event rectangles.
if (mEventRects != null) {
for (EventRect eventRect: mEventRects) {
eventRect.rectF = null;
}
}
// Iterate through each day.
Calendar day;
Calendar oldFirstVisibleDay = mFirstVisibleDay;
mFirstVisibleDay = (Calendar) mHomeDate.clone();
mFirstVisibleDay.add(Calendar.DATE, leftDaysWithGaps);
if(!mFirstVisibleDay.equals(oldFirstVisibleDay) && mScrollListener != null){
mScrollListener.onFirstVisibleDayChanged(mFirstVisibleDay, oldFirstVisibleDay);
}
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
// Check if the day is today.
day = (Calendar) mHomeDate.clone();
mLastVisibleDay = (Calendar) day.clone();
day.add(Calendar.DATE, dayNumber - 1);
mLastVisibleDay.add(Calendar.DATE, dayNumber - 2);
boolean isToday = isSameDay(day, today);
// Don't draw days which are outside the requested date range
if (!dateIsValid(day))
continue;
// Get more events if necessary. We want to store the events 3 months beforehand. Get
// events only when it is the first iteration of the loop.
if (mEventRects == null || mRefreshEvents || (dayNumber == leftDaysWithGaps + 1 && mFetchedMonths[1] != day.get(Calendar.MONTH)+1 && day.get(Calendar.DAY_OF_MONTH) == 15)) {
getMoreEvents(day);
mRefreshEvents = false;
}
// Draw background color for each day.
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0)
canvas.drawRect(start, mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), isToday ? mTodayBackgroundPaint : mDayBackgroundPaint);
// Prepare the separator lines for hours.
int i = 0;
for (int hourNumber = 0; hourNumber < 24; hourNumber++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * hourNumber + mTimeTextHeight/2 + mHeaderMarginBottom;
if (top > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0){
hourLines[i * 4] = start;
hourLines[i * 4 + 1] = top;
hourLines[i * 4 + 2] = startPixel + mWidthPerDay;
hourLines[i * 4 + 3] = top;
i++;
}
}
// Draw the lines for hours.
canvas.drawLines(hourLines, mHourSeparatorPaint);
// Draw the events.
drawEvents(day, startPixel, canvas);
// In the next iteration, start from the next day.
startPixel += mWidthPerDay + mColumnGap;
}
// Draw the header background.
canvas.drawRect(0, 0, getWidth(), mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row texts.
startPixel = startFromPixel;
for (int dayNumber=leftDaysWithGaps+1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) {
// Check if the day is today.
day = (Calendar) mHomeDate.clone();
day.add(Calendar.DATE, dayNumber - 1);
boolean isToday = isSameDay(day, today);
// Don't draw days which are outside the requested date range
if (!dateIsValid(day))
continue;
// Draw the day labels.
String dayLabel = getDateTimeInterpreter().interpretDate(day);
if (dayLabel == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null date");
canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, isToday ? mTodayHeaderTextPaint : mHeaderTextPaint);
startPixel += mWidthPerDay + mColumnGap;
}
}
/**
* Get the time and date where the user clicked on.
* @param x The x position of the touch event.
* @param y The y position of the touch event.
* @return The time and date at the clicked position.
*/
private Calendar getTimeFromPoint(float x, float y){
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0
&& x>start && x<startPixel + mWidthPerDay){
Calendar day = (Calendar) mHomeDate.clone();
day.add(Calendar.DATE, dayNumber - 1);
float pixelsFromZero = y - mCurrentOrigin.y - mHeaderTextHeight
- mHeaderRowPadding * 2 - mTimeTextHeight/2 - mHeaderMarginBottom;
int hour = (int)(pixelsFromZero / mHourHeight);
int minute = (int) (60 * (pixelsFromZero - hour * mHourHeight) / mHourHeight);
day.add(Calendar.HOUR, hour);
day.set(Calendar.MINUTE, minute);
return day;
}
startPixel += mWidthPerDay + mColumnGap;
}
return null;
}
/**
* Draw all the events of a particular day.
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date)) {
// Calculate top.
float top = mHourHeight * 24 * mEventRects.get(i).top / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 + mEventMarginVertical;
float originalTop = top;
if (top < mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2)
top = mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2;
// Calculate bottom.
float bottom = mEventRects.get(i).bottom;
bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - mEventMarginVertical;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float originalLeft = left;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
if (left < mHeaderColumnWidth) left = mHeaderColumnWidth;
// Draw the event and the event name on top of it.
RectF eventRectF = new RectF(left, top, right, bottom);
if (bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 && left < right &&
eventRectF.right > mHeaderColumnWidth &&
eventRectF.left < getWidth() &&
eventRectF.bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom &&
eventRectF.top < getHeight() &&
left < right
) {
mEventRects.get(i).rectF = eventRectF;
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
canvas.drawRect(mEventRects.get(i).rectF, mEventBackgroundPaint);
drawText(mEventRects.get(i).event.getName(), mEventRects.get(i).rectF, canvas, originalTop, originalLeft);
}
else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw the name of the event on top of the event rectangle.
* @param text The text to draw.
* @param rect The rectangle on which the text is to be drawn.
* @param canvas The canvas to draw upon.
* @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area.
* @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area.
*/
private void drawText(String text, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
// Get text dimensions
StaticLayout textLayout = new StaticLayout(text, mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Crop height
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (lineHeight < availableHeight && textLayout.getHeight() > rect.height() - mEventPadding * 2) {
int lineCount = textLayout.getLineCount();
int availableLineCount = (int) Math.floor(lineCount * availableHeight / textLayout.getHeight());
float widthAvailable = (rect.right - originalLeft - mEventPadding * 2) * availableLineCount;
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, widthAvailable, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
else if (lineHeight >= availableHeight) {
int width = (int) (rect.right - originalLeft - mEventPadding * 2);
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, width, TextUtils.TruncateAt.END), mEventTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
}
// Draw text
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
/**
* A class to hold reference to the events and their visual representation. An EventRect is
* actually the rectangle that is drawn on the calendar for a given event. There may be more
* than one rectangle for a single event (an event that expands more than one day). In that
* case two instances of the EventRect will be used for a single event. The given event will be
* stored in "originalEvent". But the event that corresponds to rectangle the rectangle
* instance will be stored in "event".
*/
private class EventRect {
public WeekViewEvent event;
public WeekViewEvent originalEvent;
public RectF rectF;
public float left;
public float width;
public float top;
public float bottom;
/**
* Create a new instance of event rect. An EventRect is actually the rectangle that is drawn
* on the calendar for a given event. There may be more than one rectangle for a single
* event (an event that expands more than one day). In that case two instances of the
* EventRect will be used for a single event. The given event will be stored in
* "originalEvent". But the event that corresponds to rectangle the rectangle instance will
* be stored in "event".
* @param event Represents the event which this instance of rectangle represents.
* @param originalEvent The original event that was passed by the user.
* @param rectF The rectangle.
*/
public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) {
this.event = event;
this.rectF = rectF;
this.originalEvent = originalEvent;
}
}
/**
* Gets more events of one/more month(s) if necessary. This method is called when the user is
* scrolling the week view. The week view stores the events of three months: the visible month,
* the previous month, the next month.
* @param day The day where the user is currently is.
*/
private void getMoreEvents(Calendar day) {
// Delete all events if its not current month +- 1.
deleteFarMonths(day);
// Get more events if the month is changed.
if (mEventRects == null)
mEventRects = new ArrayList<EventRect>();
if (mMonthChangeListener == null && !isInEditMode())
throw new IllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if (mRefreshEvents) {
mEventRects.clear();
mFetchedMonths = new int[3];
}
// Get events of previous month.
int previousMonth = (day.get(Calendar.MONTH) == 0?12:day.get(Calendar.MONTH));
int nextMonth = (day.get(Calendar.MONTH)+2 == 13 ?1:day.get(Calendar.MONTH)+2);
int[] lastFetchedMonth = mFetchedMonths.clone();
if (mFetchedMonths[0] < 1 || mFetchedMonths[0] != previousMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, previousMonth) && !isInEditMode()){
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange((previousMonth==12)?day.get(Calendar.YEAR)-1:day.get(Calendar.YEAR), previousMonth);
sortEvents(events);
for (WeekViewEvent event: events) {
cacheEvent(event);
}
}
mFetchedMonths[0] = previousMonth;
}
// Get events of this month.
if (mFetchedMonths[1] < 1 || mFetchedMonths[1] != day.get(Calendar.MONTH)+1 || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, day.get(Calendar.MONTH)+1) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(day.get(Calendar.YEAR), day.get(Calendar.MONTH) + 1);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[1] = day.get(Calendar.MONTH)+1;
}
// Get events of next month.
if (mFetchedMonths[2] < 1 || mFetchedMonths[2] != nextMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, nextMonth) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(nextMonth == 1 ? day.get(Calendar.YEAR) + 1 : day.get(Calendar.YEAR), nextMonth);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[2] = nextMonth;
}
// Prepare to calculate positions of each events.
ArrayList<EventRect> tempEvents = new ArrayList<EventRect>(mEventRects);
mEventRects = new ArrayList<EventRect>();
Calendar dayCounter = (Calendar) day.clone();
dayCounter.add(Calendar.MONTH, -1);
dayCounter.set(Calendar.DAY_OF_MONTH, 1);
Calendar maxDay = (Calendar) day.clone();
maxDay.add(Calendar.MONTH, 1);
maxDay.set(Calendar.DAY_OF_MONTH, maxDay.getActualMaximum(Calendar.DAY_OF_MONTH));
// Iterate through each day to calculate the position of the events.
while (dayCounter.getTimeInMillis() <= maxDay.getTimeInMillis()) {
ArrayList<EventRect> eventRects = new ArrayList<EventRect>();
for (EventRect eventRect : tempEvents) {
if (isSameDay(eventRect.event.getStartTime(), dayCounter))
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
dayCounter.add(Calendar.DATE, 1);
}
}
/**
* Cache the event for smooth scrolling functionality.
* @param event The event to cache.
*/
private void cacheEvent(WeekViewEvent event) {
if (!isSameDay(event.getStartTime(), event.getEndTime())) {
Calendar endTime = (Calendar) event.getStartTime().clone();
endTime.set(Calendar.HOUR_OF_DAY, 23);
endTime.set(Calendar.MINUTE, 59);
Calendar startTime = (Calendar) event.getEndTime().clone();
startTime.set(Calendar.HOUR_OF_DAY, 0);
startTime.set(Calendar.MINUTE, 0);
WeekViewEvent event1 = new WeekViewEvent(event.getId(), event.getName(), event.getStartTime(), endTime);
event1.setColor(event.getColor());
WeekViewEvent event2 = new WeekViewEvent(event.getId(), event.getName(), startTime, event.getEndTime());
event2.setColor(event.getColor());
mEventRects.add(new EventRect(event1, event, null));
mEventRects.add(new EventRect(event2, event, null));
}
else
mEventRects.add(new EventRect(event, event, null));
}
/**
* Sorts the events in ascending order.
* @param events The events to be sorted.
*/
private void sortEvents(List<WeekViewEvent> events) {
Collections.sort(events, new Comparator<WeekViewEvent>() {
@Override
public int compare(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0);
if (comparator == 0) {
long end1 = event1.getEndTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0);
}
return comparator;
}
});
}
/**
* Calculates the left and right positions of each events. This comes handy specially if events
* are overlapping.
* @param eventRects The events along with their wrapper class.
*/
private void computePositionOfEvents(List<EventRect> eventRects) {
// Make "collision groups" for all events that collide with others.
List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>();
for (EventRect eventRect : eventRects) {
boolean isPlaced = false;
outerLoop:
for (List<EventRect> collisionGroup : collisionGroups) {
for (EventRect groupEvent : collisionGroup) {
if (isEventsCollide(groupEvent.event, eventRect.event)) {
collisionGroup.add(eventRect);
isPlaced = true;
break outerLoop;
}
}
}
if (!isPlaced) {
List<EventRect> newGroup = new ArrayList<EventRect>();
newGroup.add(eventRect);
collisionGroups.add(newGroup);
}
}
for (List<EventRect> collisionGroup : collisionGroups) {
expandEventsToMaxWidth(collisionGroup);
}
}
/**
* Expands all the events to maximum possible width. The events will try to occupy maximum
* space available horizontally.
* @param collisionGroup The group of events which overlap with each other.
*/
private void expandEventsToMaxWidth(List<EventRect> collisionGroup) {
// Expand the events to maximum possible width.
List<List<EventRect>> columns = new ArrayList<List<EventRect>>();
columns.add(new ArrayList<EventRect>());
for (EventRect eventRect : collisionGroup) {
boolean isPlaced = false;
for (List<EventRect> column : columns) {
if (column.size() == 0) {
column.add(eventRect);
isPlaced = true;
}
else if (!isEventsCollide(eventRect.event, column.get(column.size()-1).event)) {
column.add(eventRect);
isPlaced = true;
break;
}
}
if (!isPlaced) {
List<EventRect> newColumn = new ArrayList<EventRect>();
newColumn.add(eventRect);
columns.add(newColumn);
}
}
// Calculate left and right position for all the events.
// Get the maxRowCount by looking in all columns.
int maxRowCount = 0;
for (List<EventRect> column : columns){
maxRowCount = Math.max(maxRowCount, column.size());
}
for (int i = 0; i < maxRowCount; i++) {
// Set the left and right values of the event.
float j = 0;
for (List<EventRect> column : columns) {
if (column.size() >= i+1) {
EventRect eventRect = column.get(i);
eventRect.width = 1f / columns.size();
eventRect.left = j / columns.size();
eventRect.top = eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getStartTime().get(Calendar.MINUTE);
eventRect.bottom = eventRect.event.getEndTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getEndTime().get(Calendar.MINUTE);
mEventRects.add(eventRect);
}
j++;
}
}
}
/**
* Checks if two events overlap.
* @param event1 The first event.
* @param event2 The second event.
* @return true if the events overlap.
*/
private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long end1 = event1.getEndTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
return !((start1 >= end2) || (end1 <= start2));
}
/**
* Checks if time1 occurs after (or at the same time) time2.
* @param time1 The time to check.
* @param time2 The time to check against.
* @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false.
*/
private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) {
return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis();
}
/**
* Deletes the events of the months that are too far away from the current month.
* @param currentDay The current day.
*/
private void deleteFarMonths(Calendar currentDay) {
if (mEventRects == null) return;
Calendar nextMonth = (Calendar) currentDay.clone();
nextMonth.add(Calendar.MONTH, 1);
nextMonth.set(Calendar.DAY_OF_MONTH, nextMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
nextMonth.set(Calendar.HOUR_OF_DAY, 12);
nextMonth.set(Calendar.MINUTE, 59);
nextMonth.set(Calendar.SECOND, 59);
Calendar prevMonth = (Calendar) currentDay.clone();
prevMonth.add(Calendar.MONTH, -1);
prevMonth.set(Calendar.DAY_OF_MONTH, 1);
prevMonth.set(Calendar.HOUR_OF_DAY, 0);
prevMonth.set(Calendar.MINUTE, 0);
prevMonth.set(Calendar.SECOND, 0);
List<EventRect> newEvents = new ArrayList<EventRect>();
for (EventRect eventRect : mEventRects) {
boolean isFarMonth = eventRect.event.getStartTime().getTimeInMillis() > nextMonth.getTimeInMillis() || eventRect.event.getEndTime().getTimeInMillis() < prevMonth.getTimeInMillis();
if (!isFarMonth) newEvents.add(eventRect);
}
mEventRects.clear();
mEventRects.addAll(newEvents);
}
@Override
public void invalidate() {
super.invalidate();
mAreDimensionsInvalid = true;
}
/**
* Recalculate a suitable home date.
*
* When the scroll offset is zero, the home date will be the leftmost day visible in the view.
*/
private void resetHomeDate() {
// Start by trying to use the current date as the home date
Calendar newHomeDate = Calendar.getInstance();
newHomeDate.set(Calendar.HOUR_OF_DAY, 0);
newHomeDate.set(Calendar.MINUTE, 0);
newHomeDate.set(Calendar.SECOND, 0);
newHomeDate.set(Calendar.MILLISECOND, 0);
// Ensure the date falls within any date limits that have been set
if (mMinDate != null && newHomeDate.before(mMinDate))
newHomeDate = (Calendar) mMinDate.clone();
if (mMaxDate != null && newHomeDate.after(mMaxDate))
newHomeDate = (Calendar) mMaxDate.clone();
// If there is a maximum date set, try to minimize the amount of blank space that will appear
// to the right of the home date when at scroll offset zero.
if (mMaxDate != null) {
// Same calculation as getXMinLimit()
Calendar date = (Calendar) mMaxDate.clone();
date.add(Calendar.DATE, 1-mNumberOfVisibleDays);
while (date.before(mMinDate))
date.add(Calendar.DATE, 1);
if (newHomeDate.after(date))
newHomeDate = date;
}
mHomeDate = newHomeDate;
}
/**
* @return The scroll offset (on the X axis) where the given day starts
*/
private float getXOriginForDate(Calendar date) {
int dateDifference = (int) (date.getTimeInMillis() - mHomeDate.getTimeInMillis()) / (1000 * 60 * 60 * 24);
return - dateDifference * (mWidthPerDay + mColumnGap);
}
private float getYMinLimit() {
return -(mHourHeight * 24
+ mHeaderTextHeight
+ mHeaderRowPadding * 2
- getHeight());
}
private float getYMaxLimit() {
return 0;
}
private float getXMinLimit() {
if (mMaxDate == null)
return Integer.MIN_VALUE;
else {
Calendar date = (Calendar) mMaxDate.clone();
date.add(Calendar.DATE, 1-mNumberOfVisibleDays);
while (date.before(mMinDate))
date.add(Calendar.DATE, 1);
return getXOriginForDate(date);
}
}
private float getXMaxLimit() {
if (mMinDate == null)
return Integer.MAX_VALUE;
else
return getXOriginForDate(mMinDate);
}
// Functions related to setting and getting the properties.
public void setOnEventClickListener (EventClickListener listener) {
this.mEventClickListener = listener;
}
public EventClickListener getEventClickListener() {
return mEventClickListener;
}
public MonthChangeListener getMonthChangeListener() {
return mMonthChangeListener;
}
public void setMonthChangeListener(MonthChangeListener monthChangeListener) {
this.mMonthChangeListener = monthChangeListener;
}
public EventLongPressListener getEventLongPressListener() {
return mEventLongPressListener;
}
public void setEventLongPressListener(EventLongPressListener eventLongPressListener) {
this.mEventLongPressListener = eventLongPressListener;
}
public void setEmptyViewClickListener(EmptyViewClickListener emptyViewClickListener){
this.mEmptyViewClickListener = emptyViewClickListener;
}
public EmptyViewClickListener getEmptyViewClickListener(){
return mEmptyViewClickListener;
}
public void setEmptyViewLongPressListener(EmptyViewLongPressListener emptyViewLongPressListener){
this.mEmptyViewLongPressListener = emptyViewLongPressListener;
}
public EmptyViewLongPressListener getEmptyViewLongPressListener(){
return mEmptyViewLongPressListener;
}
public void setScrollListener(ScrollListener scrolledListener){
this.mScrollListener = scrolledListener;
}
public ScrollListener getScrollListener(){
return mScrollListener;
}
/**
* Get the interpreter which provides the text to show in the header column and the header row.
* @return The date, time interpreter.
*/
public DateTimeInterpreter getDateTimeInterpreter() {
if (mDateTimeInterpreter == null) {
mDateTimeInterpreter = new DateTimeInterpreter() {
@Override
public String interpretDate(Calendar date) {
SimpleDateFormat sdf;
sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE") : new SimpleDateFormat("EEE");
try{
String dayName = sdf.format(date.getTime()).toUpperCase();
return String.format("%s %d/%02d", dayName, date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH));
}catch (Exception e){
e.printStackTrace();
return "";
}
}
@Override
public String interpretTime(int hour) {
String amPm;
if (hour >= 0 && hour < 12) amPm = "AM";
else amPm = "PM";
if (hour == 0) hour = 12;
if (hour > 12) hour -= 12;
return String.format("%02d %s", hour, amPm);
}
};
}
return mDateTimeInterpreter;
}
/**
* Set the interpreter which provides the text to show in the header column and the header row.
* @param dateTimeInterpreter The date, time interpreter.
*/
public void setDateTimeInterpreter(DateTimeInterpreter dateTimeInterpreter){
this.mDateTimeInterpreter = dateTimeInterpreter;
}
/**
* Get the number of visible days in a week.
* @return The number of visible days in a week.
*/
public int getNumberOfVisibleDays() {
return mNumberOfVisibleDays;
}
/**
* Set the number of visible days in a week.
* @param numberOfVisibleDays The number of visible days in a week.
*/
public void setNumberOfVisibleDays(int numberOfVisibleDays) {
this.mNumberOfVisibleDays = numberOfVisibleDays;
resetHomeDate();
mCurrentOrigin.x = 0;
mCurrentOrigin.y = 0;
invalidate();
}
public int getHourHeight() {
return mHourHeight;
}
public void setHourHeight(int hourHeight) {
mHourHeight = hourHeight;
invalidate();
}
public int getColumnGap() {
return mColumnGap;
}
public void setColumnGap(int columnGap) {
mColumnGap = columnGap;
invalidate();
}
public int getFirstDayOfWeek() {
return mFirstDayOfWeek;
}
/**
* Set the first day of the week. First day of the week is used only when the week view is first
* drawn. It does not of any effect after user starts scrolling horizontally.
* <p>
* <b>Note:</b> This method will only work if the week view is set to display more than 6 days at
* once.
* </p>
* @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY},
* {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY},
* {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY},
* {@link java.util.Calendar#FRIDAY}.
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
invalidate();
}
public int getTextSize() {
return mTextSize;
}
public void setTextSize(int textSize) {
mTextSize = textSize;
mTodayHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getHeaderColumnPadding() {
return mHeaderColumnPadding;
}
public void setHeaderColumnPadding(int headerColumnPadding) {
mHeaderColumnPadding = headerColumnPadding;
invalidate();
}
public int getHeaderColumnTextColor() {
return mHeaderColumnTextColor;
}
public void setHeaderColumnTextColor(int headerColumnTextColor) {
mHeaderColumnTextColor = headerColumnTextColor;
invalidate();
}
public int getHeaderRowPadding() {
return mHeaderRowPadding;
}
public void setHeaderRowPadding(int headerRowPadding) {
mHeaderRowPadding = headerRowPadding;
invalidate();
}
public int getHeaderRowBackgroundColor() {
return mHeaderRowBackgroundColor;
}
public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) {
mHeaderRowBackgroundColor = headerRowBackgroundColor;
invalidate();
}
public int getDayBackgroundColor() {
return mDayBackgroundColor;
}
public void setDayBackgroundColor(int dayBackgroundColor) {
mDayBackgroundColor = dayBackgroundColor;
invalidate();
}
public int getHourSeparatorColor() {
return mHourSeparatorColor;
}
public void setHourSeparatorColor(int hourSeparatorColor) {
mHourSeparatorColor = hourSeparatorColor;
invalidate();
}
public int getTodayBackgroundColor() {
return mTodayBackgroundColor;
}
public void setTodayBackgroundColor(int todayBackgroundColor) {
mTodayBackgroundColor = todayBackgroundColor;
invalidate();
}
public int getHourSeparatorHeight() {
return mHourSeparatorHeight;
}
public void setHourSeparatorHeight(int hourSeparatorHeight) {
mHourSeparatorHeight = hourSeparatorHeight;
invalidate();
}
public int getTodayHeaderTextColor() {
return mTodayHeaderTextColor;
}
public void setTodayHeaderTextColor(int todayHeaderTextColor) {
mTodayHeaderTextColor = todayHeaderTextColor;
invalidate();
}
public int getEventTextSize() {
return mEventTextSize;
}
public void setEventTextSize(int eventTextSize) {
mEventTextSize = eventTextSize;
mEventTextPaint.setTextSize(mEventTextSize);
invalidate();
}
public int getEventTextColor() {
return mEventTextColor;
}
public void setEventTextColor(int eventTextColor) {
mEventTextColor = eventTextColor;
invalidate();
}
public int getEventPadding() {
return mEventPadding;
}
public void setEventPadding(int eventPadding) {
mEventPadding = eventPadding;
invalidate();
}
public int getHeaderColumnBackgroundColor() {
return mHeaderColumnBackgroundColor;
}
public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) {
mHeaderColumnBackgroundColor = headerColumnBackgroundColor;
invalidate();
}
public int getDefaultEventColor() {
return mDefaultEventColor;
}
public void setDefaultEventColor(int defaultEventColor) {
mDefaultEventColor = defaultEventColor;
invalidate();
}
/**
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} and
* {@link #getDateTimeInterpreter()} instead.
* @return Either long or short day name is being used.
*/
@Deprecated
public int getDayNameLength() {
return mDayNameLength;
}
/**
* Set the length of the day name displayed in the header row. Example of short day names is
* 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'.
* <p>
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} instead.
* </p>
* @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and
* {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}.
*/
@Deprecated
public void setDayNameLength(int length) {
if (length != LENGTH_LONG && length != LENGTH_SHORT) {
throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT");
}
this.mDayNameLength = length;
}
public int getOverlappingEventGap() {
return mOverlappingEventGap;
}
/**
* Set the gap between overlapping events.
* @param overlappingEventGap The gap between overlapping events.
*/
public void setOverlappingEventGap(int overlappingEventGap) {
this.mOverlappingEventGap = overlappingEventGap;
invalidate();
}
public int getEventMarginVertical() {
return mEventMarginVertical;
}
/**
* Set the top and bottom margin of the event. The event will release this margin from the top
* and bottom edge. This margin is useful for differentiation consecutive events.
* @param eventMarginVertical The top and bottom margin.
*/
public void setEventMarginVertical(int eventMarginVertical) {
this.mEventMarginVertical = eventMarginVertical;
invalidate();
}
/**
* Returns the first visible day in the week view.
* @return The first visible day in the week view.
*/
public Calendar getFirstVisibleDay() {
return mFirstVisibleDay;
}
/**
* Returns the last visible day in the week view.
* @return The last visible day in the week view.
*/
public Calendar getLastVisibleDay() {
return mLastVisibleDay;
}
/**
* Get the scrolling speed factor in horizontal direction.
* @return The speed factor in horizontal direction.
*/
public float getXScrollingSpeed() {
return mXScrollingSpeed;
}
/**
* Sets the speed for horizontal scrolling.
* @param xScrollingSpeed The new horizontal scrolling speed.
*/
public void setXScrollingSpeed(float xScrollingSpeed) {
this.mXScrollingSpeed = xScrollingSpeed;
}
/**
* Get the earliest day that can be displayed. Will return null if no minimum date is set.
*/
public Calendar getMinDate() {
return mMinDate;
}
/**
* Set the earliest day that can be displayed. This will determine the left horizontal scroll
* limit. The default value is null (allow unlimited scrolling into the past).
*
* @param minDate The new minimum date (pass null for no minimum)
*/
public void setMinDate(Calendar minDate) {
if (minDate != null) {
minDate.set(Calendar.HOUR_OF_DAY, 0);
minDate.set(Calendar.MINUTE, 0);
minDate.set(Calendar.SECOND, 0);
minDate.set(Calendar.MILLISECOND, 0);
if (mMaxDate != null && minDate.after(mMaxDate)) {
throw new IllegalArgumentException("minDate cannot be later than maxDate");
}
}
mMinDate = minDate;
resetHomeDate();
mCurrentOrigin.x = 0;
invalidate();
}
/**
* Get the latest day that can be displayed. Will return null if no maximum date is set.
*/
public Calendar getMaxDate() {
return mMaxDate;
}
/**
* Set the latest day that can be displayed. This will determine the right horizontal scroll
* limit. The default value is null (allow unlimited scrolling into the future).
*
* @param maxDate The new maximum date (pass null for no maximum)
*/
public void setMaxDate(Calendar maxDate) {
if (maxDate != null) {
maxDate.set(Calendar.HOUR_OF_DAY, 0);
maxDate.set(Calendar.MINUTE, 0);
maxDate.set(Calendar.SECOND, 0);
maxDate.set(Calendar.MILLISECOND, 0);
if (mMinDate != null && maxDate.before(mMinDate)) {
throw new IllegalArgumentException("maxDate cannot be earlier than minDate");
}
}
mMaxDate = maxDate;
resetHomeDate();
mCurrentOrigin.x = 0;
invalidate();
}
// Functions related to scrolling.
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mCurrentScrollDirection == Direction.HORIZONTAL) {
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
mCurrentScrollDirection = Direction.NONE;
}
return mGestureDetector.onTouchEvent(event);
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
if (Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) < mWidthPerDay + mColumnGap && Math.abs(mScroller.getFinalX() - mScroller.getStartX()) != 0) {
mScroller.forceFinished(true);
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
if(mScroller.getFinalX() < mScroller.getCurrX())
leftDays
else
leftDays++;
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
else {
if (mCurrentFlingDirection == Direction.VERTICAL) mCurrentOrigin.y = mScroller.getCurrY();
else mCurrentOrigin.x = mScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
if (mStickyScroller.computeScrollOffset()) {
mCurrentOrigin.x = mStickyScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
// Public methods.
/**
* Show today on the week view.
*/
public void goToToday() {
Calendar today = Calendar.getInstance();
goToDate(today);
}
/**
* Show a specific day on the week view.
* @param date The date to show.
*/
public void goToDate(Calendar date) {
mScroller.forceFinished(true);
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
if(mAreDimensionsInvalid) {
mScrollToDay = date;
return;
}
// Don't try to show a date that this view will not render
if (!dateIsValid(date))
return;
// Clamp the new offset if it would fall outside the scroll limits
float newX = getXOriginForDate(date);
if (newX < getXMinLimit())
newX = getXMinLimit();
else if (newX > getXMaxLimit())
newX = getXMaxLimit();
mRefreshEvents = true;
mCurrentOrigin.x = newX;
invalidate();
}
/**
* Refreshes the view and loads the events again.
*/
public void notifyDatasetChanged(){
mRefreshEvents = true;
invalidate();
}
/**
* Vertically scroll to a specific hour in the week view.
* @param hour The hour to scroll to in 24-hour format. Supported values are 0-24.
*/
public void goToHour(double hour){
if (mAreDimensionsInvalid) {
mScrollToHour = hour;
return;
}
int verticalOffset = 0;
if (hour > 24)
verticalOffset = mHourHeight * 24;
else if (hour > 0)
verticalOffset = (int) (mHourHeight * hour);
if (verticalOffset > mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)
verticalOffset = (int)(mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom);
mCurrentOrigin.y = -verticalOffset;
invalidate();
}
/**
* Get the first hour that is visible on the screen.
* @return The first hour that is visible.
*/
public double getFirstVisibleHour(){
return -mCurrentOrigin.y / mHourHeight;
}
/**
* Determine whether a given calendar day falls within the scroll limits set for this view.
* @see #setMinDate(Calendar)
* @see #setMaxDate(Calendar)
* @return True if there are no limits or the date is within the limits.
*/
public boolean dateIsValid(Calendar day){
if (mMinDate != null && day.before(mMinDate))
return false;
if (mMaxDate != null && day.after(mMaxDate))
return false;
return true;
}
// Interfaces.
public interface EventClickListener {
public void onEventClick(WeekViewEvent event, RectF eventRect);
}
public interface MonthChangeListener {
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth);
}
public interface EventLongPressListener {
public void onEventLongPress(WeekViewEvent event, RectF eventRect);
}
public interface EmptyViewClickListener {
public void onEmptyViewClicked(Calendar time);
}
public interface EmptyViewLongPressListener {
public void onEmptyViewLongPress(Calendar time);
}
public interface ScrollListener {
/**
* Called when the first visible day has changed.
*
* (this will also be called during the first draw of the weekview)
* @param newFirstVisibleDay The new first visible day
* @param oldFirstVisibleDay The old first visible day (is null on the first call).
*/
public void onFirstVisibleDayChanged(Calendar newFirstVisibleDay, Calendar oldFirstVisibleDay);
}
// Helper methods.
/**
* Checks if an integer array contains a particular value.
* @param list The haystack.
* @param value The needle.
* @return True if the array contains the value. Otherwise returns false.
*/
private boolean containsValue(int[] list, int value) {
for (int i = 0; i < list.length; i++){
if (list[i] == value)
return true;
}
return false;
}
/**
* Checks if two times are on the same day.
* @param dayOne The first day.
* @param dayTwo The second day.
* @return Whether the times are on the same day.
*/
private boolean isSameDay(Calendar dayOne, Calendar dayTwo) {
return dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR) && dayOne.get(Calendar.DAY_OF_YEAR) == dayTwo.get(Calendar.DAY_OF_YEAR);
}
}
|
package com.facebook.litho;
import static android.support.annotation.Dimension.DP;
import static com.facebook.litho.FrameworkLogEvents.EVENT_WARNING;
import static com.facebook.litho.FrameworkLogEvents.PARAM_MESSAGE;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorInt;
import android.support.annotation.DimenRes;
import android.support.annotation.Dimension;
import android.support.annotation.DrawableRes;
import android.support.annotation.Px;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.support.annotation.VisibleForTesting;
import android.util.SparseArray;
import android.view.ViewOutlineProvider;
import com.facebook.infer.annotation.ReturnsOwnership;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.reference.DrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaEdge;
import com.facebook.yoga.YogaPositionType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
/**
* Represents a unique instance of a component. To create new {@link Component} instances, use the
* {@code create()} method in the generated subclass which returns a builder that allows you to set
* values for individual props. {@link Component} instances are immutable after creation.
*/
public abstract class Component<L extends Component> extends ComponentLifecycle
implements Cloneable, HasEventDispatcher, HasEventTrigger {
private static final AtomicInteger sIdGenerator = new AtomicInteger(0);
private int mId = sIdGenerator.getAndIncrement();
private String mGlobalKey;
@Nullable private String mKey;
private boolean mHasManualKey;
@ThreadConfined(ThreadConfined.ANY)
private ComponentContext mScopedContext;
private boolean mIsLayoutStarted = false;
// If we have a cachedLayout, onPrepare and onMeasure would have been called on it already.
@ThreadConfined(ThreadConfined.ANY)
private InternalNode mLastMeasuredLayout;
// Layout attributes that are set directly on the component itself.
@Nullable private ComponentLayoutAttributes mComponentLayoutAttributes;
/**
* Holds onto how many direct component children of each type this Component has. Used for
* automatically generating unique global keys for all sibling components of the same type.
*/
@Nullable private Map<String, Integer> mChildCounters;
protected Component() {
this(null);
}
/**
* This constructor should be called only if working with a manually crafted "special" Component.
* This should NOT be used in general use cases. Use the standard {@link #Component()} instead.
*/
protected Component(Class classType) {
super(classType);
// if (!ComponentsConfiguration.lazyInitializeComponent) {
mChildCounters = new HashMap<>();
mKey = Integer.toString(getTypeId());
}
@Deprecated
public ComponentLifecycle getLifecycle() {
return this;
}
/**
* Mostly used by logging to provide more readable messages.
*/
public abstract String getSimpleName();
/**
* Compares this component to a different one to check if they are the same
*
* This is used to be able to skip rendering a component again. We avoid using the
* {@link Object#equals(Object)} so we can optimize the code better over time since we don't have
* to adhere to the contract required for a equals method.
*
* @param other the component to compare to
* @return true if the components are of the same type and have the same props
*/
public boolean isEquivalentTo(Component<?> other) {
return this == other;
}
protected StateContainer getStateContainer() {
return null;
}
public ComponentContext getScopedContext() {
return mScopedContext;
}
public void setScopedContext(ComponentContext scopedContext) {
mScopedContext = scopedContext;
}
synchronized void markLayoutStarted() {
if (mIsLayoutStarted) {
throw new IllegalStateException("Duplicate layout of a component: " + this);
}
mIsLayoutStarted = true;
}
// Get an id that is identical across cloned instances, but otherwise unique
protected int getId() {
return mId;
}
/**
* Get a key that is unique to this component within its tree.
* @return
*/
String getGlobalKey() {
return mGlobalKey;
}
/**
* Set a key for this component that is unique within its tree.
* @param key
*
*/
// thread-safe because the one write is before all the reads
@ThreadSafe(enableChecks = false)
private void setGlobalKey(String key) {
mGlobalKey = key;
}
/**
*
* @return a key that is local to the component's parent.
*/
String getKey() {
if (mKey == null && !mHasManualKey) {
mKey = Integer.toString(getTypeId());
}
return mKey;
}
/**
* Set a key that is local to the parent of this component.
* @param key key
*/
void setKey(String key) {
mHasManualKey = true;
mKey = key;
}
/**
* Generate a global key for the given component that is unique among all of this component's
* children of the same type. If a manual key has been set on the child component using the .key()
* method, return the manual key.
*
* @param component the child component for which we're finding a unique global key
* @param key the key of the child component as determined by its lifecycle id or manual setting
* @return a unique global key for this component relative to its siblings.
*/
private String generateUniqueGlobalKeyForChild(Component component, String key) {
final String childKey = getGlobalKey() + key;
final KeyHandler keyHandler = mScopedContext.getKeyHandler();
/** Null check is for testing only, the keyHandler should never be null here otherwise. */
if (keyHandler == null) {
return childKey;
}
/** If the key is already unique, return it. */
if (!keyHandler.hasKey(childKey)) {
return childKey;
}
/** The component has a manual key set on it but that key is a duplicate * */
if (component.mHasManualKey) {
final ComponentsLogger logger = mScopedContext.getLogger();
if (logger != null) {
final LogEvent event = logger.newEvent(EVENT_WARNING);
event.addParam(
PARAM_MESSAGE,
"The manual key "
+ childKey
+ " you are setting on this "
+ component.getSimpleName()
+ " is a duplicate and will be changed into a unique one. "
+ "This will result in unexpected behavior if you don't change it.");
logger.log(event);
}
}
final String childType = component.getSimpleName();
if (mChildCounters == null) {
mChildCounters = new HashMap<>();
}
/**
* If the key is a duplicate, we start appending an index based on the child component's type
* that would uniquely identify it.
*/
int childIndex = mChildCounters.containsKey(childType) ? mChildCounters.get(childType) : 0;
/**
* Specs that implement {@link com.facebook.litho.annotations.OnCreateLayoutWithSizeSpec} will
* call onCreateLayout more than once, so we might record a key in the key handler that doesn't
* end up being used in the valid layout output. We'll need to try increasing the index until we
* hit a unique key.
*/
String uniqueKey = childKey + childIndex;
while (keyHandler.hasKey(uniqueKey)) {
uniqueKey = childKey + (childIndex++);
}
mChildCounters.put(childType, childIndex + 1);
return uniqueKey;
}
Component<L> makeCopyWithNullContext() {
try {
final Component<L> component = (Component<L>) super.clone();
component.mScopedContext = null;
return component;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public Component<L> makeShallowCopy() {
try {
final Component<L> component = (Component<L>) super.clone();
component.mIsLayoutStarted = false;
if (!ComponentsConfiguration.lazyInitializeComponent) {
component.mChildCounters = new HashMap<>();
}
component.mHasManualKey = false;
return component;
} catch (CloneNotSupportedException e) {
// This class implements Cloneable, so this is impossible
throw new RuntimeException(e);
}
}
Component<L> makeShallowCopyWithNewId() {
final Component<L> component = makeShallowCopy();
component.mId = sIdGenerator.incrementAndGet();
return component;
}
boolean hasCachedLayout() {
return (mLastMeasuredLayout != null);
}
InternalNode getCachedLayout() {
return mLastMeasuredLayout;
}
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
protected void releaseCachedLayout() {
if (mLastMeasuredLayout != null) {
LayoutState.releaseNodeTree(mLastMeasuredLayout, true /* isNestedTree */);
mLastMeasuredLayout = null;
}
}
@VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE)
protected void clearCachedLayout() {
mLastMeasuredLayout = null;
}
void release() {
mIsLayoutStarted = false;
}
/**
* Measure a component with the given {@link SizeSpec} constrain.
*
* @param c {@link ComponentContext}.
* @param widthSpec Width {@link SizeSpec} constrain.
* @param heightSpec Height {@link SizeSpec} constrain.
* @param outputSize Size object that will be set with the measured dimensions.
*/
public void measure(ComponentContext c, int widthSpec, int heightSpec, Size outputSize) {
releaseCachedLayout();
mLastMeasuredLayout = LayoutState.createAndMeasureTreeForComponent(
c,
this,
widthSpec,
heightSpec);
// This component resolution won't be deferred nor onMeasure called if it's a layout spec.
// In that case it needs to manually save the latest saze specs.
// The size specs will be checked during the calculation (or collection) of the main tree.
if (Component.isLayoutSpec(this)) {
mLastMeasuredLayout.setLastWidthSpec(widthSpec);
mLastMeasuredLayout.setLastHeightSpec(heightSpec);
}
outputSize.width = mLastMeasuredLayout.getWidth();
outputSize.height = mLastMeasuredLayout.getHeight();
}
protected void copyInterStageImpl(Component<L> component) {
}
static boolean isHostSpec(Component<?> component) {
return (component instanceof HostComponent);
}
static boolean isLayoutSpec(Component<?> component) {
return (component != null && component.getMountType() == MountType.NONE);
}
static boolean isMountSpec(Component<?> component) {
return (component != null && component.getMountType() != MountType.NONE);
}
static boolean isMountDrawableSpec(Component<?> component) {
return (component != null && component.getMountType() == MountType.DRAWABLE);
}
static boolean isMountViewSpec(Component<?> component) {
return (component != null && component.getMountType() == MountType.VIEW);
}
static boolean isLayoutSpecWithSizeSpec(Component<?> component) {
return (isLayoutSpec(component) && component.canMeasure());
}
static boolean isLayoutSpecWithExperimentalOnCreateLayout(Component<?> component) {
return (isLayoutSpec(component) && component.hasExperimentalOnCreateLayout());
}
static boolean isNestedTree(Component<?> component) {
return (isLayoutSpecWithSizeSpec(component)
|| (component != null && component.hasCachedLayout()));
}
/**
* @return whether the given component will render because it returns non-null from its
* implementation of onCreateLayout, based on its current props and state. Returns true if the
* component returns non-null, otherwise false.
*/
public static boolean willRender(ComponentLayout componentLayout) {
if (componentLayout == null || ComponentContext.NULL_LAYOUT.equals(componentLayout)) {
return false;
}
if (componentLayout instanceof InternalNode &&
((InternalNode) componentLayout).isNestedTreeHolder()) {
// Components using @OnCreateLayoutWithSizeSpec are lazily resolved after the rest of the tree
// has been measured (so that we have the proper measurements to pass in). This means we can't
// eagerly check the result of OnCreateLayoutWithSizeSpec.
throw new IllegalArgumentException(
"Cannot check willRender on a component that uses @OnCreateLayoutWithSizeSpec! "
+ "Try wrapping this component in one that uses @OnCreateLayout if possible.");
}
return true;
}
/**
* Prepares a component for calling any pending state updates on it by setting a global key,
* setting the TreeProps which the component requires from its parent,
* setting a scoped component context and applies the pending state updates.
* @param c component context
*/
void applyStateUpdates(ComponentContext c) {
if (ComponentsConfiguration.useGlobalKeys) {
final Component<?> parentScope = c.getComponentScope();
final String key = getKey();
setGlobalKey(
parentScope == null ? key : parentScope.generateUniqueGlobalKeyForChild(this, key));
}
setScopedContext(ComponentContext.withComponentScope(c, this));
getLifecycle().populateTreeProps(this, getScopedContext().getTreeProps());
if (ComponentsConfiguration.useGlobalKeys) {
final KeyHandler keyHandler = getScopedContext().getKeyHandler();
/** This is for testing, the keyHandler should never be null here otherwise. */
if (keyHandler != null && !ComponentsConfiguration.isEndToEndTestRun) {
keyHandler.registerKey(this);
}
registerEventTrigger(getGlobalKey());
}
if (getLifecycle().hasState()) {
c.getStateHandler().applyStateUpdatesForComponent(this);
}
}
private void registerEventTrigger(String globalKey) {
ComponentContext context = getScopedContext();
if (!getLifecycle().canAcceptTrigger()) {
context.unregisterTrigger(globalKey);
return;
}
context.registerTrigger(context.newEventTrigger(), globalKey);
}
ComponentLayoutAttributes getLayoutAttributes() {
return mComponentLayoutAttributes;
}
private ComponentLayoutAttributes getOrCreateLayoutAttributes() {
if (mComponentLayoutAttributes == null) {
mComponentLayoutAttributes = new ComponentLayoutAttributes();
}
return mComponentLayoutAttributes;
}
@Deprecated
@Override
public EventDispatcher getEventDispatcher() {
return this;
}
@Deprecated
@Override
public EventTriggerTarget getEventTriggerTarget() {
return this;
}
/**
* @param <T> the type of this builder. Required to ensure methods defined here in the abstract
* class correctly return the type of the concrete subclass.
*/
public abstract static class Builder<L extends Component, T extends Builder<L, T>>
extends ResourceResolver {
private ComponentContext mContext;
@AttrRes private int mDefStyleAttr;
@StyleRes private int mDefStyleRes;
private Component mComponent;
protected void init(
ComponentContext c,
@AttrRes int defStyleAttr,
@StyleRes int defStyleRes,
Component<L> component) {
super.init(c, c.getResourceCache());
mComponent = component;
mContext = c;
mDefStyleAttr = defStyleAttr;
mDefStyleRes = defStyleRes;
if (defStyleAttr != 0 || defStyleRes != 0) {
mComponent.getOrCreateLayoutAttributes().setStyle(defStyleAttr, defStyleRes);
component.loadStyle(c, defStyleAttr, defStyleRes, component);
}
}
public abstract T getThis();
/** Set a key on the component that is local to its parent. */
public T key(String key) {
mComponent.setKey(key);
return getThis();
}
@Override
protected void release() {
super.release();
mContext = null;
mDefStyleAttr = 0;
mDefStyleRes = 0;
mComponent = null;
}
/**
* Checks that all the required props are supplied, and if not throws a useful exception
*
* @param requiredPropsCount expected number of props
* @param required the bit set that identifies which props have been supplied
* @param requiredPropsNames the names of all props used for a useful error message
*/
protected static void checkArgs(
int requiredPropsCount, BitSet required, String[] requiredPropsNames) {
if (required != null && required.nextClearBit(0) < requiredPropsCount) {
List<String> missingProps = new ArrayList<>();
for (int i = 0; i < requiredPropsCount; i++) {
if (!required.get(i)) {
missingProps.add(requiredPropsNames[i]);
}
}
throw new IllegalStateException(
"The following props are not marked as optional and were not supplied: "
+ Arrays.toString(missingProps.toArray()));
}
}
public final ComponentLayout buildWithLayout() {
return this.withLayout().build();
}
/**
* @deprecated You no longer need to use this method in order to add layout attributes, you can
* just add them directly to the component.
*/
@Deprecated
public final ComponentLayout.Builder withLayout() {
// calling build() which will release this builder setting these members to null/0.
// We must capture their value before that happens.
final ComponentContext context = mContext;
final int defStyleAttr = mDefStyleAttr;
final int defStyleRes = mDefStyleRes;
return Layout.create(context, build(), defStyleAttr, defStyleRes);
}
@ReturnsOwnership
public abstract Component<L> build();
public T layoutDirection(YogaDirection layoutDirection) {
mComponent.getOrCreateLayoutAttributes().layoutDirection(layoutDirection);
return getThis();
}
public T alignSelf(YogaAlign alignSelf) {
mComponent.getOrCreateLayoutAttributes().alignSelf(alignSelf);
return getThis();
}
public T positionType(YogaPositionType positionType) {
mComponent.getOrCreateLayoutAttributes().positionType(positionType);
return getThis();
}
public T flex(float flex) {
mComponent.getOrCreateLayoutAttributes().flex(flex);
return getThis();
}
public T flexGrow(float flexGrow) {
mComponent.getOrCreateLayoutAttributes().flexGrow(flexGrow);
return getThis();
}
public T flexShrink(float flexShrink) {
mComponent.getOrCreateLayoutAttributes().flexShrink(flexShrink);
return getThis();
}
public T flexBasisPx(@Px int flexBasis) {
mComponent.getOrCreateLayoutAttributes().flexBasisPx(flexBasis);
return getThis();
}
public T flexBasisPercent(float percent) {
mComponent.getOrCreateLayoutAttributes().flexBasisPercent(percent);
return getThis();
}
public T flexBasisAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return flexBasisPx(resolveDimenSizeAttr(resId, defaultResId));
}
public T flexBasisAttr(@AttrRes int resId) {
return flexBasisAttr(resId, 0);
}
public T flexBasisRes(@DimenRes int resId) {
return flexBasisPx(resolveDimenSizeRes(resId));
}
public T flexBasisDip(@Dimension(unit = DP) float flexBasis) {
return flexBasisPx(dipsToPixels(flexBasis));
}
public T importantForAccessibility(int importantForAccessibility) {
mComponent.getOrCreateLayoutAttributes().importantForAccessibility(importantForAccessibility);
return getThis();
}
public T duplicateParentState(boolean duplicateParentState) {
mComponent.getOrCreateLayoutAttributes().duplicateParentState(duplicateParentState);
return getThis();
}
public T marginPx(YogaEdge edge, @Px int margin) {
mComponent.getOrCreateLayoutAttributes().marginPx(edge, margin);
return getThis();
}
public T marginPercent(YogaEdge edge, float percent) {
mComponent.getOrCreateLayoutAttributes().marginPercent(edge, percent);
return getThis();
}
public T marginAuto(YogaEdge edge) {
mComponent.getOrCreateLayoutAttributes().marginAuto(edge);
return getThis();
}
public T marginAttr(YogaEdge edge, @AttrRes int resId, @DimenRes int defaultResId) {
return marginPx(edge, resolveDimenSizeAttr(resId, defaultResId));
}
public T marginAttr(YogaEdge edge, @AttrRes int resId) {
return marginAttr(edge, resId, 0);
}
public T marginRes(YogaEdge edge, @DimenRes int resId) {
return marginPx(edge, resolveDimenSizeRes(resId));
}
public T marginDip(YogaEdge edge, @Dimension(unit = DP) float margin) {
return marginPx(edge, dipsToPixels(margin));
}
public T paddingPx(YogaEdge edge, @Px int padding) {
mComponent.getOrCreateLayoutAttributes().paddingPx(edge, padding);
return getThis();
}
public T paddingPercent(YogaEdge edge, float percent) {
mComponent.getOrCreateLayoutAttributes().paddingPercent(edge, percent);
return getThis();
}
public T paddingAttr(YogaEdge edge, @AttrRes int resId, @DimenRes int defaultResId) {
return paddingPx(edge, resolveDimenSizeAttr(resId, defaultResId));
}
public T paddingAttr(YogaEdge edge, @AttrRes int resId) {
return paddingAttr(edge, resId, 0);
}
public T paddingRes(YogaEdge edge, @DimenRes int resId) {
return paddingPx(edge, resolveDimenSizeRes(resId));
}
public T paddingDip(YogaEdge edge, @Dimension(unit = DP) float padding) {
return paddingPx(edge, dipsToPixels(padding));
}
public T border(Border border) {
mComponent.getOrCreateLayoutAttributes().border(border);
return getThis();
}
public T positionPx(YogaEdge edge, @Px int position) {
mComponent.getOrCreateLayoutAttributes().positionPx(edge, position);
return getThis();
}
public T positionPercent(YogaEdge edge, float percent) {
mComponent.getOrCreateLayoutAttributes().positionPercent(edge, percent);
return getThis();
}
public T positionAttr(YogaEdge edge, @AttrRes int resId, @DimenRes int defaultResId) {
return positionPx(edge, resolveDimenSizeAttr(resId, defaultResId));
}
public T positionAttr(YogaEdge edge, @AttrRes int resId) {
return positionAttr(edge, resId, 0);
}
public T positionRes(YogaEdge edge, @DimenRes int resId) {
return positionPx(edge, resolveDimenSizeRes(resId));
}
public T positionDip(YogaEdge edge, @Dimension(unit = DP) float position) {
return positionPx(edge, dipsToPixels(position));
}
public T widthPx(@Px int width) {
mComponent.getOrCreateLayoutAttributes().widthPx(width);
return getThis();
}
public T widthPercent(float percent) {
mComponent.getOrCreateLayoutAttributes().widthPercent(percent);
return getThis();
}
public T widthRes(@DimenRes int resId) {
return widthPx(resolveDimenSizeRes(resId));
}
public T widthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return widthPx(resolveDimenSizeAttr(resId, defaultResId));
}
public T widthAttr(@AttrRes int resId) {
return widthAttr(resId, 0);
}
public T widthDip(@Dimension(unit = DP) float width) {
return widthPx(dipsToPixels(width));
}
public T minWidthPx(@Px int minWidth) {
mComponent.getOrCreateLayoutAttributes().minWidthPx(minWidth);
return getThis();
}
public T minWidthPercent(float percent) {
mComponent.getOrCreateLayoutAttributes().minWidthPercent(percent);
return getThis();
}
public T minWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return minWidthPx(resolveDimenSizeAttr(resId, defaultResId));
}
public T minWidthAttr(@AttrRes int resId) {
return minWidthAttr(resId, 0);
}
public T minWidthRes(@DimenRes int resId) {
return minWidthPx(resolveDimenSizeRes(resId));
}
public T minWidthDip(@Dimension(unit = DP) float minWidth) {
return minWidthPx(dipsToPixels(minWidth));
}
public T maxWidthPx(@Px int maxWidth) {
mComponent.getOrCreateLayoutAttributes().maxWidthPx(maxWidth);
return getThis();
}
public T maxWidthPercent(float percent) {
mComponent.getOrCreateLayoutAttributes().maxWidthPercent(percent);
return getThis();
}
public T maxWidthAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return maxWidthPx(resolveDimenSizeAttr(resId, defaultResId));
}
public T maxWidthAttr(@AttrRes int resId) {
return maxWidthAttr(resId, 0);
}
public T maxWidthRes(@DimenRes int resId) {
return maxWidthPx(resolveDimenSizeRes(resId));
}
public T maxWidthDip(@Dimension(unit = DP) float maxWidth) {
return maxWidthPx(dipsToPixels(maxWidth));
}
public T heightPx(@Px int height) {
mComponent.getOrCreateLayoutAttributes().heightPx(height);
return getThis();
}
public T heightPercent(float percent) {
mComponent.getOrCreateLayoutAttributes().heightPercent(percent);
return getThis();
}
public T heightRes(@DimenRes int resId) {
return heightPx(resolveDimenSizeRes(resId));
}
public T heightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return heightPx(resolveDimenSizeAttr(resId, defaultResId));
}
public T heightAttr(@AttrRes int resId) {
return heightAttr(resId, 0);
}
public T heightDip(@Dimension(unit = DP) float height) {
return heightPx(dipsToPixels(height));
}
public T minHeightPx(@Px int minHeight) {
mComponent.getOrCreateLayoutAttributes().minHeightPx(minHeight);
return getThis();
}
public T minHeightPercent(float percent) {
mComponent.getOrCreateLayoutAttributes().minHeightPercent(percent);
return getThis();
}
public T minHeightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return minHeightPx(resolveDimenSizeAttr(resId, defaultResId));
}
public T minHeightAttr(@AttrRes int resId) {
return minHeightAttr(resId, 0);
}
public T minHeightRes(@DimenRes int resId) {
return minHeightPx(resolveDimenSizeRes(resId));
}
public T minHeightDip(@Dimension(unit = DP) float minHeight) {
return minHeightPx(dipsToPixels(minHeight));
}
public T maxHeightPx(@Px int maxHeight) {
mComponent.getOrCreateLayoutAttributes().maxHeightPx(maxHeight);
return getThis();
}
public T maxHeightPercent(float percent) {
mComponent.getOrCreateLayoutAttributes().maxHeightPercent(percent);
return getThis();
}
public T maxHeightAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return maxHeightPx(resolveDimenSizeAttr(resId, defaultResId));
}
public T maxHeightAttr(@AttrRes int resId) {
return maxHeightAttr(resId, 0);
}
public T maxHeightRes(@DimenRes int resId) {
return maxHeightPx(resolveDimenSizeRes(resId));
}
public T maxHeightDip(@Dimension(unit = DP) float maxHeight) {
return maxHeightPx(dipsToPixels(maxHeight));
}
public T aspectRatio(float aspectRatio) {
mComponent.getOrCreateLayoutAttributes().aspectRatio(aspectRatio);
return getThis();
}
public T touchExpansionPx(YogaEdge edge, @Px int touchExpansion) {
mComponent.getOrCreateLayoutAttributes().touchExpansionPx(edge, touchExpansion);
return getThis();
}
public T touchExpansionAttr(YogaEdge edge, @AttrRes int resId, @DimenRes int defaultResId) {
return touchExpansionPx(edge, resolveDimenSizeAttr(resId, defaultResId));
}
public T touchExpansionAttr(YogaEdge edge, @AttrRes int resId) {
return touchExpansionAttr(edge, resId, 0);
}
public T touchExpansionRes(YogaEdge edge, @DimenRes int resId) {
return touchExpansionPx(edge, resolveDimenSizeRes(resId));
}
public T touchExpansionDip(YogaEdge edge, @Dimension(unit = DP) float touchExpansion) {
return touchExpansionPx(edge, dipsToPixels(touchExpansion));
}
public T background(Reference<? extends Drawable> background) {
mComponent.getOrCreateLayoutAttributes().background(background);
return getThis();
}
public T background(Reference.Builder<? extends Drawable> builder) {
return background(builder.build());
}
public T background(Drawable background) {
return background(DrawableReference.create().drawable(background));
}
public T backgroundAttr(@AttrRes int resId, @DrawableRes int defaultResId) {
return backgroundRes(resolveResIdAttr(resId, defaultResId));
}
public T backgroundAttr(@AttrRes int resId) {
return backgroundAttr(resId, 0);
}
public T backgroundRes(@DrawableRes int resId) {
if (resId == 0) {
return background((Reference<? extends Drawable>) null);
}
return background(mContext.getResources().getDrawable(resId));
}
public T backgroundColor(@ColorInt int backgroundColor) {
return background(new ColorDrawable(backgroundColor));
}
public T foreground(Drawable foreground) {
mComponent.getOrCreateLayoutAttributes().foreground(foreground);
return getThis();
}
public T foregroundAttr(@AttrRes int resId, @DrawableRes int defaultResId) {
return foregroundRes(resolveResIdAttr(resId, defaultResId));
}
public T foregroundAttr(@AttrRes int resId) {
return foregroundAttr(resId, 0);
}
public T foregroundRes(@DrawableRes int resId) {
if (resId == 0) {
return foreground(null);
}
return foreground(mContext.getResources().getDrawable(resId));
}
public T foregroundColor(@ColorInt int foregroundColor) {
return foreground(new ColorDrawable(foregroundColor));
}
public T wrapInView() {
mComponent.getOrCreateLayoutAttributes().wrapInView();
return getThis();
}
public T clickHandler(EventHandler<ClickEvent> clickHandler) {
mComponent.getOrCreateLayoutAttributes().clickHandler(clickHandler);
return getThis();
}
public T longClickHandler(EventHandler<LongClickEvent> longClickHandler) {
mComponent.getOrCreateLayoutAttributes().longClickHandler(longClickHandler);
return getThis();
}
public T focusChangeHandler(EventHandler<FocusChangedEvent> focusChangeHandler) {
mComponent.getOrCreateLayoutAttributes().focusChangeHandler(focusChangeHandler);
return getThis();
}
public T touchHandler(EventHandler<TouchEvent> touchHandler) {
mComponent.getOrCreateLayoutAttributes().touchHandler(touchHandler);
return getThis();
}
public T interceptTouchHandler(EventHandler<InterceptTouchEvent> interceptTouchHandler) {
mComponent.getOrCreateLayoutAttributes().interceptTouchHandler(interceptTouchHandler);
return getThis();
}
public T focusable(boolean isFocusable) {
mComponent.getOrCreateLayoutAttributes().focusable(isFocusable);
return getThis();
}
public T enabled(boolean isEnabled) {
mComponent.getOrCreateLayoutAttributes().enabled(isEnabled);
return getThis();
}
public T visibleHeightRatio(float visibleHeightRatio) {
mComponent.getOrCreateLayoutAttributes().visibleHeightRatio(visibleHeightRatio);
return getThis();
}
public T visibleWidthRatio(float visibleWidthRatio) {
mComponent.getOrCreateLayoutAttributes().visibleWidthRatio(visibleWidthRatio);
return getThis();
}
public T visibleHandler(EventHandler<VisibleEvent> visibleHandler) {
mComponent.getOrCreateLayoutAttributes().visibleHandler(visibleHandler);
return getThis();
}
public T focusedHandler(EventHandler<FocusedVisibleEvent> focusedHandler) {
mComponent.getOrCreateLayoutAttributes().focusedHandler(focusedHandler);
return getThis();
}
public T unfocusedHandler(EventHandler<UnfocusedVisibleEvent> unfocusedHandler) {
mComponent.getOrCreateLayoutAttributes().unfocusedHandler(unfocusedHandler);
return getThis();
}
public T fullImpressionHandler(EventHandler<FullImpressionVisibleEvent> fullImpressionHandler) {
mComponent.getOrCreateLayoutAttributes().fullImpressionHandler(fullImpressionHandler);
return getThis();
}
public T invisibleHandler(EventHandler<InvisibleEvent> invisibleHandler) {
mComponent.getOrCreateLayoutAttributes().invisibleHandler(invisibleHandler);
return getThis();
}
public T contentDescription(CharSequence contentDescription) {
mComponent.getOrCreateLayoutAttributes().contentDescription(contentDescription);
return getThis();
}
public T contentDescription(@StringRes int stringId) {
return contentDescription(mContext.getResources().getString(stringId));
}
public T contentDescription(@StringRes int stringId, Object... formatArgs) {
return contentDescription(mContext.getResources().getString(stringId, formatArgs));
}
public T viewTag(Object viewTag) {
mComponent.getOrCreateLayoutAttributes().viewTag(viewTag);
return getThis();
}
public T viewTags(SparseArray<Object> viewTags) {
mComponent.getOrCreateLayoutAttributes().viewTags(viewTags);
return getThis();
}
public T shadowElevationPx(float shadowElevation) {
mComponent.getOrCreateLayoutAttributes().shadowElevationPx(shadowElevation);
return getThis();
}
public T shadowElevationAttr(@AttrRes int resId, @DimenRes int defaultResId) {
return shadowElevationPx(resolveDimenSizeAttr(resId, defaultResId));
}
public T shadowElevationAttr(@AttrRes int resId) {
return shadowElevationAttr(resId, 0);
}
public T shadowElevationRes(@DimenRes int resId) {
return shadowElevationPx(resolveDimenSizeRes(resId));
}
public T shadowElevationDip(@Dimension(unit = DP) float shadowElevation) {
return shadowElevationPx(dipsToPixels(shadowElevation));
}
public T outlineProvider(ViewOutlineProvider outlineProvider) {
mComponent.getOrCreateLayoutAttributes().outlineProvider(outlineProvider);
return getThis();
}
public T clipToOutline(boolean clipToOutline) {
mComponent.getOrCreateLayoutAttributes().clipToOutline(clipToOutline);
return getThis();
}
public T testKey(String testKey) {
mComponent.getOrCreateLayoutAttributes().testKey(testKey);
return getThis();
}
public T dispatchPopulateAccessibilityEventHandler(
EventHandler<DispatchPopulateAccessibilityEventEvent>
dispatchPopulateAccessibilityEventHandler) {
mComponent
.getOrCreateLayoutAttributes()
.dispatchPopulateAccessibilityEventHandler(dispatchPopulateAccessibilityEventHandler);
return getThis();
}
public T onInitializeAccessibilityEventHandler(
EventHandler<OnInitializeAccessibilityEventEvent> onInitializeAccessibilityEventHandler) {
mComponent
.getOrCreateLayoutAttributes()
.onInitializeAccessibilityEventHandler(onInitializeAccessibilityEventHandler);
return getThis();
}
public T onInitializeAccessibilityNodeInfoHandler(
EventHandler<OnInitializeAccessibilityNodeInfoEvent>
onInitializeAccessibilityNodeInfoHandler) {
mComponent
.getOrCreateLayoutAttributes()
.onInitializeAccessibilityNodeInfoHandler(onInitializeAccessibilityNodeInfoHandler);
return getThis();
}
public T onPopulateAccessibilityEventHandler(
EventHandler<OnPopulateAccessibilityEventEvent> onPopulateAccessibilityEventHandler) {
mComponent
.getOrCreateLayoutAttributes()
.onPopulateAccessibilityEventHandler(onPopulateAccessibilityEventHandler);
return getThis();
}
public T onRequestSendAccessibilityEventHandler(
EventHandler<OnRequestSendAccessibilityEventEvent> onRequestSendAccessibilityEventHandler) {
mComponent
.getOrCreateLayoutAttributes()
.onRequestSendAccessibilityEventHandler(onRequestSendAccessibilityEventHandler);
return getThis();
}
public T performAccessibilityActionHandler(
EventHandler<PerformAccessibilityActionEvent> performAccessibilityActionHandler) {
mComponent
.getOrCreateLayoutAttributes()
.performAccessibilityActionHandler(performAccessibilityActionHandler);
return getThis();
}
public T sendAccessibilityEventHandler(
EventHandler<SendAccessibilityEventEvent> sendAccessibilityEventHandler) {
mComponent
.getOrCreateLayoutAttributes()
.sendAccessibilityEventHandler(sendAccessibilityEventHandler);
return getThis();
}
public T sendAccessibilityEventUncheckedHandler(
EventHandler<SendAccessibilityEventUncheckedEvent> sendAccessibilityEventUncheckedHandler) {
mComponent
.getOrCreateLayoutAttributes()
.sendAccessibilityEventUncheckedHandler(sendAccessibilityEventUncheckedHandler);
return getThis();
}
public T transitionKey(String key) {
mComponent.getOrCreateLayoutAttributes().transitionKey(key);
return getThis();
}
public T alpha(float alpha) {
mComponent.getOrCreateLayoutAttributes().alpha(alpha);
return getThis();
}
public T scale(float scale) {
mComponent.getOrCreateLayoutAttributes().scale(scale);
return getThis();
}
}
}
|
package org.cloudname.log.archiver;
import org.cloudname.log.pb.Timber;
import java.io.File;
import java.io.IOException;
/**
* This class implements a very simplistic log archiver that will
* archive logs using the Timber format to archive log messages in
* archive slots.
*
* <i> This implementation was originally written for the Timber log
* server but was moved here since we want to use the same code in
* multiple different settings. This is why this log archiver has
* some machinery for managing multiple open slots; in a server
* setting we have to assume that some portion of the log messages
* will be delayed. This code will be revisited and optimized if it
* is deemed necessary.</i>
*
* @author borud
*/
public class Archiver {
private static final int MAX_FILES_OPEN = 2;
private String service = "";
private final SlotMapper slotMapper = new SlotMapper();
private final SlotLruCache<String,Slot> slotLruCache = new SlotLruCache<String,Slot>(MAX_FILES_OPEN);
private final String logPath;
private final long maxFileSize;
private boolean closed = false;
/**
* The directory
* @param logPath folder to store logs
* @param service name of the service storing logs
* @param maxFileSize maximum file size in bytes
*/
public Archiver(String logPath, String service, long maxFileSize) {
this.logPath = logPath;
this.service = service;
this.maxFileSize = maxFileSize;
}
/**
* Initialize the archiver. If the logging directory specified in
* the constructor does not exist it will be created.
*/
public void init() {
final File logDir = new File(logPath);
// Make the root log directory if it does not exist
if (! logDir.exists()) {
logDir.mkdirs();
}
}
public WriteReport handle(final Timber.LogEvent logEvent) {
if (closed) {
throw new IllegalStateException("Archiver was closed");
}
try {
return getSlot(logEvent).write(logEvent);
} catch (IOException e) {
throw new ArchiverException("Got IOException while handling logEvent", e);
}
}
/**
* Ensure that all currently opened slot files are flushed to
* disk.
*
* @throws ArchiverException if an io error occurred when trying
* to flush the slot files. The original IO exception causing
* the problem will be chained.
*
*/
public void flush() {
for (final Slot slot : slotLruCache.values()) {
try {
slot.flush();
} catch (IOException e) {
throw new ArchiverException("Got IOException while flushing " + slot.toString(), e);
}
}
}
public void close() {
for (final Slot slot : slotLruCache.values()) {
try {
slot.close();
} catch (IOException e) {
throw new ArchiverException("Got IOException while closing " + slot.toString(), e);
}
}
closed = true;
}
/**
* @return the slot a Timber.LogEvent belongs in.
*/
private Slot getSlot(Timber.LogEvent event) {
String slotPathPrefix = logPath + File.separator + slotMapper.map(event.getTimestamp(), service);
Slot slot = slotLruCache.get(slotPathPrefix);
if (null != slot) {
return slot;
}
slot = new Slot(slotPathPrefix, maxFileSize);
slotLruCache.put(slotPathPrefix, slot);
return slot;
}
}
|
package lucee.commons.io;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletContext;
import lucee.aprint;
import lucee.commons.digest.MD5;
import lucee.commons.io.log.Log;
import lucee.commons.io.log.LogUtil;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.ResourceProvider;
import lucee.commons.io.res.ResourcesImpl;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.lang.ClassUtil;
import lucee.commons.lang.StringUtil;
import lucee.loader.TP;
import lucee.loader.engine.CFMLEngineFactory;
import lucee.runtime.Info;
import lucee.runtime.PageContext;
import lucee.runtime.PageContextImpl;
import lucee.runtime.config.Config;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.DatabaseException;
import lucee.runtime.exp.StopException;
import lucee.runtime.functions.other.CreateUniqueId;
import lucee.runtime.net.http.ReqRspUtil;
import lucee.runtime.op.Caster;
import lucee.runtime.type.Array;
import lucee.runtime.type.Collection;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Query;
import lucee.runtime.type.QueryImpl;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.util.KeyConstants;
import lucee.runtime.type.util.ListUtil;
import com.jezhumble.javasysmon.CpuTimes;
import com.jezhumble.javasysmon.JavaSysMon;
import com.jezhumble.javasysmon.MemoryStats;
public final class SystemUtil {
public static final int MEMORY_TYPE_ALL=0;
public static final int MEMORY_TYPE_HEAP=1;
public static final int MEMORY_TYPE_NON_HEAP=2;
public static final int ARCH_UNKNOW=0;
public static final int ARCH_32=32;
public static final int ARCH_64=64;
public static final char CHAR_DOLLAR=(char)36;
public static final char CHAR_POUND=(char)163;
public static final char CHAR_EURO=(char)8364;
public static final int JAVA_VERSION_1_0 = 0;
public static final int JAVA_VERSION_1_1 = 1;
public static final int JAVA_VERSION_1_2 = 2;
public static final int JAVA_VERSION_1_3 = 3;
public static final int JAVA_VERSION_1_4 = 4;
public static final int JAVA_VERSION_1_5 = 5;
public static final int JAVA_VERSION_1_6 = 6;
public static final int JAVA_VERSION_1_7 = 7;
public static final int JAVA_VERSION_1_8 = 8;
public static final int JAVA_VERSION_1_9 = 9;
public static final int OUT = 0;
public static final int ERR = 1;
private static final PrintWriter PRINTWRITER_OUT = new PrintWriter(System.out);
private static final PrintWriter PRINTWRITER_ERR = new PrintWriter(System.err);
private static PrintWriter[] printWriter=new PrintWriter[2];
private static final boolean isWindows=System.getProperty("os.name").toLowerCase().startsWith("windows");
private static final boolean isUnix=!isWindows && File.separatorChar == '/';
private static final String JAVA_VERSION_STRING = System.getProperty("java.version");
public static final int JAVA_VERSION;
static {
if(JAVA_VERSION_STRING.startsWith("1.9.")) JAVA_VERSION=JAVA_VERSION_1_9;
else if(JAVA_VERSION_STRING.startsWith("1.8.")) JAVA_VERSION=JAVA_VERSION_1_8;
else if(JAVA_VERSION_STRING.startsWith("1.7.")) JAVA_VERSION=JAVA_VERSION_1_7;
else if(JAVA_VERSION_STRING.startsWith("1.6.")) JAVA_VERSION=JAVA_VERSION_1_6;
else if(JAVA_VERSION_STRING.startsWith("1.5.")) JAVA_VERSION=JAVA_VERSION_1_5;
else if(JAVA_VERSION_STRING.startsWith("1.4.")) JAVA_VERSION=JAVA_VERSION_1_4;
else if(JAVA_VERSION_STRING.startsWith("1.3.")) JAVA_VERSION=JAVA_VERSION_1_3;
else if(JAVA_VERSION_STRING.startsWith("1.2.")) JAVA_VERSION=JAVA_VERSION_1_2;
else if(JAVA_VERSION_STRING.startsWith("1.1.")) JAVA_VERSION=JAVA_VERSION_1_1;
else JAVA_VERSION=JAVA_VERSION_1_0;
}
private static Resource tempFile;
private static Resource homeFile;
private static Resource[] classPathes;
private static Charset charset;
private static String lineSeparator=System.getProperty("line.separator","\n");
private static MemoryPoolMXBean permGenSpaceBean;
public static int osArch=-1;
public static int jreArch=-1;
static {
String strCharset=System.getProperty("file.encoding");
if(strCharset==null || strCharset.equalsIgnoreCase("MacRoman"))
strCharset="cp1252";
if(strCharset.equalsIgnoreCase("utf-8")) charset=CharsetUtil.UTF8;
else if(strCharset.equalsIgnoreCase("iso-8859-1")) charset=CharsetUtil.ISO88591;
else charset=CharsetUtil.toCharset(strCharset,null);
// Perm Gen
permGenSpaceBean=getPermGenSpaceBean();
// make sure the JVM does not always a new bean
MemoryPoolMXBean tmp = getPermGenSpaceBean();
if(tmp!=permGenSpaceBean)permGenSpaceBean=null;
}
public static MemoryPoolMXBean getPermGenSpaceBean() {
java.util.List<MemoryPoolMXBean> manager = ManagementFactory.getMemoryPoolMXBeans();
MemoryPoolMXBean bean;
// PERM GEN
Iterator<MemoryPoolMXBean> it = manager.iterator();
while(it.hasNext()){
bean = it.next();
if("Perm Gen".equalsIgnoreCase(bean.getName()) || "CMS Perm Gen".equalsIgnoreCase(bean.getName())) {
return bean;
}
}
it = manager.iterator();
while(it.hasNext()){
bean = it.next();
if(StringUtil.indexOfIgnoreCase(bean.getName(),"Perm Gen")!=-1 || StringUtil.indexOfIgnoreCase(bean.getName(),"PermGen")!=-1) {
return bean;
}
}
// take none-heap when only one
it = manager.iterator();
LinkedList<MemoryPoolMXBean> beans=new LinkedList<MemoryPoolMXBean>();
while(it.hasNext()){
bean = it.next();
if(bean.getType().equals(MemoryType.NON_HEAP)) {
beans.add(bean);
return bean;
}
}
if(beans.size()==1) return beans.getFirst();
// Class Memory/ClassBlock Memory?
it = manager.iterator();
while(it.hasNext()){
bean = it.next();
if(StringUtil.indexOfIgnoreCase(bean.getName(),"Class Memory")!=-1) {
return bean;
}
}
return null;
}
private static Boolean isFSCaseSensitive;
private static JavaSysMon jsm;
private static Boolean isCLI;
private static double loaderVersion=0D;
private static String macAddress;
/**
* returns if the file system case sensitive or not
* @return is the file system case sensitive or not
*/
public static boolean isFSCaseSensitive() {
if(isFSCaseSensitive==null) {
try {
_isFSCaseSensitive(File.createTempFile("abcx","txt"));
}
catch (IOException e) {
File f = new File("abcx.txt").getAbsoluteFile();
try {
f.createNewFile();
_isFSCaseSensitive(f);
} catch (IOException e1) {
throw new RuntimeException(e1.getMessage());
}
}
}
return isFSCaseSensitive.booleanValue();
}
private static void _isFSCaseSensitive(File f) {
File temp=new File(f.getPath().toUpperCase());
isFSCaseSensitive=temp.exists()?Boolean.FALSE:Boolean.TRUE;
f.delete();
}
/**
* fixes a java canonical path to a Windows path
* e.g. /C:/Windows/System32 will be changed to C:\Windows\System32
*
* @param path
* @return
*/
public static String fixWindowsPath(String path) {
if ( isWindows && path.length() > 3 && path.charAt(0) == '/' && path.charAt(2) == ':' ) {
path = path.substring(1).replace( '/', '\\' );
}
return path;
}
/**
* @return is local machine a Windows Machine
*/
public static boolean isWindows() {
return isWindows;
}
/**
* @return is local machine a Unix Machine
*/
public static boolean isUnix() {
return isUnix;
}
/**
* @return return System directory
*/
public static Resource getSystemDirectory() {
String pathes=System.getProperty("java.library.path");
ResourceProvider fr = ResourcesImpl.getFileResourceProvider();
if(pathes!=null) {
String[] arr=ListUtil.toStringArrayEL(ListUtil.listToArray(pathes,File.pathSeparatorChar));
for(int i=0;i<arr.length;i++) {
if(arr[i].toLowerCase().indexOf("windows\\system")!=-1) {
Resource file = fr.getResource(arr[i]);
if(file.exists() && file.isDirectory() && file.isWriteable()) return ResourceUtil.getCanonicalResourceEL(file);
}
}
for(int i=0;i<arr.length;i++) {
if(arr[i].toLowerCase().indexOf("windows")!=-1) {
Resource file = fr.getResource(arr[i]);
if(file.exists() && file.isDirectory() && file.isWriteable()) return ResourceUtil.getCanonicalResourceEL(file);
}
}
for(int i=0;i<arr.length;i++) {
if(arr[i].toLowerCase().indexOf("winnt")!=-1) {
Resource file = fr.getResource(arr[i]);
if(file.exists() && file.isDirectory() && file.isWriteable()) return ResourceUtil.getCanonicalResourceEL(file);
}
}
for(int i=0;i<arr.length;i++) {
if(arr[i].toLowerCase().indexOf("win")!=-1) {
Resource file = fr.getResource(arr[i]);
if(file.exists() && file.isDirectory() && file.isWriteable()) return ResourceUtil.getCanonicalResourceEL(file);
}
}
for(int i=0;i<arr.length;i++) {
Resource file = fr.getResource(arr[i]);
if(file.exists() && file.isDirectory() && file.isWriteable()) return ResourceUtil.getCanonicalResourceEL(file);
}
}
return null;
}
/**
* @return return running context root
*/
public static Resource getRuningContextRoot() {
ResourceProvider frp = ResourcesImpl.getFileResourceProvider();
try {
return frp.getResource(".").getCanonicalResource();
} catch (IOException e) {}
URL url=new Info().getClass().getClassLoader().getResource(".");
try {
return frp.getResource(FileUtil.URLToFile(url).getAbsolutePath());
} catch (MalformedURLException e) {
return null;
}
}
/**
* returns the Temp Directory of the System
* @return temp directory
*/
public static Resource getTempDirectory() {
if(tempFile!=null) return tempFile;
ResourceProvider fr = ResourcesImpl.getFileResourceProvider();
String tmpStr = System.getProperty("java.io.tmpdir");
if(tmpStr!=null) {
tempFile=fr.getResource(tmpStr);
if(tempFile.exists()) {
tempFile=ResourceUtil.getCanonicalResourceEL(tempFile);
return tempFile;
}
}
File tmp =null;
try {
tmp = File.createTempFile("a","a");
tempFile=fr.getResource(tmp.getParent());
tempFile=ResourceUtil.getCanonicalResourceEL(tempFile);
}
catch(IOException ioe) {}
finally {
if(tmp!=null)tmp.delete();
}
return tempFile;
}
/**
* returns the a unique temp file (with no auto delete)
* @param extension
* @return temp directory
* @throws IOException
*/
public static Resource getTempFile(String extension, boolean touch) throws IOException {
String filename=CreateUniqueId.invoke();
if(!StringUtil.isEmpty(extension,true)){
if(extension.startsWith("."))filename+=extension;
else filename+="."+extension;
}
Resource file = getTempDirectory().getRealResource(filename);
if(touch)ResourceUtil.touch(file);
return file;
}
/**
* returns the Hoome Directory of the System
* @return home directory
*/
public static Resource getHomeDirectory() {
if(homeFile!=null) return homeFile;
ResourceProvider frp = ResourcesImpl.getFileResourceProvider();
String homeStr = System.getProperty("user.home");
if(homeStr!=null) {
homeFile=frp.getResource(homeStr);
homeFile=ResourceUtil.getCanonicalResourceEL(homeFile);
}
return homeFile;
}
public static Resource getClassLoadeDirectory(){
return ResourceUtil.toResource(CFMLEngineFactory.getClassLoaderRoot(TP.class.getClassLoader()));
}
/**
* get class pathes from all url ClassLoaders
* @param ucl URL Class Loader
* @param pathes Hashmap with allpathes
*/
private static void getClassPathesFromClassLoader(URLClassLoader ucl, ArrayList pathes) {
ClassLoader pcl=ucl.getParent();
// parent first
if(pcl instanceof URLClassLoader)
getClassPathesFromClassLoader((URLClassLoader) pcl, pathes);
ResourceProvider frp = ResourcesImpl.getFileResourceProvider();
// get all pathes
URL[] urls=ucl.getURLs();
for(int i=0;i<urls.length;i++) {
Resource file=frp.getResource(urls[i].getPath());
if(file.exists())
pathes.add(ResourceUtil.getCanonicalResourceEL(file));
}
}
/**
* @return returns a string list of all pathes
*/
public static Resource[] getClassPathes() {
if(classPathes!=null)
return classPathes;
ArrayList pathes=new ArrayList();
String pathSeperator=System.getProperty("path.separator");
if(pathSeperator==null)pathSeperator=";";
// java.ext.dirs
ResourceProvider frp = ResourcesImpl.getFileResourceProvider();
// pathes from system properties
String strPathes=System.getProperty("java.class.path");
if(strPathes!=null) {
Array arr=ListUtil.listToArrayRemoveEmpty(strPathes,pathSeperator);
int len=arr.size();
for(int i=1;i<=len;i++) {
Resource file=frp.getResource(Caster.toString(arr.get(i,""),"").trim());
if(file.exists())
pathes.add(ResourceUtil.getCanonicalResourceEL(file));
}
}
// pathes from url class Loader (dynamic loaded classes)
ClassLoader cl = new Info().getClass().getClassLoader();
if(cl instanceof URLClassLoader)
getClassPathesFromClassLoader((URLClassLoader) cl, pathes);
return classPathes=(Resource[]) pathes.toArray(new Resource[pathes.size()]);
}
public static long getUsedMemory() {
Runtime r = Runtime.getRuntime();
return r.totalMemory()-r.freeMemory();
}
public static long getAvailableMemory() {
Runtime r = Runtime.getRuntime();
return r.freeMemory();
}
/**
* replace path placeholder with the real path, placeholders are [{temp-directory},{system-directory},{home-directory}]
* @param path
* @return updated path
*/
public static String parsePlaceHolder(String path) {
if(path==null) return path;
// Temp
if(path.startsWith("{temp")) {
if(path.startsWith("}",5)) path=getTempDirectory().getRealResource(path.substring(6)).toString();
else if(path.startsWith("-dir}",5)) path=getTempDirectory().getRealResource(path.substring(10)).toString();
else if(path.startsWith("-directory}",5)) path=getTempDirectory().getRealResource(path.substring(16)).toString();
}
// System
else if(path.startsWith("{system")) {
if(path.startsWith("}",7)) path=getSystemDirectory().getRealResource(path.substring(8)).toString();
else if(path.startsWith("-dir}",7)) path=getSystemDirectory().getRealResource(path.substring(12)).toString();
else if(path.startsWith("-directory}",7)) path=getSystemDirectory().getRealResource(path.substring(18)).toString();
}
// Home
else if(path.startsWith("{home")) {
if(path.startsWith("}",5)) path=getHomeDirectory().getRealResource(path.substring(6)).toString();
else if(path.startsWith("-dir}",5)) path=getHomeDirectory().getRealResource(path.substring(10)).toString();
else if(path.startsWith("-directory}",5)) path=getHomeDirectory().getRealResource(path.substring(16)).toString();
}
// ClassLoaderDir
else if(path.startsWith("{classloader")) {
if(path.startsWith("}",12)) path=getClassLoadeDirectory().getRealResource(path.substring(13)).toString();
else if(path.startsWith("-dir}",12)) path=getClassLoadeDirectory().getRealResource(path.substring(17)).toString();
else if(path.startsWith("-directory}",12)) path=getClassLoadeDirectory().getRealResource(path.substring(23)).toString();
}
return path;
}
public static String addPlaceHolder(Resource file, String defaultValue) {
// Temp
String path=addPlaceHolder(getTempDirectory(),file,"{temp-directory}");
if(!StringUtil.isEmpty(path)) return path;
// System
path=addPlaceHolder(getSystemDirectory(),file,"{system-directory}");
if(!StringUtil.isEmpty(path)) return path;
// Home
path=addPlaceHolder(getHomeDirectory(),file,"{home-directory}");
if(!StringUtil.isEmpty(path)) return path;
return defaultValue;
}
private static String addPlaceHolder(Resource dir, Resource file,String placeholder) {
if(ResourceUtil.isChildOf(file, dir)){
try {
return StringUtil.replace(file.getCanonicalPath(), dir.getCanonicalPath(), placeholder, true);
}
catch (IOException e) {}
}
return null;
}
public static String addPlaceHolder(Resource file, Config config, String defaultValue) {
//ResourceProvider frp = ResourcesImpl.getFileResourceProvider();
// temp
Resource dir = config.getTempDirectory();
String path = addPlaceHolder(dir,file,"{temp-directory}");
if(!StringUtil.isEmpty(path)) return path;
// Config
dir = config.getConfigDir();
path = addPlaceHolder(dir,file,"{lucee-config-directory}");
if(!StringUtil.isEmpty(path)) return path;
/* / Config WEB
dir = config.getConfigDir();
path = addPlaceHolder(dir,file,"{lucee-server-directory}");
if(!StringUtil.isEmpty(path)) return path;
*/
// Web root
dir = config.getRootDirectory();
path = addPlaceHolder(dir,file,"{web-root-directory}");
if(!StringUtil.isEmpty(path)) return path;
return addPlaceHolder(file, defaultValue);
}
public static String parsePlaceHolder(String path, ServletContext sc, Map<String,String> labels) {
if(path==null) return null;
if(path.indexOf('{')!=-1){
if((path.indexOf("{web-context-label}"))!=-1){
String id=hash(sc);
String label=labels.get(id);
if(StringUtil.isEmpty(label)) label=id;
path=StringUtil.replace(path, "{web-context-label}", label, false);
}
}
return parsePlaceHolder(path, sc);
}
public static String parsePlaceHolder(String path, ServletContext sc) {
ResourceProvider frp = ResourcesImpl.getFileResourceProvider();
if(path==null) return null;
if(path.indexOf('{')!=-1){
if(StringUtil.startsWith(path,'{')){
// Web Root
if(path.startsWith("{web-root")) {
if(path.startsWith("}",9)) path=frp.getResource(ReqRspUtil.getRootPath(sc)).getRealResource(path.substring(10)).toString();
else if(path.startsWith("-dir}",9)) path=frp.getResource(ReqRspUtil.getRootPath(sc)).getRealResource(path.substring(14)).toString();
else if(path.startsWith("-directory}",9)) path=frp.getResource(ReqRspUtil.getRootPath(sc)).getRealResource(path.substring(20)).toString();
}
else path=SystemUtil.parsePlaceHolder(path);
}
if((path.indexOf("{web-context-hash}"))!=-1){
String id=hash(sc);
path=StringUtil.replace(path, "{web-context-hash}", id, false);
}
}
return path;
}
public static String hash(ServletContext sc) {
String id=null;
try {
id=MD5.getDigestAsString(ReqRspUtil.getRootPath(sc));
}
catch (IOException e) {}
return id;
}
public static Charset getCharset() {
return charset;
}
public static void setCharset(String charset) {
SystemUtil.charset = CharsetUtil.toCharset(charset);
}
public static void setCharset(Charset charset) {
SystemUtil.charset = charset;
}
public static String getOSSpecificLineSeparator() {
return lineSeparator;
}
public static void sleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {}
}
public static void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {}
}
public static void join(Thread t) {
try {
t.join();
} catch (InterruptedException e) {}
}
/**
* locks the object (synchronized) before calling wait
* @param lock
* @param timeout
* @throws InterruptedException
*/
public static void wait(Object lock, long timeout) {
try {
synchronized (lock) {lock.wait(timeout);}
} catch (InterruptedException e) {}
}
/**
* locks the object (synchronized) before calling wait (no timeout)
* @param lock
* @throws InterruptedException
*/
public static void wait(Object lock) {
try {
synchronized (lock) {lock.wait();}
} catch (InterruptedException e) {}
}
/**
* locks the object (synchronized) before calling notify
* @param lock
* @param timeout
* @throws InterruptedException
*/
public static void notify(Object lock) {
synchronized (lock) {lock.notify();}
}
/**
* locks the object (synchronized) before calling notifyAll
* @param lock
* @param timeout
* @throws InterruptedException
*/
public static void notifyAll(Object lock) {
synchronized (lock) {lock.notifyAll();}
}
/**
* return the operating system architecture
* @return one of the following SystemUtil.ARCH_UNKNOW, SystemUtil.ARCH_32, SystemUtil.ARCH_64
*/
public static int getOSArch(){
if(osArch==-1) {
osArch = toIntArch(System.getProperty("os.arch.data.model"));
if(osArch==ARCH_UNKNOW)osArch = toIntArch(System.getProperty("os.arch"));
}
return osArch;
}
/**
* return the JRE (Java Runtime Engine) architecture, this can be different from the operating system architecture
* @return one of the following SystemUtil.ARCH_UNKNOW, SystemUtil.ARCH_32, SystemUtil.ARCH_64
*/
public static int getJREArch(){
if(jreArch==-1) {
jreArch = toIntArch(System.getProperty("sun.arch.data.model"));
if(jreArch==ARCH_UNKNOW)jreArch = toIntArch(System.getProperty("com.ibm.vm.bitmode"));
if(jreArch==ARCH_UNKNOW)jreArch = toIntArch(System.getProperty("java.vm.name"));
if(jreArch==ARCH_UNKNOW) {
int addrSize = getAddressSize();
if(addrSize==4) return ARCH_32;
if(addrSize==8) return ARCH_64;
}
}
return jreArch;
}
private static int toIntArch(String strArch){
if(!StringUtil.isEmpty(strArch)) {
if(strArch.indexOf("64")!=-1) return ARCH_64;
if(strArch.indexOf("32")!=-1) return ARCH_32;
if(strArch.indexOf("i386")!=-1) return ARCH_32;
if(strArch.indexOf("x86")!=-1) return ARCH_32;
}
return ARCH_UNKNOW;
}
public static int getAddressSize() {
try {
Class unsafe = ClassUtil.loadClass(null,"sun.misc.Unsafe",null);
if(unsafe==null) return 0;
Field unsafeField = unsafe.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Object obj = unsafeField.get(null);
Method addressSize = unsafe.getMethod("addressSize", new Class[0]);
Object res = addressSize.invoke(obj, new Object[0]);
return Caster.toIntValue(res,0);
}
catch(Throwable t){
return 0;
}
}
/*private static MemoryUsage getPermGenSpaceSize() {
MemoryUsage mu = getPermGenSpaceSize(null);
if(mu!=null) return mu;
// create error message including info about available memory blocks
StringBuilder sb=new StringBuilder();
java.util.List<MemoryPoolMXBean> manager = ManagementFactory.getMemoryPoolMXBeans();
Iterator<MemoryPoolMXBean> it = manager.iterator();
MemoryPoolMXBean bean;
while(it.hasNext()){
bean = it.next();
if(sb.length()>0)sb.append(", ");
sb.append(bean.getName());
}
throw new RuntimeException("PermGen Space information not available, available Memory blocks are ["+sb+"]");
}*/
private static MemoryUsage getPermGenSpaceSize(MemoryUsage defaultValue) {
if(permGenSpaceBean!=null) return permGenSpaceBean.getUsage();
// create on the fly when the bean is not permanent
MemoryPoolMXBean tmp = getPermGenSpaceBean();
if(tmp!=null) return tmp.getUsage();
return defaultValue;
}
public static long getFreePermGenSpaceSize() {
MemoryUsage mu = getPermGenSpaceSize(null);
if(mu==null) return -1;
long max = mu.getMax();
long used = mu.getUsed();
if(max<0 || used<0) return -1;
return max-used;
}
public static int getPermGenFreeSpaceAsAPercentageOfAvailable() {
MemoryUsage mu = getPermGenSpaceSize(null);
if(mu == null) return -1;
long max = mu.getMax();
long used = mu.getUsed();
if( max < 0 || used < 0) return -1;
//return a value that equates to a percentage of available free memory
return 100 - ((int)(100 * (((double)used) / ((double)max))));
}
public static int getFreePermGenSpacePromille() {
MemoryUsage mu = getPermGenSpaceSize(null);
if(mu==null) return -1;
long max = mu.getMax();
long used = mu.getUsed();
if(max<0 || used<0) return -1;
return (int)(1000L-(1000L*used/max));
}
public static Query getMemoryUsageAsQuery(int type) throws DatabaseException {
java.util.List<MemoryPoolMXBean> manager = ManagementFactory.getMemoryPoolMXBeans();
Iterator<MemoryPoolMXBean> it = manager.iterator();
Query qry=new QueryImpl(new Collection.Key[]{
KeyConstants._name,
KeyConstants._type,
KeyConstants._used,
KeyConstants._max,
KeyConstants._init
},0,"memory");
int row=0;
MemoryPoolMXBean bean;
MemoryUsage usage;
MemoryType _type;
while(it.hasNext()){
bean = it.next();
usage = bean.getUsage();
_type = bean.getType();
if(type==MEMORY_TYPE_HEAP && _type!=MemoryType.HEAP)continue;
if(type==MEMORY_TYPE_NON_HEAP && _type!=MemoryType.NON_HEAP)continue;
row++;
qry.addRow();
qry.setAtEL(KeyConstants._name, row, bean.getName());
qry.setAtEL(KeyConstants._type, row, _type.name());
qry.setAtEL(KeyConstants._max, row, Caster.toDouble(usage.getMax()));
qry.setAtEL(KeyConstants._used, row, Caster.toDouble(usage.getUsed()));
qry.setAtEL(KeyConstants._init, row, Caster.toDouble(usage.getInit()));
}
return qry;
}
public static Struct getMemoryUsageAsStruct(int type) {
java.util.List<MemoryPoolMXBean> manager = ManagementFactory.getMemoryPoolMXBeans();
Iterator<MemoryPoolMXBean> it = manager.iterator();
MemoryPoolMXBean bean;
MemoryUsage usage;
MemoryType _type;
long used=0,max=0,init=0;
while(it.hasNext()){
bean = it.next();
usage = bean.getUsage();
_type = bean.getType();
if((type==MEMORY_TYPE_HEAP && _type==MemoryType.HEAP) || (type==MEMORY_TYPE_NON_HEAP && _type==MemoryType.NON_HEAP)){
used+=usage.getUsed();
max+=usage.getMax();
init+=usage.getInit();
}
}
Struct sct=new StructImpl();
sct.setEL(KeyConstants._used, Caster.toDouble(used));
sct.setEL(KeyConstants._max, Caster.toDouble(max));
sct.setEL(KeyConstants._init, Caster.toDouble(init));
sct.setEL(KeyImpl.init("available"), Caster.toDouble(max-used));
return sct;
}
public static Struct getMemoryUsageCompact(int type) {
java.util.List<MemoryPoolMXBean> manager = ManagementFactory.getMemoryPoolMXBeans();
Iterator<MemoryPoolMXBean> it = manager.iterator();
MemoryPoolMXBean bean;
MemoryUsage usage;
MemoryType _type;
Struct sct=new StructImpl();
while(it.hasNext()){
bean = it.next();
usage = bean.getUsage();
_type = bean.getType();
if(type==MEMORY_TYPE_HEAP && _type!=MemoryType.HEAP)continue;
if(type==MEMORY_TYPE_NON_HEAP && _type!=MemoryType.NON_HEAP)continue;
double d=((int)(100D/usage.getMax()*usage.getUsed()))/100D;
sct.setEL(KeyImpl.init(bean.getName()), Caster.toDouble(d));
}
return sct;
}
public static String getPropertyEL(String key) {
try{
String str = System.getProperty(key);
if(!StringUtil.isEmpty(str,true)) return str;
Iterator<Entry<Object, Object>> it = System.getProperties().entrySet().iterator();
Entry<Object, Object> e;
String n;
while(it.hasNext()){
e = it.next();
n=(String) e.getKey();
if(key.equalsIgnoreCase(n)) return (String) e.getValue();
}
}
catch(Throwable t){}
return null;
}
public static long microTime() {
return System.nanoTime()/1000L;
}
public static TemplateLine getCurrentContext() {
StackTraceElement[] traces = Thread.currentThread().getStackTrace();
int line=0;
String template;
StackTraceElement trace=null;
for(int i=0;i<traces.length;i++) {
trace=traces[i];
template=trace.getFileName();
if(trace.getLineNumber()<=0 || template==null || ResourceUtil.getExtension(template,"").equals("java")) continue;
line=trace.getLineNumber();
return new TemplateLine(template,line);
}
return null;
}
public static class TemplateLine implements Serializable {
private static final long serialVersionUID = 6610978291828389799L;
public final String template;
public final int line;
public TemplateLine(String template, int line) {
this.template=template;
this.line=line;
}
public String toString(){
return template+":"+line;
}
}
public static long getFreeBytes() throws ApplicationException {
return physical().getFreeBytes();
}
public static long getTotalBytes() throws ApplicationException {
return physical().getTotalBytes();
}
public static double getCpuUsage(long time) throws ApplicationException {
if(time<1) throw new ApplicationException("time has to be bigger than 0");
if(jsm==null) jsm=new JavaSysMon();
CpuTimes cput = jsm.cpuTimes();
if(cput==null) throw new ApplicationException("CPU information are not available for this OS");
CpuTimes previous = new CpuTimes(cput.getUserMillis(),cput.getSystemMillis(),cput.getIdleMillis());
sleep(time);
return jsm.cpuTimes().getCpuUsage(previous)*100D;
}
private synchronized static MemoryStats physical() throws ApplicationException {
if(jsm==null) jsm=new JavaSysMon();
MemoryStats p = jsm.physical();
if(p==null) throw new ApplicationException("Memory information are not available for this OS");
return p;
}
public static void setPrintWriter(int type,PrintWriter pw) {
printWriter[type]=pw;
}
public static PrintWriter getPrintWriter(int type) {
if(printWriter[type]==null) {
if(type==OUT) printWriter[OUT]=PRINTWRITER_OUT;
else printWriter[ERR]=PRINTWRITER_ERR;
}
return printWriter[type];
}
public static boolean isCLICall() {
if(isCLI==null){
isCLI=Caster.toBoolean(System.getProperty("lucee.cli.call"),Boolean.FALSE);
}
return isCLI.booleanValue();
}
public static double getLoaderVersion() {
// this is done via reflection to make it work in older version, where the class lucee.loader.Version does not exist
if(loaderVersion==0D) {
loaderVersion=4D;
Class cVersion = ClassUtil.loadClass(TP.class.getClassLoader(),"lucee.loader.Version",null);
if(cVersion!=null) {
try {
Field f = cVersion.getField("VERSION");
loaderVersion=f.getDouble(null);
}
catch (Throwable t) {t.printStackTrace();}
}
}
return loaderVersion;
}
public static String getMacAddress() {
if(macAddress==null) {
try{
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
macAddress= sb.toString();
}
catch(Throwable t){}
}
return macAddress;
}
@Deprecated
public static void stop(Thread thread,Log log) {
new StopThread(thread,new StopException(thread),null).start();
/*if(thread.isAlive()){
try{
thread.stop(new StopException(thread));
}
catch(UnsupportedOperationException uoe){// Java 8 does not support Thread.stop(Throwable)
thread.stop();
}
}*/
}
public static void stop(PageContext pc,Log log) {
stop(pc,new StopException(pc.getThread()),log);
}
public static void stop(PageContext pc, Throwable t,Log log) {
new StopThread(pc,t,log).start();
}
}
class StopThread extends Thread {
private final PageContext pc;
private final Throwable t;
private final Log log;
private final Thread thread;
public StopThread(PageContext pc, Throwable t, Log log) {
this.pc=pc;
this.t=t;
this.log=log;
this.thread=pc.getThread();
}
public StopThread(Thread thread, Throwable t, Log log) {
this.pc=null;
this.t=t;
this.log=log;
this.thread=thread;
}
public void run(){
if(pc!=null){
PageContextImpl pci=(PageContextImpl) pc;
pci.stop(t);
}
int count=0;
if(thread.isAlive()) {
do{
try{
if(count>0 && log!=null) {
LogUtil.log(log, Log.LEVEL_ERROR, "", "could not stop the thread on the "+count+" approach", thread.getStackTrace());
}
if(count++>10) {
if(log!=null)LogUtil.log(log, Log.LEVEL_ERROR, "", "could not terminate the thread", thread.getStackTrace());
aprint.e(thread.getStackTrace());
break; // should never happen
}
try{
thread.stop(t);
}
catch(UnsupportedOperationException uoe){
LogUtil.log(log, Log.LEVEL_INFO, "", "Thread.stop(Throwable) is not supported by this JVM and failed with UnsupportedOperationException", thread.getStackTrace());
try {
Method m = thread.getClass().getMethod("stop0", new Class[]{Object.class});
m.setAccessible(true); // allow to access private method
m.invoke(thread, new Object[]{t});
}
catch (Throwable t) {
//LogUtil.log(log, Log.LEVEL_ERROR, "", t);
thread.stop();
}
}
}
// catch any exception
catch(Throwable t){
LogUtil.log(log, Log.LEVEL_ERROR, "", t);
}
SystemUtil.sleep(1000);
}
while(thread.isAlive() && (pc==null || ((PageContextImpl)pc).isInitialized()));
}
}
}
|
package ikube.action.rule;
import ikube.Integration;
import ikube.action.IAction;
import ikube.model.IndexContext;
import ikube.toolkit.ApplicationContextManager;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.junit.Ignore;
import org.junit.Test;
/**
* This test can be used ad-hoc to see if the rules are configured property.
*
* @author Michael Couck
* @since 20.03.11
* @version 01.00
*/
@Ignore
public class RulesIntegration extends Integration {
private Logger logger = Logger.getLogger(this.getClass());
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void evaluate() {
Map<String, IAction> actions = ApplicationContextManager.getBeans(IAction.class);
for (IAction action : actions.values()) {
logger.info("Action : " + action);
Object rules = action.getRules();
logger.info("Rules : " + rules);
if (List.class.isAssignableFrom(rules.getClass())) {
for (IRule<IndexContext> rule : (List<IRule<IndexContext>>) rules) {
for (final IndexContext indexContext : ApplicationContextManager.getBeans(IndexContext.class).values()) {
boolean result = rule.evaluate(indexContext);
logger.info("Rule : " + rule + ", result : " + result);
}
}
}
}
}
}
|
// RandomAccessInputStream.java
package loci.common;
import java.io.DataInput;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class RandomAccessInputStream extends InputStream implements DataInput {
// -- Constants --
/** Maximum size of the buffer used by the DataInputStream. */
protected static final int MAX_OVERHEAD = 1048576;
/**
* Block size to use when searching through the stream.
*/
protected static final int DEFAULT_BLOCK_SIZE = 256 * 1024; // 256 KB
/** Maximum number of bytes to search when searching through the stream. */
protected static final int MAX_SEARCH_SIZE = 512 * 1024 * 1024; // 512 MB
// -- Fields --
protected IRandomAccess raf;
/** The file name. */
protected String file;
// -- Constructors --
/**
* Constructs a hybrid RandomAccessFile/DataInputStream
* around the given file.
*/
public RandomAccessInputStream(String file) throws IOException {
this(Location.getHandle(file));
this.file = file;
}
/** Constructs a random access stream around the given handle. */
public RandomAccessInputStream(IRandomAccess handle) throws IOException {
raf = handle;
raf.setOrder(ByteOrder.BIG_ENDIAN);
}
/** Constructs a random access stream around the given byte array. */
public RandomAccessInputStream(byte[] array) throws IOException {
this(new ByteArrayHandle(array));
}
// -- RandomAccessInputStream API methods --
/** Seeks to the given offset within the stream. */
public void seek(long pos) throws IOException {
raf.seek(pos);
}
/** Gets the number of bytes in the file. */
public long length() throws IOException {
return raf.length();
}
/** Gets the current (absolute) file pointer. */
public long getFilePointer() throws IOException {
return raf.getFilePointer();
}
/** Closes the streams. */
public void close() throws IOException {
if (Location.getMappedFile(file) != null) return;
if (raf != null) raf.close();
raf = null;
}
/** Sets the endianness of the stream. */
public void order(boolean little) {
if (raf != null) {
raf.setOrder(little ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
}
}
/** Gets the endianness of the stream. */
public boolean isLittleEndian() {
return raf.getOrder() == ByteOrder.LITTLE_ENDIAN;
}
/**
* Reads a string ending with one of the characters in the given string.
*
* @see #findString(String...)
*/
public String readString(String lastChars) throws IOException {
if (lastChars.length() == 1) return findString(lastChars);
else {
String[] terminators = new String[lastChars.length()];
for (int i=0; i<terminators.length; i++) {
terminators[i] = lastChars.substring(i, i + 1);
}
return findString(terminators);
}
}
/**
* Reads a string ending with one of the given terminating substrings.
*
* @param terminators The strings for which to search.
*
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found.
*/
public String findString(String... terminators) throws IOException {
return findString(true, DEFAULT_BLOCK_SIZE, terminators);
}
/**
* Reads or skips a string ending with
* one of the given terminating substrings.
*
* @param saveString Whether to collect the string from the current file
* pointer to the terminating bytes, and return it. If false, returns null.
* @param terminators The strings for which to search.
*
* @throws IOException If saveString flag is set
* and the maximum search length (512 MB) is exceeded.
*
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found, or null if saveString flag is unset.
*/
public String findString(boolean saveString, String... terminators)
throws IOException
{
return findString(saveString, DEFAULT_BLOCK_SIZE, terminators);
}
/**
* Reads a string ending with one of the given terminating
* substrings, using the specified block size for buffering.
*
* @param blockSize The block size to use when reading bytes in chunks.
* @param terminators The strings for which to search.
*
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found.
*/
public String findString(int blockSize, String... terminators)
throws IOException
{
return findString(true, blockSize, terminators);
}
/**
* Reads or skips a string ending with one of the given terminating
* substrings, using the specified block size for buffering.
*
* @param saveString Whether to collect the string from the current file
* pointer to the terminating bytes, and return it. If false, returns null.
* @param blockSize The block size to use when reading bytes in chunks.
* @param terminators The strings for which to search.
*
* @throws IOException If saveString flag is set
* and the maximum search length (512 MB) is exceeded.
*
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found, or null if saveString flag is unset.
*/
public String findString(boolean saveString, int blockSize,
String... terminators) throws IOException
{
StringBuilder out = new StringBuilder();
long startPos = getFilePointer();
long bytesDropped = 0;
long inputLen = length();
long maxLen = inputLen - startPos;
boolean tooLong = saveString && maxLen > MAX_SEARCH_SIZE;
if (tooLong) maxLen = MAX_SEARCH_SIZE;
boolean match = false;
int maxTermLen = 0;
for (String term : terminators) {
int len = term.length();
if (len > maxTermLen) maxTermLen = len;
}
// ensure that we don't try to read more bytes than are in the file
if (blockSize > maxLen / 2) {
blockSize = (int) (maxLen / 2);
}
InputStreamReader in = new InputStreamReader(this);
char[] buf = new char[blockSize];
long loc = 0;
while (loc < maxLen) {
// if we're not saving the string, drop any old, unnecessary output
if (!saveString) {
int outLen = out.length();
if (outLen >= maxTermLen) {
int dropIndex = outLen - maxTermLen + 1;
String last = out.substring(dropIndex, outLen);
out.setLength(0);
out.append(last);
bytesDropped += dropIndex;
}
}
// read block from stream
int r = in.read(buf, 0, blockSize);
if (r <= 0) throw new IOException("Cannot read from stream: " + r);
// append block to output
out.append(buf, 0, r);
// check output, returning smallest possible string
int min = Integer.MAX_VALUE, tagLen = 0;
for (int t=0; t<terminators.length; t++) {
int len = terminators[t].length();
int start = (int) (loc - bytesDropped - len);
int value = out.indexOf(terminators[t], start < 0 ? 0 : start);
if (value >= 0 && value < min) {
match = true;
min = value;
tagLen = len;
}
}
if (match) {
// reset stream to proper location
seek(startPos + bytesDropped + min + tagLen);
// trim output string
if (saveString) {
out.setLength(min + tagLen);
return out.toString();
}
else return null;
}
loc += r;
}
// no match
if (tooLong) throw new IOException("Maximum search length reached.");
return null;
}
// -- DataInput API methods --
/** Read an input byte and return true if the byte is nonzero. */
public boolean readBoolean() throws IOException {
return raf.readBoolean();
}
/** Read one byte and return it. */
public byte readByte() throws IOException {
return raf.readByte();
}
/** Read an input char. */
public char readChar() throws IOException {
return raf.readChar();
}
/** Read eight bytes and return a double value. */
public double readDouble() throws IOException {
return raf.readDouble();
}
/** Read four bytes and return a float value. */
public float readFloat() throws IOException {
return raf.readFloat();
}
/** Read four input bytes and return an int value. */
public int readInt() throws IOException {
return raf.readInt();
}
/** Read the next line of text from the input stream. */
public String readLine() throws IOException {
return findString("\n");
}
/** Read a string of arbitrary length, terminated by a null char. */
public String readCString() throws IOException {
return findString("\0");
}
/** Read a string of length n. */
public String readString(int n) throws IOException {
byte[] b = new byte[n];
readFully(b);
return new String(b);
}
/** Read eight input bytes and return a long value. */
public long readLong() throws IOException {
return raf.readLong();
}
/** Read two input bytes and return a short value. */
public short readShort() throws IOException {
return raf.readShort();
}
/** Read an input byte and zero extend it appropriately. */
public int readUnsignedByte() throws IOException {
return raf.readUnsignedByte();
}
/** Read two bytes and return an int in the range 0 through 65535. */
public int readUnsignedShort() throws IOException {
return raf.readUnsignedShort();
}
/** Read a string that has been encoded using a modified UTF-8 format. */
public String readUTF() throws IOException {
return raf.readUTF();
}
/** Skip n bytes within the stream. */
public int skipBytes(int n) throws IOException {
return raf.skipBytes(n);
}
/** Read bytes from the stream into the given array. */
public int read(byte[] array) throws IOException {
return raf.read(array);
}
/**
* Read n bytes from the stream into the given array at the specified offset.
*/
public int read(byte[] array, int offset, int n) throws IOException {
return raf.read(array, offset, n);
}
/** Read bytes from the stream into the given buffer. */
public int read(ByteBuffer buf) throws IOException {
return raf.read(buf);
}
/**
* Read n bytes from the stream into the given buffer at the specified offset.
*/
public int read(ByteBuffer buf, int offset, int n) throws IOException {
return raf.read(buf, offset, n);
}
/** Read bytes from the stream into the given array. */
public void readFully(byte[] array) throws IOException {
raf.readFully(array);
}
/**
* Read n bytes from the stream into the given array at the specified offset.
*/
public void readFully(byte[] array, int offset, int n) throws IOException {
raf.readFully(array, offset, n);
}
// -- InputStream API methods --
public int read() throws IOException {
int b = (int) readByte();
if (b == -1 && (getFilePointer() >= length())) return 0;
return b;
}
public int available() throws IOException {
long fp = getFilePointer();
if (fp > Integer.MAX_VALUE) return Integer.MAX_VALUE;
return (int) fp;
}
public void mark(int readLimit) { }
public boolean markSupported() { return false; }
public void reset() throws IOException { }
}
|
// RandomAccessInputStream.java
package loci.common;
import java.io.BufferedInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class RandomAccessInputStream extends InputStream implements DataInput {
// -- Constants --
/** Maximum size of the buffer used by the DataInputStream. */
protected static final int MAX_OVERHEAD = 1048576;
/**
* Block size to use when searching through the stream.
* This value should not exceed MAX_OVERHEAD!
*/
protected static final int DEFAULT_BLOCK_SIZE = 256 * 1024; // 256 KB
/** Maximum number of bytes to search when searching through the stream. */
protected static final int MAX_SEARCH_SIZE = 512 * 1024 * 1024; // 512 MB
/** Maximum number of open files. */
protected static final int MAX_FILES = 100;
/** Indicators for most efficient method of reading. */
protected static final int DIS = 0;
protected static final int RAF = 1;
protected static final int ARRAY = 2;
// -- Static fields --
/** Hashtable of all files that have been opened at some point. */
private static Hashtable<RandomAccessInputStream, Boolean> fileCache =
new Hashtable<RandomAccessInputStream, Boolean>();
/** Number of currently open files. */
private static int openFiles = 0;
// -- Fields --
protected IRandomAccess raf;
protected DataInputStream dis;
/** Length of the file. */
protected long length;
/** The file pointer within the DIS. */
protected long fp;
/** The "absolute" file pointer. */
protected long afp;
/** Most recent mark. */
protected long mark;
/** Next place to mark. */
protected long nextMark;
/** The file name. */
protected String file;
/** Starting buffer. */
protected byte[] buf;
/** Endianness of the stream. */
protected boolean littleEndian = false;
/** Number of bytes by which to extend the stream. */
protected int ext = 0;
/** Flag indicating this file has been compressed. */
protected boolean compressed = false;
// -- Constructors --
/**
* Constructs a hybrid RandomAccessFile/DataInputStream
* around the given file.
*/
public RandomAccessInputStream(String file) throws IOException {
this.file = file;
reopen();
fp = 0;
afp = 0;
}
/** Constructs a random access stream around the given byte array. */
public RandomAccessInputStream(byte[] array) throws IOException {
// this doesn't use a file descriptor, so we don't need to add it to the
// file cache
raf = new ByteArrayHandle(array);
fp = 0;
afp = 0;
length = raf.length();
}
// -- RandomAccessInputStream API methods --
/** Returns the underlying InputStream. */
public DataInputStream getInputStream() {
try {
if (Boolean.FALSE.equals(fileCache.get(this))) reopen();
}
catch (IOException e) {
return null;
}
return dis;
}
/**
* Sets the number of bytes by which to extend the stream. This only applies
* to InputStream API methods.
*/
public void setExtend(int extend) { ext = extend; }
/** Seeks to the given offset within the stream. */
public void seek(long pos) throws IOException { afp = pos; }
/** Alias for readByte(). */
public int read() throws IOException {
int b = (int) readByte();
if (b == -1 && (afp >= length()) && ext > 0) return 0;
return b;
}
/** Gets the number of bytes in the file. */
public long length() throws IOException {
if (Boolean.FALSE.equals(fileCache.get(this))) reopen();
return length;
}
/** Gets the current (absolute) file pointer. */
public long getFilePointer() { return afp; }
/** Closes the streams. */
public void close() throws IOException {
if (Location.getMappedFile(file) != null) return;
if (raf != null) raf.close();
raf = null;
if (dis != null) dis.close();
dis = null;
buf = null;
if (Boolean.TRUE.equals(fileCache.get(this))) {
fileCache.put(this, false);
openFiles
}
}
/** Sets the endianness of the stream. */
public void order(boolean little) { littleEndian = little; }
/** Gets the endianness of the stream. */
public boolean isLittleEndian() { return littleEndian; }
/**
* Reads a string ending with one of the characters in the given string.
*
* @see #findString(String)
*/
public String readString(String lastChars) throws IOException {
if (lastChars.length() == 1) return findString(lastChars);
else {
String[] terminators = new String[lastChars.length()];
for (int i=0; i<terminators.length; i++) {
terminators[i] = lastChars.substring(i, i + 1);
}
return findString(terminators);
}
}
/**
* Reads a string ending with one of the given terminating substrings.
*
* @param terminators The strings for which to search.
*
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found.
*/
public String findString(String... terminators) throws IOException {
return findString(DEFAULT_BLOCK_SIZE, terminators);
}
/**
* Reads a string ending with one of the given terminating substrings,
* using the specified block size for buffering.
*
* @param terminators The strings for which to search.
* @param blockSize The block size to use when reading bytes in chunks.
*
* @throws IOException If the maximum search length (512 MB) is exceeded.
*
* @return The string from the initial position through the end of the
* terminating sequence, or through the end of the stream if no
* terminating sequence is found.
*/
public String findString(int blockSize, String... terminators)
throws IOException
{
StringBuilder out = new StringBuilder();
long startPos = getFilePointer();
long inputLen = length();
long maxLen = inputLen - startPos;
if (maxLen > MAX_SEARCH_SIZE) maxLen = MAX_SEARCH_SIZE;
boolean match = false;
InputStreamReader in = new InputStreamReader(this);
char[] buf = new char[blockSize];
int i = 0;
while (i < maxLen) {
long pos = startPos + i;
int num = blockSize;
if (pos + blockSize > inputLen) num = (int) (inputLen - pos);
// read block from stream
int r = in.read(buf, 0, blockSize);
if (r <= 0) throw new IOException("Cannot read from stream: " + r);
// append block to output
out.append(buf, 0, r);
// check output
int[] indices = new int[terminators.length];
for (int t=0; t<terminators.length; t++) {
int tagLen = terminators[t].length();
indices[t] = out.indexOf(terminators[t], i == 0 ? 0 : i - tagLen);
if (!match) {
match = indices[t] >= 0;
}
}
// return smallest possible string
if (match) {
int min = Integer.MAX_VALUE;
int minIndex = Integer.MAX_VALUE;
for (int t=0; t<indices.length; t++) {
if (indices[t] >= 0 && indices[t] < min) {
min = indices[t];
minIndex = t;
}
}
int tagLen = terminators[minIndex].length();
seek(startPos + min + tagLen); // reset stream to proper location
out.setLength(min + tagLen); // trim output
break;
}
i += r;
}
if (!match) throw new IOException("Maximum search length reached.");
return out.toString();
}
// -- DataInput API methods --
/** Read an input byte and return true if the byte is nonzero. */
public boolean readBoolean() throws IOException {
return (readByte() != 0);
}
/** Read one byte and return it. */
public byte readByte() throws IOException {
int status = checkEfficiency(1);
long oldAFP = afp;
if (afp < length - 1) afp++;
if (status == DIS) {
byte b = dis.readByte();
fp++;
return b;
}
else if (status == ARRAY) {
return buf[(int) oldAFP];
}
else {
byte b = raf.readByte();
return b;
}
}
/** Read an input char. */
public char readChar() throws IOException {
return (char) readByte();
}
/** Read eight bytes and return a double value. */
public double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
/** Read four bytes and return a float value. */
public float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
/** Read four input bytes and return an int value. */
public int readInt() throws IOException {
return DataTools.read4SignedBytes(this, littleEndian);
}
/** Read the next line of text from the input stream. */
public String readLine() throws IOException {
return findString("\n");
}
/** Read a string of arbitrary length, terminated by a null char. */
public String readCString() throws IOException {
return findString("\0");
}
/** Read a string of length n. */
public String readString(int n) throws IOException {
byte[] b = new byte[n];
readFully(b);
return new String(b);
}
/** Read eight input bytes and return a long value. */
public long readLong() throws IOException {
return DataTools.read8SignedBytes(this, littleEndian);
}
/** Read two input bytes and return a short value. */
public short readShort() throws IOException {
return DataTools.read2SignedBytes(this, littleEndian);
}
/** Read an input byte and zero extend it appropriately. */
public int readUnsignedByte() throws IOException {
return DataTools.readUnsignedByte(this);
}
/** Read two bytes and return an int in the range 0 through 65535. */
public int readUnsignedShort() throws IOException {
return DataTools.read2UnsignedBytes(this, littleEndian);
}
/** Read a string that has been encoded using a modified UTF-8 format. */
public String readUTF() throws IOException {
return null; // not implemented yet...we don't really need this
}
/** Skip n bytes within the stream. */
public int skipBytes(int n) throws IOException {
afp += n;
return n;
}
/** Read bytes from the stream into the given array. */
public int read(byte[] array) throws IOException {
return read(array, 0, array.length);
}
/**
* Read n bytes from the stream into the given array at the specified offset.
*/
public int read(byte[] array, int offset, int n) throws IOException {
int toRead = n;
int status = checkEfficiency(n);
try {
if (status == DIS) {
int p = dis.read(array, offset, n);
if (p == -1) return -1;
if ((p >= 0) && ((fp + p) < length)) {
int k = p;
while ((k >= 0) && (p < n) && ((afp + p) <= length) &&
((offset + p) < array.length))
{
k = dis.read(array, offset + p, n - p);
if (k >= 0) p += k;
}
}
n = p;
}
else if (status == ARRAY) {
if ((buf.length - afp) < n) n = buf.length - (int) afp;
System.arraycopy(buf, (int) afp, array, offset, n);
}
else {
n = raf.read(array, offset, n);
}
}
catch (IOException e) {
throw new HandleException("Error reading from" + file, e);
}
afp += n;
if (status == DIS) fp += n;
if (n < toRead && ext > 0) {
while (n < array.length && ext > 0) {
n++;
ext
}
}
return n;
}
/** Read bytes from the stream into the given array. */
public void readFully(byte[] array) throws IOException {
readFully(array, 0, array.length);
}
/**
* Read n bytes from the stream into the given array at the specified offset.
*/
public void readFully(byte[] array, int offset, int n) throws IOException {
int status = checkEfficiency(n);
try {
if (status == DIS) {
dis.readFully(array, offset, n);
}
else if (status == ARRAY) {
System.arraycopy(buf, (int) afp, array, offset, n);
}
else {
raf.readFully(array, offset, n);
}
}
catch (IOException e) {
throw new HandleException("Error reading from " + file, e);
}
afp += n;
if (status == DIS) fp += n;
}
// -- InputStream API methods --
public int available() throws IOException {
if (Boolean.FALSE.equals(fileCache.get(this))) reopen();
int available = dis != null ? dis.available() + ext :
(int) (length() - getFilePointer());
if (available < 0) available = Integer.MAX_VALUE;
return available;
}
public void mark(int readLimit) {
try {
if (Boolean.FALSE.equals(fileCache.get(this))) reopen();
}
catch (IOException e) { }
if (!compressed) dis.mark(readLimit);
}
public boolean markSupported() { return !compressed; }
public void reset() throws IOException {
if (Boolean.FALSE.equals(fileCache.get(this))) reopen();
dis.reset();
fp = length() - dis.available();
}
// -- Helper methods - I/O --
/**
* Determine whether it is more efficient to use the DataInputStream or
* RandomAccessFile for reading (based on the current file pointers).
* Returns 0 if we should use the DataInputStream, 1 if we should use the
* RandomAccessFile, and 2 for a direct array access.
*/
protected int checkEfficiency(int toRead) throws IOException {
if (Boolean.FALSE.equals(fileCache.get(this))) reopen();
// case 0:
// ending file pointer is less than the starting buffer's length
if (buf != null && afp + toRead < buf.length) {
return ARRAY;
}
// case 1:
// current file pointer is greater than or equal to the previous
// file pointer (seek forward)
if (dis != null && afp >= fp) {
long skipped = dis.skip(afp - fp);
while (skipped < afp - fp) {
skipped += dis.skip(afp - fp - skipped);
}
fp = afp;
return DIS;
}
// case 2:
// current file pointer is less than the previous file pointer
// and the current file pointer is greater than or equal to the
// DIS' mark offset
if (dis != null && afp < fp && afp >= mark) {
try {
dis.reset();
long skipped = dis.skip(afp - mark);
while (skipped < afp - mark) {
skipped += dis.skip(afp - mark - skipped);
}
fp = afp;
resetMark();
return DIS;
}
catch (IOException e) { }
}
// case 3:
// current file pointer is less than the previous file pointer
// or the DIS was null in cases #1 and #2
if (raf != null) {
raf.seek(afp);
return RAF;
}
// case 4:
// current file pointer is less than the previous file pointer
// and the RAF is null
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(Location.getMappedId(file)), MAX_OVERHEAD);
if (dis != null) dis.close();
dis = new DataInputStream(bis);
fp = 0;
nextMark = 0;
resetMark();
long skipped = dis.skip(afp);
while (skipped < afp) {
skipped += dis.skip(afp - skipped);
}
fp = afp;
return DIS;
}
private void resetMark() {
if (fp >= nextMark) {
dis.mark(MAX_OVERHEAD);
}
nextMark = fp + MAX_OVERHEAD;
mark = fp;
}
// -- Helper methods - cache management --
/** Re-open a file that has been closed */
private void reopen() throws IOException {
String path = Location.getMappedId(file);
File f = new File(path).getAbsoluteFile();
raf = Location.getHandle(file);
length = raf.length();
if (raf == null) {
throw new IOException("File not found: " + file);
}
if (f.exists()) {
compressed = raf instanceof CompressedRandomAccess;
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(path), MAX_OVERHEAD);
if (dis != null) dis.close();
if (!compressed) dis = new DataInputStream(bis);
else dis = null;
buf = new byte[(int) (length < MAX_OVERHEAD ? length : MAX_OVERHEAD)];
raf.readFully(buf);
raf.seek(0);
nextMark = MAX_OVERHEAD;
}
fileCache.put(this, true);
openFiles++;
if (openFiles > MAX_FILES) cleanCache();
}
/** If we have too many open files, close most of them. */
private void cleanCache() {
int toClose = MAX_FILES - 10;
RandomAccessInputStream[] files =
fileCache.keySet().toArray(new RandomAccessInputStream[0]);
int closed = 0;
int ndx = 0;
while (closed < toClose) {
if (!this.equals(files[ndx]) && files[ndx].file != null &&
Boolean.TRUE.equals(fileCache.get(files[ndx])))
{
try { files[ndx].close(); }
catch (IOException exc) { LogTools.trace(exc); }
closed++;
}
ndx++;
}
}
}
|
package de.golfgl.gdxgamesvcs;
import com.badlogic.gdx.utils.JsonValue;
import de.golfgl.gdxgamesvcs.leaderboard.ILeaderBoardEntry;
public class GjScoreboardEntry implements ILeaderBoardEntry {
protected String score;
protected long sort;
protected String tag;
protected String displayName;
protected String rank;
protected String userId;
protected String stored;
protected boolean currentPlayer;
protected static GjScoreboardEntry fromJson(JsonValue json, int rank, String currentPlayer) {
GjScoreboardEntry gje = new GjScoreboardEntry();
gje.rank = String.valueOf(rank);
gje.score = json.getString("score");
gje.sort = json.getLong("sort");
gje.tag = json.getString("extra_data");
String userId = json.getString("user_id");
if (userId != null && !userId.isEmpty()) {
gje.userId = userId;
gje.displayName = json.getString("user");
gje.currentPlayer = (currentPlayer != null && currentPlayer.equalsIgnoreCase(gje.displayName));
} else
gje.displayName = json.getString("guest");
gje.stored = json.getString("stored");
return gje;
}
@Override
public String getFormattedValue() {
return score;
}
@Override
public String getScoreRank() {
return rank;
}
@Override
public String getAvatarUrl() {
return null;
}
@Override
public boolean isCurrentPlayer() {
return currentPlayer;
}
@Override
public long getSortValue() {
return sort;
}
@Override
public String getScoreTag() {
return tag;
}
@Override
public String getUserDisplayName() {
return displayName;
}
@Override
public String getUserId() {
return userId;
}
}
|
package io.github.bobdesaunois.amazighvillagegame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Render
{
public Render ()
{
// Insert initialization code
}
public void render () {
// Clear the screen
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
///////////////////////////// TESTING CODE /////////////////////////////
SpriteBatch testBatch = new SpriteBatch();
Texture texture = new Texture ("badlogic.jpg");
testBatch.begin();
testBatch.draw (texture, 0, 0);
testBatch.end();
///////////////////////////// TESTING CODE /////////////////////////////
// Insert render code
}
}
|
package com.google.mu.util.stream;
import static com.google.mu.util.stream.BiStream.kv;
import static java.util.Arrays.asList;
import static java.util.Objects.requireNonNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
/**
* A re-streamable collection of pairs. Suitable when the pairs aren't logically a {@code Map}
* or {@code Multimap}.
*
* <p>This class is thread-safe if the underlying collection is thread-safe. For example:
* <pre> {@code
* BiStream.zip(dtos, domains).toBiCollection()
* }</pre> doesn't guarantee thread safety; whereas
* <pre> {@code
* BiStream.zip(dtos, domains).toBiCollection(ImmutableList::toImmutableList)
* }</pre> is guaranteed to be immutable and thread safe.
*
* @since 1.3
*/
public final class BiCollection<L, R> {
private final Collection<? extends Map.Entry<? extends L, ? extends R>> entries;
private BiCollection(Collection<? extends Entry<? extends L, ? extends R>> underlying) {
this.entries = requireNonNull(underlying);
}
/** Returns an empty {@code BiCollection}. */
public static <L, R> BiCollection<L, R> of() {
return from(Collections.emptyList());
}
/** Returns a {@code BiCollection} for {@code left} and {@code right}. */
public static <L, R> BiCollection<L, R> of(L left, R right) {
return from(asList(kv(left, right)));
}
/** Returns a {@code BiCollection} for two pairs. */
public static <L, R> BiCollection<L, R> of(L left1, R right1, L left2, R right2) {
return from(asList(kv(left1, right1), kv(left2, right2)));
}
/** Returns a {@code BiCollection} for three pairs. */
public static <L, R> BiCollection<L, R> of(L left1, R right1, L left2, R right2, L left3, R right3) {
return from(asList(kv(left1, right1), kv(left2, right2), kv(left3, right3)));
}
/** Returns a {@code BiCollection} for four pairs. */
public static <L, R> BiCollection<L, R> of(
L left1, R right1, L left2, R right2, L left3, R right3, L left4, R right4) {
return from(asList(kv(left1, right1), kv(left2, right2), kv(left3, right3), kv(left4, right4)));
}
/** Returns a {@code BiCollection} for five pairs. */
public static <L, R> BiCollection<L, R> of(
L left1, R right1, L left2, R right2, L left3, R right3, L left4, R right4, L left5, R right5) {
return from(asList(
kv(left1, right1), kv(left2, right2), kv(left3, right3), kv(left4, right4), kv(left5, right5)));
}
/** Wraps {@code entries} in a {@code BiCollection}. */
public static <L, R> BiCollection<L, R> from(
Collection<? extends Map.Entry<? extends L, ? extends R>> entries) {
return new BiCollection<>(entries);
}
/**
* Wraps entries in {@code map} as a {@code BiCollection}. Note that the returned
* {@code BiCollection} is a view of the input map entries.
*/
public static <L, R> BiCollection<L, R> from(Map<? extends L, ? extends R> map) {
return from(map.entrySet());
}
/**
* Returns a {@code Collector} that extracts the pairs from the input stream,
* and then collects them into a {@code BiCollection}.
*
* @param leftFunction extracts the first element of each pair
* @param rightFunction extracts the second element of each pair
* @param collectorStrategy determines the kind of collection to use. For example:
* {@code Collectors::toList} or {@code ImmutableList::toImmutableList}.
*/
public static <T, L, R> Collector<T, ?, BiCollection<L, R>> toBiCollection(
Function<? super T, ? extends L> leftFunction,
Function<? super T, ? extends R> rightFunction,
CollectorStrategy collectorStrategy) {
requireNonNull(leftFunction);
requireNonNull(rightFunction);
Function<T, Map.Entry<L, R>> toEntry = x -> kv(leftFunction.apply(x), rightFunction.apply(x));
Collector<T, ?, ? extends Collection<? extends Map.Entry<? extends L, ? extends R>>> entryCollector =
Collectors.mapping(toEntry, collectorStrategy.collector());
return Collectors.collectingAndThen(entryCollector, BiCollection::from);
}
/**
* Returns a {@code Collector} that extracts the pairs from the input stream,
* and then collects them into a {@code BiCollection}.
*
* @param leftFunction extracts the first element of each pair
* @param rightFunction extracts the second element of each pair
*/
public static <T, L, R> Collector<T, ?, BiCollection<L, R>> toBiCollection(
Function<? super T, ? extends L> leftFunction,
Function<? super T, ? extends R> rightFunction) {
return toBiCollection(leftFunction, rightFunction, Collectors::toList);
}
/** Returns the size of the collection. */
public int size() {
return entries.size();
}
/** Streams over this {@code BiCollection}. */
public BiStream<L, R> stream() {
return new BiStream<>(entries.stream());
}
/**
* Builds {@link BiCollection}.
*
* @since 1.3
*/
public static final class Builder<L, R> {
private final List<Map.Entry<L, R>> pairs = new ArrayList<>();
/** Puts a new pair of {@code left} and {@code right}. */
public Builder<L, R> put(L left, R right) {
pairs.add(kv(left, right));
return this;
}
/** Puts all key-value pairs from {@code map} into this builder. */
public Builder<L, R> putAll(Map<? extends L, ? extends R> map) {
return putAll(map.entrySet());
}
/** Puts all key-value pairs from {@code entries} into this builder. */
public Builder<L, R> putAll(Collection<? extends Map.Entry<? extends L, ? extends R>> entries) {
for (Map.Entry<? extends L, ? extends R> entry : entries) {
pairs.add(kv(entry.getKey(), entry.getValue()));
}
return this;
}
/**
* Returns a new {@link BiCollection} encapsulating the snapshot of pairs in this builder
* at the time {@code build()} is invoked.
*/
public BiCollection<L, R> build() {
return from(new ArrayList<>(pairs));
}
}
}
|
package org.xillium.core;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.util.*;
import java.util.jar.*;
import java.util.logging.*;
import java.util.regex.*;
import javax.management.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.InputStreamResource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.web.context.*;
import org.springframework.web.context.support.*;
import org.xillium.base.etc.Arrays;
import org.xillium.base.beans.*;
import org.xillium.data.*;
import org.xillium.data.persistence.*;
import org.xillium.core.conf.*;
import org.xillium.core.management.*;
import org.xillium.core.intrinsic.*;
import org.xillium.core.util.ModuleSorter;
/**
* Platform Service Dispatcher.
*
* This servlet dispatches inbound HTTP calls to registered services based on request URI. A valid request URI is in the form of
* <pre>
* /[context]/[module]/[service]?[params]=...
* </pre>
* When a request URI matches the above pattern, this servlet looks up a Service instance registered under the name 'module/service'.
* <p/>
* The fabric of operation, administration, and maintenance (foam)
* <ul>
* <li><code>/[context]/x!/[service]</code><p/>
* <ul>
* <li>list</li>
* <li>desc - parameter description</li>
* </ul>
* </li>
* </ul>
*/
public class HttpServiceDispatcher extends HttpServlet {
private static final String DOMAIN_NAME = "Xillium-Domain-Name";
private static final String MODULE_NAME = "Xillium-Module-Name";
private static final String MODULE_BASE = "Xillium-Module-Base";
private static final String REQUEST_VOCABULARY = "request-vocabulary.xml";
private static final String SERVICE_CONFIG = "service-configuration.xml";
private static final String STORAGE_CONFIG = "storage-configuration.xml";
private static final Pattern URI_REGEX = Pattern.compile("/[^/?]+/([^/?]+/[^/?]+)"); // '/context/module/service'
private static final File TEMPORARY = null;
private static final Logger _logger = Logger.getLogger(HttpServiceDispatcher.class.getName());
private final Stack<List<PlatformLifeCycleAware>> _plca = new Stack<List<PlatformLifeCycleAware>>();
private final Map<String, Service> _services = new HashMap<String, Service>();
private final org.xillium.data.validation.Dictionary _dict = new org.xillium.data.validation.Dictionary();
// Wired in spring application context
private Persistence _persistence;
public HttpServiceDispatcher() {
_logger.log(Level.INFO, "START HTTP service dispatcher " + getClass().getName());
_logger.log(Level.INFO, "java.util.logging.config.class=" + System.getProperty("java.util.logging.config.class"));
}
/**
* Initializes the servlet, loading and initializing xillium modules.
*/
public void init() throws ServletException {
ApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
_dict.addTypeSet(org.xillium.data.validation.StandardDataTypes.class);
_persistence = (Persistence)wac.getBean("persistence");
// if intrinsic services are wanted
Map<String, String> descriptions = new HashMap<String, String>();
ModuleSorter.Sorted sorted = sortServiceModules();
// scan special modules, configuring and initializing PlatformLifeCycleAware objects as each module is loaded
wac = scanServiceModules(sorted.specials(), wac, descriptions, null);
// scan regular modules, collecting all PlatformLifeCycleAware objects
List<PlatformLifeCycleAware> plcas = new ArrayList<PlatformLifeCycleAware>();
scanServiceModules(sorted.regulars(), wac, descriptions, plcas);
_logger.info("configure PlatformLifeCycleAware objects in regular modules");
for (PlatformLifeCycleAware plca: plcas) {
_logger.info("Configuring REGULAR PlatformLifeCycleAware " + plca.getClass().getName());
plca.configure();
}
_logger.info("initialize PlatformLifeCycleAware objects in regular modules");
for (PlatformLifeCycleAware plca: plcas) {
_logger.info("Initalizing REGULAR PlatformLifeCycleAware " + plca.getClass().getName());
plca.initialize();
}
_plca.push(plcas);
_services.put("x!/desc", new DescService(descriptions));
_services.put("x!/list", new ListService(_services));
}
public void destroy() {
_logger.info("Terminating service dispatcher");
while (!_plca.empty()) {
List<PlatformLifeCycleAware> plcas = _plca.pop();
// terminate PlatformLifeCycleAware objects in this level
for (PlatformLifeCycleAware plca: plcas) {
plca.terminate();
}
}
}
/**
* Dispatcher entry point
*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
Service service;
String id;
_logger.fine("Request URI = " + req.getRequestURI());
Matcher m = URI_REGEX.matcher(req.getRequestURI());
if (m.matches()) {
id = m.group(1);
_logger.fine("Request service id = " + id);
service = (Service)_services.get(id);
if (service == null) {
_logger.warning("Request not recognized");
res.sendError(404);
return;
}
} else {
_logger.warning("Request not recognized");
res.sendError(404);
return;
}
List<File> upload = new ArrayList<File>();
DataBinder binder = new DataBinder();
try {
if (ServletFileUpload.isMultipartContent(req)) {
try {
FileItemIterator it = new ServletFileUpload().getItemIterator(req);
while (it.hasNext()) {
FileItemStream item = it.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
binder.put(name, Streams.asString(stream));
} else {
// File field with file name in item.getName()
String original = item.getName();
int dot = original.lastIndexOf('.');
// store the file in a temporary place
File file = File.createTempFile("xillium", dot > 0 ? original.substring(dot) : null, TEMPORARY);
OutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024*1024];
int length;
while ((length = stream.read(buffer)) >= 0) out.write(buffer, 0, length);
out.close();
binder.put(name, original);
binder.put(name + ":path", file.getAbsolutePath());
upload.add(file);
}
}
} catch (FileUploadException x) {
throw new RuntimeException("Failed to parse multipart content", x);
}
} else {
java.util.Enumeration<String> en = req.getParameterNames();
while (en.hasMoreElements()) {
String name = en.nextElement();
String[] values = req.getParameterValues(name);
if (values.length == 1) {
binder.put(name, values[0]);
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length; ++i) {
sb.append('{').append(values[i]).append('}');
}
binder.put(name, sb.toString());
}
}
}
// auto-parameters
binder.put(Service.REQUEST_CLIENT_ADDR, req.getRemoteAddr());
binder.put(Service.REQUEST_CLIENT_PORT, String.valueOf(req.getRemotePort()));
binder.put(Service.REQUEST_SERVER_PORT, String.valueOf(req.getServerPort()));
binder.put(Service.REQUEST_HTTP_METHOD, req.getMethod());
// TODO: pre-service filter
if (service instanceof Service.Secured) {
_logger.fine("Trying to authorize invocation of a secured service");
((Service.Secured)service).authorize(id, binder, _persistence);
}
binder = service.run(binder, _dict, _persistence);
try {
Runnable task = (Runnable)binder.getNamedObject(Service.SERVICE_POST_ACTION);
if (task != null) {
task.run();
}
} catch (Throwable t) {
_logger.warning("In post-service processing caught " + t.getClass() + ": " + t.getMessage());
}
} catch (Throwable x) {
String message = Throwables.getFirstMessage(x);
if (message == null || message.length() == 0) {
message = "***"+Throwables.getRootCause(x).getClass().getSimpleName();
}
binder.put(Service.FAILURE_MESSAGE, message);
_logger.warning("Exception caught in dispatcher: " + message);
_logger.log(Level.INFO, "Exception stack trace:", x);
CharArrayWriter sw = new CharArrayWriter();
x.printStackTrace(new PrintWriter(sw));
binder.put(Service.FAILURE_STACK, sw.toString());
} finally {
// TODO: post-service filter
if (service instanceof Service.Extended) {
_logger.fine("Invoking extended operations");
try {
((Service.Extended)service).complete(binder);
} catch (Throwable t) {
_logger.log(Level.WARNING, "Extended service: complete() failed", t);
}
}
res.setHeader("Access-Control-Allow-Headers", "origin,x-prototype-version,x-requested-with,accept");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Content-Type", "application/json;charset=UTF-8");
try {
binder.clearAutoValues();
String json = binder.get(Service.SERVICE_JSON_TUNNEL);
if (json == null) {
JSONBuilder jb = new JSONBuilder(binder.estimateMaximumBytes()).append('{');
jb.quote("params").append(":{ ");
Iterator<String> it = binder.keySet().iterator();
for (int i = 0; it.hasNext(); ++i) {
String key = it.next();
String val = binder.get(key);
if (val == null) {
jb.quote(key).append(":null");
} else if (val.startsWith("json:")) {
jb.quote(key).append(':').append(val.substring(5));
} else {
jb.serialize(key, val);
}
jb.append(',');
}
jb.replaceLast('}').append(',');
jb.quote("tables").append(":{ ");
Set<String> rsets = binder.getResultSetNames();
it = rsets.iterator();
while (it.hasNext()) {
String name = it.next();
jb.quote(name).append(":");
binder.getResultSet(name).toJSON(jb);
jb.append(',');
}
jb.replaceLast('}');
jb.append('}');
json = jb.toString();
}
res.getWriter().append(json).flush();
} finally {
for (File tmp: upload) {
try { tmp.delete(); } catch (Exception x) {}
}
}
}
}
private ModuleSorter.Sorted sortServiceModules() throws ServletException {
ModuleSorter sorter = new ModuleSorter();
ServletContext context = getServletContext();
try {
Set<String> jars = context.getResourcePaths("/WEB-INF/lib/");
_logger.info("There are " + jars.size() + " resource paths");
for (String jar : jars) {
try {
//_logger.info("... " + jar);
JarInputStream jis = new JarInputStream(context.getResourceAsStream(jar));
try {
String name = jis.getManifest().getMainAttributes().getValue(MODULE_NAME);
if (name != null) {
sorter.add(new ModuleSorter.Entry(name, jis.getManifest().getMainAttributes().getValue(MODULE_BASE), jar));
}
} finally {
jis.close();
}
} catch (IOException x) {
// ignore this jar
_logger.log(Level.WARNING, "Error during jar inspection, ignored", x);
}
}
} catch (Exception x) {
throw new ServletException("Failed to sort service modules", x);
}
return sorter.sort();
}
private ApplicationContext scanServiceModules(Iterator<ModuleSorter.Entry> it, ApplicationContext wac, Map<String, String> descs, List<PlatformLifeCycleAware> plcas) throws ServletException {
ServletContext context = getServletContext();
boolean isSpecial = plcas == null;
if (isSpecial) {
plcas = new ArrayList<PlatformLifeCycleAware>();
}
try {
BurnedInArgumentsObjectFactory factory = new BurnedInArgumentsObjectFactory(ValidationConfiguration.class, _dict);
XMLBeanAssembler assembler = new XMLBeanAssembler(factory);
while (it.hasNext()) {
ModuleSorter.Entry module = it.next();
try {
JarInputStream jis = new JarInputStream(context.getResourceAsStream(module.path));
try {
String domain = jis.getManifest().getMainAttributes().getValue(DOMAIN_NAME);
_logger.fine("Scanning module " + module.name + ", special=" + isSpecial);
factory.setBurnedIn(StorageConfiguration.class, _persistence.getStatementMap(), module.name);
JarEntry entry;
while ((entry = jis.getNextJarEntry()) != null) {
if (SERVICE_CONFIG.equals(entry.getName())) {
_logger.info("Services:" + module.path + ":" + entry.getName());
if (isSpecial) {
wac =
loadServiceModule(wac, domain, module.name, new ByteArrayInputStream(Arrays.read(jis)), descs, plcas);
} else {
loadServiceModule(wac, domain, module.name, new ByteArrayInputStream(Arrays.read(jis)), descs, plcas);
}
} else if (STORAGE_CONFIG.equals(entry.getName())) {
_logger.info("Storages:" + module.path + ":" + entry.getName());
assembler.build(new ByteArrayInputStream(Arrays.read(jis)));
} else if (REQUEST_VOCABULARY.equals(entry.getName())) {
_logger.info("RequestVocabulary:" + module.path + ":" + entry.getName());
assembler.build(new ByteArrayInputStream(Arrays.read(jis)));
}
}
} finally {
jis.close();
}
if (isSpecial) {
for (PlatformLifeCycleAware plca: plcas) {
_logger.info("Configuring SPECIAL PlatformLifeCycleAware " + plca.getClass().getName());
plca.configure();
}
for (PlatformLifeCycleAware plca: plcas) {
_logger.info("Initalizing SPECIAL PlatformLifeCycleAware " + plca.getClass().getName());
plca.initialize();
}
//plcas.clear();
_plca.push(plcas);
plcas = new ArrayList<PlatformLifeCycleAware>();
}
} catch (IOException x) {
// ignore this jar
_logger.log(Level.WARNING, "Error during jar inspection, ignored", x);
}
}
} catch (Exception x) {
throw new ServletException("Failed to construct an XMLBeanAssembler", x);
}
_logger.info("Done with service modules scanning (" + (isSpecial ? "SPECIAL" : "REGULAR") + ')');
return wac;
}
private ApplicationContext loadServiceModule(ApplicationContext wac, String domain, String name, InputStream stream, Map<String, String> desc, List<PlatformLifeCycleAware> plcas) {
GenericApplicationContext gac = new GenericApplicationContext(wac);
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(gac);
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
reader.loadBeanDefinitions(new InputStreamResource(stream));
gac.refresh();
_logger.info("Loading service modules from ApplicationContext " + gac.getId());
for (String id: gac.getBeanNamesForType(Service.class)) {
String fullname = name + '/' + id;
BeanDefinition def = gac.getBeanDefinition(id);
try {
Class<?> request = Class.forName(def.getBeanClassName()+"$Request");
if (DataObject.class.isAssignableFrom(request)) {
_logger.info("Service '" + fullname + "' request description captured: " + request.getName());
desc.put(fullname, "json:" + DataObject.Util.describe((Class<? extends DataObject>)request));
} else {
_logger.warning("Service '" + fullname + "' defines a Request type that is not a DataObject");
desc.put(fullname, "json:{}");
}
} catch (ClassNotFoundException x) {
try {
Class<? extends DataObject> request = ((DynamicService)gac.getBean(id)).getRequestType();
_logger.info("Service '" + fullname + "' request description captured: " + request.getName());
desc.put(fullname, "json:" + DataObject.Util.describe((Class<? extends DataObject>)request));
} catch (Exception t) {
_logger.warning("Service '" + fullname + "' does not expose its request structure" + t.getClass());
desc.put(fullname, "json:{}");
}
}
_logger.info("Service '" + fullname + "' class=" + gac.getBean(id).getClass().getName());
_services.put(fullname, (Service)gac.getBean(id));
}
for (String id: gac.getBeanNamesForType(PlatformLifeCycleAware.class)) {
plcas.add((PlatformLifeCycleAware)gac.getBean(id));
}
// Manageable object registration: objects are registered under "bean-id/context-path"
String contextPath = getServletContext().getContextPath();
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
for (String id: gac.getBeanNamesForType(Manageable.class)) {
try {
_logger.info("Registering MBean '" + id + "', domain=" + domain);
ObjectName on = new ObjectName(domain == null ? "org.xillium.core.management" : domain, "type", id + contextPath);
Manageable manageable = (Manageable)gac.getBean(id);
manageable.assignObjectName(on);
mbs.registerMBean(manageable, on);
} catch (Exception x) {
_logger.log(Level.WARNING, "MBean '" + id + "' failed to register", x);
}
}
_logger.info("Done with service modules in ApplicationContext " + gac.getId());
return gac;
}
private static InputStream getJarEntryAsStream(JarInputStream jis) throws IOException {
return new ByteArrayInputStream(Arrays.read(jis));
}
}
|
package com.zyeeda.framework.unittest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.HasControls;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.PagedResultsControl;
import javax.naming.ldap.PagedResultsResponseControl;
import javax.naming.ldap.SortControl;
import javax.naming.ldap.SortResponseControl;
import org.apache.commons.codec.digest.DigestUtils;
public class LDAPTest {
public LDAPTest() {}
public static LdapContext getLdapContext() throws NamingException {
String root = "dc=ehv,dc=csg,dc=cn";
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://192.168.1.85:10389/" + root);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=admin");
env.put(Context.SECURITY_CREDENTIALS, "admin");
LdapContext ctx = new InitialLdapContext(env, null);
return ctx;
}
public static void ldapPageView() throws NamingException, IOException {
LdapContext ctx = getLdapContext();
int pageSize = 5; // 5 entries per page
byte[] cookie = null;
int total = 0;
// ctx.setRequestControls(new Control[] { new PagedResultsControl(
// pageSize, Control.CRITICAL) });
String sortKey = "uid";
// ctx.setRequestControls(new Control[] {
// new SortControl(sortKey, Control.NONCRITICAL) });
// Perform the search
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
String condition = "Test";
NamingEnumeration<SearchResult> results = ctx.search("", "uid=Test5",
sc);
// Iterate over a batch of search results sent by the server
while (results != null && results.hasMore()) {
// Display an entry
SearchResult entry = (SearchResult) results.next();
Attributes attributes = entry.getAttributes();
// System.out.println(new String((byte[])attributes.get("userpassword").get()));
// System.out.println(attributes.get("userpassword").get());
System.out.println(new String((byte[]) attributes.get("userpassword").get()));
// Handle the entry's response controls (if any)
if (entry instanceof HasControls) {
// ((HasControls)entry).getControls();
}
}
// Examine the paged results control response
Control[] controls = ctx.getResponseControls();
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
total = prrc.getResultSize();
cookie = prrc.getCookie();
} else {
// Handle other response controls (if any)
}
}
}
// Re-activate paged results
ctx.setRequestControls(new Control[] {new PagedResultsControl(pageSize,
cookie,
Control.CRITICAL)});
}
public static void sort() throws NamingException, IOException {
LdapContext ctx = getLdapContext();
String sortKey = "ou";
ctx.setRequestControls(new Control[] { new SortControl(sortKey,
Control.CRITICAL) });
ctx.setRequestControls(new Control[] { new SortControl("o",
Control.CRITICAL) });
// Perform a search
NamingEnumeration<SearchResult> results = ctx.search("", "(objectclass=*)",
new SearchControls());
// Iterate over sorted search results
while (results != null && results.hasMore()) {
// Display an entry
SearchResult entry = (SearchResult) results.next();
System.out.println(entry.getName());
// Handle the entry's response controls (if any)
if (entry instanceof HasControls) {
// ((HasControls)entry).getControls();
}
}
// Examine the sort control response
Control[] controls = ctx.getResponseControls();
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof SortResponseControl) {
SortResponseControl src = (SortResponseControl) controls[i];
if (!src.isSorted()) {
throw src.getException();
}
} else {
// Handle other response controls (if any)
}
}
}
}
public static void save() throws NamingException, UnsupportedEncodingException {
LdapContext ctx = getLdapContext();
String dn = "uid=Test5,o=";
Attributes attrs = new BasicAttributes();
attrs.put("objectClass", "top");
attrs.put("objectClass", "person");
attrs.put("objectClass", "organizationalPerson");
attrs.put("objectClass", "inetOrgPerson");
attrs.put("objectClass", "employee");
attrs.put("cn", "Tes5");
attrs.put("sn", "Tes5");
attrs.put("userPassword", "111111");
ctx.bind(dn, null, attrs);
}
public static void saveUserRefObject() throws NamingException {
LdapContext ctx = getLdapContext();
String dn = "username=y,uid=Test2,o=";
Attributes attrs = new BasicAttributes();
attrs.put("objectClass", "top");
attrs.put("objectClass", "person");
attrs.put("objectClass", "organizationalPerson");
attrs.put("objectClass", "inetOrgPerson");
attrs.put("objectClass", "userReferenceSystem");
attrs.put("cn", "Tes2");
attrs.put("sn", "Tes2");
attrs.put("username", "test");
attrs.put("password", DigestUtils.sha256("123456"));
attrs.put("systemName", "test");
ctx.bind(dn, null, attrs);
}
public static void updateUserDeptFullPath() throws NamingException {
LdapContext ctx = getLdapContext();
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = ctx.search("", "(uid=*)",
sc);
ModificationItem[] mods = new ModificationItem[3];
SearchResult rs = null;
while (results.hasMore()) {
rs = results.next();
if (!rs.getNameInNamespace().startsWith("uid=admin")) {
System.out.println(new String((byte[]) rs.getAttributes().get("userpassword").get()));
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("deptName",
rs.getNameInNamespace().replaceAll(",dc=ehv,dc=csg,dc=cn", "").substring(
rs.getNameInNamespace().replaceAll(",dc=ehv,dc=csg,dc=cn", "").indexOf(",") + 1,
rs.getNameInNamespace().replaceAll(",dc=ehv,dc=csg,dc=cn", "").length())));
mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("deptFullPath",
rs.getNameInNamespace().replaceAll(",dc=ehv,dc=csg,dc=cn", "")));
mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("userPassword", DigestUtils.md5Hex("111111")));
ctx.modifyAttributes(rs.getNameInNamespace().replaceAll(",dc=ehv,dc=csg,dc=cn", "")
, mods);
}
}
}
public static void main(String[] args) throws NamingException, IOException {
// System.exit(0);
// saveUserRefObject();
// ldapPageView();
// getAllUser();
updateUserDeptFullPath();
// ldapPageView();
// save();
}
}
|
package org.commcare.suite.model;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.core.model.instance.ExternalDataInstance;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapList;
import org.javarosa.core.util.externalizable.ExtWrapMap;
import org.javarosa.core.util.externalizable.ExtWrapNullable;
import org.javarosa.core.util.externalizable.ExtWrapTagged;
import org.javarosa.core.util.externalizable.Externalizable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* <p>An Entry definition describes a user
* initiated form entry action, what information
* needs to be collected before that action can
* begin, and what the User Interface should
* present to the user regarding these actions</p>
*
* @author ctsims
*/
public class Entry implements Externalizable, MenuDisplayable {
private String xFormNamespace;
Vector<SessionDatum> data;
DisplayUnit display;
private String commandId;
Hashtable<String, DataInstance> instances;
Vector<StackOperation> stackOperations;
AssertionSet assertions;
/**
* Serialization only!
*/
public Entry() {
}
public Entry(String commandId, DisplayUnit display, Vector<SessionDatum> data, String formNamespace, Hashtable<String, DataInstance> instances,
Vector<StackOperation> stackOperations, AssertionSet assertions) {
this.commandId = commandId == null ? "" : commandId;
this.display = display;
this.data = data;
xFormNamespace = formNamespace;
this.instances = instances;
this.stackOperations = stackOperations;
this.assertions = assertions;
}
/**
* @return the ID of this entry command. Used by Menus to determine
* where the command should be located.
*/
public String getCommandId() {
return commandId;
}
/**
* @return A text whose evaluated string should be presented to the
* user as the entry point for this operation
*/
public Text getText() {
return display.getText();
}
/**
* @return The XForm Namespce of the form which should be filled out in
* the form entry session triggered by this action. null if no entry
* should occur [HACK].
*/
public String getXFormNamespace() {
return xFormNamespace;
}
public String getImageURI() {
if (display.getImageURI() == null) {
return null;
}
return display.getImageURI().evaluate();
}
public String getAudioURI() {
if (display.getAudioURI() == null) {
return null;
}
return display.getAudioURI().evaluate();
}
public String getDisplayText() {
if (display.getText() == null) {
return null;
}
return display.getText().evaluate();
}
public Vector<SessionDatum> getSessionDataReqs() {
return data;
}
public Hashtable<String, DataInstance> getInstances() {
Hashtable<String, DataInstance> copy = new Hashtable<String, DataInstance>();
for (Enumeration en = instances.keys(); en.hasMoreElements(); ) {
String key = (String)en.nextElement();
//This is silly, all of these are externaldata instances. TODO: save their
//construction details instead.
DataInstance cur = instances.get(key);
if (cur instanceof ExternalDataInstance) {
//Copy the EDI so when it gets populated we don't keep it dependent on this object's lifecycle!!
copy.put(key, new ExternalDataInstance(((ExternalDataInstance)cur).getReference(), cur.getInstanceId()));
} else {
copy.put(key, cur);
}
}
return copy;
}
public AssertionSet getAssertions() {
return assertions == null ? new AssertionSet(new Vector<String>(), new Vector<Text>()) : assertions;
}
/*
* (non-Javadoc)
* @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory)
*/
public void readExternal(DataInputStream in, PrototypeFactory pf)
throws IOException, DeserializationException {
this.xFormNamespace = ExtUtil.nullIfEmpty(ExtUtil.readString(in));
this.commandId = ExtUtil.readString(in);
this.display = (DisplayUnit)ExtUtil.read(in, DisplayUnit.class, pf);
data = (Vector<SessionDatum>)ExtUtil.read(in, new ExtWrapList(SessionDatum.class), pf);
instances = (Hashtable<String, DataInstance>)ExtUtil.read(in, new ExtWrapMap(String.class, new ExtWrapTagged()), pf);
stackOperations = (Vector<StackOperation>)ExtUtil.read(in, new ExtWrapList(StackOperation.class), pf);
assertions = (AssertionSet)ExtUtil.read(in, new ExtWrapNullable(AssertionSet.class));
}
/*
* (non-Javadoc)
* @see org.javarosa.core.util.externalizable.Externalizable#writeExternal(java.io.DataOutputStream)
*/
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.writeString(out, ExtUtil.emptyIfNull(xFormNamespace));
ExtUtil.writeString(out, commandId);
ExtUtil.write(out, display);
ExtUtil.write(out, new ExtWrapList(data));
ExtUtil.write(out, new ExtWrapMap(instances, new ExtWrapTagged()));
ExtUtil.write(out, new ExtWrapList(stackOperations));
ExtUtil.write(out, new ExtWrapNullable(assertions));
}
/**
* Retrieve the stack operations that should be processed after this entry
* session has successfully completed.
*
* @return a Vector of Stack Operation models.
*/
public Vector<StackOperation> getPostEntrySessionOperations() {
return stackOperations;
}
}
|
package cz.hobrasoft.pdfmu;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.Namespace;
// Handle unset output file (in-place change)
public class InOutPdfArgs implements ArgsConfiguration, AutoCloseable {
private final String metavarIn = "IN.pdf";
public final InPdfArgs in = new InPdfArgs(metavarIn);
public final OutPdfArgs out = new OutPdfArgs(metavarIn);
@Override
public void addArguments(ArgumentParser parser) {
in.addArguments(parser);
out.addArguments(parser);
}
@Override
public void setFromNamespace(Namespace namespace) {
in.setFromNamespace(namespace);
out.setFromNamespace(namespace);
}
public void open() throws OperationException {
open(false);
}
public void openSignature() throws OperationException {
open(true);
}
public void open(boolean signature) throws OperationException {
open(signature, '\0');
}
public void open(char pdfVersion) throws OperationException {
open(false, pdfVersion);
}
public void open(boolean signature, char pdfVersion) throws OperationException {
PdfReader reader = in.open();
out.setDefaultFile(in.getFile());
out.open(reader, signature, pdfVersion);
}
public PdfReader getPdfReader() {
return in.getPdfReader();
}
public PdfStamper getPdfStamper() {
return out.getPdfStamper();
}
@Override
public void close() throws OperationException {
out.close();
in.close();
}
public InPdfArgs getIn() {
return in;
}
public OutPdfArgs getOut() {
return out;
}
}
|
package dt.call.aclient.screens;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;
import dt.call.aclient.CallState;
import dt.call.aclient.Const;
import dt.call.aclient.Voip.SoundEffects;
import dt.call.aclient.Voip.Voice;
import dt.call.aclient.background.async.OperatorCommand;
import dt.call.aclient.R;
import dt.call.aclient.Utils;
import dt.call.aclient.Vars;
public class CallMain extends AppCompatActivity implements View.OnClickListener, SensorEventListener
{
private static final String WAKELOCK_INCALLA9 = "dt.call.aclient:incalla9";
private static final String tag = "CallMain";
public static final String DIALING_MODE = "DIALING_MODE";
private LinearLayout micContainer, spkContainer, acceptContainer;
private FloatingActionButton end, mic, speaker, accept;
private Button stats;
private boolean onSpeaker = false;
private boolean screenShowing;
private ImageView userImage;
private TextView status, time, callerid;
private int min=0, sec=0;
private Timer counter = new Timer();
private BroadcastReceiver myReceiver;
private String missingLabel, garbageLabel, txLabel, rxLabel, rxSeqLabel, txSeqLabel, skippedLabel, oorangeLabel;
private boolean showStats = false;
private boolean isDialing;
private boolean selfEndedCall = false;
private AudioManager audioManager;
private SensorManager sensorManager;
private Sensor proximity = null;
private final DecimalFormat decimalFormat = new DecimalFormat("
private final StringBuilder statsBuilder = new StringBuilder();
private final StringBuilder timeBuilder = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_main);
isDialing = getIntent().getBooleanExtra(DIALING_MODE, true);
//allow this screen to show even when there is a password/pattern lock screen
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
//cell phone now awake. release the wakelock
if(Vars.incomingCallLock != null)
{
Vars.incomingCallLock.release();
Vars.incomingCallLock = null;
}
end = findViewById(R.id.call_main_end_call);
end.setOnClickListener(this);
micContainer = findViewById(R.id.call_main_mic_container);
mic = findViewById(R.id.call_main_mic);
mic.setOnClickListener(this);
mic.setEnabled(false);
spkContainer = findViewById(R.id.call_main_spk_container);
speaker = findViewById(R.id.call_main_spk);
speaker.setOnClickListener(this);
speaker.setEnabled(false);
acceptContainer = findViewById(R.id.call_main_accept_container);
accept = findViewById(R.id.call_main_accept);
accept.setOnClickListener(this);
accept.setEnabled(!isDialing);
stats = findViewById(R.id.call_main_stats);
stats.setOnClickListener(this);
status = findViewById(R.id.call_main_status); //by default ringing. change it when in a call
callerid = findViewById(R.id.call_main_callerid);
callerid.setText(Utils.getCallerID(Vars.callWith));
time = findViewById(R.id.call_main_time);
userImage = findViewById(R.id.call_main_user_image);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
proximity = sensorManager != null ? sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY) : null;
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
TimerTask counterTask = new TimerTask()
{
@Override
public void run()
{
//if the person hasn't answered after 20 seconds give up. it's probably not going to happen.
if((Vars.state == CallState.INIT) && (sec == Const.CALL_TIMEOUT))
{
new OperatorCommand().execute(OperatorCommand.END);
onStopWrapper();
}
updateTime();
updateStats();
}
};
counter.schedule(counterTask, 0, 1000);
missingLabel = getString(R.string.call_main_stat_mia);
txLabel = getString(R.string.call_main_stat_tx);
rxLabel = getString(R.string.call_main_stat_rx);
garbageLabel = getString(R.string.call_main_stat_garbage);
rxSeqLabel = getString(R.string.call_main_stat_rx_seq);
txSeqLabel = getString(R.string.call_main_stat_tx_seq);
skippedLabel = getString(R.string.call_main_stat_skipped);
oorangeLabel = getString(R.string.call_main_stat_oorange);
myReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String response = intent.getStringExtra(Const.BROADCAST_CALL_RESP);
if(response.equals(Const.BROADCAST_CALL_START))
{
min = sec = 0;
changeToCallMode();
}
else if(response.equals(Const.BROADCAST_CALL_END))
{
//whether the call was rejected or time to end, it's the same result
//so share the same variable to avoid 2 sendBroadcast chunks of code that are almost the same
//media read/write are stopped in command listener when it got the call end
//Vars.state would've already been set by the server command that's broadcasting a call end
onStopWrapper();
}
String micEnable = intent.getStringExtra(Const.BROADCAST_CALL_MIC);
if(micEnable != null)
{
if(micEnable.equals(Boolean.TRUE.toString()))
{
mic.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_mic_white_48dp));
}
else
{
mic.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_mic_off_white_48dp));
}
}
}
};
registerReceiver(myReceiver, new IntentFilter(Const.BROADCAST_CALL));
if(isDialing && Vars.state == CallState.INIT)
{
acceptContainer.setVisibility(View.GONE);
SoundEffects.getInstance().playDialtone();
}
else if(!isDialing && Vars.state == CallState.INIT)
{
SoundEffects.getInstance().playRingtone();
}
//android 9.0 (and probably newer) has a stupid "power saving feature" where sending data
// is heavily throttled when the screen is off. No workaround exists whether using JNI to
// send data or using a foreground service.
//ABSOLUTELY MUST keep the screen on while talking to keep the conversation going
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
{
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
Vars.incallA9Workaround = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, WAKELOCK_INCALLA9);
Vars.incallA9Workaround.acquire();
//some kind of indication that the battery killing android 9 workaround is being used
status.setTextColor(ContextCompat.getColor(this, R.color.material_yellow));
}
}
@Override
protected void onResume()
{
super.onResume();
screenShowing = true;
if(proximity != null)
{
sensorManager.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL);
}
if(!isDialing && Vars.state == CallState.INIT)
{
spkContainer.setVisibility(View.GONE);
micContainer.setVisibility(View.GONE);
}
}
@Override
protected void onPause()
{
super.onPause();
screenShowing = false;
sensorManager.unregisterListener(this);
}
protected void onStopWrapper()
{
try
{
//onStop() is only ever manually called when the call ends and you want to leave this screen
Vars.state = CallState.NONE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
onStop();
}
});
}
else
{
onStop();
}
}
catch(Exception e)
{
//if the screen is already gone and this is the second time it's being called, not much you can do
}
}
@Override
protected void onStop()
{
super.onStop();
screenShowing = false;
/*
* onStop() is called when the CallMain screen isn't visible anymore. Either from ending a call
* or from going to another app during a call. To make sure the call doesn't stop, only do the
* cleanup if you're leaving the screen because the call ended.
*
* Vars.state = NONE will be set before calling onStop() manually to guarantee that onStop() sees
* the call state as none. The 2 async calls: end, timeout will set state = NONE, BUT BECAUSE they're
* async there is a chance that onStop() is called before the async is. Don't leave it to dumb luck.
*/
if(Vars.state == CallState.NONE)
{
if(selfEndedCall) //don't send call end to the server if you were told by the server to stop.
{
new OperatorCommand().execute(OperatorCommand.END);
}
//for cases when you make a call but decide you don't want to anymore
SoundEffects.getInstance().stopDialtone();
SoundEffects.getInstance().stopRingtone();
Voice.getInstance().stop();
//double check the counter to timeout is stopped or it will leak and crash when it's supposed to stop and this screen is gone
if(counter != null)
{
counter.cancel();
counter.purge();
}
try
{
unregisterReceiver(myReceiver);
}
catch(IllegalArgumentException i)
{
Utils.logcat(Const.LOGW, tag, "don't unregister you get a leak, do unregister you get an exception... ");
}
SoundEffects.getInstance().playEndTone();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && Vars.incallA9Workaround != null)
{
Vars.incallA9Workaround.release();
Vars.incallA9Workaround = null;
}
//go back to the home screen and clear the back history so there is no way to come back
Intent goHome = new Intent(this, UserHome.class);
goHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(goHome);
}
}
@Override
public void onClick(View v)
{
if(v == end)
{
selfEndedCall = true;
onStopWrapper();
}
else if (v == mic)
{
//update the mic icon in the encoder thread when the actual mute/unmute happens.
//it can take up to 1 second to change the status because of the sleep when going from mute-->unmute
Toast checkMic = Toast.makeText(this, getString(R.string.call_main_toast_micstatus), Toast.LENGTH_LONG);
checkMic.show();
Voice.getInstance().toggleMic();
}
else if (v == speaker)
{
onSpeaker = !onSpeaker;
if(onSpeaker)
{
speaker.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_volume_up_white_48dp));
audioManager.setSpeakerphoneOn(true);
}
else
{
speaker.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_phone_in_talk_white_48dp));
audioManager.setSpeakerphoneOn(false);
}
}
else if (v == stats)
{
showStats = !showStats;
if(showStats)
{
stats.setTextColor(ContextCompat.getColor(this, R.color.material_green));
userImage.setVisibility(View.INVISIBLE);
}
else
{
stats.setTextColor(ContextCompat.getColor(this, android.R.color.white));
callerid.setText(Utils.getCallerID(Vars.callWith));
userImage.setVisibility(View.VISIBLE);
}
}
else if(v == accept)
{
new OperatorCommand().execute(OperatorCommand.ACCEPT);
}
}
private void updateTime()
{
if(sec == 59)
{
sec = 0;
min++;
}
else
{
sec++;
}
if(screenShowing)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
timeBuilder.setLength(0);
if(sec < 10)
{
time.setText(timeBuilder.append(min).append(":0").append(sec).toString());
}
else
{
time.setText(timeBuilder.append(min).append(":").append(sec).toString());
}
}
});
}
}
private void updateStats()
{
if(screenShowing && showStats)
{
Voice voice = Voice.getInstance();
final String rxDisp=formatInternetMeteric(voice.getRxData()), txDisp=formatInternetMeteric(voice.getTxData());
final int missing = voice.getTxSeq()-voice.getRxSeq();
statsBuilder.setLength(0);
statsBuilder
.append(missingLabel).append(": ").append(missing > 0 ? missing : 0).append(" ").append(garbageLabel).append(": ").append(voice.getGarbage()).append("\n")
.append(rxLabel).append(":").append(rxDisp).append(" ").append(txLabel).append(":").append(txDisp).append("\n")
.append(rxSeqLabel).append(":").append(voice.getRxSeq()).append(" ").append(txSeqLabel).append(":").append(voice.getTxSeq()).append("\n")
.append(skippedLabel).append(":").append(voice.getSkipped()).append(" ").append(oorangeLabel).append(": ").append(voice.getOorange());
runOnUiThread(new Runnable()
{
@Override
public void run()
{
callerid.setText(statsBuilder.toString());
}
});
}
}
private void changeToCallMode()
{
micContainer.setVisibility(View.VISIBLE);
spkContainer.setVisibility(View.VISIBLE);
acceptContainer.setVisibility(View.GONE);
accept.setEnabled(false);
if(isDialing)
{
SoundEffects.getInstance().stopDialtone();
}
else
{
SoundEffects.getInstance().stopRingtone();
}
//it is impossible to change the status bar @ run time below 5.0, only the action bar color.
//results in a weird blue/green look. only change the look for >= 5.0
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
final ActionBar actionBar = getSupportActionBar();
if(actionBar != null)
{
actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(CallMain.this, R.color.material_green)));
}
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(CallMain.this, R.color.material_dark_green));
window.setNavigationBarColor(ContextCompat.getColor(CallMain.this, R.color.material_dark_green));
}
status.setText(getString(R.string.call_main_status_incall));
mic.setEnabled(true);
speaker.setEnabled(true);
Voice.getInstance().start();
}
@Override
public void onBackPressed()
{
// Do nothing. If you're in a call then there's no reason to go back to the User Home
}
@Override
public void onSensorChanged(SensorEvent event)
{
final float x = event.values[0];
if(x < 5)
{
//with there being no good information on turning the screen on and off
//go with the next best thing of disabling all the buttons
screenShowing = false;
end.setEnabled(false);
mic.setEnabled(false);
speaker.setEnabled(false);
}
else
{
screenShowing = true;
end.setEnabled(true);
mic.setEnabled(true);
speaker.setEnabled(true);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
//not relevant for proximity sensor so do nothing
}
private String formatInternetMeteric(int n)
{
final int mega = 1000000;
final int kilo = 1000;
if(n > mega)
{
return decimalFormat.format((float)n / (float)mega) + "M";
}
else if (n > kilo)
{
return (n/kilo) + "K";
}
else
{
return Integer.toString(n);
}
}
}
|
package org.pitest.maven;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.maven.scm.ChangeFile;
import org.apache.maven.scm.ChangeSet;
import org.apache.maven.scm.ScmBranch;
import org.apache.maven.scm.ScmException;
import org.apache.maven.scm.ScmFile;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.ScmFileStatus;
import org.apache.maven.scm.command.changelog.ChangeLogScmRequest;
import org.apache.maven.scm.command.changelog.ChangeLogScmResult;
import org.apache.maven.scm.command.status.StatusScmResult;
import org.apache.maven.scm.manager.ScmManager;
import org.apache.maven.scm.repository.ScmRepository;
import org.codehaus.plexus.util.StringUtils;
import org.pitest.functional.F;
import org.pitest.functional.FCollection;
import org.pitest.functional.Option;
import org.pitest.functional.predicate.Predicate;
import org.pitest.mutationtest.config.PluginServices;
import org.pitest.mutationtest.config.ReportOptions;
import org.pitest.mutationtest.tooling.CombinedStatistics;
/**
* Goal which runs a coverage mutation report only for files that have been
* modified or introduced locally based on the source control configured in
* maven.
*/
@Mojo(name = "scmMutationCoverage",
defaultPhase = LifecyclePhase.VERIFY,
requiresDependencyResolution = ResolutionScope.TEST,
threadSafe = true)
public class ScmMojo extends AbstractPitMojo {
private static final int NO_LIMIT = -1;
@Component
private ScmManager manager;
/**
* List of scm status to include. Names match those defined by the maven scm
* plugin.
*
* Common values include ADDED,MODIFIED (the defaults) & UNKNOWN.
*/
@Parameter(property = "include")
private HashSet<String> include;
/**
* Analyze last commit. If set to true analyzes last commited change set.
*/
@Parameter(defaultValue = "false", property = "analyseLastCommit")
private boolean analyseLastCommit;
@Parameter(property = "originBranch")
private String originBranch;
@Parameter(property = "destinationBranch", defaultValue = "master")
private String destinationBranch;
/**
* Connection type to use when querying scm for changed files. Can either be
* "connection" or "developerConnection".
*/
@Parameter(property = "connectionType", defaultValue = "connection")
private String connectionType;
/**
* Project basedir
*/
@Parameter(property = "basedir", required = true)
private File basedir;
/**
* Base of scm root. For a multi module project this is probably the parent
* project.
*/
@Parameter(property = "project.parent.basedir")
private File scmRootDir;
public ScmMojo(final RunPitStrategy executionStrategy,
final ScmManager manager, Predicate<Artifact> filter,
PluginServices plugins, boolean analyseLastCommit, Predicate<MavenProject> nonEmptyProjectCheck) {
super(executionStrategy, filter, plugins, nonEmptyProjectCheck);
this.manager = manager;
this.analyseLastCommit = analyseLastCommit;
}
public ScmMojo() {
}
@Override
protected Option<CombinedStatistics> analyse() throws MojoExecutionException {
this.targetClasses = makeConcreteList(findModifiedClassNames());
if (this.targetClasses.isEmpty()) {
this.getLog().info(
"No modified files found - nothing to mutation test, analyseLastCommit=" + this.analyseLastCommit);
return Option.none();
}
logClassNames();
defaultTargetTestsToGroupNameIfNoValueSet();
final ReportOptions data = new MojoToReportOptionsConverter(this,
new SurefireConfigConverter(), filter).convert();
data.setFailWhenNoMutations(false);
return Option.some(this.goalStrategy.execute(detectBaseDir(), data,
plugins, new HashMap<String, String>()));
}
private void defaultTargetTestsToGroupNameIfNoValueSet() {
if (this.getTargetTests() == null || this.getTargetTests().isEmpty()) {
this.targetTests = makeConcreteList(Collections.singletonList(this
.getProject().getGroupId() + "*"));
}
}
private void logClassNames() {
for (final String each : this.targetClasses) {
this.getLog().info("Will mutate changed class " + each);
}
}
private List<String> findModifiedClassNames() throws MojoExecutionException {
final File sourceRoot = new File(this.project.getBuild()
.getSourceDirectory());
final List<String> modifiedPaths = FCollection.map(findModifiedPaths(), pathByScmDir());
return FCollection.flatMap(modifiedPaths, new PathToJavaClassConverter(
sourceRoot.getAbsolutePath()));
}
private F<String,String> pathByScmDir() {
return new F<String, String>() {
@Override
public String apply(final String a) {
return scmRootDir.getAbsolutePath() + "/" + a;
}
};
}
private Set<String> findModifiedPaths() throws MojoExecutionException {
try {
final ScmRepository repository = this.manager
.makeScmRepository(getSCMConnection());
final File scmRoot = scmRoot();
this.getLog().info("Scm root dir is " + scmRoot);
final Set<ScmFileStatus> statusToInclude = makeStatusSet();
final Set<String> modifiedPaths;
if (analyseLastCommit) {
modifiedPaths = lastCommitChanges(statusToInclude, repository, scmRoot);
} else if (originBranch != null && destinationBranch != null) {
modifiedPaths = changesBetweenBranchs(originBranch, destinationBranch, statusToInclude, repository, scmRoot);
} else {
modifiedPaths = localChanges(statusToInclude, repository, scmRoot);
}
return modifiedPaths;
} catch (final ScmException e) {
throw new MojoExecutionException("Error while querying scm", e);
}
}
private Set<String> lastCommitChanges(Set<ScmFileStatus> statusToInclude, ScmRepository repository, File scmRoot) throws ScmException {
ChangeLogScmRequest scmRequest = new ChangeLogScmRequest(repository, new ScmFileSet(scmRoot));
scmRequest.setLimit(1);
return pathsAffectedByChange(scmRequest, statusToInclude, 1);
}
private Set<String> changesBetweenBranchs(String origine, String destination, Set<ScmFileStatus> statusToInclude, ScmRepository repository, File scmRoot) throws ScmException {
ChangeLogScmRequest scmRequest = new ChangeLogScmRequest(repository, new ScmFileSet(scmRoot));
scmRequest.setScmBranch(new ScmBranch(destination + ".." + origine));
return pathsAffectedByChange(scmRequest, statusToInclude, NO_LIMIT);
}
private Set<String> pathsAffectedByChange(ChangeLogScmRequest scmRequest, Set<ScmFileStatus> statusToInclude, int limit) throws ScmException {
Set<String> affected = new LinkedHashSet<String>();
ChangeLogScmResult changeLogScmResult = this.manager.changeLog(scmRequest);
if (changeLogScmResult.isSuccess()) {
List<ChangeSet> changeSets = limit(changeLogScmResult.getChangeLog().getChangeSets(),limit);
for (ChangeSet change : changeSets) {
List<ChangeFile> files = change.getFiles();
for (final ChangeFile changeFile : files) {
if (statusToInclude.contains(changeFile.getAction())) {
affected.add(changeFile.getName());
}
}
}
}
return affected;
}
private Set<String> localChanges(Set<ScmFileStatus> statusToInclude, ScmRepository repository, File scmRoot) throws ScmException {
final StatusScmResult status = this.manager.status(repository,
new ScmFileSet(scmRoot));
Set<String> affected = new LinkedHashSet<String>();
for (final ScmFile file : status.getChangedFiles()) {
if (statusToInclude.contains(file.getStatus())) {
affected.add(file.getPath());
}
}
return affected;
}
private List<ChangeSet> limit(List<ChangeSet> changeSets, int limit) {
if (limit < 0) {
return changeSets;
}
return changeSets.subList(0, limit);
}
private Set<ScmFileStatus> makeStatusSet() {
if ((this.include == null) || this.include.isEmpty()) {
return new HashSet<ScmFileStatus>(Arrays.asList(
ScmStatus.ADDED.getStatus(), ScmStatus.MODIFIED.getStatus()));
}
final Set<ScmFileStatus> s = new HashSet<ScmFileStatus>();
FCollection.mapTo(this.include, stringToMavenScmStatus(), s);
return s;
}
private static F<String, ScmFileStatus> stringToMavenScmStatus() {
return new F<String, ScmFileStatus>() {
@Override
public ScmFileStatus apply(final String a) {
return ScmStatus.valueOf(a.toUpperCase()).getStatus();
}
};
}
private File scmRoot() {
if (this.scmRootDir != null) {
return this.scmRootDir;
}
return this.basedir;
}
private String getSCMConnection() throws MojoExecutionException {
if (this.project.getScm() == null) {
throw new MojoExecutionException("No SCM Connection configured.");
}
final String scmConnection = this.project.getScm().getConnection();
if ("connection".equalsIgnoreCase(this.connectionType)
&& StringUtils.isNotEmpty(scmConnection)) {
return scmConnection;
}
final String scmDeveloper = this.project.getScm().getDeveloperConnection();
if ("developerconnection".equalsIgnoreCase(this.connectionType)
&& StringUtils.isNotEmpty(scmDeveloper)) {
return scmDeveloper;
}
throw new MojoExecutionException("SCM Connection is not set.");
}
public void setConnectionType(final String connectionType) {
this.connectionType = connectionType;
}
public void setScmRootDir(final File scmRootDir) {
this.scmRootDir = scmRootDir;
}
/**
* A bug in maven 2 requires that all list fields declare a concrete list type
*/
private static ArrayList<String> makeConcreteList(List<String> list) {
return new ArrayList<String>(list);
}
}
|
package org.protempa.cli;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.lang.StringUtils;
import org.protempa.Protempa;
import org.protempa.ProtempaStartupException;
/**
* Convenience class for creating command line applications using PROTEMPA.
*
* @author Andrew Post
*/
public abstract class CLI {
/**
* For defining command line arguments that are not prefixed by the option
* syntax.
*/
public static final class Argument {
private final String name;
private final boolean required;
/**
* Instantiates an instance with the name of the argument and
* whether or not it is required.
*
* @param name the argument's name, a {@link String}.
* @param required <code>true</code> if the argument is required,
* <code>false</code> if not.
*/
public Argument(String name, boolean required) {
if (name == null || name.trim().length() == 0) {
throw new IllegalArgumentException(
"name cannot be null or empty");
}
this.name = name;
this.required = required;
}
/**
* Returns the argument's name.
*
* @return a {@link String}.
*/
public String getName() {
return this.name;
}
/**
* Returns whether the argument is required.
*
* @return <code>true</code> if the argument is required,
* <code>false</code> if not.
*/
public boolean isRequired() {
return this.required;
}
/**
* Gets the argument formatted as a string suitable for a usage
* statement.
*
* @return a {@link String}.
*/
public String getFormatted() {
if (this.required) {
return this.name;
} else {
return '[' + this.name + ']';
}
}
}
private Protempa protempa;
private CommandLine commandLine;
private final String shellCommand;
private final Argument[] arguments;
private final boolean configurationIdEnabled;
/**
* Instantiates the application with a required shell command name.
*
* @param shellCommand a {@link String}, cannot be <code>null</code> or
* empty.
*/
protected CLI(String shellCommand) {
this(shellCommand, null);
}
/**
* Instantiates the application with a required shell command name and
* optional arguments that are not prefixed with option syntax.
*
* To add options, override
* {@link #addCustomCliOptions(org.apache.commons.cli.Options)}.
*
* @param shellCommand a {@link String}, cannot be <code>null</code> or
* empty.
* @param arguments a {@link Argument[]}.
*/
protected CLI(String shellCommand, Argument[] arguments) {
this(shellCommand, arguments, true);
}
/**
* Instantiates the application with a required shell command name,
* optional arguments that are not prefixed with option syntax, and
* whether to create the configuration id option. The latter is
* <code>true</code> by default, and normally would be unless PROTEMPA
* would not be initialized by the program for some reason.
*
* To add options, override
* {@link #addCustomCliOptions(org.apache.commons.cli.Options)}.
*
* @param shellCommand a {@link String}, cannot be <code>null</code> or
* empty.
* @param arguments a {@link Argument[]}.
* @param configurationIdEnabled whether or not the configuration id option
* should be created.
*/
protected CLI(String shellCommand, Argument[] arguments,
boolean configurationIdEnabled) {
if (shellCommand == null || shellCommand.trim().length() == 0) {
throw new IllegalArgumentException(
"shellCommand cannot be null or empty");
}
this.shellCommand = shellCommand;
if (arguments == null) {
arguments = new Argument[0];
}
this.arguments = arguments;
this.configurationIdEnabled = configurationIdEnabled;
}
/**
* Gets the shell command.
*
* @return a {@link String}.
*/
public final String getShellCommand() {
return this.shellCommand;
}
/**
* Gets optional arguments that are not prefixed with option syntax.
*
* @return a {@link Argument[]}. Guaranteed not <code>null</code>.
*/
public final Argument[] getArguments() {
return this.arguments.clone();
}
/**
* Whether the configuration option will be created. This is
* <code>true</code> unless otherwise specified, and must be
* <code>true</code> if {@link #initialize()} will be called.
*
* @return <code>true</code> or <code>false</code>.
*/
public final boolean isConfigurationIdEnabled() {
return this.configurationIdEnabled;
}
/**
* Initializes PROTEMPA with the specified configuration. Must be called
* after {@link #processArgs(java.lang.String[], int, int) }.
*
* @param configurationId the id {@link String} of a configuration.
* @throws ProtempaStartupException if an error occurred starting up
* PROTEMPA.
*/
public final void initialize()
throws ProtempaStartupException {
if (!this.configurationIdEnabled) {
throw new IllegalStateException(
"Cannot initialize without a configuration id");
}
this.protempa = Protempa.newInstance(commandLine.getOptionValue("c"));
}
/**
* Implemented with whatever is done with the instance of PROTEMPA
* created with {@link #initialize(java.lang.String)}, and processing of
* any arguments and command line options specified in
* {@link #addCustomCliOptions(org.apache.commons.cli.Options)}. The
* default implementation is a no-op.
*
* @param protempa an instance of {@link Protempa}.
* @param commandLine the {@link CommandLine} options passed in by the
* caller.
* @throws CLIException if some exception was thrown by the implementation
* of this method. The convention is for any such exceptions to be nested
* in an instance of {@link CLIException}.
*/
public void execute(Protempa protempa, CommandLine commandLine)
throws CLIException {
}
/**
* Prints to the console an exception's message and its nested
* exception's message (if any).
*
* @param cliException the {@link Exception} to print.
*/
public final void printException(Exception cliException) {
System.err.print(cliException.getMessage());
Throwable cause = cliException.getCause();
if (cause != null && cause.getMessage() != null
&& cause.getMessage().length() > 0) {
System.err.print(": ");
System.err.println(cause.getMessage());
} else {
System.err.println();
}
}
/**
* Calls the code in
* {@link #execute(org.protempa.Protempa, org.apache.commons.cli.CommandLine)}.
* @throws CLIException if
* {@link #execute(org.protempa.Protempa, org.apache.commons.cli.CommandLine)}
* throws an exception.
*/
public final void execute() throws CLIException {
if (this.protempa == null) {
throw new IllegalStateException("PROTEMPA not initialized.");
}
execute(this.protempa, this.commandLine);
}
public final void close() {
if (this.protempa == null)
throw new IllegalStateException("PROTEMPA not initialized");
this.protempa.close();
this.protempa = null;
}
/**
* Processes command line options. The default command line options are -h
* or --help, which prints usage and the list of options, and -c or
* --configuration, which is followed by the id of a PROTEMPA
* configuration. The latter is required unless -h is specified. Any additional
* options that are specified in {@link #addCustomCliOptions(org.apache.commons.cli.Options)}
* should be handled by {@link #execute(org.protempa.Protempa, org.apache.commons.cli.CommandLine) }.
* There always must be at least one argument for the configuration id.
*
* @param args the argument {@link String[]} passed into <code>main</code>.
* @return a {@link CommandLine} instance.
*/
public final CommandLine processOptionsAndArgs(String[] args) {
if (args == null) {
throw new IllegalArgumentException("args cannot be null");
}
Options cliOptions = constructCliOptions();
CommandLineParser parser = new PosixParser();
try {
this.commandLine = parser.parse(cliOptions, args);
} catch (ParseException ex) {
System.err.println(ex.getMessage());
System.exit(1);
}
String commandLineSyntax = commandLineSyntax(this.arguments);
if (this.commandLine.hasOption("h")) {
new HelpFormatter().printHelp(commandLineSyntax, cliOptions);
System.exit(0);
}
if (this.configurationIdEnabled && !this.commandLine.hasOption("c")) {
System.err.println("missing option: c");
System.exit(1);
}
checkInvalidArguments(this.arguments);
return this.commandLine;
}
/**
* Like calling {@link #initialize(java.lang.String)},
* {@link #execute()} and {@link #close()} in succession. Must be called
* only after {@link #processArgs(java.lang.String[], int, int) }.
*
* @param configurationId a PROTEMPA configuration id {@link String}.
*/
public final void initializeExecuteAndClose() {
try {
initialize();
} catch (ProtempaStartupException ex) {
printException(ex);
System.exit(1);
}
boolean error = false;
try {
execute();
} catch (CLIException ex) {
printException(ex);
error = true;
} finally {
close();
}
if (error) {
System.exit(1);
}
}
/**
* Override to specify any custom command line options.
*
* @param options the command line {@link Options}.
*/
protected void addCustomCliOptions(Options options) {
}
private String commandLineSyntax(Argument[] arguments) {
StringBuilder argumentStringBuilder = new StringBuilder();
if (arguments.length > 0) {
argumentStringBuilder.append(' ');
}
for (int i = 0; i < arguments.length; i++) {
argumentStringBuilder.append(arguments[i].getFormatted());
if (i < arguments.length - 1) {
argumentStringBuilder.append(' ');
}
}
String commandLineSyntax = this.shellCommand + " [options]"
+ argumentStringBuilder.toString();
return commandLineSyntax;
}
private Options constructCliOptions() {
Options options = new Options();
options.addOption("h", "help", false, "print this message");
if (configurationIdEnabled) {
options.addOption("c", "configuration", true,
"PROTEMPA configuration id");
}
addCustomCliOptions(options);
return options;
}
private void checkInvalidArguments(Argument[] arguments) {
String[] leftOverArgs = commandLine.getArgs();
List<Argument> requiredArguments = new ArrayList<Argument>();
for (Argument argument : arguments) {
if (argument.isRequired()) {
requiredArguments.add(argument);
}
}
List<String> missingRequiredArgs = new ArrayList<String>();
if (leftOverArgs.length < requiredArguments.size()) {
for (int i = leftOverArgs.length, n = requiredArguments.size();
i < n; i++) {
missingRequiredArgs.add(requiredArguments.get(i).getName());
}
}
if (!missingRequiredArgs.isEmpty()) {
System.err.println("Missing argument(s): "
+ StringUtils.join(missingRequiredArgs, ", "));
System.exit(1);
}
if (leftOverArgs.length > arguments.length) {
List<String> extraArgs = new ArrayList<String>();
for (int i = arguments.length; i < leftOverArgs.length; i++) {
extraArgs.add(leftOverArgs[i]);
}
System.err.println("Invalid extra argument(s): "
+ StringUtils.join(extraArgs, ","));
System.exit(1);
}
}
}
|
package com.henrikrydgard.libnative;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ConfigurationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Point;
import android.media.AudioManager;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists())
writeInstallationFile(installation);
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
public class NativeActivity extends Activity {
// Remember to loadLibrary your JNI .so in a static {} block
// Adjust these as necessary
private static String TAG = "NativeActivity";
// Allows us to skip a lot of initialization on secondary calls to onCreate.
private static boolean initialized = false;
// Graphics and audio interfaces
private GLSurfaceView mGLSurfaceView;
private NativeAudioPlayer audioPlayer;
private NativeRenderer nativeRenderer;
boolean useOpenSL = false;
public static String runCommand;
public static String commandParameter;
public static String installID;
// Settings for best audio latency
private int optimalFramesPerBuffer;
private int optimalSampleRate;
@TargetApi(17)
private void detectOptimalAudioSettings() {
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
optimalFramesPerBuffer = Integer.parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
optimalSampleRate = Integer.parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
}
String getApplicationLibraryDir(ApplicationInfo application) {
String libdir = null;
try {
// Starting from Android 2.3, nativeLibraryDir is available:
Field field = ApplicationInfo.class.getField("nativeLibraryDir");
libdir = (String) field.get(application);
} catch (SecurityException e1) {
} catch (NoSuchFieldException e1) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
}
if (libdir == null) {
// Fallback for Android < 2.3:
libdir = application.dataDir + "/lib";
}
return libdir;
}
@TargetApi(13)
void GetScreenSizeHC(Point size) {
WindowManager w = getWindowManager();
w.getDefaultDisplay().getSize(size);
}
void GetScreenSize(Point size) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
GetScreenSizeHC(size);
} else {
WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
size.x = d.getWidth();
size.y = d.getHeight();
}
}
public void Initialize() {
if (Build.VERSION.SDK_INT >= 9) {
// Native OpenSL is available. Let's use it!
useOpenSL = true;
}
if (Build.VERSION.SDK_INT >= 17) {
// Get the optimal buffer sz
detectOptimalAudioSettings();
}
/*
if (NativeApp.isLandscape()) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}*/
Log.i(TAG, "onCreate");
// Get system information
ApplicationInfo appInfo = null;
PackageManager packMgmr = getPackageManager();
String packageName = getPackageName();
try {
appInfo = packMgmr.getApplicationInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
String libraryDir = getApplicationLibraryDir(appInfo);
File sdcard = Environment.getExternalStorageDirectory();
Display display = ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
@SuppressWarnings("deprecation")
int scrPixelFormat = display.getPixelFormat();
Point size = new Point();
GetScreenSize(size);
int scrWidth = size.x;
int scrHeight = size.y;
float scrRefreshRate = display.getRefreshRate();
String externalStorageDir = sdcard.getAbsolutePath();
String dataDir = this.getFilesDir().getAbsolutePath();
String apkFilePath = appInfo.sourceDir;
NativeApp.sendMessage("Message from Java", "Hot Coffee");
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int dpi = metrics.densityDpi;
// INIT!
NativeApp.audioConfig(optimalFramesPerBuffer, optimalSampleRate);
NativeApp.init(scrWidth, scrHeight, dpi, apkFilePath, dataDir, externalStorageDir, libraryDir, installID, useOpenSL);
Log.i(TAG, "W : " + scrWidth + " H: " + scrHeight + " rate: " + scrRefreshRate + " fmt: " + scrPixelFormat);
// Initialize Graphics
if (!detectOpenGLES20()) {
Log.i(TAG, "OpenGL ES 2.0 NOT detected.");
} else {
Log.i(TAG, "OpenGL ES 2.0 detected.");
}
/*
editText = new EditText(this);
editText.setText("Hello world");
addContentView(editText, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
*/
// inputBox("Please ener a s", "", "Save");
// Toast.makeText(this, "Value: " + input.getText().toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
installID = Installation.id(this);
if (!initialized) {
Initialize();
initialized = true;
}
// Keep the screen bright - very annoying if it goes dark when tilting away
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (!useOpenSL)
audioPlayer = new NativeAudioPlayer();
NativeApp.audioInit();
Point size = new Point();
GetScreenSize(size);
NativeApp.resized(size.x, size.y);
mGLSurfaceView = new NativeGLView(this);
nativeRenderer = new NativeRenderer(this);
mGLSurfaceView.setRenderer(nativeRenderer);
setContentView(mGLSurfaceView);
if (Build.VERSION.SDK_INT >= 14) {
darkenOnScreenButtons();
}
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop - do nothing, just let's switch away");
}
@Override
protected void onDestroy() {
super.onDestroy();
nativeRenderer.onDestroyed();
Log.e(TAG, "onDestroy");
NativeApp.audioShutdown();
audioPlayer = null;
mGLSurfaceView = null;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void darkenOnScreenButtons() {
mGLSurfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
private boolean detectOpenGLES20() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ConfigurationInfo info = am.getDeviceConfigurationInfo();
return info.reqGlEsVersion >= 0x20000;
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause");
if (audioPlayer != null) {
audioPlayer.stop();
}
Log.i(TAG, "nativeapp pause");
NativeApp.pause();
Log.i(TAG, "gl pause");
mGLSurfaceView.onPause();
Log.i(TAG, "onPause returning");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume");
if (mGLSurfaceView != null) {
mGLSurfaceView.onResume();
} else {
Log.e(TAG, "mGLSurfaceView really shouldn't be null in onResume");
}
if (audioPlayer != null) {
audioPlayer.play();
}
NativeApp.resume();
if (Build.VERSION.SDK_INT >= 14) {
darkenOnScreenButtons();
}
}
public boolean overrideKeys() {
return true;
}
// Prevent destroying and recreating the main activity when the device rotates etc,
// since this would stop the sound.
@Override
public void onConfigurationChanged(Configuration newConfig) {
// Ignore orientation change
super.onConfigurationChanged(newConfig);
}
public static boolean inputBoxCancelled;
InputDeviceState inputPlayerA;
String inputPlayerADesc;
// We simply grab the first input device to produce an event and ignore all others that are connected.
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private InputDeviceState getInputDeviceState(InputEvent event) {
InputDevice device = event.getDevice();
if (device == null) {
return null;
}
if (inputPlayerA == null) {
inputPlayerA = new InputDeviceState(device);
inputPlayerADesc = getInputDesc(device);
}
if (inputPlayerA.getDevice() == device) {
return inputPlayerA;
}
/*
if (inputPlayerB == null) {
inputPlyerB = new InputDeviceStats(device);
}
if (inputPlayerB.getDevice() == device) {
return inputPlayerB;
}*/
return null;
}
// We grab the keys before onKeyDown/... even see them. This is also better because it lets us
// distinguish devices.
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
InputDeviceState state = getInputDeviceState(event);
if (state == null) {
return super.dispatchKeyEvent(event);
}
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
if (state.onKeyDown(event)) {
return true;
}
break;
case KeyEvent.ACTION_UP:
if (state.onKeyUp(event)) {
return true;
}
break;
}
}
// Let's go through the old path (onKeyUp, onKeyDown).
return super.dispatchKeyEvent(event);
}
@TargetApi(16)
static public String getInputDesc(InputDevice input) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return input.getDescriptor();
} else {
List<InputDevice.MotionRange> motions = input.getMotionRanges();
String fakeid = "";
for (InputDevice.MotionRange range : motions)
fakeid += range.getAxis();
return fakeid;
}
}
@Override
@TargetApi(12)
public boolean onGenericMotionEvent(MotionEvent event) {
// Log.d(TAG, "onGenericMotionEvent: " + event);
if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) {
if (Build.VERSION.SDK_INT >= 12) {
InputDeviceState state = getInputDeviceState(event);
if (state == null) {
Log.w(TAG, "Joystick event but failed to get input device state.");
return super.onGenericMotionEvent(event);
}
state.onJoystickMotion(event);
return true;
}
}
if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
switch (event.getAction()) {
case MotionEvent.ACTION_HOVER_MOVE:
// process the mouse hover movement...
return true;
case MotionEvent.ACTION_SCROLL:
NativeApp.mouseWheelEvent(event.getX(), event.getY());
return true;
}
}
return super.onGenericMotionEvent(event);
}
@SuppressLint("NewApi")
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Eat these keys, to avoid accidental exits / other screwups.
// Maybe there's even more we need to eat on tablets?
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.isAltPressed()) {
NativeApp.keyDown(0, 1004); // special custom keycode
} else if (NativeApp.isAtTopLevel()) {
Log.i(TAG, "IsAtTopLevel returned true.");
return super.onKeyUp(keyCode, event);
} else {
NativeApp.keyDown(0, keyCode);
}
return true;
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_SEARCH:
NativeApp.keyDown(0, keyCode);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
// NativeApp should ignore these.
return super.onKeyDown(keyCode, event);
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// Joysticks are supported in Honeycomb MR1 and later via the onGenericMotionEvent method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && event.getSource() == InputDevice.SOURCE_JOYSTICK) {
return super.onKeyUp(keyCode, event);
}
// Fall through
default:
// send the rest of the keys through.
// TODO: get rid of the three special cases above by adjusting the native side of the code.
// Log.d(TAG, "Key down: " + keyCode + ", KeyEvent: " + event);
NativeApp.keyDown(0, keyCode);
return true;
}
}
@SuppressLint("NewApi")
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.isAltPressed()) {
NativeApp.keyUp(0, 1004); // special custom keycode
} else if (NativeApp.isAtTopLevel()) {
Log.i(TAG, "IsAtTopLevel returned true.");
return super.onKeyUp(keyCode, event);
} else {
NativeApp.keyUp(0, keyCode);
}
return true;
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_SEARCH:
// Search probably should also be ignored. We send it to the app.
NativeApp.keyUp(0, keyCode);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_VOLUME_UP:
return super.onKeyUp(keyCode, event);
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// Joysticks are supported in Honeycomb MR1 and later via the onGenericMotionEvent method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && event.getSource() == InputDevice.SOURCE_JOYSTICK) {
return super.onKeyUp(keyCode, event);
}
// Fall through
default:
// send the rest of the keys through.
// TODO: get rid of the three special cases above by adjusting the native side of the code.
// Log.d(TAG, "Key down: " + keyCode + ", KeyEvent: " + event);
NativeApp.keyUp(0, keyCode);
return true;
}
}
public String inputBox(String title, String defaultText, String defaultAction) {
final FrameLayout fl = new FrameLayout(this);
final EditText input = new EditText(this);
input.setGravity(Gravity.CENTER);
inputBoxCancelled = false;
FrameLayout.LayoutParams editBoxLayout = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
editBoxLayout.setMargins(2, 20, 2, 20);
fl.addView(input, editBoxLayout);
input.setText(defaultText);
input.selectAll();
AlertDialog dlg = new AlertDialog.Builder(this)
.setView(fl)
.setTitle(title)
.setPositiveButton(defaultAction, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface d, int which) {
d.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface d, int which) {
d.cancel();
NativeActivity.inputBoxCancelled = false;
}
}).create();
dlg.setCancelable(false);
dlg.show();
if (inputBoxCancelled)
return null;
NativeApp.sendMessage("INPUTBOX:" + title, input.getText().toString());
return input.getText().toString();
}
public void processCommand(String command, String params) {
if (command.equals("launchBrowser")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(params));
startActivity(i);
} else if (command.equals("launchEmail")) {
Intent send = new Intent(Intent.ACTION_SENDTO);
String uriText;
uriText = "mailto:email@gmail.com" +
"?subject=Your app is..." +
"&body=great! Or?";
uriText = uriText.replace(" ", "%20");
Uri uri = Uri.parse(uriText);
send.setData(uri);
startActivity(Intent.createChooser(send, "E-mail the app author!"));
} else if (command.equals("launchMarket")) {
// Don't need this, can just use launchBrowser with a market:
// http://developer.android.com/guide/publishing/publishing.html#marketintent
} else if (command.equals("toast")) {
Toast toast = Toast.makeText(this, params, Toast.LENGTH_SHORT);
toast.show();
} else if (command.equals("showKeyboard")) {
//InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//inputMethodManager.toggleSoftInputFromWindow(this, InputMethodManager.SHOW_FORCED, 0);
} else if (command.equals("inputBox")) {
inputBox(params, "", "OK");
} else {
Log.e(TAG, "Unsupported command " + command + " , param: " + params);
}
}
}
|
package bisq.apitest.linux;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import static bisq.apitest.linux.BashCommand.isAlive;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static joptsimple.internal.Strings.EMPTY;
import bisq.apitest.config.ApiTestConfig;
// Some cmds:
// bitcoin-cli -regtest generatetoaddress 1 "2MyBq4jbtDF6CfKNrrQdp7qkRc8mKuCpKno"
// bitcoin-cli -regtest getbalance
// note: getbalance does not include immature coins (<100 blks deep)
// bitcoin-cli -regtest getbalances
// bitcoin-cli -regtest getrpcinfo
@Slf4j
public class BitcoinDaemon extends AbstractLinuxProcess implements LinuxProcess {
public BitcoinDaemon(ApiTestConfig config) {
super("bitcoind", config);
}
@Override
public void start() throws InterruptedException, IOException {
// If the bitcoind binary is dynamically linked to berkeley db libs, export the
// configured berkeley-db lib path. If statically linked, the berkeley db lib
// path will not be exported.
String berkeleyDbLibPathExport = config.berkeleyDbLibPath.equals(EMPTY) ? EMPTY
: "export LD_LIBRARY_PATH=" + config.berkeleyDbLibPath + "; ";
String bitcoindCmd = berkeleyDbLibPathExport
+ config.bitcoinPath + "/bitcoind"
+ " -datadir=" + config.bitcoinDatadir
+ " -daemon";
BashCommand cmd = new BashCommand(bitcoindCmd).run();
log.info("Starting ...\n$ {}", cmd.getCommand());
if (cmd.getExitStatus() != 0) {
startupExceptions.add(new IllegalStateException(
format("Error starting bitcoind%nstatus: %d%nerror msg: %s",
cmd.getExitStatus(), cmd.getError())));
return;
}
pid = BashCommand.getPid("bitcoind");
if (!isAlive(pid))
throw new IllegalStateException("Error starting regtest bitcoind daemon:\n" + cmd.getCommand());
log.info("Running with pid {}", pid);
log.info("Log {}", config.bitcoinDatadir + "/regtest/debug.log");
}
@Override
public long getPid() {
return this.pid;
}
@Override
public void shutdown() throws IOException, InterruptedException {
try {
log.info("Shutting down bitcoind daemon...");
if (!isAlive(pid))
throw new IllegalStateException("bitcoind already shut down");
if (new BashCommand("kill -15 " + pid).run().getExitStatus() != 0)
throw new IllegalStateException("Could not shut down bitcoind; probably already stopped.");
MILLISECONDS.sleep(2000); // allow it time to shutdown
log.info("Stopped");
} catch (Exception e) {
throw new IllegalStateException("Error shutting down bitcoind", e);
} finally {
if (isAlive(pid))
//noinspection ThrowFromFinallyBlock
throw new IllegalStateException("bitcoind shutdown did not work");
}
}
}
|
package com.rho.sync;
import com.rho.IRhoRubyHelper;
import com.rho.RhoClassFactory;
import com.rho.RhoEmptyLogger;
import com.rho.RhoLogger;
import com.rho.db.*;
import com.rho.net.*;
import com.rho.*;
import java.util.Vector;
import java.util.Hashtable;
import org.json.me.JSONException;
class SyncEngine implements NetRequest.IRhoSession
{
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("Sync");
class SyncNotification
{
String m_strUrl, m_strParams;
SyncNotification(String strUrl, String strParams){ m_strUrl = strUrl; m_strParams = strParams; }
};
public static final int esNone = 0, esSyncAllSources = 1, esSyncSource = 2, esStop = 3, esExit = 4;
public static final int DEFAULT_SYNC_PORT = 100;
static String SYNC_SOURCE_FORMAT() { return "?format=json"; }
static String SYNC_ASK_ACTION() { return "/ask"; }
static String SYNC_PAGE_SIZE() { return "200"; }
Vector/*<SyncSource*>*/ m_sources = new Vector();
DBAdapter m_dbAdapter;
NetRequest m_NetRequest;
int m_syncState;
String m_clientID = "";
Hashtable/*<int,SyncNotification>*/ m_mapNotifications = new Hashtable();
Mutex m_mxNotifications = new Mutex();
String m_strSession = "";
ISyncStatusListener m_statusListener = null;
public void setStatusListener(ISyncStatusListener listener) { m_statusListener = listener; }
private void reportStatus(String status, int error) {
if (m_statusListener != null) {
m_statusListener.reportStatus(status, error);
}
LOG.INFO(status);
}
void setState(int eState){ m_syncState = eState; }
int getState(){ return m_syncState; }
boolean isContinueSync(){ return m_syncState != esExit && m_syncState != esStop; }
boolean isSyncing(){ return m_syncState == esSyncAllSources || m_syncState == esSyncSource; }
void stopSync(){ if (isContinueSync()){ setState(esStop); getNet().cancelAll();} }
void exitSync(){ setState(esExit); getNet().cancelAll(); }
String getClientID(){ return m_clientID; }
void setSession(String strSession){m_strSession=strSession;}
public String getSession(){ return m_strSession; }
boolean isSessionExist(){ return m_strSession != null && m_strSession.length() > 0; }
DBAdapter getDB(){ return m_dbAdapter; }
NetRequest getNet(){ return m_NetRequest;}
SyncEngine(DBAdapter db){
m_dbAdapter = db;
m_dbAdapter.setDbCallback(new DBCallback());
m_NetRequest = null;
m_syncState = esNone;
}
void setFactory(RhoClassFactory factory)throws Exception{
m_NetRequest = factory.createNetRequest();
}
void doSyncAllSources()
{
String status_report = "Sync complete.";
int error = 0;
setState(esSyncAllSources);
try
{
loadAllSources();
m_strSession = loadSession();
if ( isSessionExist() ) {
loadClientID();
} else {
status_report = "Client is not logged in. No sync will be performed.";
error = 1;
}
syncAllSources();
}catch(Exception exc)
{
LOG.ERROR("Sync failed.", exc);
status_report = "Sync failed.";
}
setState(esNone);
reportStatus( status_report, error );
}
void doSyncSource(int nSrcId)
{
String status_report = null;
int error = 0;
LOG.INFO( "Started synchronization of the data source #" + nSrcId );
setState(esSyncSource);
SyncSource src = null;
try
{
loadAllSources();
m_strSession = loadSession();
if ( isSessionExist() ) {
loadClientID();
} else {
status_report = "Client is not logged in. No sync will be performed.";
error = 1;
}
src = findSourceByID(nSrcId);
if ( src != null )
{
if ( isSessionExist() && getState() != esStop )
src.sync(m_statusListener);
fireNotification(src, true);
} else {
throw new RuntimeException("Sync one source : Unknown Source ID: " + nSrcId );
}
} catch(Exception exc) {
LOG.ERROR("Sync source: " + nSrcId + " failed.", exc);
status_report = "Sync failed for " + src.getName() + ".";
}
setState(esNone);
if(status_report != null) {
reportStatus(status_report, error);
}
}
SyncSource findSourceByID(int nSrcId)
{
for( int i = 0; i < m_sources.size(); i++ )
{
SyncSource src = (SyncSource)m_sources.elementAt(i);
if ( src.getID().intValue() == nSrcId )
return src;
}
return null;
}
void loadAllSources()throws DBException
{
m_sources.removeAllElements();
IDBResult res = getDB().executeSQL("SELECT source_id,source_url,token,name from sources order by source_id");
for ( ; !res.isEnd(); res.next() )
{
String strUrl = res.getStringByIdx(1);
String name = res.getStringByIdx(3);
if ( strUrl.length() > 0 )
m_sources.addElement( new SyncSource( res.getIntByIdx(0), strUrl, name, res.getUInt64ByIdx(2), this) );
}
}
void loadClientID()throws Exception
{
m_clientID = "";
boolean bResetClient = false;
{
IDBResult res = getDB().executeSQL("SELECT client_id,reset from client_info");
if ( !res.isEnd() )
{
m_clientID = res.getStringByIdx(0);
bResetClient = res.getIntByIdx(1) > 0;
}
}
if ( m_clientID.length() == 0 )
{
m_clientID = requestClientIDByNet();
getDB().executeSQL("DELETE FROM client_info");
getDB().executeSQL("INSERT INTO client_info (client_id) values (?)", m_clientID);
}else if ( bResetClient )
{
if ( !resetClientIDByNet() )
stopSync();
else
getDB().executeSQL("UPDATE client_info SET reset=? where client_id=?", new Integer(0), m_clientID );
}
}
boolean resetClientIDByNet()throws Exception
{
if ( m_sources.size() == 0 )
return true;
SyncSource src = (SyncSource)m_sources.elementAt(0);
String strUrl = src.getUrl() + "/clientreset";
String strQuery = SYNC_SOURCE_FORMAT();
String strBody = "";
try{
IRhoRubyHelper helper = RhoClassFactory.createRhoRubyHelper();
strBody += "&device_pin=" + helper.getDeviceId() + "&device_type=" + helper.getPlatform();
}catch(Exception e)
{
LOG.ERROR("getDeviceId or getPlatform failed", e);
}
int port = RhoConf.getInstance().getInt("push_port");
strBody += "&device_port=" + (port > 0 ? port : DEFAULT_SYNC_PORT);
String szData = getNet().pullData(strUrl+strQuery, strBody, this).getCharData();
return szData != null;
}
String requestClientIDByNet()throws Exception
{
if ( m_sources.size() == 0 )
return "";
SyncSource src = (SyncSource)m_sources.elementAt(0);
String strUrl = src.getUrl() + "/clientcreate";
String strQuery = SYNC_SOURCE_FORMAT();
String strBody = "";
try{
IRhoRubyHelper helper = RhoClassFactory.createRhoRubyHelper();
strBody += "&device_pin=" + helper.getDeviceId() + "&device_type=" + helper.getPlatform();
}catch(Exception e)
{
LOG.ERROR("getDeviceId or getPlatform failed", e);
}
int port = RhoConf.getInstance().getInt("push_port");
strBody += "&device_port=" + (port > 0 ? port : DEFAULT_SYNC_PORT);
String szData = getNet().pullData(strUrl+strQuery, strBody, this).getCharData();
if ( szData != null )
{
JSONEntry oJsonEntry = new JSONEntry(szData);
JSONEntry oJsonObject = oJsonEntry.getEntry("client");
if ( !oJsonObject.isEmpty() )
return oJsonObject.getString("client_id");
}
return "";
}
int getStartSource()
{
for( int i = 0; i < m_sources.size(); i++ )
{
SyncSource src = (SyncSource)m_sources.elementAt(i);
if ( !src.isEmptyToken() )
return i;
}
return 0;
}
void syncAllSources()throws Exception
{
for( int i = getStartSource(); i < m_sources.size() && getState() != esExit; i++ )
{
SyncSource src = (SyncSource)m_sources.elementAt(i);
if ( isSessionExist() && getState() != esStop )
src.sync(m_statusListener);
fireNotification(src, true);
}
}
boolean login(String name, String password)throws Exception
{
loadAllSources();
return doLogin(name,password);
}
boolean doLogin(String name, String password)throws Exception
{
if ( m_sources.size() == 0 )
return true;
//All sources should be from one domain
SyncSource src0 = (SyncSource)m_sources.elementAt(0);
String srv0 = getServerFromUrl(src0.getUrl());
for( int i = 1; i < m_sources.size(); i++ )
{
SyncSource src = (SyncSource)m_sources.elementAt(i);
String srv = getServerFromUrl(src.getUrl());
if ( srv.equals( srv0 ) != true )
return false;
}
String strBody = "login=" + name + "&password=" + password + "&remember_me=1";
try{
IRhoRubyHelper helper = RhoClassFactory.createRhoRubyHelper();
strBody += "&device_pin=" + helper.getDeviceId() + "&device_type=" + helper.getPlatform();
}catch(Exception e)
{
LOG.ERROR("getDeviceId or getPlatform failed", e);
}
int port = RhoConf.getInstance().getInt("push_port");
strBody += "&device_port=" + (port > 0 ? port : DEFAULT_SYNC_PORT);
String strSession = getNet().pullCookies( src0.getUrl()+"/client_login", strBody, this);
if ( strSession == null || strSession.length() == 0 )
return false;
getDB().executeSQL( "UPDATE sources SET session=?", strSession );
return true;
}
boolean isLoggedIn()throws DBException
{
int nCount = 0;
IDBResult res = getDB().executeSQL("SELECT count(session) FROM sources WHERE session IS NOT NULL");
if ( !res.isEnd() )
nCount = res.getIntByIdx(0);
return nCount > 0;
}
String loadSession()throws DBException
{
String strRes = "";
IDBResult res = getDB().executeSQL("SELECT session FROM sources WHERE session IS NOT NULL");
if ( !res.isEnd() )
strRes = res.getStringByIdx(0);
return strRes;
}
public void logout()throws Exception
{
getDB().executeSQL( "UPDATE sources SET session = NULL");
getNet().deleteCookie("");
loadAllSources();
for( int i = 0; i < m_sources.size(); i++ )
{
SyncSource src = (SyncSource)m_sources.elementAt(i);
getNet().deleteCookie(src.getUrl());
}
}
void resetSyncDB()throws DBException
{
getDB().executeSQL( "DELETE from object_values" );
getDB().executeSQL( "DELETE from client_info" );
getDB().executeSQL( "UPDATE sources SET token=?", "" );
//getDB().executeSQL( "VACUUM" );
m_clientID = "";
}
void setNotification(int source_id, String strUrl, String strParams )throws Exception
{
LOG.INFO( "Set notification. Source ID: " + source_id + "; Url :" + strUrl + "; Params: " + strParams );
String strFullUrl = getNet().resolveUrl(strUrl);
if ( source_id == -1 )
{
synchronized(m_mxNotifications){
m_mapNotifications.clear();
if ( strFullUrl.length() > 0 )
{
loadAllSources();
for( int i = 0; i < m_sources.size(); i++ )
{
SyncSource src = (SyncSource)m_sources.elementAt(i);
m_mapNotifications.put( src.getID(),new SyncNotification( strFullUrl, strParams ) );
}
}
}
LOG.INFO( " Done Set notification for all sources; Url :" + strFullUrl + "; Params: " + strParams );
}else
{
clearNotification(source_id);
if ( strFullUrl.length() > 0 )
{
synchronized(m_mxNotifications){
m_mapNotifications.put(new Integer(source_id),new SyncNotification( strFullUrl, strParams ) );
}
LOG.INFO( " Done Set notification. Source ID: " + source_id + "; Url :" + strFullUrl + "; Params: " + strParams );
}
}
}
void fireNotification( SyncSource src, boolean bFinish)throws Exception
{
String strBody = "", strUrl;
{
synchronized(m_mxNotifications){
SyncNotification sn = (SyncNotification)m_mapNotifications.get(src.getID());
if ( sn == null )
return;
strUrl = sn.m_strUrl;
strBody += "total_count=" + src.getTotalCount();
strBody += "&processed_count=" + src.getCurPageCount();
strBody = "&status=";
if ( bFinish )
strBody += (src.getServerObjectsCount() > 0 ?"ok":"error");
else
strBody += "in_progress";
if ( sn.m_strParams.length() > 0 )
strBody += "&" + sn.m_strParams;
}
}
LOG.INFO( "Fire notification. Source ID: " + src.getID() + "; Url :" + strUrl + "; Body: " + strBody );
getNet().pushData( strUrl, strBody, this );
clearNotification(src.getID().intValue());
}
void clearNotification(int source_id)
{
LOG.INFO( "Clear notification. Source ID: " + source_id );
synchronized(m_mxNotifications){
m_mapNotifications.remove(new Integer(source_id));
}
}
static String getServerFromUrl( String strUrl )
{
URI uri = new URI(strUrl);
return uri.getHost();
}
public static class DBCallback implements IDBCallback{
public void OnDeleteAll() {
OnDeleteAllFromTable("object_values");
}
public void OnDeleteAllFromTable(String tableName) {
if ( !tableName.equals("object_values") )
return;
try{
String fName = DBAdapter.makeBlobFolderName();
RhoClassFactory.createFile().delete(fName);
}catch(Exception exc){
LOG.ERROR("DBCallback.OnDeleteAllFromTable: Error delete files from table: " + tableName, exc);
}
}
public void OnDeleteFromTable(String tableName, IDBResult rows2Delete)
{
if ( !tableName.equalsIgnoreCase("object_values") )
return;
for( ; !rows2Delete.isEnd(); rows2Delete.next() )
{
if ( !rows2Delete.getString("attrib_type").equals("blob.file") )
continue;
String strUpdateType = rows2Delete.getString("update_type");
if ( strUpdateType.equals("create") || strUpdateType.equals("update") )
continue;
String url = rows2Delete.getString("value");
if ( url == null || url.length() == 0 )
continue;
try{
SimpleFile oFile = RhoClassFactory.createFile();
oFile.delete(url);
}catch(Exception exc){
LOG.ERROR("DBCallback.OnDeleteFromTable: Error delete file: " + url, exc);
}
}
}
}
}
|
package com.intellij.openapi.util;
import com.intellij.util.Function;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class Pair<A, B> {
public final A first;
public final B second;
@NotNull
public static <A, B> Pair<A, B> create(A first, B second) {
//noinspection DontUsePairConstructor
return new Pair<A, B>(first, second);
}
@NotNull
public static <A, B> NonNull<A, B> createNonNull(@NotNull A first, @NotNull B second) {
return new NonNull<A, B>(first, second);
}
@NotNull
@SuppressWarnings("MethodNamesDifferingOnlyByCase")
public static <A, B> Pair<A, B> pair(A first, B second) {
//noinspection DontUsePairConstructor
return new Pair<A, B>(first, second);
}
@NotNull
public static <A, B> Function<A, Pair<A, B>> createFunction(final B value) {
return new Function<A, Pair<A, B>>() {
public Pair<A, B> fun(A a) {
return create(a, value);
}
};
}
public static <T> T getFirst(@Nullable Pair<T, ?> pair) {
return pair != null ? pair.first : null;
}
public static <T> T getSecond(@Nullable Pair<?, T> pair) {
return pair != null ? pair.second : null;
}
@SuppressWarnings("unchecked")
private static final Pair EMPTY = create(null, null);
@SuppressWarnings("unchecked")
public static <A, B> Pair<A, B> empty() {
return EMPTY;
}
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public final A getFirst() {
return first;
}
public final B getSecond() {
return second;
}
@Override
public final boolean equals(Object o) {
return o instanceof Pair && Comparing.equal(first, ((Pair)o).first) && Comparing.equal(second, ((Pair)o).second);
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "<" + first + "," + second + ">";
}
public static class NonNull<A, B> extends Pair<A,B> {
public NonNull(@NotNull A first, @NotNull B second) {
super(first, second);
}
}
}
|
package org.neo4j.com;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* The counterpart of {@link BlockLogBuffer}, sits on the receiving end and
* reads chunks of log. It is provided with a {@link ChannelBuffer} which feeds
* a series of chunks formatted as follows: <li>If the first byte is 0, then it
* is 256 bytes in total size (including the first byte) AND there are more
* coming.</li> <li>If the first byte is not 0, then its value cast as an
* integer is the total size of the chunk AND there are no more - the stream is
* complete</li>
*
*/
public class BlockLogReader implements ReadableByteChannel
{
private final ChannelBuffer source;
private final byte[] byteArray = new byte[BlockLogBuffer.MAX_SIZE];
private final ByteBuffer byteBuffer = ByteBuffer.wrap( byteArray );
private boolean moreBlocks;
public BlockLogReader( ChannelBuffer source )
{
this.source = source;
readNextBlock();
}
/**
* Read a block from the channel. Read the first byte, determine size and if
* more are coming, set state accordingly and store content. NOTE: After
* this op the buffer is flipped, ready to read.
*/
private void readNextBlock()
{
int blockSize = source.readUnsignedByte();
byteBuffer.clear();
moreBlocks = blockSize == BlockLogBuffer.FULL_BLOCK_AND_MORE;
int limit = moreBlocks ? BlockLogBuffer.DATA_SIZE : blockSize;
byteBuffer.limit( limit );
source.readBytes( byteBuffer );
byteBuffer.flip();
}
public boolean isOpen()
{
return true;
}
public void close() throws IOException
{
// This is to make sure that reader index in the ChannelBuffer is left
// in the right place even if this reader wasn't completely read through.
readToTheEnd();
}
public int read( ByteBuffer dst ) throws IOException
{
/*
* Fill up dst with what comes from the channel, until dst is full.
* readAsMuchAsPossible() is constantly called reading essentially
* one chunk at a time until either it runs out of stuff coming
* from the channel or the actual target buffer is filled.
*/
int bytesWanted = dst.limit();
int bytesRead = 0;
while ( bytesWanted > 0 )
{
int bytesReadThisTime = readAsMuchAsPossible( dst, bytesWanted );
if ( bytesReadThisTime == 0 )
{
break;
}
bytesRead += bytesReadThisTime;
bytesWanted -= bytesReadThisTime;
}
return bytesRead == 0 && !moreBlocks ? -1 : bytesRead;
}
/**
* Reads in at most {@code maxBytesWanted} in {@code dst} but never more
* than a chunk.
*
* @param dst The buffer to write the reads bytes to
* @param maxBytesWanted The maximum number of bytes to read.
* @return The number of bytes actually read
*/
private int readAsMuchAsPossible( ByteBuffer dst, int maxBytesWanted )
{
/*
assert maxBytesWanted <= BlockLogBuffer.MAX_SIZE : maxBytesWanted
+ " is larger than the chunk size";
*/
if ( byteBuffer.remaining() == 0 && moreBlocks )
{
readNextBlock();
}
int bytesToRead = Math.min( maxBytesWanted, byteBuffer.remaining() );
dst.put( byteArray, byteBuffer.position(), bytesToRead );
byteBuffer.position( byteBuffer.position()+bytesToRead );
return bytesToRead;
}
/**
* Reads everything that can be read from the channel. Stops when a chunk
* starting with a non zero byte is met.
*/
private void readToTheEnd()
{
while ( moreBlocks )
{
readNextBlock();
}
}
}
|
package org.sagebionetworks.bridge.services;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.sagebionetworks.bridge.dao.ParticipantOption.EXTERNAL_IDENTIFIER;
import static org.sagebionetworks.bridge.dao.ParticipantOption.SHARING_SCOPE;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sagebionetworks.bridge.dao.AccountDao;
import org.sagebionetworks.bridge.dao.ParticipantOption.SharingScope;
import org.sagebionetworks.bridge.dao.UserConsentDao;
import org.sagebionetworks.bridge.exceptions.EntityAlreadyExistsException;
import org.sagebionetworks.bridge.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.models.CriteriaContext;
import org.sagebionetworks.bridge.models.accounts.Account;
import org.sagebionetworks.bridge.models.accounts.ConsentStatus;
import org.sagebionetworks.bridge.models.accounts.StudyParticipant;
import org.sagebionetworks.bridge.models.accounts.UserConsent;
import org.sagebionetworks.bridge.models.accounts.UserConsentHistory;
import org.sagebionetworks.bridge.models.accounts.UserSession;
import org.sagebionetworks.bridge.models.accounts.Withdrawal;
import org.sagebionetworks.bridge.models.studies.Study;
import org.sagebionetworks.bridge.models.subpopulations.ConsentSignature;
import org.sagebionetworks.bridge.models.subpopulations.StudyConsentView;
import org.sagebionetworks.bridge.models.subpopulations.Subpopulation;
import org.sagebionetworks.bridge.models.subpopulations.SubpopulationGuid;
import org.sagebionetworks.bridge.services.email.ConsentEmailProvider;
import org.sagebionetworks.bridge.services.email.MimeTypeEmailProvider;
import org.sagebionetworks.bridge.services.email.WithdrawConsentEmailProvider;
import org.sagebionetworks.bridge.util.BridgeCollectors;
import org.sagebionetworks.bridge.validators.ConsentAgeValidator;
import org.sagebionetworks.bridge.validators.Validate;
import com.google.common.collect.ImmutableMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConsentService {
private final Logger LOGGER = LoggerFactory.getLogger(ConsentService.class);
private AccountDao accountDao;
private ParticipantOptionsService optionsService;
private SendMailService sendMailService;
private StudyConsentService studyConsentService;
private UserConsentDao userConsentDao;
private ActivityEventService activityEventService;
private SubpopulationService subpopService;
private String consentTemplate;
@Value("classpath:study-defaults/consent-page.xhtml")
final void setConsentTemplate(org.springframework.core.io.Resource resource) throws IOException {
this.consentTemplate = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
}
@Resource(name="stormpathAccountDao")
final void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Autowired
final void setOptionsService(ParticipantOptionsService optionsService) {
this.optionsService = optionsService;
}
@Autowired
final void setSendMailService(SendMailService sendMailService) {
this.sendMailService = sendMailService;
}
@Autowired
final void setStudyConsentService(StudyConsentService studyConsentService) {
this.studyConsentService = studyConsentService;
}
@Autowired
final void setUserConsentDao(UserConsentDao userConsentDao) {
this.userConsentDao = userConsentDao;
}
@Autowired
final void setActivityEventService(ActivityEventService activityEventService) {
this.activityEventService = activityEventService;
}
@Autowired
final void setSubpopulationService(SubpopulationService subpopService) {
this.subpopService = subpopService;
};
/**
* Get the user's active consent signature (a signature that has not been withdrawn).
* @param study
* @param subpopGuid
* @param userId
* @return
* @throws EntityNotFoundException if no consent exists
*/
public ConsentSignature getConsentSignature(Study study, SubpopulationGuid subpopGuid, String userId) {
checkNotNull(study);
checkNotNull(subpopGuid);
checkNotNull(userId);
// This will throw an EntityNotFoundException if the subpopulation is not in the user's study
subpopService.getSubpopulation(study, subpopGuid);
Account account = accountDao.getAccount(study, userId);
ConsentSignature signature = account.getActiveConsentSignature(subpopGuid);
if (signature == null) {
throw new EntityNotFoundException(ConsentSignature.class);
}
return signature;
}
/**
* Consent this user to research. User will be updated to reflect consent.
* @param study
* @param subpopGuid
* @param session
* @param consentSignature
* @param sharingScope
* @param sendEmail
* @return
* @throws EntityAlreadyExistsException
* if the user already has an active consent to participate in research
* @throws StudyLimitExceededException
* if enrolling the user would exceed the study enrollment limit
*/
public void consentToResearch(Study study, SubpopulationGuid subpopGuid, UserSession session, ConsentSignature consentSignature,
SharingScope sharingScope, boolean sendEmail) {
checkNotNull(study, Validate.CANNOT_BE_NULL, "study");
checkNotNull(subpopGuid, Validate.CANNOT_BE_NULL, "subpopulationGuid");
checkNotNull(session, Validate.CANNOT_BE_NULL, "session");
checkNotNull(consentSignature, Validate.CANNOT_BE_NULL, "consentSignature");
checkNotNull(sharingScope, Validate.CANNOT_BE_NULL, "sharingScope");
ConsentStatus status = session.getConsentStatuses().get(subpopGuid);
// There will be a status object for each subpopulation the user is mapped to. If
// there's no status object, then in effect the subpopulation does not exist for
// this user and they should get back a 404.
if (status == null) {
throw new EntityNotFoundException(Subpopulation.class);
}
if (status != null && status.isConsented()) {
throw new EntityAlreadyExistsException(consentSignature);
}
ConsentAgeValidator validator = new ConsentAgeValidator(study);
Validate.entityThrowingException(validator, consentSignature);
StudyConsentView studyConsent = studyConsentService.getActiveConsent(subpopGuid);
Account account = accountDao.getAccount(study, session.getParticipant().getId());
account.getConsentSignatureHistory(subpopGuid).add(consentSignature);
accountDao.updateAccount(account);
UserConsent userConsent = null;
try {
userConsent = userConsentDao.giveConsent(session.getHealthCode(), subpopGuid,
studyConsent.getCreatedOn(), consentSignature.getSignedOn());
} catch (Throwable e) {
int len = account.getConsentSignatureHistory(subpopGuid).size();
account.getConsentSignatureHistory(subpopGuid).remove(len-1);
accountDao.updateAccount(account);
throw e;
}
// Save supplemental records, fire events, etc.
if (userConsent != null){
activityEventService.publishEnrollmentEvent(session.getParticipant().getHealthCode(), userConsent);
}
optionsService.setEnum(study, session.getParticipant().getHealthCode(), SHARING_SCOPE, sharingScope);
updateSessionConsentStatuses(session, subpopGuid, true);
if (sendEmail) {
MimeTypeEmailProvider consentEmail = new ConsentEmailProvider(study, subpopGuid,
session.getParticipant().getEmail(), consentSignature, sharingScope, studyConsentService,
consentTemplate);
sendMailService.sendEmail(consentEmail);
}
}
/**
* Get all the consent status objects for this user. From these, we determine if the user
* has consented to the right consents to have access to the study, whether or not those
* consents are up-to-date, etc.
* @param context
* @return
*/
public Map<SubpopulationGuid,ConsentStatus> getConsentStatuses(CriteriaContext context) {
checkNotNull(context);
checkNotNull(context.getHealthCode());
ImmutableMap.Builder<SubpopulationGuid, ConsentStatus> builder = new ImmutableMap.Builder<>();
for (Subpopulation subpop : subpopService.getSubpopulationForUser(context)) {
boolean consented = userConsentDao.hasConsented(context.getHealthCode(), subpop.getGuid());
boolean mostRecent = hasUserSignedActiveConsent(context.getHealthCode(), subpop.getGuid());
ConsentStatus status = new ConsentStatus.Builder().withName(subpop.getName())
.withGuid(subpop.getGuid()).withRequired(subpop.isRequired())
.withConsented(consented).withSignedMostRecentConsent(mostRecent)
.build();
builder.put(subpop.getGuid(), status);
}
return builder.build();
}
/**
* Withdraw consent in this study. The withdrawal date is recorded and the user can no longer
* access any APIs that require consent, although the user's account (along with the history of
* the user's participation) will not be delted.
* @param study
* @param subpopGuid
* @param user
* @param withdrawal
* @param withdrewOn
*/
public void withdrawConsent(Study study, SubpopulationGuid subpopGuid, UserSession session, Withdrawal withdrawal, long withdrewOn) {
checkNotNull(study);
checkNotNull(subpopGuid);
checkNotNull(session);
checkNotNull(withdrawal);
checkArgument(withdrewOn > 0);
Account account = accountDao.getAccount(study, session.getParticipant().getId());
ConsentSignature active = account.getActiveConsentSignature(subpopGuid);
if (active == null) {
throw new EntityNotFoundException(ConsentSignature.class);
}
ConsentSignature withdrawn = new ConsentSignature.Builder()
.withConsentSignature(active)
.withWithdrewOn(withdrewOn).build();
int index = account.getConsentSignatureHistory(subpopGuid).indexOf(active); // should be length-1
account.getConsentSignatureHistory(subpopGuid).set(index, withdrawn);
accountDao.updateAccount(account);
try {
userConsentDao.withdrawConsent(session.getParticipant().getHealthCode(), subpopGuid, withdrewOn);
} catch(Exception e) {
// Could not record the consent, compensate and rethrow the exception
account.getConsentSignatureHistory(subpopGuid).set(index, active);
accountDao.updateAccount(account);
throw e;
}
// Update the user's consent status
updateSessionConsentStatuses(session, subpopGuid, false);
// Only turn of sharing if the upshot of your change in consents is that you are not consented.
if (!session.doesConsent()) {
optionsService.setEnum(study, session.getParticipant().getHealthCode(), SHARING_SCOPE, SharingScope.NO_SHARING);
StudyParticipant participant = new StudyParticipant.Builder().copyOf(session.getParticipant())
.withSharingScope(SharingScope.NO_SHARING).build();
session.setParticipant(participant);
}
String externalId = optionsService.getOptions(session.getParticipant().getHealthCode())
.getString(EXTERNAL_IDENTIFIER);
MimeTypeEmailProvider consentEmail = new WithdrawConsentEmailProvider(study, externalId, account, withdrawal,
withdrewOn);
sendMailService.sendEmail(consentEmail);
}
/**
* Withdraw user from any and all consents, and turn off sharing. Because a user's criteria for being included in a
* consent can change over time, this is really the best method for ensuring a user is withdrawn from everything.
* But in cases where there are studies with distinct and separate consents, you must selectively withdraw from
* the consent for a specific subpopulation.
*
* @param study
* @param userId
* @param withdrawal
* @param withdrewOn
*/
public void withdrawAllConsents(Study study, String userId, Withdrawal withdrawal, long withdrewOn) {
checkNotNull(study);
checkNotNull(userId);
checkNotNull(withdrawal);
checkArgument(withdrewOn > 0);
Account account = accountDao.getAccount(study, userId);
// Do this first, as it directly impacts the export of data, and if nothing else, we'd like this to succeed.
optionsService.setEnum(study.getStudyIdentifier(), account.getHealthCode(), SHARING_SCOPE, SharingScope.NO_SHARING);
boolean accountUpdated = false;
for (Subpopulation subpop : subpopService.getSubpopulations(study.getStudyIdentifier())) {
ConsentSignature active = account.getActiveConsentSignature(subpop.getGuid());
if (active != null) {
ConsentSignature withdrawn = new ConsentSignature.Builder()
.withConsentSignature(active)
.withWithdrewOn(withdrewOn).build();
int index = account.getConsentSignatureHistory(subpop.getGuid()).indexOf(active); // should be length-1
account.getConsentSignatureHistory(subpop.getGuid()).set(index, withdrawn);
try {
userConsentDao.withdrawConsent(account.getHealthCode(), subpop.getGuid(), withdrewOn);
} catch(Exception e) {
// This shouldn't happen, but no matter what, keep withdrawing the user
LOGGER.warn("Error updating DDB consent record for consent withdrawal", e);
}
accountUpdated = true;
}
}
if (accountUpdated) {
try {
accountDao.updateAccount(account);
} catch(Exception e) {
// Keep withdrawing the user, whether this succeeds or fails
LOGGER.warn("Error updating user account for consent withdrawal", e);
}
}
String externalId = optionsService.getOptions(account.getHealthCode()).getString(EXTERNAL_IDENTIFIER);
MimeTypeEmailProvider consentEmail = new WithdrawConsentEmailProvider(
study, externalId, account, withdrawal, withdrewOn);
sendMailService.sendEmail(consentEmail);
}
/**
* Get a history of all consent records, whether withdrawn or not, including information from the
* consent signature and user consent records. The information is sufficient to identify the
* consent that exists for a healthCode, and to retrieve the version of the consent the participant
* signed to join the study.
* @param study
* @param subpopGuid
* @param healthCode
* @param email
*/
public List<UserConsentHistory> getUserConsentHistory(Study study, SubpopulationGuid subpopGuid, String healthCode, String id) {
Account account = accountDao.getAccount(study, id);
return account.getConsentSignatureHistory(subpopGuid).stream().map(signature -> {
UserConsent consent = userConsentDao.getUserConsent(
healthCode, subpopGuid, signature.getSignedOn());
boolean hasSignedActiveConsent = hasUserSignedActiveConsent(healthCode, subpopGuid);
UserConsentHistory.Builder builder = new UserConsentHistory.Builder();
builder.withName(signature.getName())
.withSubpopulationGuid(SubpopulationGuid.create(consent.getSubpopulationGuid()))
.withBirthdate(signature.getBirthdate())
.withImageData(signature.getImageData())
.withImageMimeType(signature.getImageMimeType())
.withSignedOn(signature.getSignedOn())
.withHealthCode(healthCode)
.withWithdrewOn(consent.getWithdrewOn())
.withConsentCreatedOn(consent.getConsentCreatedOn())
.withHasSignedActiveConsent(hasSignedActiveConsent);
return builder.build();
}).collect(BridgeCollectors.toImmutableList());
}
/**
* Delete all consent records, withdrawn or active, in the process of deleting a user account. This is
* used for tests, do not call this method to withdraw a user from a study, or we will not have auditable
* records about their participation.
* @param study
* @param healthCode
*/
public void deleteAllConsentsForUser(Study study, String healthCode) {
checkNotNull(study);
checkNotNull(healthCode);
// May exceed the subpopulations the user matches, but that's okay
List<Subpopulation> subpopGuids = subpopService.getSubpopulations(study);
for (Subpopulation subpop : subpopGuids) {
userConsentDao.deleteAllConsents(healthCode, subpop.getGuid());
}
}
/**
* Email the participant's signed consent agreement to the user's email address.
* @param study
* @param subpopGuid
* @param participant
*/
public void emailConsentAgreement(Study study, SubpopulationGuid subpopGuid, StudyParticipant participant) {
checkNotNull(study);
checkNotNull(subpopGuid);
checkNotNull(participant);
final ConsentSignature consentSignature = getConsentSignature(study, subpopGuid, participant.getId());
if (consentSignature == null) {
throw new EntityNotFoundException(ConsentSignature.class);
}
final SharingScope sharingScope = optionsService.getOptions(participant.getHealthCode())
.getEnum(SHARING_SCOPE, SharingScope.class);
MimeTypeEmailProvider consentEmail = new ConsentEmailProvider(study, subpopGuid,
participant.getEmail(), consentSignature, sharingScope, studyConsentService,
consentTemplate);
sendMailService.sendEmail(consentEmail);
}
private boolean hasUserSignedActiveConsent(String healthCode, SubpopulationGuid subpopGuid) {
checkNotNull(healthCode);
checkNotNull(subpopGuid);
UserConsent userConsent = userConsentDao.getActiveUserConsent(healthCode, subpopGuid);
StudyConsentView mostRecentConsent = studyConsentService.getActiveConsent(subpopGuid);
if (mostRecentConsent != null && userConsent != null) {
return userConsent.getConsentCreatedOn() == mostRecentConsent.getCreatedOn();
} else {
return false;
}
}
private void updateSessionConsentStatuses(UserSession session, SubpopulationGuid subpopGuid, boolean consented) {
if (session.getConsentStatuses() != null) {
ImmutableMap.Builder<SubpopulationGuid, ConsentStatus> builder = new ImmutableMap.Builder<>();
for (Map.Entry<SubpopulationGuid,ConsentStatus> entry : session.getConsentStatuses().entrySet()) {
if (entry.getKey().equals(subpopGuid)) {
ConsentStatus updatedStatus = new ConsentStatus.Builder().withConsentStatus(entry.getValue())
.withConsented(consented).withSignedMostRecentConsent(consented).build();
builder.put(subpopGuid, updatedStatus);
} else {
builder.put(entry.getKey(), entry.getValue());
}
}
session.setConsentStatuses(builder.build());
}
}
}
|
package com.ayros.historycleaner.cleaning;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.Build;
import android.provider.CallLog;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ayros.historycleaner.R;
import com.ayros.historycleaner.cleaning.SimpleDatabaseItem.DBQuery;
import com.ayros.historycleaner.cleaning.items._System_BrowserHistory;
import com.ayros.historycleaner.cleaning.items._System_Cache;
import com.ayros.historycleaner.cleaning.items._System_Calls;
import com.ayros.historycleaner.cleaning.items._System_Clipboard;
import com.ayros.historycleaner.cleaning.items._System_FrequentContacts;
import com.ayros.historycleaner.cleaning.items._System_SMS;
public class CategoryList
{
private List<Category> cats;
public CategoryList()
{
cats = new ArrayList<Category>();
Category cat;
cat = new Category("System");
cat.addItem(new _System_Cache(cat));
cat.addItem(new _System_BrowserHistory(cat));
cat.addItem(new _System_Clipboard(cat));
cat.addItem(new _System_FrequentContacts(cat));
cat.addItem(new SimpleDatabaseItem
(
cat, "Google Play History", "com.android.vending", "/databases/suggestions.db",
new DBQuery
(
new String[] { "Search Term" },
"suggestions",
new String[] { "query" }
),
new String[] { "DELETE FROM suggestions;" }
));
cat.addItem(new _System_Calls(cat, "Outgoing Calls", CallLog.Calls.OUTGOING_TYPE));
cat.addItem(new _System_Calls(cat, "Incoming Calls", CallLog.Calls.INCOMING_TYPE));
cat.addItem(new _System_Calls(cat, "Missed Calls", CallLog.Calls.MISSED_TYPE));
cat.addItem(new SimpleDatabaseItem
(
cat, "Settings Searches", "com.android.settings", "/databases/search_index.db",
new DBQuery
(
new String[] { "Search Term", "Timestamp" },
"saved_queries",
new String[] { "query", "timestamp" }
),
new String[] { "DELETE FROM saved_queries;" }
)
{
@Override
public boolean isApplicable()
{
return Build.VERSION.SDK_INT >= 21; // Lollipop
}
});
cat.addItem(new _System_SMS(cat));
cats.add(cat);
cat = new Category("Adobe Reader");
cat.addItem(new com.ayros.historycleaner.cleaning.items._AdobeReader_Recent(cat));
cats.add(cat);
cat = new Category("Amazon");
cat.addItem(new SimpleDatabaseItem
(
cat, "Recently Viewed", "com.amazon.mShop.android", "/databases/history.db",
new DBQuery
(
new String[] { "Type", "Amazon Product ID" },
"history",
new String[] { "type", "asin" }
),
new String[] { "DELETE FROM history;" }
));
cats.add(cat);
cat = new Category("Chrome");
/**
* Returns a list of all items contained within profile.
*
* @param p
* @return
*/
public List<CleanItem> getProfileItems(Profile profile)
{
List<CleanItem> items = new ArrayList<CleanItem>();
for (String itemName : profile.getItemNames())
{
CleanItem item = getItemByUniqueName(itemName);
if (item != null)
{
items.add(item);
}
}
return items;
}
public CleanItem getItemByView(View v)
{
for (CleanItem item : getAllItems(false))
{
ViewGroup itemView = item.getView();
View nameView = itemView.findViewById(R.id.item_name);
if (v.equals(nameView))
{
return item;
}
}
return null;
}
public CleanItem getItemByUniqueId(int uniqueId)
{
for (CleanItem ci : getAllItems(false))
{
if (ci.getUniqueId() == uniqueId)
{
return ci;
}
}
return null;
}
public CleanItem getItemByUniqueName(String uniqueName)
{
for (CleanItem ci : getAllItems(false))
{
if (ci.getUniqueName().equals(uniqueName))
{
return ci;
}
}
return null;
}
public List<CleanItem> getAllItems(boolean enabledOnly)
{
List<CleanItem> items = new ArrayList<CleanItem>();
for (Category cat : cats)
{
for (CleanItem item : cat.getItems())
{
if (!enabledOnly || item.isChecked())
{
items.add(item);
}
}
}
return items;
}
public void loadProfile(Profile p)
{
if (p != null)
{
List<CleanItem> items = getAllItems(false);
for (CleanItem item : items)
{
item.setChecked(p.isSelected(item) && item.isApplicable());
}
}
}
public View makeCategoriesView(Context c)
{
ViewGroup catLayout = (ViewGroup)View.inflate(c, R.layout.category_list, null);
for (int i = 0; i < cats.size(); i++)
{
Category cat = cats.get(i);
catLayout.addView(cat.getCategoryView(c));
}
return catLayout;
}
public void registerContextMenu(Fragment f)
{
for (CleanItem item : getAllItems(false))
{
ViewGroup itemView = item.getView();
if (itemView != null)
{
TextView itemName = (TextView)itemView.findViewById(R.id.item_name);
f.registerForContextMenu(itemName);
}
}
}
public boolean saveProfile(Profile p)
{
if (p != null)
{
p.selectedItems.clear();
for (CleanItem ci : getAllItems(true))
{
p.selectedItems.add(ci.getUniqueName());
}
return p.saveChanges();
}
return false;
}
}
|
package com.quchen.flappycow;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.gms.games.Games;
public class StartscreenView extends View{
private static Bitmap splash = null;
private static Bitmap logInOut = null;
private static Bitmap play = null;
private static Bitmap achievements = null;
private static Bitmap leaderboard = null;
private static Bitmap speaker = null;
private static Bitmap info = null;
private static Bitmap socket = null;
// Button regions: left, top, right, bottom
private final static float[] REGION_LOG_IN_OUT = {175/720.0f, 397/1280f, 547/720.0f, 506/1280.0f};
private final static float[] REGION_PLAY = {169/720.0f, 515/1280f, 553/720.0f, 699/1280.0f};
private final static float[] REGION_INFO = {585/720.0f, 1141/1280f, 700/720.0f, 1256/1280.0f};
private final static float[] REGION_SPEAKER = {25/720.0f, 1140/1280f, 140/720.0f, 1255/1280.0f};
private final static float[] REGION_SOCKET = {233/720.0f, 1149/1280f, 487/720.0f, 1248/1280.0f};
private final static float[] REGION_ACHIEVEMENT = {176/720.0f, 709/1280f, 316/720.0f, 849/1280.0f};
private final static float[] REGION_LEADERBOARD = {413/720.0f, 708/1280f, 553/720.0f, 849/1280.0f};
private Rect dstSplash;
private Rect srcSplash;
private Rect dstLogInOut;
private Rect srcLogInOut;
private Rect dstPlay;
private Rect srcPlay;
private Rect dstAchievements;
private Rect srcAchievements;
private Rect dstLeaderboard;
private Rect srcLeaderboard;
private Rect dstSpeaker;
private Rect srcSpeaker;
private Rect dstInfo;
private Rect srcInfo;
private Rect dstSocket;
private Rect srcSocket;
private boolean online;
private MainActivity mainActivity;
public StartscreenView(MainActivity context) {
super(context);
this.mainActivity = context;
if(splash == null) {
splash = Util.getBitmapAlpha8(mainActivity, R.drawable.splash);
}
srcSplash = new Rect(0, 0, splash.getWidth(), splash.getHeight());
if(logInOut == null) {
logInOut = Util.getBitmapAlpha8(mainActivity, R.drawable.signinout);
}
if(play == null) {
play = Util.getBitmapAlpha8(mainActivity, R.drawable.play_button);
}
srcPlay = new Rect(0, 0, play.getWidth(), play.getHeight());
if(achievements == null) {
achievements = Util.getBitmapAlpha8(mainActivity, R.drawable.achievement_button);
}
srcAchievements = new Rect(0, 0, achievements.getWidth(), achievements.getHeight());
if(leaderboard == null) {
leaderboard = Util.getBitmapAlpha8(mainActivity, R.drawable.highscore_button);
}
srcLeaderboard = new Rect(0, 0, leaderboard.getWidth(), leaderboard.getHeight());
if(speaker == null) {
speaker = Util.getBitmapAlpha8(mainActivity, R.drawable.speaker);
}
if(info == null) {
info = Util.getBitmapAlpha8(mainActivity, R.drawable.about);
}
srcInfo = new Rect(0, 0, info.getWidth(), info.getHeight());
if(socket == null) {
socket = Util.getBitmapAlpha8(mainActivity, R.drawable.socket);
}
setWillNotDraw(false);
setOnline(false);
setSpeaker(true);
setSocket(0);
}
public void setSpeaker(boolean on) {
if(on) {
srcSpeaker = new Rect(0, 0, speaker.getWidth(), speaker.getHeight()/2);
} else {
srcSpeaker = new Rect(0, speaker.getHeight()/2, speaker.getWidth(), speaker.getHeight());
}
}
public void setOnline(boolean online) {
this.online = online;
if(online) {
srcLogInOut = new Rect(0, logInOut.getHeight()/2, logInOut.getWidth(), logInOut.getHeight());
} else {
srcLogInOut = new Rect(0, 0, logInOut.getWidth(), logInOut.getHeight()/2);
}
}
public void setSocket(int level) {
srcSocket = new Rect(0, level*socket.getHeight()/4, socket.getWidth(), (level+1)*socket.getHeight()/4);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(splash, srcSplash, dstSplash, null);
canvas.drawBitmap(logInOut, srcLogInOut, dstLogInOut, null);
canvas.drawBitmap(play, srcPlay, dstPlay, null);
canvas.drawBitmap(speaker, srcSpeaker, dstSpeaker, null);
canvas.drawBitmap(info, srcInfo, dstInfo, null);
canvas.drawBitmap(socket, srcSocket, dstSocket, null);
if(online) {
canvas.drawBitmap(achievements, srcAchievements, dstAchievements, null);
canvas.drawBitmap(leaderboard, srcLeaderboard, dstLeaderboard, null);
}
}
@Override
public boolean performClick() {
return super.performClick();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
dstSplash = new Rect(0, 0, getWidth(), getHeight());
dstLogInOut = new Rect( (int)(getWidth()*REGION_LOG_IN_OUT[0]),
(int)(getHeight()*REGION_LOG_IN_OUT[1]),
(int)(getWidth()*REGION_LOG_IN_OUT[2]),
(int)(getHeight()*REGION_LOG_IN_OUT[3]));
dstPlay = new Rect( (int)(getWidth()*REGION_PLAY[0]),
(int)(getHeight()*REGION_PLAY[1]),
(int)(getWidth()*REGION_PLAY[2]),
(int)(getHeight()*REGION_PLAY[3]));
dstAchievements = new Rect( (int)(getWidth()*REGION_ACHIEVEMENT[0]),
(int)(getHeight()*REGION_ACHIEVEMENT[1]),
(int)(getWidth()*REGION_ACHIEVEMENT[2]),
(int)(getHeight()*REGION_ACHIEVEMENT[3]));
dstLeaderboard = new Rect( (int)(getWidth()*REGION_LEADERBOARD[0]),
(int)(getHeight()*REGION_LEADERBOARD[1]),
(int)(getWidth()*REGION_LEADERBOARD[2]),
(int)(getHeight()*REGION_LEADERBOARD[3]));
dstSpeaker = new Rect( (int)(getWidth()*REGION_SPEAKER[0]),
(int)(getHeight()*REGION_SPEAKER[1]),
(int)(getWidth()*REGION_SPEAKER[2]),
(int)(getHeight()*REGION_SPEAKER[3]));
dstInfo = new Rect( (int)(getWidth()*REGION_INFO[0]),
(int)(getHeight()*REGION_INFO[1]),
(int)(getWidth()*REGION_INFO[2]),
(int)(getHeight()*REGION_INFO[3]));
dstSocket = new Rect( (int)(getWidth()*REGION_SOCKET[0]),
(int)(getHeight()*REGION_SOCKET[1]),
(int)(getWidth()*REGION_SOCKET[2]),
(int)(getHeight()*REGION_SOCKET[3]));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
performClick();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
if( (event.getX() > REGION_LOG_IN_OUT[0] * getWidth())
&& (event.getX() < REGION_LOG_IN_OUT[2] * getWidth())
&& (event.getY() > REGION_LOG_IN_OUT[1] * getHeight())
&& (event.getY() < REGION_LOG_IN_OUT[3] * getHeight()) ) {
if(online) {
mainActivity.logout();
} else {
mainActivity.login();
}
} else if( (event.getX() > REGION_PLAY[0] * getWidth())
&& (event.getX() < REGION_PLAY[2] * getWidth())
&& (event.getY() > REGION_PLAY[1] * getHeight())
&& (event.getY() < REGION_PLAY[3] * getHeight()) ) {
mainActivity.startActivity(new Intent("com.quchen.flappycow.Game"));
} else if( (event.getX() > REGION_SPEAKER[0] * getWidth())
&& (event.getX() < REGION_SPEAKER[2] * getWidth())
&& (event.getY() > REGION_SPEAKER[1] * getHeight())
&& (event.getY() < REGION_SPEAKER[3] * getHeight()) ) {
mainActivity.muteToggle();
} else if( (event.getX() > REGION_INFO[0] * getWidth())
&& (event.getX() < REGION_INFO[2] * getWidth())
&& (event.getY() > REGION_INFO[1] * getHeight())
&& (event.getY() < REGION_INFO[3] * getHeight()) ) {
mainActivity.startActivity(new Intent("com.quchen.flappycow.About"));
} else if(online) {
if( (event.getX() > REGION_ACHIEVEMENT[0] * getWidth())
&& (event.getX() < REGION_ACHIEVEMENT[2] * getWidth())
&& (event.getY() > REGION_ACHIEVEMENT[1] * getHeight())
&& (event.getY() < REGION_ACHIEVEMENT[3] * getHeight()) ) {
mainActivity.startActivityForResult(Games.Achievements.getAchievementsIntent(mainActivity.getApiClient()), 0);;
} else if( (event.getX() > REGION_LEADERBOARD[0] * getWidth())
&& (event.getX() < REGION_LEADERBOARD[2] * getWidth())
&& (event.getY() > REGION_LEADERBOARD[1] * getHeight())
&& (event.getY() < REGION_LEADERBOARD[3] * getHeight()) ) {
mainActivity.startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mainActivity.getApiClient(),
getResources().getString(R.string.leaderboard_highscore)), 0);
}
}
}
return true;
}
}
|
package com.samourai.sentinel;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
//import android.widget.Toast;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import com.samourai.sentinel.access.AccessFactory;
import com.samourai.sentinel.util.AppUtil;
import com.samourai.sentinel.util.FormatsUtil;
import net.sourceforge.zbar.Symbol;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.Base58;
import org.json.JSONException;
import java.io.IOException;
import java.nio.ByteBuffer;
public class InsertActivity extends Activity {
private final static int SCAN_XPUB = 2011;
private final static int INSERT_BIP49 = 2012;
public final static int TYPE_BITCOIN_ADDRESS = 0;
public final static int TYPE_LEGACY_XPUB = 1;
public final static int TYPE_SEGWIT_XPUB = 2;
private int storedType = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
setTitle(R.string.track_new);
InsertActivity.this.setFinishOnTouchOutside(false);
LinearLayout addressLayout = (LinearLayout)findViewById(R.id.address);
addressLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
storedType = TYPE_BITCOIN_ADDRESS;
initDialog(TYPE_BITCOIN_ADDRESS);
return false;
}
});
LinearLayout bip44Layout = (LinearLayout)findViewById(R.id.bip44);
bip44Layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
storedType = TYPE_LEGACY_XPUB;
initDialog(TYPE_LEGACY_XPUB);
return false;
}
});
LinearLayout bip49Layout = (LinearLayout)findViewById(R.id.bip49);
bip49Layout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
storedType = TYPE_SEGWIT_XPUB;
initDialog(TYPE_SEGWIT_XPUB);
return false;
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK && requestCode == SCAN_XPUB) {
if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
if(strResult.startsWith("bitcoin:")) {
strResult = strResult.substring(8);
}
if(strResult.indexOf("?") != -1) {
strResult = strResult.substring(0, strResult.indexOf("?"));
}
addXPUB(strResult, storedType);
}
}
else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_XPUB) {
;
}
else if(resultCode == Activity.RESULT_OK && requestCode == INSERT_BIP49) {
String xpub = data.getStringExtra("xpub");
String label = data.getStringExtra("label");
updateXPUBs(xpub, label, true);
Log.d("InitActivity", "xpub inserted:" + xpub);
Log.d("InitActivity", "label inserted:" + label);
Toast.makeText(InsertActivity.this, R.string.xpub_add_ok, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(InsertActivity.this, BalanceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else if(resultCode == Activity.RESULT_CANCELED && requestCode == INSERT_BIP49) {
Toast.makeText(InsertActivity.this, R.string.xpub_add_ko, Toast.LENGTH_SHORT).show();
}
else {
;
}
}
private void initDialog(final int type) {
AccessFactory.getInstance(InsertActivity.this).setIsLoggedIn(false);
new AlertDialog.Builder(this)
.setTitle(R.string.app_name)
.setMessage(R.string.please_select)
.setPositiveButton(R.string.manual, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
final EditText xpub = new EditText(InsertActivity.this);
xpub.setSingleLine(true);
new AlertDialog.Builder(InsertActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.enter_xpub)
.setView(xpub)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
String xpubStr = xpub.getText().toString().trim();
if (xpubStr != null && xpubStr.length() > 0) {
addXPUB(xpubStr, type);
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}).show();
}
})
.setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
doScan();
}
}).show();
}
private void doScan() {
Intent intent = new Intent(InsertActivity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, SCAN_XPUB);
}
private void addXPUB(final String xpubStr, final int type) {
final EditText etLabel = new EditText(InsertActivity.this);
etLabel.setSingleLine(true);
etLabel.setHint(getText(R.string.xpub_label));
new AlertDialog.Builder(InsertActivity.this)
.setTitle(R.string.app_name)
.setView(etLabel)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
final String label = etLabel.getText().toString().trim();
if(FormatsUtil.getInstance().isValidBitcoinAddress(xpubStr)) {
updateXPUBs(xpubStr, label, false);
Intent intent = new Intent(InsertActivity.this, BalanceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
if(type == TYPE_SEGWIT_XPUB) {
Intent intent = new Intent(InsertActivity.this, InsertBIP49Activity.class);
intent.putExtra("xpub", xpubStr);
intent.putExtra("label", label);
startActivityForResult(intent, INSERT_BIP49);
}
else {
updateXPUBs(xpubStr, label, false);
Intent intent = new Intent(InsertActivity.this, BalanceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}).show();
}
private void updateXPUBs(String xpub, String label, boolean isBIP49) {
if (label == null || label.length() < 1) {
label = getString(R.string.new_account);
}
if(FormatsUtil.getInstance().isValidXpub(xpub)) {
try {
// get depth
byte[] xpubBytes = Base58.decodeChecked(xpub);
ByteBuffer bb = ByteBuffer.wrap(xpubBytes);
bb.getInt();
// depth:
byte depth = bb.get();
switch(depth) {
// BIP32 account
case 1:
Toast.makeText(InsertActivity.this, R.string.bip32_account, Toast.LENGTH_SHORT).show();
break;
// BIP44 account
case 3:
if(isBIP49) {
Toast.makeText(InsertActivity.this, R.string.bip49_account, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(InsertActivity.this, R.string.bip44_account, Toast.LENGTH_SHORT).show();
}
break;
default:
// unknown
Toast.makeText(InsertActivity.this, InsertActivity.this.getText(R.string.unknown_xpub) + ":" + depth, Toast.LENGTH_SHORT).show();
}
}
catch(AddressFormatException afe) {
Toast.makeText(InsertActivity.this, R.string.base58_error, Toast.LENGTH_SHORT).show();
return;
}
if(isBIP49) {
SamouraiSentinel.getInstance(InsertActivity.this).getBIP49().put(xpub, label);
}
else {
SamouraiSentinel.getInstance(InsertActivity.this).getXPUBs().put(xpub, label);
}
}
else if(FormatsUtil.getInstance().isValidBitcoinAddress(xpub)) {
SamouraiSentinel.getInstance(InsertActivity.this).getLegacy().put(xpub, label);
}
else {
Toast.makeText(InsertActivity.this, R.string.invalid_entry, Toast.LENGTH_SHORT).show();
}
try {
SamouraiSentinel.getInstance(InsertActivity.this).serialize(SamouraiSentinel.getInstance(InsertActivity.this).toJSON(), null);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (JSONException je) {
je.printStackTrace();
}
}
}
|
package com.samourai.wallet;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
//import android.util.Log;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.bip47.rpc.NotSecp256k1Exception;
import com.samourai.wallet.bip47.rpc.PaymentAddress;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.ricochet.RicochetMeta;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.PushTx;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.params.MainNetParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Iterator;
public class RicochetActivity extends Activity {
private String strPCode = null;
private boolean samouraiFeeViaBIP47 = false;
private ProgressDialog progress = null;
private String strProgressTitle = null;
private String strProgressMessage = null;
private final static long SLEEP_DELAY = 10L * 1000L;
private boolean broadcastOK = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ricochet);
if(RicochetMeta.getInstance(RicochetActivity.this).size() > 0) {
new QueueTask().execute(new String[]{ null });
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.ricochet, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.action_show_script) {
doShowScript();
}
else if (id == R.id.action_replay_script) {
doReplayScript();
}
else {
;
}
return super.onOptionsItemSelected(item);
}
private class QueueTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
PayloadUtil.getInstance(RicochetActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(RicochetActivity.this).getGUID() + AccessFactory.getInstance(RicochetActivity.this).getPIN()));
final Iterator<JSONObject> itr = RicochetMeta.getInstance(RicochetActivity.this).getIterator();
while(itr.hasNext()){
boolean hasConfirmation = false;
boolean txSeen = false;
JSONObject jObj = itr.next();
JSONArray jHops = jObj.getJSONArray("hops");
if(jHops.length() > 0) {
JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);
String txHash = jHop.getString("hash");
JSONObject txObj = APIFactory.getInstance(RicochetActivity.this).getTxInfo(txHash);
if(txObj != null && txObj.has("block_height") && txObj.getInt("block_height") != -1) {
hasConfirmation = true;
}
else if(txObj != null) {
txSeen = true;
}
else {
;
}
if(hasConfirmation) {
itr.remove();
continue;
}
}
if(!txSeen) {
if(jObj.has("pcode") && jObj.getString("pcode").length() > 0) {
strPCode = jObj.getString("pcode");
}
if(jObj.has("samouraiFeeViaBIP47")) {
samouraiFeeViaBIP47 = jObj.getBoolean("samouraiFeeViaBIP47");
}
String[] txs = new String[jHops.length()];
String[] dests = new String[jHops.length()];
for(int i = 0; i < jHops.length(); i++) {
JSONObject jSeq = jHops.getJSONObject(i);
int seq = jSeq.getInt("seq");
assert(seq == i);
String tx = jSeq.getString("tx");
// Log.d("RicochetActivity", "seq:" + seq + ":" + tx);
txs[i] = tx;
String dest = jSeq.getString("destination");
// Log.d("RicochetActivity", "seq:" + seq + ":" + dest);
dests[i] = dest;
}
if(txs.length >= 5 && dests.length >= 5) {
boolean isOK = false;
int i = 0;
while(i < txs.length) {
isOK = false;
String response = PushTx.getInstance(RicochetActivity.this).samourai(txs[i]);
// Log.d("RicochetActivity", "pushTx:" + response);
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) {
isOK = true;
}
if(isOK) {
strProgressTitle = RicochetActivity.this.getText(R.string.ricochet_hop).toString() + " " + i;
strProgressMessage = RicochetActivity.this.getText(R.string.ricochet_hopping).toString() + " " + dests[i];
publishProgress();
if(i == (txs.length - 1)) {
broadcastOK = true;
RicochetMeta.getInstance(RicochetActivity.this).setLastRicochet(jObj);
// increment change address
try {
HD_WalletFactory.getInstance(RicochetActivity.this).get().getAccount(0).getChange().incAddrIdx();
}
catch(IOException ioe) {
;
}
catch(MnemonicException.MnemonicLengthException mle) {
;
}
// increment BIP47 receive if send to BIP47
if(strPCode != null && strPCode.length() > 0) {
BIP47Meta.getInstance().getPCode4AddrLookup().put(dests[i], strPCode);
BIP47Meta.getInstance().inc(strPCode);
}
// increment BIP47 donation if fee to BIP47 donation
if(samouraiFeeViaBIP47) {
PaymentCode pcode = new PaymentCode(BIP47Meta.strSamouraiDonationPCode);
PaymentAddress paymentAddress = BIP47Util.getInstance(RicochetActivity.this).getSendAddress(pcode, BIP47Meta.getInstance().getOutgoingIdx(BIP47Meta.strSamouraiDonationPCode));
String strAddress = paymentAddress.getSendECKey().toAddress(MainNetParams.get()).toString();
BIP47Meta.getInstance().getPCode4AddrLookup().put(strAddress, BIP47Meta.strSamouraiDonationPCode);
BIP47Meta.getInstance().inc(BIP47Meta.strSamouraiDonationPCode);
}
}
i++;
if(i < txs.length) {
Thread.sleep(SLEEP_DELAY);
}
}
else {
Thread.sleep(SLEEP_DELAY);
continue;
}
}
}
else {
// badly formed error
}
}
}
}
catch(JSONException je) {
je.printStackTrace();
}
catch (InterruptedException ie) {
ie.printStackTrace();
}
catch (NotSecp256k1Exception nse) {
nse.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return "OK";
}
@Override
protected void onPostExecute(String result) {
if(progress != null && progress.isShowing()) {
progress.dismiss();
}
if(broadcastOK) {
AlertDialog.Builder dlg = new AlertDialog.Builder(RicochetActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.ricochet_broadcast)
.setCancelable(false)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent intent = new Intent(RicochetActivity.this, BalanceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
});
if(!isFinishing()) {
dlg.show();
}
}
else {
AlertDialog.Builder dlg = new AlertDialog.Builder(RicochetActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.ricochet_not_broadcast_replay)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
RicochetActivity.this.recreate();
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
});
if(!isFinishing()) {
dlg.show();
}
}
}
@Override
protected void onPreExecute() {
progress = new ProgressDialog(RicochetActivity.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.please_wait_ricochet));
progress.show();
}
@Override
protected void onProgressUpdate(Void... values) {
progress.setTitle(strProgressTitle);
progress.setMessage(strProgressMessage);
}
}
private void doReplayScript() {
if(RicochetMeta.getInstance(RicochetActivity.this).size() > 0) {
new AlertDialog.Builder(RicochetActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.ricochet_replay)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
new QueueTask().execute(new String[]{ null });
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
else {
Toast.makeText(RicochetActivity.this, R.string.no_ricochet_replay, Toast.LENGTH_SHORT).show();
}
}
private void doShowScript() {
if(RicochetMeta.getInstance(RicochetActivity.this).getLastRicochet() != null) {
TextView showText = new TextView(RicochetActivity.this);
showText.setText(RicochetMeta.getInstance(RicochetActivity.this).getLastRicochet().toString());
showText.setTextIsSelectable(true);
showText.setPadding(40, 10, 40, 10);
showText.setTextSize(18.0f);
new AlertDialog.Builder(RicochetActivity.this)
.setTitle(R.string.app_name)
.setView(showText)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
else {
Toast.makeText(RicochetActivity.this, R.string.no_ricochet_display, Toast.LENGTH_SHORT).show();
}
}
}
|
package build.pluto.builder;
import java.util.ArrayList;
import java.util.List;
import build.pluto.BuildUnit;
public class RequiredBuilderFailed extends RuntimeException {
private static final long serialVersionUID = 3080806736856580512L;
public static class BuilderResult {
public Builder<?, ?> builder;
public BuildUnit<?> result;
public BuilderResult(Builder<?, ?> builder, BuildUnit<?> result) {
this.builder = builder;
this.result = result;
}
}
private List<BuilderResult> builders;
public RequiredBuilderFailed(Builder<?, ?> builder, BuildUnit<?> result, Throwable cause) {
super(cause);
builders = new ArrayList<>();
builders.add(new BuilderResult(builder, result));
}
public void addBuilder(Builder<?, ?> builder, BuildUnit<?> result) {
builders.add(new BuilderResult(builder, result));
}
public BuilderResult getLastAddedBuilder() {
return builders.get(builders.size() - 1);
}
public List<BuilderResult> getBuilders() {
return builders;
}
@Override
public String getMessage() {
BuilderResult p = builders.get(0);
return "Required builder failed. Error occurred in build step \"" + p.builder.description() + (getCause() == null ? "" : "\": " + getCause().getMessage());
}
static RequiredBuilderFailed enqueueBuilder(RequiredBuilderFailed e, BuildUnit<?> depResult, Builder<?,?> builder) {
BuilderResult required = e.getLastAddedBuilder();
depResult.requires(required.result);
depResult.setState(BuildUnit.State.FAILURE);
e.addBuilder(builder, depResult);
return e;
}
static RequiredBuilderFailed init(Builder<?, ?> builder, BuildUnit<?> result, Throwable cause) {
return new RequiredBuilderFailed(builder, result, cause);
}
}
|
package com.veyndan.redditclient;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import rawjava.Reddit;
import rawjava.model.Link;
import rawjava.model.Thing;
import rawjava.network.VoteDirection;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
private static final String TAG = "veyndan_PostAdapter";
private final List<Thing<Link>> posts;
private final Reddit reddit;
public PostAdapter(List<Thing<Link>> posts, Reddit reddit) {
this.posts = posts;
this.reddit = reddit;
}
@Override
public PostAdapter.PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post, parent, false);
return new PostViewHolder(v);
}
@Override
public void onBindViewHolder(final PostAdapter.PostViewHolder holder, int position) {
Thing<Link> post = posts.get(position);
holder.title.setText(post.data.title);
CharSequence age = DateUtils.getRelativeTimeSpanString(
TimeUnit.SECONDS.toMillis(post.data.createdUtc), System.currentTimeMillis(),
DateUtils.SECOND_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT | DateUtils.FORMAT_NO_MONTH_DAY);
String urlHost;
try {
urlHost = new URL(post.data.url).getHost();
} catch (MalformedURLException e) {
Log.e(TAG, e.getMessage(), e);
urlHost = post.data.url;
}
holder.subtitle.setText(post.data.author + " · " + age + " · " + post.data.subreddit + " · " + urlHost);
holder.score.setText(holder.itemView.getContext().getResources().getQuantityString(R.plurals.points, post.data.score, post.data.score));
Boolean likes = post.data.likes;
holder.upvote.setChecked(likes != null && likes);
holder.upvote.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Ensure that downvote and upvote aren't checked at the same time.
if (isChecked) {
holder.downvote.setChecked(false);
}
Thing<Link> post = posts.get(holder.getAdapterPosition());
post.data.likes = isChecked ? true : null;
reddit.vote(isChecked ? VoteDirection.UPVOTE : VoteDirection.UNVOTE, post.kind + "_" + post.data.id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
post.data.score += isChecked ? 1 : -1;
holder.score.setText(holder.itemView.getContext().getResources().getQuantityString(R.plurals.points, post.data.score, post.data.score));
}
});
holder.downvote.setChecked(likes != null && !likes);
holder.downvote.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Ensure that downvote and upvote aren't checked at the same time.
if (isChecked) {
holder.upvote.setChecked(false);
}
Thing<Link> post = posts.get(holder.getAdapterPosition());
post.data.likes = isChecked ? false : null;
reddit.vote(isChecked ? VoteDirection.DOWNVOTE : VoteDirection.UNVOTE, post.kind + "_" + post.data.id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
post.data.score += isChecked ? -1 : 1;
holder.score.setText(holder.itemView.getContext().getResources().getQuantityString(R.plurals.points, post.data.score, post.data.score));
}
});
holder.save.setChecked(post.data.saved);
holder.save.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Thing<Link> post = posts.get(holder.getAdapterPosition());
post.data.saved = isChecked;
if (isChecked) {
reddit.save("", post.kind + "_" + post.data.id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
} else {
reddit.unsave(post.kind + "_" + post.data.id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe();
}
}
});
}
@Override
public int getItemCount() {
return posts.size();
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
final TextView title;
final TextView subtitle;
final TextView score;
final ToggleButton upvote;
final ToggleButton downvote;
final ToggleButton save;
public PostViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.post_title);
subtitle = (TextView) itemView.findViewById(R.id.post_subtitle);
score = (TextView) itemView.findViewById(R.id.post_score);
upvote = (ToggleButton) itemView.findViewById(R.id.post_upvote);
downvote = (ToggleButton) itemView.findViewById(R.id.post_downvote);
save = (ToggleButton) itemView.findViewById(R.id.post_save);
}
}
}
|
package org.mskcc.cgds.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.regex.Pattern;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mskcc.cgds.dao.DaoCancerStudy;
import org.mskcc.cgds.dao.DaoCase;
import org.mskcc.cgds.dao.DaoCaseList;
import org.mskcc.cgds.dao.DaoException;
import org.mskcc.cgds.dao.DaoGeneticProfile;
import org.mskcc.cgds.model.CancerStudy;
import org.mskcc.cgds.model.CaseList;
import org.mskcc.cgds.model.GeneticProfile;
import org.mskcc.cgds.util.AccessControl;
import org.mskcc.cgds.util.DatabaseProperties;
import org.mskcc.cgds.web_api.GetCaseLists;
import org.mskcc.cgds.web_api.GetClinicalData;
import org.mskcc.cgds.web_api.GetGeneticProfiles;
import org.mskcc.cgds.web_api.GetMutationData;
import org.mskcc.cgds.web_api.GetMutationFrequencies;
import org.mskcc.cgds.web_api.GetNetwork;
import org.mskcc.cgds.web_api.GetMutSig;
import org.mskcc.cgds.web_api.GetProfileData;
import org.mskcc.cgds.web_api.GetProteinArrayData;
import org.mskcc.cgds.web_api.GetTypesOfCancer;
import org.mskcc.cgds.web_api.ProtocolException;
import org.mskcc.cgds.web_api.WebApiUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Core Web Service.
*
* @author Ethan Cerami.
* @author Arthur Goldberg goldberg@cbio.mskcc.org
*/
public class WebService extends HttpServlet {
public static final String CANCER_STUDY_ID = "cancer_study_id";
public static final String CANCER_TYPE_ID = "cancer_type_id";
public static final String GENETIC_PROFILE_ID = "genetic_profile_id";
public static final String GENE_LIST = "gene_list";
public static final String CMD = "cmd";
public static final String Q_VALUE_THRESHOLD = "q_value_threshold";
public static final String GENE_SYMBOL = "gene_symbol";
public static final String ENTREZ_GENE_ID = "entrez_gene_id";
public static final String CASE_LIST = "case_list";
public static final String CASE_SET_ID = "case_set_id";
public static final String SUPPRESS_MONDRIAN_HEADER = "suppress_mondrian_header";
public static final String EMAIL_ADDRESS = "email_address";
public static final String SECRET_KEY = "secret_key";
public static final String PROTEIN_ARRAY_TYPE = "protein_array_type";
public static final String PROTEIN_ARRAY_ID = "protein_array_id";
// ref to access control
private AccessControl accessControl;
/**
* Shutdown the Servlet.
*/
public void destroy() {
super.destroy();
}
/**
* Initializes Servlet with parameters in web.xml file.
*
* @throws javax.servlet.ServletException Servlet Initialization Error.
*/
public void init() throws ServletException {
super.init();
System.out.println("Starting up the Cancer Genomics Data Server...");
System.out.println("Reading in init parameters from web.xml");
DatabaseProperties dbProperties = DatabaseProperties.getInstance();
ServletConfig config = this.getServletConfig();
String dbHost = config.getInitParameter("db_host");
String dbUser = config.getInitParameter("db_user");
String dbPassword = config.getInitParameter("db_password");
String dbName = config.getInitParameter("db_name");
System.out.println("Starting CGDS Server");
dbProperties.setDbName(dbName);
dbProperties.setDbHost(dbHost);
dbProperties.setDbUser(dbUser);
dbProperties.setDbPassword(dbPassword);
verifyDbConnection();
// setup our context and init some beans
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:applicationContext-security.xml");
accessControl = (AccessControl)context.getBean("accessControl");
}
/**
* Handles GET Requests.
*
* @param httpServletRequest HttpServlet Request.
* @param httpServletResponse HttpServlet Response.
* @throws ServletException Servlet Error.
* @throws IOException IO Error.
*/
protected void doGet(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
processClient(httpServletRequest, httpServletResponse);
}
/**
* Handles POST Requests.
*
* @param httpServletRequest HttpServlet Request.
* @param httpServletResponse HttpServlet Response.
* @throws ServletException Servlet Error.
* @throws IOException IO Error.
*/
protected void doPost(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
processClient(httpServletRequest, httpServletResponse);
}
/**
* Processes all Client Requests.
*
* @param httpServletRequest HttpServlet Request.
* @param httpServletResponse HttpServlet Response.
* @throws IOException IO Error.
*/
public void processClient(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws IOException {
PrintWriter writer = httpServletResponse.getWriter();
Date startTime = new Date();
String cmd = httpServletRequest.getParameter(CMD);
try {
httpServletResponse.setContentType("text/plain");
writer.print(WebApiUtil.WEP_API_HEADER);
// Branch, based on command.
if (null == cmd) {
outputMissingParameterError(writer, CMD);
return;
}
// check command
if (!goodCommand(writer, cmd)) {
return;
}
if (cmd.equals("getTypesOfCancer")) {
// getTypesOfCancer requires no access control
getTypesOfCancer(writer);
return;
}
if (cmd.equals("getNetwork")) {
// getNetwork doesn't access any data; so no access control needed
getNetwork(httpServletRequest, writer);
return;
}
if (cmd.equals("getProteinArrayInfo")) {
getProteinArrayInfo(httpServletRequest, writer);
return;
}
if (cmd.equals("getProteinArrayData")) {
getProteinArrayData(httpServletRequest, writer);
return;
}
// We support the new getCancerStudies plus the deprecated getCancerTypes command
if (cmd.equals("getCancerStudies") || cmd.equals("getCancerTypes")) {
// getCancerStudies requires special access control
// identify every study accessible to the user
getCancerStudies(httpServletRequest, writer);
return;
}
// TODO: CASES: REMOVE?
// no cancer_study_id or no case_set_id or genetic_profile_id
if (null == getCancerStudyId(httpServletRequest) &&
null == httpServletRequest.getParameter(WebService.CASE_SET_ID) &&
null == httpServletRequest.getParameter(WebService.GENETIC_PROFILE_ID) &&
null == httpServletRequest.getParameter(WebService.CASE_LIST)) {
outputError(writer, "No cancer study (cancer_study_id), or genetic profile (genetic_profile_id) " +
"or case list or (case_list) case set (case_set_id) provided by request. " +
"Please reformulate request.");
return;
}
HashSet<String> cancerStudyIDs = getCancerStudyIDs(httpServletRequest);
if (null == cancerStudyIDs) {
outputError(writer, "Problem when identifying a cancer study for the request.");
return;
}
// TODO: if cancerStudyID == CancerStudy.NO_SUCH_STUDY report an error with more info
for (String cancerStudyID : cancerStudyIDs) {
if (!DaoCancerStudy.doesCancerStudyExistByStableId(cancerStudyID)) {
outputError(writer, "The cancer study identified by the request (" + cancerStudyID +
") is not in the dbms. Please reformulate request.");
return;
}
}
// check access control
for (String cancerStudyID : cancerStudyIDs) {
CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByStableId(cancerStudyID);
if (!checkAccess(httpServletRequest, writer, cancerStudyID)) {
// access denied
outputError(writer, "User cannot access the cancer study called '" + cancerStudy.getName()
+ "'. Please provide credentials to access private data.");
return;
}
}
// IMPORTANT IMPORTANT IMPORTANT IMPORTANT
// all web api commands that access private data (except getcancerstudies, which is a special case)
// must be placed AFTER this comment, so that the user's right to access the data is verified
if (cmd.equals("getGeneticProfiles")) {
// PROVIDES CANCER_STUDY_ID
getGeneticProfiles(httpServletRequest, writer);
} else if (cmd.equals("getProfileData")) {
// PROVIDES genetic_profile_id
getProfileData(httpServletRequest, writer);
} else if (cmd.equals("getCaseLists")) {
// PROVIDES CANCER_STUDY_ID
getCaseLists(httpServletRequest, writer);
} else if (cmd.equals("getClinicalData")) {
// PROVIDES case_set_id
getClinicalData(httpServletRequest, writer);
} else if (cmd.equals("getMutationData")) {
// PROVIDES genetic_profile_id
getMutationData(httpServletRequest, writer);
} else if (cmd.equals("getMutationFrequency")) {
// PROVIDES CANCER_STUDY_ID
getMutationFrequency(httpServletRequest, writer);
} else if (cmd.equals("getMutSig")) {
//Provides MutSig Data
getMutSig(httpServletRequest, writer);
} else {
throw new ProtocolException("Unrecognized command: " + cmd);
}
} catch (DaoException e) {
e.printStackTrace();
outputError(writer, "internal error: " + e.getMessage());
} catch (ProtocolException e) {
e.printStackTrace();
outputError(writer, e.getMsg());
} catch (Exception e) {
e.printStackTrace();
outputError(writer, e.toString());
} finally {
writer.flush();
writer.close();
Date stopTime = new Date();
long timeElapsed = stopTime.getTime() - startTime.getTime();
}
}
/**
* Gets the Network of Interest.
*
* @param httpServletRequest HttpServletRequest Object.
* @param writer Print Writer Object.
* @throws DaoException Database Exception.
* @throws ProtocolException Protocol Exception.
*/
private void getNetwork(HttpServletRequest httpServletRequest,
PrintWriter writer) throws DaoException, ProtocolException {
String geneList = httpServletRequest.getParameter(GENE_LIST);
if (geneList == null || geneList.length() == 0) {
throw new ProtocolException("Missing Parameter: " + GENE_LIST);
}
ArrayList<String> targetGeneList = getGeneList(httpServletRequest);
String out = GetNetwork.getNetwork(targetGeneList);
writer.print(out);
}
private void getProteinArrayInfo(HttpServletRequest httpServletRequest,
PrintWriter writer) throws DaoException, ProtocolException {
String geneList = httpServletRequest.getParameter(GENE_LIST);
ArrayList <String> targetGeneList;
if (geneList == null || geneList.length() == 0) {
targetGeneList = null;
}else {
targetGeneList = getGeneList (httpServletRequest);
}
String type = httpServletRequest.getParameter(PROTEIN_ARRAY_TYPE);
writer.print(GetProteinArrayData.getProteinArrayInfo(targetGeneList,type));
}
private void getProteinArrayData(HttpServletRequest httpServletRequest,
PrintWriter writer) throws DaoException, ProtocolException {
String arrayId = httpServletRequest.getParameter(PROTEIN_ARRAY_ID);
if (arrayId == null || arrayId.length() == 0) {
throw new ProtocolException ("Missing Parameter: " + PROTEIN_ARRAY_ID);
}
ArrayList<String> targetCaseIds = null;
if (null != httpServletRequest.getParameter(CASE_LIST)
|| null != httpServletRequest.getParameter(CASE_SET_ID))
targetCaseIds = getCaseList(httpServletRequest);
writer.print(GetProteinArrayData.getProteinArrayData(arrayId, targetCaseIds));
}
private void getTypesOfCancer(PrintWriter writer) throws DaoException, ProtocolException {
String out = GetTypesOfCancer.getTypesOfCancer();
writer.print(out);
}
private void getCancerStudies(HttpServletRequest httpServletRequest, PrintWriter writer) throws DaoException,
ProtocolException {
//String out = accessControl.getCancerStudies(httpServletRequest.getParameter(EMAIL_ADDRESS),
// httpServletRequest.getParameter(SECRET_KEY));
String out = accessControl.getCancerStudies();
writer.print(out);
}
private boolean checkAccess(HttpServletRequest httpServletRequest, PrintWriter writer,
String stableStudyId) throws DaoException {
//return accessControl.checkAccess(httpServletRequest.getParameter(EMAIL_ADDRESS),
// httpServletRequest.getParameter(SECRET_KEY), stableStudyId);
return accessControl.checkAccess(stableStudyId);
}
private void getMutationFrequency(HttpServletRequest httpServletRequest, PrintWriter writer)
throws DaoException, ProtocolException {
String cancerStudyId = getCancerStudyId(httpServletRequest);
if (cancerStudyId == null) {
outputMissingParameterError(writer, CANCER_STUDY_ID);
} else {
String out = GetMutationFrequencies.getMutationFrequencies(Integer.parseInt(cancerStudyId),
httpServletRequest);
writer.print(out);
}
}
private void getGeneticProfiles(HttpServletRequest httpServletRequest, PrintWriter writer)
throws DaoException {
String cancerStudyStableId = getCancerStudyId(httpServletRequest);
if (cancerStudyStableId == null) {
outputMissingParameterError(writer, CANCER_STUDY_ID);
} else {
String out = GetGeneticProfiles.getGeneticProfiles(cancerStudyStableId);
writer.print(out);
}
}
private void getCaseLists(HttpServletRequest httpServletRequest, PrintWriter writer)
throws DaoException {
String cancerStudyStableId = getCancerStudyId(httpServletRequest);
if (cancerStudyStableId == null) {
outputMissingParameterError(writer, CANCER_STUDY_ID);
} else {
String out = GetCaseLists.getCaseLists(cancerStudyStableId);
writer.print(out);
}
}
private void outputError(PrintWriter writer, String msg) {
writer.print("Error: " + msg + "\n");
}
private void getProfileData(HttpServletRequest request, PrintWriter writer)
throws DaoException, ProtocolException, UnsupportedEncodingException {
ArrayList<String> caseList = getCaseList(request);
validateRequestForProfileOrMutationData(request);
ArrayList<String> geneticProfileIdList = getGeneticProfileId(request);
ArrayList<String> targetGeneList = getGeneList(request);
if (targetGeneList.size() > 1 && geneticProfileIdList.size() > 1) {
throw new ProtocolException
("You can specify multiple genes or multiple genetic profiles, " +
"but not both at once!");
}
Boolean suppressMondrianHeader = new Boolean(request.getParameter(SUPPRESS_MONDRIAN_HEADER));
String out = GetProfileData.getProfileData(geneticProfileIdList, targetGeneList,
caseList, suppressMondrianHeader);
writer.print(out);
}
private void getClinicalData(HttpServletRequest request, PrintWriter writer)
throws DaoException, ProtocolException, UnsupportedEncodingException {
HashSet<String> caseSet = new HashSet<String>(getCaseList(request));
String out = GetClinicalData.getClinicalData(caseSet);
writer.print(out);
}
/*
* For getMutSig client specifies a Cancer Study ID,
* and either a q_value_threshold, or a gene list.
* The two latter parameters are optional.
*/
private void getMutSig(HttpServletRequest request, PrintWriter writer)
throws DaoException {
String cancerStudyID = getCancerStudyId(request);
String q_value_threshold = request.getParameter(Q_VALUE_THRESHOLD);
String gene_list = request.getParameter(GENE_LIST);
int cancerID = Integer.parseInt(cancerStudyID);
if ((q_value_threshold == null || q_value_threshold.length() == 0)
&& (gene_list == null || gene_list.length() == 0)) {
StringBuffer output = GetMutSig.GetAMutSig(cancerID);
writer.print(output);
} else if ((q_value_threshold != null || q_value_threshold.length() != 0)
&& (gene_list == null || gene_list.length() == 0)) {
StringBuffer output = GetMutSig.GetAMutSig(cancerID, q_value_threshold, true);
writer.print(output);
} else if ((q_value_threshold == null || q_value_threshold.length() == 0)
&& (gene_list != null || gene_list.length() != 0)) {
StringBuffer output = GetMutSig.GetAMutSig(cancerID, gene_list, false);
writer.print(output);
} else {
writer.print("Invalid command. Please input a valid Q-Value Threshold, or Gene List.");
}
}
private void getMutationData(HttpServletRequest request, PrintWriter writer)
throws DaoException, ProtocolException, UnsupportedEncodingException {
ArrayList<String> caseList = getCaseList(request);
validateRequestForProfileOrMutationData(request);
ArrayList<String> geneticProfileIdList = getGeneticProfileId(request);
String geneticProfileId = geneticProfileIdList.get(0);
ArrayList<String> targetGeneList = getGeneList(request);
String out = GetMutationData.getProfileData(geneticProfileId, targetGeneList,
caseList);
writer.print(out);
}
private ArrayList<String> getGeneList(HttpServletRequest request) {
String geneList = request.getParameter(GENE_LIST);
// Split on white space or commas
Pattern p = Pattern.compile("[,\\s]+");
String genes[] = p.split(geneList);
ArrayList<String> targetGeneList = new ArrayList<String>();
for (String gene : genes) {
gene = gene.trim();
if (gene.length() == 0) continue;
targetGeneList.add(gene);
}
return targetGeneList;
}
private void validateRequestForProfileOrMutationData(HttpServletRequest request)
throws ProtocolException {
String geneticProfileIdStr = request.getParameter(GENETIC_PROFILE_ID);
String geneList = request.getParameter(GENE_LIST);
if (geneticProfileIdStr == null || geneticProfileIdStr.length() == 0) {
throw new ProtocolException("Missing Parameter: " + GENETIC_PROFILE_ID);
}
if (geneList == null || geneList.length() == 0) {
throw new ProtocolException("Missing Parameter: " + GENE_LIST);
}
}
// TODO: rename TO getGeneticProfileId, as the return value is PLURAL
private static ArrayList<String> getGeneticProfileId(HttpServletRequest request) throws ProtocolException {
String geneticProfileIdStr = request.getParameter(GENETIC_PROFILE_ID);
// Split on white space or commas
Pattern p = Pattern.compile("[,\\s]+");
String geneticProfileIds[] = p.split(geneticProfileIdStr);
ArrayList<String> geneticProfileIdList = new ArrayList<String>();
for (String geneticProfileId : geneticProfileIds) {
geneticProfileId = geneticProfileId.trim();
geneticProfileIdList.add(geneticProfileId);
}
return geneticProfileIdList;
}
private ArrayList<String> getCaseList(HttpServletRequest request) throws ProtocolException,
DaoException {
String cases = request.getParameter(CASE_LIST);
String caseSetId = request.getParameter(CASE_SET_ID);
ArrayList<String> caseList = new ArrayList<String>();
if (caseSetId != null) {
DaoCaseList dao = new DaoCaseList();
CaseList selectedCaseList = dao.getCaseListByStableId(caseSetId);
if (selectedCaseList == null) {
throw new ProtocolException("Invalid " + CASE_SET_ID + ": " + caseSetId + ".");
}
caseList = selectedCaseList.getCaseList();
} else if (cases != null) {
for (String _case : cases.split("[\\s,]+")) {
_case = _case.trim();
if (_case.length() == 0) continue;
caseList.add(_case);
}
} else {
throw new ProtocolException(CASE_SET_ID + " or " + CASE_LIST + " must be specified.");
}
return caseList;
}
private void outputMissingParameterError(PrintWriter writer, String missingParameter) {
outputError(writer, "you must specify a " + missingParameter + " parameter.");
}
/**
* Verifies Database Connection. In the event of an error, log
* messages are written out to catalina.out.
*/
private void verifyDbConnection() {
//System.out.println("Verifying Database Connection...");
try {
//System.out.println("Attempting to retrieve Cancer Types...");
DaoCancerStudy.getAllCancerStudies();
//System.out.println("Database Connection --> [OK]");
} catch (DaoException e) {
System.err.println("**** Fatal Error in CGDS. Could not connect to "
+ "database");
}
}
private boolean goodCommand(PrintWriter writer, String cmd ){
// check that command is correct
String[] commands = { "getTypesOfCancer", "getNetwork", "getCancerStudies",
"getCancerTypes", "getGeneticProfiles", "getProfileData", "getCaseLists",
"getClinicalData", "getMutationData", "getMutationFrequency",
"getProteinArrayInfo", "getProteinArrayData", "getMutSig"};
for( String aCmd : commands ){
if( aCmd.equals(cmd)){
return true;
}
}
outputError( writer, "'" + cmd + "' not a valid command." );
return false;
}
/**
* Given an HttpServletRequest, determine all cancer_study_ids associated with it.
* cancer study identifiers can be inferred from profile_ids, case_list_ids, or case_ids.
* this returns the set of ALL POSSIBLE cancer study identifiers
*
* @param request
* @return the cancer_study_ids associated with the request, which will be empty
* if none can be determined; or null if a problem arises.
* @throws DaoException
* @throws ProtocolException
*/
public static HashSet<String> getCancerStudyIDs(HttpServletRequest request)
throws DaoException, ProtocolException {
HashSet<String> cancerStudies = new HashSet<String>();
// a CANCER_STUDY_ID is explicitly provided, as in getGeneticProfiles, getCaseLists, etc.
// make sure the cancer_study_id provided in the request points to a real study
String studyIDstring = getCancerStudyId(request);
if (studyIDstring != null) {
if (DaoCancerStudy.doesCancerStudyExistByStableId(studyIDstring)) {
cancerStudies.add(studyIDstring);
} else {
return null;
}
}
// a genetic_profile_id is explicitly provided, as in getProfileData
if (null != request.getParameter(GENETIC_PROFILE_ID)) {
ArrayList<String> genetic_profile_ids = getGeneticProfileId(request);
for (String genetic_profile_id : genetic_profile_ids) {
if (genetic_profile_id == null) {
return null;
}
DaoGeneticProfile aDaoGeneticProfile = new DaoGeneticProfile();
GeneticProfile aGeneticProfile = aDaoGeneticProfile.getGeneticProfileByStableId(genetic_profile_id);
if (aGeneticProfile != null &&
DaoCancerStudy.doesCancerStudyExistByInternalId(aGeneticProfile.getCancerStudyId())) {
cancerStudies.add(DaoCancerStudy.getCancerStudyByInternalId
(aGeneticProfile.getCancerStudyId()).getCancerStudyIdentifier());
}
}
}
// a case_set_id is explicitly provided, as in getProfileData, getMutationData, getClinicalData, etc.
String caseSetId = request.getParameter(WebService.CASE_SET_ID);
if (caseSetId != null) {
DaoCaseList aDaoCaseList = new DaoCaseList();
CaseList aCaseList = aDaoCaseList.getCaseListByStableId(caseSetId);
if (aCaseList == null) {
return null;
}
if (DaoCancerStudy.doesCancerStudyExistByInternalId(aCaseList.getCancerStudyId())) {
cancerStudies.add(DaoCancerStudy.getCancerStudyByInternalId
(aCaseList.getCancerStudyId()).getCancerStudyIdentifier());
} else {
return null;
}
}
// a case_list is explicitly provided, as in getClinicalData, etc.
String caseList = request.getParameter(WebService.CASE_LIST);
if (caseList != null) {
DaoCase aDaoCase = new DaoCase();
for (String _case : caseList.split("[\\s,]+")) {
_case = _case.trim();
if (_case.length() == 0) continue;
int profileId = aDaoCase.getProfileIdForCase(_case);
if (DaoCase.NO_SUCH_PROFILE_ID == profileId) {
return null;
}
DaoGeneticProfile aDaoGeneticProfile = new DaoGeneticProfile();
GeneticProfile aGeneticProfile = aDaoGeneticProfile.getGeneticProfileById(profileId);
if (aGeneticProfile == null) {
return null;
}
if (DaoCancerStudy.doesCancerStudyExistByInternalId(aGeneticProfile.getCancerStudyId())) {
cancerStudies.add(DaoCancerStudy.getCancerStudyByInternalId
(aGeneticProfile.getCancerStudyId()).getCancerStudyIdentifier());
} else {
return null;
}
}
}
return cancerStudies;
}
/**
* Get Cancer Study ID in a backward compatible fashion.
*/
private static String getCancerStudyId(HttpServletRequest request) {
String cancerStudyId = request.getParameter(WebService.CANCER_STUDY_ID);
if (cancerStudyId == null || cancerStudyId.length() == 0) {
cancerStudyId = request.getParameter(WebService.CANCER_TYPE_ID);
}
return cancerStudyId;
}
}
|
/** @author Viktoria Koleskina (mailto:viktoriakoleskina@yandex.ru)
* @version $Id$
* @since 0.1**/
package ru.job4j.max;
/**
* Max.
**/
public class Max {
/**
* @param maxValue.
*/
private int maxValue;
/**
* @param first **first parameter**
* @param second **sec parameter**
* @return **return return**
*/
public int max(int first, int second) {
this.maxValue = first < second ? second : first;
return this.maxValue;
}
}
|
package hu.rijkswaterstaat.rvaar;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
public class OverviewMap extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
public static final int DRAW_DISTANCE_MARKERS = 20000;
public static final int NEAREST_MARKER_METER = 10000;
/**
* The desired interval for location updates. Inexact. Updates may be more or less frequent.
*/
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
/**
* The fastest rate for active location updates. Exact. Updates will never be more frequent
* than this value.
*/
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
protected static final String TAG = "location-updates-sample";
public GoogleMap mMap;
public boolean AnimatedCameraOnce = true;
public MarkerOptions nearestMarkerLoc;
// Keys for storing activity state in the Bundle.
public ArrayList<MarkerOptions> markers;
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Stores parameters for requests to the FusedLocationProviderApi.
*/
protected LocationRequest mLocationRequest;
/**
* Represents a geographical location.
*/
protected Location mCurrentLocation;
// UI Widgets.
/**
* Tracks the status of the location updates request. Value changes when the user presses the
* Start Updates and Stop Updates buttons.
*/
/**
* Time when the location was updated represented as a String.
*/
protected String mLastUpdateTime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview_map);
markers = new ArrayList<>();
mLastUpdateTime = "";
// Update values using data stored in the Bundle.
// Kick off the process of building a GoogleApiClient and requesting the LocationServices
// API.
buildGoogleApiClient();
setUpMapIfNeeded();
}
/**
* Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
* LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
mMap.setMyLocationEnabled(true);
addMarkersToMap();
}
if (mMap != null) {
setUpMap();
}
}
private void setUpMap() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
MarkerDAOimpl positionDao = new MarkerDAOimpl();
markers = positionDao.getMarkers();
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Sets up the location request. Android has two location request settings:
* {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control
* the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
* the AndroidManifest.xml.
* <p/>
* When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
* interval (5 seconds), the Fused Location Provider API returns location updates that are
* accurate to within a few feet.
* <p/>
* These settings are appropriate for mapping applications that show real-time location
* updates.
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
protected void startLocationUpdates() {
// The final argument to {@code requestLocationUpdates()} is a LocationListener
Log.d("startLocup", "startLocup");
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Removes location updates from the FusedLocationApi.
*/
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
// The final argument to {@code requestLocationUpdates()} is a LocationListener
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
@Override
public void onResume() {
super.onResume();
// Within {@code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
@Override
protected void onPause() {
super.onPause();
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
@Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
// If the initial location was never previously requested, we use
// FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
// its value in the Bundle and check for it in onCreate(). We
// do not request it again unless the user specifically requests location updates by pressing
// the Start Updates button.
// Because we cache the value of the initial location in the Bundle, it means that if the
// user launches the activity,
// moves to a new location, and then changes the device orientation, the original location
// is displayed as the activity is re-created.
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
}
startLocationUpdates();
}
/**
* Callback that fires when the location changes.
*/
@Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMap.getUiSettings().setMyLocationButtonEnabled(false);
Log.d("startLocch", "startLocch");
mMap.clear();
addMarkersToMap();
MarkerOptions k = new MarkerOptions();
k.position(loc);
mMap.addMarker(k.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_markericon)));
findNearestMarker();
if (AnimatedCameraOnce) { // tijdelijk
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(loc) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
AnimatedCameraOnce = false;
}
Log.d("Latitude", "Current Latitude " + location.getLatitude());
Log.d("Longitude", "Current Longitude " + location.getLongitude());
Toast.makeText(this, getResources().getString(R.string.location_updated_message),
Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
/**
* Stores activity data in the Bundle.
*/
public void findNearestMarker() {
double minDist = 1E38;
int minIndex = -1;
for (int i = 0; i < markers.size(); i++) {
Location currentIndexMarkerLoc = new Location("Marker");
currentIndexMarkerLoc.setLatitude(markers.get(i).getPosition().latitude);
currentIndexMarkerLoc.setLongitude(markers.get(i).getPosition().longitude);
currentIndexMarkerLoc.setTime(new Date().getTime());
float test = mCurrentLocation.distanceTo(currentIndexMarkerLoc);
if (test < minDist) {
minDist = test;
minIndex = i;
}
}
if (minIndex >= 0) {
nearestMarkerLoc = markers.get(minIndex);
nearestMarkerLoc.icon(null); // testen
nearestMarkerLoc.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
// mMap.addMarker(nearestMarkerLoc);
Log.d("nearestLocation name", "nearestLocation name" + nearestMarkerLoc.getTitle());
notifyUser(nearestMarkerLoc);
} else {
nearestMarkerLoc.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
}
}
public void notifyUser(MarkerOptions marker) {
Location notifcationLoc = new Location("Marker");
notifcationLoc.setLatitude(marker.getPosition().latitude);
notifcationLoc.setLongitude(marker.getPosition().longitude);
float distanceInMeters = mCurrentLocation.distanceTo(notifcationLoc);
int notifyID = 1;
if (distanceInMeters < NEAREST_MARKER_METER) { // in seconden te doen, in alle gevallen is het dan gelijk
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("rVaar")
.setContentText("Over " + distanceInMeters + " nadert u de kruispunt " + marker.getTitle())
.setSmallIcon(R.drawable.ic_rvaar);
Intent resultIntent = new Intent(this, OverviewMap.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(OverviewMap.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notifyID, mBuilder.build()); // test on screen update/
mBuilder.setDefaults(-1); // http://developer.android.com/reference/android/app/Notification.html#DEFAULT_ALL
}
}
public void addMarkersToMap() {
for (MarkerOptions m : markers) {
Location loc = new Location("");
loc.setLongitude(m.getPosition().longitude);
loc.setLatitude(m.getPosition().latitude);
if (mCurrentLocation.distanceTo(loc) < DRAW_DISTANCE_MARKERS) {
if (m == nearestMarkerLoc) {
mMap.addMarker(m);
} else {
m.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_iconkruispunt));
mMap.addMarker(m);
}
}
}
}
}
|
package ru.job4j;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**Test of Max class.
*@author gimazetdinov
*@version 1.0
*@since 24.01.2017
*/
public class MaxTest {
/**Test max() method which returns max value of two.*/
@Test
public void whenFiveAndTwoThenFive() {
final int first = 5;
final int second = 2;
final int expected = 5;
Max obj = new Max();
assertThat(obj.max(first, second), is(expected));
}
/**Test max() method which returns max value of three.*/
@Test
public void whenFiveTwoAndEightThenEight() {
final int first = 5;
final int second = 2;
final int third = 8;
final int expected = 8;
Max obj = new Max();
assertThat(obj.max(first, second, third), is(expected));
}
}
|
package com.google.sps.agents;
// Imports the Google Cloud client library
import com.google.gson.Gson;
import com.google.protobuf.Value;
import com.google.sps.data.Book;
import com.google.sps.data.BookQuery;
import com.google.sps.utils.BookUtils;
import com.google.sps.utils.BooksMemoryUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
/** Books Agent */
public class Books implements Agent {
private final String intentName;
private final String userInput;
private String output;
private String display;
private String redirect;
private BookQuery query;
private int displayNum;
public Books(String intentName, String userInput, Map<String, Value> parameters)
throws IOException {
this.displayNum = 5;
this.intentName = intentName;
this.userInput = userInput;
setParameters(parameters);
}
@Override
public void setParameters(Map<String, Value> parameters) throws IOException {
if (intentName.equals("search")) {
// Create new BookQuery request, sets startIndex at 0
BookQuery query = BookQuery.createBookQuery(this.userInput, parameters);
// Retrieve books
int startIndex = 0;
ArrayList<Book> results = BookUtils.getRequestedBooks(query, startIndex);
int totalResults = BookUtils.getTotalVolumesFound(query, startIndex);
int resultsReturned = results.size();
if (resultsReturned > 0) {
// Delete stored BookQuery, Book results, totalResults, resultsReturned
BooksMemoryUtils.deleteAllStoredBookInformation();
// Store BookQuery, Book results, totalResults, resultsReturned
BooksMemoryUtils.storeBooks(results, startIndex);
BooksMemoryUtils.storeBookQuery(query);
BooksMemoryUtils.storeIndices(startIndex, totalResults, resultsReturned);
ArrayList<Book> booksToDisplay =
BooksMemoryUtils.getStoredBooksToDisplay(displayNum, startIndex);
this.display = bookListToString(booksToDisplay);
this.output = "Here's what I found.";
} else {
this.output = "I couldn't find any results. Can you try again?";
}
} else if (intentName.equals("more")) {
// Load BookQuery, totalResults, resultsStored
BookQuery prevQuery = BooksMemoryUtils.getStoredBookQuery();
int prevStartIndex = BooksMemoryUtils.getStoredStartIndex();
int resultsStored = BooksMemoryUtils.getStoredResultsNum();
int totalResults = BooksMemoryUtils.getStoredTotalResults();
// Increment startIndex
int startIndex = getNextStartIndex(prevStartIndex, totalResults);
if (startIndex == -1) {
this.output = "I'm sorry, there are no more results.";
return;
} else if (startIndex + displayNum <= resultsStored) {
// Replace indices
BooksMemoryUtils.deleteStoredEntities("Indices");
BooksMemoryUtils.storeIndices(startIndex, totalResults, resultsStored);
} else {
// Retrieve books
ArrayList<Book> results = BookUtils.getRequestedBooks(prevQuery, startIndex);
int resultsReturned = results.size();
int newResultsStored = resultsReturned + resultsStored;
// Even though there are more results, if Volume objects don't have a title
// then we don't create any Book objects, so we still have to check for an empty Book list
if (resultsReturned == 0) {
this.output = "I'm sorry, there are no more results.";
return;
} else {
// Delete stored Book results and indices
BooksMemoryUtils.deleteStoredEntities("Indices");
// Store Book results and indices
BooksMemoryUtils.storeBooks(results, startIndex);
BooksMemoryUtils.storeIndices(startIndex, totalResults, newResultsStored);
}
}
ArrayList<Book> booksToDisplay =
BooksMemoryUtils.getStoredBooksToDisplay(displayNum, startIndex);
this.display = bookListToString(booksToDisplay);
this.output = "Here's the next page of results";
} else if (intentName.equals("previous")) {
// Load BookQuery, totalResults, resultsStored
BookQuery prevQuery = BooksMemoryUtils.getStoredBookQuery();
int prevStartIndex = BooksMemoryUtils.getStoredStartIndex();
int resultsStored = BooksMemoryUtils.getStoredResultsNum();
int totalResults = BooksMemoryUtils.getStoredTotalResults();
// Increment startIndex
int startIndex = prevStartIndex - displayNum;
if (startIndex < -1) {
this.output = "This is the first page of results.";
startIndex = 0;
} else {
// Replace indices
BooksMemoryUtils.deleteStoredEntities("Indices");
BooksMemoryUtils.storeIndices(startIndex, totalResults, resultsStored);
this.output = "Here's the previous page of results";
}
ArrayList<Book> booksToDisplay =
BooksMemoryUtils.getStoredBooksToDisplay(displayNum, startIndex);
this.display = bookListToString(booksToDisplay);
} else if (intentName.equals("about")) {
// TODO: Load Book results, totalResults, resultsReturned
// TODO: Get information about requested Book
// TODO: Make output information
// TODO: Don't change any stored information
} else if (intentName.equals("preview")) {
// TODO: Load Book results, totalResults, resultsReturned
// TODO: Get information about requested Book
// TODO: Make output information
// TODO: Don't change any stored information
} else if (intentName.equals("results")) {
// TODO: Load Book results, totalResults, resultsReturned
// TODO: Get output information from stored Book results
// TODO: Don't change any stored information
}
}
@Override
public String getOutput() {
return this.output;
}
@Override
public String getDisplay() {
return this.display;
}
@Override
public String getRedirect() {
return this.redirect;
}
private int getNextStartIndex(int prevIndex, int total) {
int nextIndex = prevIndex + displayNum;
if (nextIndex < total) {
return nextIndex;
}
return -1;
}
private String bookListToString(ArrayList<Book> books) {
Gson gson = new Gson();
return gson.toJson(books);
}
}
|
package ru.job4j.map;
import javafx.beans.binding.ObjectExpression;
public class Map<K, V> {
public Object[] container = new Object[10];
private int capacity = 10;
private int index = 0;
public Object[] ensureCapacity(int length) {
capacity = capacity + length;
Object[] newArray = new Object[capacity];
for (int i = 0; i < container.length; i++) {
if (container[i] != null) {
int cell = Math.abs(i % newArray.length);
if (newArray[cell] == null) {
newArray[cell] = container[i];
}
}
}
return newArray;
}
public int getCell(K key) {
return Math.abs(key.hashCode() % container.length);
}
public boolean addEntry(Object[] array, K key, V value) {
int cell = getCell(key);
if (array[cell] == null) {
array[cell] = value;
index++;
return true;
} else {
return false;
}
}
public boolean insert(K key, V value) {
if (index > container.length - 1) {
container = ensureCapacity(index + 10);
}
return addEntry(container, key, value);
}
public V get(K key) {
int cell = getCell(key);
return (V) container[cell];
}
public boolean delete(K key) {
int cell = getCell(key);
if (container[cell] != null) {
container[cell] = null;
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Entry<Integer, String> entry1 = new Entry<>(1, "first");
Entry<Integer, String> entry2 = new Entry<>(2, "second");
Entry<Integer, String> entry3 = new Entry<>(3, "third");
Map<Integer, String> map = new Map<>();
map.insert(entry1.key, entry1.value);
map.insert(entry2.key, entry2.value);
map.insert(entry3.key, entry3.value);
for (int i = 0; i < map.container.length; i++) {
System.out.println(i+ ") " + map.container[i]);
}
}
}
|
package jp.takke.cpustats;
import java.util.ArrayList;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.preference.PreferenceManager;
class OneCpuInfo {
long idle = 0;
long total = 0;
}
public class UsageUpdateService extends Service {
private static final int MY_USAGE_NOTIFICATION_ID = 1;
private static final int MY_FREQ_NOTIFICATION_ID = 2;
private long mIntervalMs = C.PREF_DEFAULT_UPDATE_INTERVAL_SEC * 1000;
private boolean mShowUsageNotification = true;
private boolean mShowFrequencyNotification = false;
private boolean mStopResident = false;
private boolean mSleeping = false;
// CPU min/max
private int mMinFreq = -1;
private String mMinFreqText = "";
private int mMaxFreq = -1;
private String mMaxFreqText = "";
// CPU
private int mLastCpuClock = -1;
private ArrayList<OneCpuInfo> mLastInfo = null;
private int[] mLastCpuUsages = null;
private final RemoteCallbackList<IUsageUpdateCallback> mCallbackList = new RemoteCallbackList<IUsageUpdateCallback>();
private int mCallbackListSize = 0;
private final IUsageUpdateService.Stub mBinder = new IUsageUpdateService.Stub() {
public void registerCallback(IUsageUpdateCallback callback) throws RemoteException {
mCallbackList.register(callback);
mCallbackListSize ++;
}
public void unregisterCallback(IUsageUpdateCallback callback) throws RemoteException {
mCallbackList.unregister(callback);
if (mCallbackListSize > 0) {
mCallbackListSize
}
}
public void stopResident() throws RemoteException {
UsageUpdateService.this.stopResident();
}
public void startResident() throws RemoteException {
mStopResident = false;
// onStart
UsageUpdateService.this.scheduleNextTime(100);
}
public void reloadSettings() throws RemoteException {
loadSettings();
if (!mShowUsageNotification) {
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(MY_USAGE_NOTIFICATION_ID);
}
if (!mShowFrequencyNotification) {
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(MY_FREQ_NOTIFICATION_ID);
}
}
};
/**
* (SCREEN_ON/OFF)
*/
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
MyLog.d("screen on");
mSleeping = false;
// onStart
mNotificationTimeKeep = System.currentTimeMillis() + 30*1000;
UsageUpdateService.this.scheduleNextTime(mIntervalMs);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
MyLog.d("screen off");
mSleeping = true;
stopAlarm();
}
}
};
@Override
public IBinder onBind(Intent intent) {
if (IUsageUpdateService.class.getName().equals(intent.getAction())) {
return mBinder;
}
return null;
}
@Override
public void onCreate() {
super.onCreate();
MyLog.d("UsageUpdateService.onCreate");
loadSettings();
if (mLastInfo == null) {
mLastInfo = MyUtil.takeCpuUsageSnapshot();
}
getApplicationContext().registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
getApplicationContext().registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
scheduleNextTime(mIntervalMs);
}
private void loadSettings() {
MyLog.i("load settings");
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
final String updateIntervalSec = pref.getString(C.PREF_KEY_UPDATE_INTERVAL_SEC, ""+C.PREF_DEFAULT_UPDATE_INTERVAL_SEC);
try {
mIntervalMs = (int)(Double.parseDouble(updateIntervalSec) * 1000.0);
MyLog.i(" interval[" + mIntervalMs + "ms]");
} catch (NumberFormatException e) {
MyLog.e(e);
}
// CPU
mShowUsageNotification = pref.getBoolean(C.PREF_KEY_SHOW_USAGE_NOTIFICATION, true);
mShowFrequencyNotification = pref.getBoolean(C.PREF_KEY_SHOW_FREQUENCY_NOTIFICATION, false);
}
@SuppressWarnings("deprecation")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
MyLog.d("UsageUpdateService.onStart");
// TODO Task
execTask();
}
private void execTask() {
// CPU
final int currentCpuClock = MyUtil.takeCurrentCpuFreq();
if (mMinFreq < 0) {
mMinFreq = MyUtil.takeMinCpuFreq();
mMinFreqText = MyUtil.formatFreq(mMinFreq);
}
if (mMaxFreq < 0) {
mMaxFreq = MyUtil.takeMaxCpuFreq();
mMaxFreqText = MyUtil.formatFreq(mMaxFreq);
}
if (MyLog.debugMode) {
MyLog.d("CPU:" + currentCpuClock + " [" + mMinFreq + "," + mMaxFreq + "]");
}
// CPU
// CPU snapshot
final ArrayList<OneCpuInfo> currentInfo = MyUtil.takeCpuUsageSnapshot();
// CPU
final int[] cpuUsages = MyUtil.calcCpuUsages(currentInfo, mLastInfo);
// CPU
boolean updated = false;
if (mLastCpuClock != currentCpuClock) {
updated = true;
} else if (mLastCpuUsages == null || cpuUsages == null) {
updated = true;
} else if (cpuUsages.length != mLastCpuUsages.length) {
// (Galaxy S II)
updated = true;
} else {
final int n = cpuUsages.length;
for (int i=0; i<n; i++) {
if (cpuUsages[i] != mLastCpuUsages[i]) {
updated = true;
break;
}
}
}
mLastCpuUsages = cpuUsages;
mLastCpuClock = currentCpuClock;
if (!updated) {
if (MyLog.debugMode) {
MyLog.d(" skipping caused by no diff.");
}
} else {
updateCpuUsageNotifications(cpuUsages, currentCpuClock);
if (mCallbackListSize >= 1) {
final int n = mCallbackList.beginBroadcast();
mCallbackListSize = n;
if (MyLog.debugMode) {
MyLog.d(" broadcast:" + n);
}
for (int i=0; i<n; i++) {
try {
mCallbackList.getBroadcastItem(i).updateUsage(cpuUsages, currentCpuClock);
} catch (RemoteException e) {
// MyLog.e(e);
}
}
mCallbackList.finishBroadcast();
}
}
// snapshot
mLastInfo = currentInfo;
scheduleNextTime(mIntervalMs);
}
@Override
public void onDestroy() {
MyLog.d("UsageUpdateService.onDestroy");
getApplicationContext().unregisterReceiver(mReceiver);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancelAll();
super.onDestroy();
}
private long mNotificationTime = 0;
protected long mNotificationTimeKeep = 0;
@SuppressWarnings("deprecation")
private void updateCpuUsageNotifications(int[] cpuUsages, int currentCpuClock) {
final long now = System.currentTimeMillis();
if (now > mNotificationTime + 3*60*1000 && now > mNotificationTimeKeep) {
mNotificationTime = now;
}
final NotificationManager nm = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE));
final Intent intent = new Intent(this, PreviewActivity.class);
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
if (cpuUsages != null && mShowUsageNotification) {
final String notificationTitle0 = "CPU Usage";
// Notification.Builder API Level11
final int iconId = ResourceUtil.getIconIdForCpuUsage(cpuUsages);
final Notification notification = new Notification(iconId, notificationTitle0, mNotificationTime);
notification.flags = Notification.FLAG_ONGOING_EVENT;
// Lollipop:
setPriorityForKeyguardOnLollipop(notification);
final StringBuilder sb = new StringBuilder(128);
if (cpuUsages.length >= 3) {
sb.append("Cores: ");
for (int i=1; i<cpuUsages.length; i++) {
if (i>=2) {
sb.append(" ");
}
sb.append(cpuUsages[i]).append("%");
}
}
final String notificationContent = sb.toString();
if (MyLog.debugMode) {
MyLog.d(" " + notificationContent);
}
final String notificationTitle = "CPU Usage " + cpuUsages[0] + "%";
notification.setLatestEventInfo(this, notificationTitle, notificationContent, pendingIntent);
nm.notify(MY_USAGE_NOTIFICATION_ID, notification);
}
if (currentCpuClock > 0 && mShowFrequencyNotification) {
final String notificationTitle0 = "CPU Frequency";
// Notification.Builder API Level11
final int iconId = ResourceUtil.getIconIdForCpuFreq(currentCpuClock);
final Notification notification = new Notification(iconId, notificationTitle0, mNotificationTime);
notification.flags = Notification.FLAG_ONGOING_EVENT;
// Lollipop:
setPriorityForKeyguardOnLollipop(notification);
final String notificationTitle = "CPU Frequency " + MyUtil.formatFreq(currentCpuClock);
final String notificationContent = "Max Freq " + mMaxFreqText + " Min Freq " + mMinFreqText;
notification.setLatestEventInfo(this, notificationTitle, notificationContent, pendingIntent);
nm.notify(MY_FREQ_NOTIFICATION_ID, notification);
}
}
private void setPriorityForKeyguardOnLollipop(Notification notification) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return;
}
final KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if (km.inKeyguardRestrictedInputMode()) {
MyLog.d("set notification priority: min");
// same as: notification.priority = Notification.PRIORITY_MIN;
try {
final int Notification_PRIORITY_MIN = -2; // Notification.PRIORITY_MIN
notification.getClass().getField("priority").setInt(notification, Notification_PRIORITY_MIN);
} catch (Exception e) {
MyLog.e(e);
}
}
}
public void scheduleNextTime(long intervalMs) {
if (mStopResident) {
return;
}
if (mSleeping) {
return;
}
final long now = System.currentTimeMillis();
final Intent intent = new Intent(this, this.getClass());
final PendingIntent alarmSender = PendingIntent.getService(
this,
0,
intent,
0
);
final AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC, now + intervalMs, alarmSender);
MyLog.d(" scheduled[" + intervalMs + "]");
}
public void stopResident() {
mStopResident = true;
stopAlarm();
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancelAll();
stopSelf();
}
private void stopAlarm() {
final Intent intent = new Intent(this, this.getClass());
final PendingIntent pendingIntent = PendingIntent.getService(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
final AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
}
}
|
package org.hisp.dhis.android.app;
import android.app.Application;
import org.hisp.dhis.android.app.selector.SelectorPresenter;
import org.hisp.dhis.android.app.selector.SelectorPresenterImpl;
import org.hisp.dhis.android.app.sync.SyncWrapper;
import org.hisp.dhis.client.sdk.core.D2;
import org.hisp.dhis.client.sdk.core.trackedentity.TrackedEntityDataValueInteractor;
import org.hisp.dhis.client.sdk.core.trackedentity.TrackedEntityDataValueInteractorImpl;
import org.hisp.dhis.client.sdk.core.user.UserInteractor;
import org.hisp.dhis.client.sdk.ui.AppPreferences;
import org.hisp.dhis.client.sdk.ui.AppPreferencesImpl;
import org.hisp.dhis.client.sdk.ui.bindings.commons.ApiExceptionHandler;
import org.hisp.dhis.client.sdk.ui.bindings.commons.ApiExceptionHandlerImpl;
import org.hisp.dhis.client.sdk.ui.bindings.commons.SyncDateWrapper;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.HomePresenter;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.HomePresenterImpl;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.LauncherPresenter;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.LauncherPresenterImpl;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.LoginPresenter;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.LoginPresenterImpl;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.ProfilePresenter;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.ProfilePresenterImpl;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.SettingsPresenter;
import org.hisp.dhis.client.sdk.ui.bindings.presenters.SettingsPresenterImpl;
import org.hisp.dhis.client.sdk.utils.Logger;
import javax.annotation.Nullable;
import dagger.Module;
import dagger.Provides;
import static org.hisp.dhis.client.sdk.utils.StringUtils.isEmpty;
@Module
public final class UserModule {
private D2 sdkInstance;
public UserModule(Application application) {
this.sdkInstance = D2.builder(application).build();
}
public UserModule(Application application, String serverUrl) {
if (isEmpty(serverUrl)) {
throw new IllegalArgumentException("serverUrl must not be null");
}
try {
this.sdkInstance = D2.builder(application)
.baseUrl(serverUrl)
.build();
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("serverUrl must be valid", e);
}
}
@Provides
@PerUser
public D2 sdkInstance() {
return sdkInstance;
}
@Provides
@PerUser
@Nullable
public UserInteractor userInteractor(D2 d2) {
if (!isEmpty(d2.serverUrl())) {
return d2.me();
}
return null;
}
@Provides
@PerUser
public ApiExceptionHandler apiExceptionHandler(Logger logger) {
return new ApiExceptionHandlerImpl(sdkInstance.application().getApplicationContext(), logger);
}
@Provides
@PerUser
public LauncherPresenter launcherPresenter(@Nullable UserInteractor userInteractor) {
return new LauncherPresenterImpl(userInteractor);
}
@Provides
@PerUser
public LoginPresenter loginPresenter(@Nullable UserInteractor userInteractor, ApiExceptionHandler apiExceptionHandler, Logger logger) {
return new LoginPresenterImpl(userInteractor, apiExceptionHandler, logger);
}
@Provides
@PerUser
public AppPreferences appPreferences() {
return new AppPreferencesImpl(sdkInstance.application().getApplicationContext());
}
@Provides
@PerUser
public SyncDateWrapper syncDateWrapper(@Nullable AppPreferences appPreferences) {
return new SyncDateWrapper(appPreferences);
}
@Provides
@PerUser
public HomePresenter homePresenter(@Nullable UserInteractor userInteractor, Logger logger) {
return new HomePresenterImpl(userInteractor, null, logger);
}
@Provides
@PerUser
public ProfilePresenter profilePresenter(@Nullable UserInteractor userInteractor, Logger logger) {
return new ProfilePresenterImpl(userInteractor, null, null, null, logger);
}
@Provides
@PerUser
public SettingsPresenter settingsPresenter() {
return new SettingsPresenterImpl(null, null);
}
@Provides
@PerUser
public SyncWrapper syncWrapper() {
return new SyncWrapper(sdkInstance.organisationUnits(), sdkInstance.programs(), sdkInstance.events(), syncDateWrapper(appPreferences()));
}
@Provides
@PerUser
public SelectorPresenter selectorPresenter(ApiExceptionHandler apiExceptionHandler, Logger logger) {
return new SelectorPresenterImpl(sdkInstance.organisationUnits(), sdkInstance.programs(), sdkInstance.events(), sdkInstance.trackedEntityDataValues()
, null, syncWrapper(), apiExceptionHandler, logger);
}
@Provides
@PerUser
public TrackedEntityDataValueInteractor trackedEntityDataValueInteractor() {
return new TrackedEntityDataValueInteractorImpl(null);
}
}
|
package org.wikipedia.dataclient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.wikipedia.dataclient.okhttp.OfflineCacheInterceptor;
import org.wikipedia.dataclient.page.PageSummary;
import org.wikipedia.dataclient.page.TalkPage;
import org.wikipedia.dataclient.restbase.RbDefinition;
import org.wikipedia.dataclient.restbase.RbRelatedPages;
import org.wikipedia.feed.aggregated.AggregatedFeedContent;
import org.wikipedia.feed.announcement.AnnouncementList;
import org.wikipedia.feed.configure.FeedAvailability;
import org.wikipedia.feed.onthisday.OnThisDay;
import org.wikipedia.gallery.MediaList;
import org.wikipedia.readinglist.sync.SyncedReadingLists;
import org.wikipedia.suggestededits.provider.SuggestedEditItem;
import java.util.List;
import java.util.Map;
import io.reactivex.rxjava3.core.Observable;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface RestService {
String REST_API_PREFIX = "/api/rest_v1";
String ACCEPT_HEADER_PREFIX = "application/json; charset=utf-8; profile=\"https:
String ACCEPT_HEADER_SUMMARY = ACCEPT_HEADER_PREFIX + "Summary/1.2.0\"";
String ACCEPT_HEADER_DEFINITION = ACCEPT_HEADER_PREFIX + "definition/0.7.2\"";
String ACCEPT_HEADER_MOBILE_HTML = ACCEPT_HEADER_PREFIX + "Mobile-HTML/1.2.1\"";
String PAGE_HTML_ENDPOINT = "page/mobile-html/";
String PAGE_HTML_PREVIEW_ENDPOINT = "transform/wikitext/to/mobile-html/";
/**
* Gets a page summary for a given title -- for link previews
*
* @param title the page title to be used including prefix
*/
@Headers({
"x-analytics: preview=1",
"Accept: " + ACCEPT_HEADER_SUMMARY
})
@GET("page/summary/{title}")
@NonNull
Observable<Response<PageSummary>> getSummaryResponse(@NonNull @Path("title") String title,
@Nullable @Header("Referer") String referrerUrl,
@Nullable @Header("Cache-Control") String cacheControl,
@Nullable @Header(OfflineCacheInterceptor.SAVE_HEADER) String saveHeader,
@Nullable @Header(OfflineCacheInterceptor.LANG_HEADER) String langHeader,
@Nullable @Header(OfflineCacheInterceptor.TITLE_HEADER) String titleHeader);
@Headers({
"x-analytics: preview=1",
"Accept: " + ACCEPT_HEADER_SUMMARY
})
@GET("page/summary/{title}")
@NonNull
Observable<PageSummary> getSummary(@Nullable @Header("Referer") String referrerUrl,
@NonNull @Path("title") String title);
// todo: this Content Service-only endpoint is under page/ but that implementation detail should
// probably not be reflected here. Move to WordDefinitionClient
/**
* Gets selected Wiktionary content for a given title derived from user-selected text
*
* @param title the Wiktionary page title derived from user-selected Wikipedia article text
*/
@Headers("Accept: " + ACCEPT_HEADER_DEFINITION)
@GET("page/definition/{title}")
@NonNull Observable<Map<String, RbDefinition.Usage[]>> getDefinition(@NonNull @Path("title") String title);
@Headers("Accept: " + ACCEPT_HEADER_SUMMARY)
@GET("page/random/summary")
@NonNull Observable<PageSummary> getRandomSummary();
@Headers("Accept: " + ACCEPT_HEADER_SUMMARY)
@GET("page/related/{title}")
@NonNull Observable<RbRelatedPages> getRelatedPages(@Path("title") String title);
@GET("page/media-list/{title}/{revision}")
@NonNull Observable<MediaList> getMediaList(@NonNull @Path("title") String title,
@Path("revision") long revision);
@GET("page/media-list/{title}/{revision}")
@NonNull Observable<Response<MediaList>> getMediaListResponse(@Path("title") String title,
@Path("revision") long revision,
@Nullable @Header("Cache-Control") String cacheControl,
@Nullable @Header(OfflineCacheInterceptor.SAVE_HEADER) String saveHeader,
@Nullable @Header(OfflineCacheInterceptor.LANG_HEADER) String langHeader,
@Nullable @Header(OfflineCacheInterceptor.TITLE_HEADER) String titleHeader);
@GET("feed/onthisday/events/{mm}/{dd}")
@NonNull Observable<OnThisDay> getOnThisDay(@Path("mm") int month, @Path("dd") int day);
@Headers("Accept: " + ACCEPT_HEADER_PREFIX + "announcements/0.1.0\"")
@GET("feed/announcements")
@NonNull Observable<AnnouncementList> getAnnouncements();
@Headers("Accept: " + ACCEPT_HEADER_PREFIX + "aggregated-feed/0.5.0\"")
@GET("feed/featured/{year}/{month}/{day}")
@NonNull Observable<AggregatedFeedContent> getAggregatedFeed(@Path("year") String year,
@Path("month") String month,
@Path("day") String day);
@GET("feed/availability")
@NonNull Observable<FeedAvailability> getFeedAvailability();
@Headers("Cache-Control: no-cache")
@POST("data/lists/setup")
@NonNull Call<Void> setupReadingLists(@Query("csrf_token") String token);
@Headers("Cache-Control: no-cache")
@POST("data/lists/teardown")
@NonNull Call<Void> tearDownReadingLists(@Query("csrf_token") String token);
@Headers("Cache-Control: no-cache")
@GET("data/lists/")
@NonNull Call<SyncedReadingLists> getReadingLists(@Query("next") String next);
@Headers("Cache-Control: no-cache")
@POST("data/lists/")
@NonNull Call<SyncedReadingLists.RemoteIdResponse> createReadingList(@Query("csrf_token") String token,
@Body SyncedReadingLists.RemoteReadingList list);
@Headers("Cache-Control: no-cache")
@PUT("data/lists/{id}")
@NonNull Call<Void> updateReadingList(@Path("id") long listId, @Query("csrf_token") String token,
@Body SyncedReadingLists.RemoteReadingList list);
@Headers("Cache-Control: no-cache")
@DELETE("data/lists/{id}")
@NonNull Call<Void> deleteReadingList(@Path("id") long listId, @Query("csrf_token") String token);
@Headers("Cache-Control: no-cache")
@GET("data/lists/changes/since/{date}")
@NonNull Call<SyncedReadingLists> getReadingListChangesSince(@Path("date") String iso8601Date,
@Query("next") String next);
@Headers("Cache-Control: no-cache")
@GET("data/lists/pages/{project}/{title}")
@NonNull Call<SyncedReadingLists> getReadingListsContaining(@Path("project") String project,
@Path("title") String title,
@Query("next") String next);
@Headers("Cache-Control: no-cache")
@GET("data/lists/{id}/entries/")
@NonNull Call<SyncedReadingLists> getReadingListEntries(@Path("id") long listId, @Query("next") String next);
@Headers("Cache-Control: no-cache")
@POST("data/lists/{id}/entries/")
@NonNull Call<SyncedReadingLists.RemoteIdResponse> addEntryToReadingList(@Path("id") long listId,
@Query("csrf_token") String token,
@Body SyncedReadingLists.RemoteReadingListEntry entry);
@Headers("Cache-Control: no-cache")
@POST("data/lists/{id}/entries/batch")
@NonNull Call<SyncedReadingLists.RemoteIdResponseBatch> addEntriesToReadingList(@Path("id") long listId,
@Query("csrf_token") String token,
@Body SyncedReadingLists.RemoteReadingListEntryBatch batch);
@Headers("Cache-Control: no-cache")
@DELETE("data/lists/{id}/entries/{entry_id}")
@NonNull Call<Void> deleteEntryFromReadingList(@Path("id") long listId, @Path("entry_id") long entryId,
@Query("csrf_token") String token);
@Headers("Cache-Control: no-cache")
@GET("data/recommendation/caption/addition/{lang}")
@NonNull
Observable<List<SuggestedEditItem>> getImagesWithoutCaptions(@NonNull @Path("lang") String lang);
@Headers("Cache-Control: no-cache")
@GET("data/recommendation/caption/translation/from/{fromLang}/to/{toLang}")
@NonNull
Observable<List<SuggestedEditItem>> getImagesWithTranslatableCaptions(@NonNull @Path("fromLang") String fromLang,
@NonNull @Path("toLang") String toLang);
@Headers("Cache-Control: no-cache")
@GET("data/recommendation/description/addition/{lang}")
@NonNull
Observable<List<SuggestedEditItem>> getArticlesWithoutDescriptions(@NonNull @Path("lang") String lang);
@Headers("Cache-Control: no-cache")
@GET("data/recommendation/description/translation/from/{fromLang}/to/{toLang}")
@NonNull
Observable<List<SuggestedEditItem>> getArticlesWithTranslatableDescriptions(@NonNull @Path("fromLang") String fromLang,
@NonNull @Path("toLang") String toLang);
@Headers("Cache-Control: no-cache")
@GET("page/talk/User_talk:{user}")
@NonNull
Observable<TalkPage> getTalkPage(@NonNull @Path("user") String user);
}
|
package net.md_5.bungee;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import java.util.Objects;
import java.util.Queue;
import lombok.RequiredArgsConstructor;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.event.ServerKickEvent;
import net.md_5.bungee.api.event.ServerSwitchEvent;
import net.md_5.bungee.api.score.Objective;
import net.md_5.bungee.api.score.Scoreboard;
import net.md_5.bungee.api.score.Team;
import net.md_5.bungee.chat.ComponentSerializer;
import net.md_5.bungee.connection.CancelSendSignal;
import net.md_5.bungee.connection.DownstreamBridge;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.PacketHandler;
import net.md_5.bungee.protocol.MinecraftOutput;
import net.md_5.bungee.protocol.DefinedPacket;
import net.md_5.bungee.protocol.Protocol;
import net.md_5.bungee.protocol.packet.EncryptionRequest;
import net.md_5.bungee.protocol.packet.Handshake;
import net.md_5.bungee.protocol.packet.Login;
import net.md_5.bungee.protocol.packet.Respawn;
import net.md_5.bungee.protocol.packet.ScoreboardObjective;
import net.md_5.bungee.protocol.packet.PluginMessage;
import net.md_5.bungee.protocol.packet.Kick;
import net.md_5.bungee.protocol.packet.LoginSuccess;
@RequiredArgsConstructor
public class ServerConnector extends PacketHandler
{
private final ProxyServer bungee;
private ChannelWrapper ch;
private final UserConnection user;
private final BungeeServerInfo target;
private State thisState = State.LOGIN_SUCCESS;
private enum State
{
LOGIN_SUCCESS, ENCRYPT_RESPONSE, LOGIN, FINISHED;
}
@Override
public void exception(Throwable t) throws Exception
{
String message = "Exception Connecting:" + Util.exception( t );
if ( user.getServer() == null )
{
user.disconnect( message );
} else
{
user.sendMessage( ChatColor.RED + message );
}
}
@Override
public void connected(ChannelWrapper channel) throws Exception
{
this.ch = channel;
Handshake originalHandshake = user.getPendingConnection().getHandshake();
Handshake copiedHandshake = new Handshake( originalHandshake.getProtocolVersion(), originalHandshake.getHost(), originalHandshake.getPort(), 2 );
if ( BungeeCord.getInstance().config.isIpFoward() )
{
copiedHandshake.setHost( copiedHandshake.getHost() + "\00" + user.getAddress().getHostString() + "\00" + user.getUUID() );
}
channel.write( copiedHandshake );
channel.setProtocol( Protocol.LOGIN );
channel.write( user.getPendingConnection().getLoginRequest() );
}
@Override
public void disconnected(ChannelWrapper channel) throws Exception
{
user.getPendingConnects().remove( target );
}
@Override
public void handle(LoginSuccess loginSuccess) throws Exception
{
Preconditions.checkState( thisState == State.LOGIN_SUCCESS, "Not exepcting LOGIN_SUCCESS" );
ch.setProtocol( Protocol.GAME );
thisState = State.LOGIN;
throw new CancelSendSignal();
}
@Override
public void handle(Login login) throws Exception
{
Preconditions.checkState( thisState == State.LOGIN, "Not exepcting LOGIN" );
ServerConnection server = new ServerConnection( ch, target );
ServerConnectedEvent event = new ServerConnectedEvent( user, server );
bungee.getPluginManager().callEvent( event );
ch.write( BungeeCord.getInstance().registerChannels() );
Queue<DefinedPacket> packetQueue = target.getPacketQueue();
synchronized ( packetQueue )
{
while ( !packetQueue.isEmpty() )
{
ch.write( packetQueue.poll() );
}
}
if ( user.getSettings() != null )
{
ch.write( user.getSettings() );
}
synchronized ( user.getSwitchMutex() )
{
if ( user.getServer() == null )
{
// Once again, first connection
user.setClientEntityId( login.getEntityId() );
user.setServerEntityId( login.getEntityId() );
// Set tab list size, this sucks balls, TODO: what shall we do about packet mutability
Login modLogin = new Login( login.getEntityId(), login.getGameMode(), (byte) login.getDimension(), login.getDifficulty(),
(byte) user.getPendingConnection().getListener().getTabListSize(), login.getLevelType() );
user.unsafe().sendPacket( modLogin );
MinecraftOutput out = new MinecraftOutput();
out.writeStringUTF8WithoutLengthHeaderBecauseDinnerboneStuffedUpTheMCBrandPacket( ProxyServer.getInstance().getName() + " (" + ProxyServer.getInstance().getVersion() + ")" );
user.unsafe().sendPacket( new PluginMessage( "MC|Brand", out.toArray() ) );
} else
{
user.getTabList().onServerChange();
Scoreboard serverScoreboard = user.getServerSentScoreboard();
for ( Objective objective : serverScoreboard.getObjectives() )
{
user.unsafe().sendPacket( new ScoreboardObjective( objective.getName(), objective.getValue(), (byte) 1 ) );
}
for ( Team team : serverScoreboard.getTeams() )
{
user.unsafe().sendPacket( new net.md_5.bungee.protocol.packet.Team( team.getName() ) );
}
serverScoreboard.clear();
user.sendDimensionSwitch();
user.setServerEntityId( login.getEntityId() );
user.unsafe().sendPacket( new Respawn( login.getDimension(), login.getDifficulty(), login.getGameMode(), login.getLevelType() ) );
// Remove from old servers
user.getServer().setObsolete( true );
user.getServer().disconnect( "Quitting" );
}
// TODO: Fix this?
if ( !user.isActive() )
{
server.disconnect( "Quitting" );
// Silly server admins see stack trace and die
bungee.getLogger().warning( "No client connected for pending server!" );
return;
}
// Add to new server
// TODO: Move this to the connected() method of DownstreamBridge
target.addPlayer( user );
user.getPendingConnects().remove( target );
user.setDimensionChange( false );
user.setServer( server );
ch.getHandle().pipeline().get( HandlerBoss.class ).setHandler( new DownstreamBridge( bungee, user, server ) );
}
bungee.getPluginManager().callEvent( new ServerSwitchEvent( user ) );
thisState = State.FINISHED;
throw new CancelSendSignal();
}
@Override
public void handle(EncryptionRequest encryptionRequest) throws Exception
{
throw new RuntimeException( "Server is online mode!" );
}
@Override
public void handle(Kick kick) throws Exception
{
ServerInfo def = bungee.getServerInfo( user.getPendingConnection().getListener().getFallbackServer() );
if ( Objects.equals( target, def ) )
{
def = null;
}
ServerKickEvent event = bungee.getPluginManager().callEvent( new ServerKickEvent( user, ComponentSerializer.parse( kick.getMessage() ), def, ServerKickEvent.State.CONNECTING ) );
if ( event.isCancelled() && event.getCancelServer() != null )
{
user.connect( event.getCancelServer() );
throw new CancelSendSignal();
}
String message = bungee.getTranslation( "connect_kick" ) + target.getName() + ": " + event.getKickReason();
if ( user.isDimensionChange() )
{
user.disconnect( message );
} else
{
user.sendMessage( message );
}
throw new CancelSendSignal();
}
@Override
public String toString()
{
return "[" + user.getName() + "] <-> ServerConnector [" + target.getName() + "]";
}
}
|
package com.fsck.k9.activity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import com.fsck.k9.Account;
import com.fsck.k9.Account.FolderMode;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.activity.FolderListFilter.FolderAdapter;
import com.fsck.k9.controller.MessageReference;
import com.fsck.k9.ui.R;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.controller.MessagingListener;
import com.fsck.k9.controller.SimpleMessagingListener;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mailstore.LocalFolder;
import com.fsck.k9.ui.folders.FolderIconProvider;
import timber.log.Timber;
import static java.util.Collections.emptyList;
public class ChooseFolder extends K9ListActivity {
public static final String EXTRA_ACCOUNT = "com.fsck.k9.ChooseFolder_account";
public static final String EXTRA_CUR_FOLDER = "com.fsck.k9.ChooseFolder_curfolder";
public static final String EXTRA_SEL_FOLDER = "com.fsck.k9.ChooseFolder_selfolder";
public static final String EXTRA_NEW_FOLDER = "com.fsck.k9.ChooseFolder_newfolder";
public static final String EXTRA_MESSAGE = "com.fsck.k9.ChooseFolder_message";
public static final String EXTRA_SHOW_CURRENT = "com.fsck.k9.ChooseFolder_showcurrent";
public static final String EXTRA_SHOW_DISPLAYABLE_ONLY = "com.fsck.k9.ChooseFolder_showDisplayableOnly";
public static final String RESULT_FOLDER_DISPLAY_NAME = "folderDisplayName";
private String currentFolder;
private String selectFolder;
private Account account;
private MessageReference messageReference;
private FolderListAdapter listAdapter;
private ChooseFolderHandler handler = new ChooseFolderHandler();
private boolean hideCurrentFolder = true;
private boolean showDisplayableOnly = false;
/**
* What folders to display.<br/>
* Initialized to whatever is configured
* but can be overridden via {@link #onOptionsItemSelected(MenuItem)}
* while this activity is showing.
*/
private Account.FolderMode mode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setLayout(R.layout.list_content_simple);
getListView().setFastScrollEnabled(true);
getListView().setItemsCanFocus(false);
getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
Intent intent = getIntent();
String accountUuid = intent.getStringExtra(EXTRA_ACCOUNT);
account = Preferences.getPreferences(this).getAccount(accountUuid);
if (intent.hasExtra(EXTRA_MESSAGE)) {
String messageReferenceString = intent.getStringExtra(EXTRA_MESSAGE);
messageReference = MessageReference.parse(messageReferenceString);
}
currentFolder = intent.getStringExtra(EXTRA_CUR_FOLDER);
selectFolder = intent.getStringExtra(EXTRA_SEL_FOLDER);
if (intent.getStringExtra(EXTRA_SHOW_CURRENT) != null) {
hideCurrentFolder = false;
}
if (intent.getStringExtra(EXTRA_SHOW_DISPLAYABLE_ONLY) != null) {
showDisplayableOnly = true;
}
if (currentFolder == null)
currentFolder = "";
listAdapter = new FolderListAdapter();
setListAdapter(listAdapter);
mode = account.getFolderTargetMode();
MessagingController.getInstance(getApplication()).listFolders(account, false, mListener);
this.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FolderInfoHolder folder = listAdapter.getItem(position);
if (folder == null) {
throw new AssertionError("Couldn't get item at adapter position " + position);
}
Intent result = new Intent();
result.putExtra(EXTRA_ACCOUNT, account.getUuid());
result.putExtra(EXTRA_CUR_FOLDER, currentFolder);
String targetFolder = folder.serverId;
result.putExtra(EXTRA_NEW_FOLDER, targetFolder);
if (messageReference != null) {
result.putExtra(EXTRA_MESSAGE, messageReference.toIdentityString());
}
result.putExtra(RESULT_FOLDER_DISPLAY_NAME, folder.displayName);
setResult(RESULT_OK, result);
finish();
}
});
}
class ChooseFolderHandler extends Handler {
private static final int MSG_PROGRESS = 1;
private static final int MSG_SET_SELECTED_FOLDER = 2;
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_PROGRESS: {
setProgressBarIndeterminateVisibility(msg.arg1 != 0);
break;
}
case MSG_SET_SELECTED_FOLDER: {
getListView().setSelection(msg.arg1);
break;
}
}
}
public void progress(boolean progress) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_PROGRESS;
msg.arg1 = progress ? 1 : 0;
sendMessage(msg);
}
public void setSelectedFolder(int position) {
android.os.Message msg = new android.os.Message();
msg.what = MSG_SET_SELECTED_FOLDER;
msg.arg1 = position;
sendMessage(msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.folder_select_option, menu);
configureFolderSearchView(menu);
return true;
}
private void configureFolderSearchView(Menu menu) {
final MenuItem folderMenuItem = menu.findItem(R.id.filter_folders);
final SearchView folderSearchView = (SearchView) folderMenuItem.getActionView();
folderSearchView.setQueryHint(getString(R.string.folder_list_filter_hint));
folderSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
folderMenuItem.collapseActionView();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
listAdapter.getFilter().filter(newText);
return true;
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.display_1st_class) {
setDisplayMode(FolderMode.FIRST_CLASS);
return true;
} else if (id == R.id.display_1st_and_2nd_class) {
setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS);
return true;
} else if (id == R.id.display_not_second_class) {
setDisplayMode(FolderMode.NOT_SECOND_CLASS);
return true;
} else if (id == R.id.display_all) {
setDisplayMode(FolderMode.ALL);
return true;
} else if (id == R.id.list_folders) {
onRefresh();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
private void onRefresh() {
MessagingController.getInstance(getApplication()).listFolders(account, true, mListener);
}
private void setDisplayMode(FolderMode aMode) {
mode = aMode;
//re-populate the list
MessagingController.getInstance(getApplication()).listFolders(account, false, mListener);
}
private MessagingListener mListener = new SimpleMessagingListener() {
@Override
public void listFoldersStarted(Account account) {
if (!account.equals(ChooseFolder.this.account)) {
return;
}
handler.progress(true);
}
@Override
public void listFoldersFailed(Account account, String message) {
if (!account.equals(ChooseFolder.this.account)) {
return;
}
handler.progress(false);
}
@Override
public void listFoldersFinished(Account account) {
if (!account.equals(ChooseFolder.this.account)) {
return;
}
handler.progress(false);
}
@Override
public void listFolders(Account account, List<LocalFolder> folders) {
if (!account.equals(ChooseFolder.this.account)) {
return;
}
Account.FolderMode aMode = mode;
List<FolderInfoHolder> newFolders = new ArrayList<>();
List<FolderInfoHolder> topFolders = new ArrayList<>();
for (LocalFolder folder : folders) {
String serverId = folder.getServerId();
if (hideCurrentFolder && serverId.equals(currentFolder)) {
continue;
}
if (account.getOutboxFolder().equals(serverId)) {
continue;
}
Folder.FolderClass fMode = folder.getDisplayClass();
if ((aMode == FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS) || (
aMode == FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS) || (
aMode == FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS)) {
continue;
}
FolderInfoHolder folderDisplayData = new FolderInfoHolder(folder, account);
if (folder.isInTopGroup()) {
topFolders.add(folderDisplayData);
} else {
newFolders.add(folderDisplayData);
}
}
final Comparator<FolderInfoHolder> comparator = new Comparator<FolderInfoHolder>() {
@Override
public int compare(FolderInfoHolder lhs, FolderInfoHolder rhs) {
int result = lhs.displayName.compareToIgnoreCase(rhs.displayName);
return (result != 0) ? result : lhs.displayName.compareTo(rhs.displayName);
}
};
Collections.sort(topFolders, comparator);
Collections.sort(newFolders, comparator);
final List<FolderInfoHolder> folderList = new ArrayList<>(newFolders.size() + topFolders.size());
folderList.addAll(topFolders);
folderList.addAll(newFolders);
int selectedFolder = -1;
/*
* We're not allowed to change the adapter from a background thread, so we collect the
* folder names and update the adapter in the UI thread (see finally block).
*/
try {
int position = 0;
for (FolderInfoHolder folder : folderList) {
if (selectFolder != null) {
/*
* Never select EXTRA_CUR_FOLDER (mFolder) if EXTRA_SEL_FOLDER
* (mSelectedFolder) was provided.
*/
if (folder.serverId.equals(selectFolder)) {
selectedFolder = position;
break;
}
} else if (folder.serverId.equals(currentFolder)) {
selectedFolder = position;
break;
}
position++;
}
} finally {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Now we're in the UI-thread, we can safely change the contents of the adapter.
listAdapter.setFolders(folderList);
}
});
}
if (selectedFolder != -1) {
handler.setSelectedFolder(selectedFolder);
}
}
};
class FolderListAdapter extends BaseAdapter implements Filterable, FolderAdapter {
private List<FolderInfoHolder> mFolders = emptyList();
private List<FolderInfoHolder> mFilteredFolders = emptyList();
private Filter mFilter = new FolderListFilter(this, mFolders);
private FolderIconProvider folderIconProvider = new FolderIconProvider(getTheme());
private CharSequence filterText;
public FolderInfoHolder getItem(long position) {
return getItem((int)position);
}
@Override
public FolderInfoHolder getItem(int position) {
return mFilteredFolders.get(position);
}
@Override
public long getItemId(int position) {
return mFilteredFolders.get(position).folder.getDatabaseId();
}
@Override
public int getCount() {
return mFilteredFolders.size();
}
@Override
public boolean isEnabled(int item) {
return true;
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position <= getCount()) {
return getItemView(position, convertView, parent);
} else {
Timber.e("getView with illegal position=%d called! count is only %d", position, getCount());
return null;
}
}
public View getItemView(int itemPosition, View convertView, ViewGroup parent) {
FolderInfoHolder folder = getItem(itemPosition);
View view;
if (convertView != null) {
view = convertView;
} else {
view = View.inflate(ChooseFolder.this, R.layout.choose_folder_list_item, null);
}
FolderViewHolder holder = (FolderViewHolder) view.getTag();
if (holder == null) {
holder = new FolderViewHolder();
holder.folderName = view.findViewById(R.id.folder_name);
holder.folderIcon = view.findViewById(R.id.folder_icon);
holder.folderListItemLayout = view.findViewById(R.id.folder_list_item_layout);
view.setTag(holder);
}
if (folder == null) {
return view;
}
holder.folderName.setText(folder.displayName);
holder.folderIcon.setImageResource(folderIconProvider.getFolderIcon(folder.folder.getType()));
if (K9.isWrapFolderNames()) {
holder.folderName.setEllipsize(null);
holder.folderName.setSingleLine(false);
}
else {
holder.folderName.setEllipsize(TextUtils.TruncateAt.START);
holder.folderName.setSingleLine(true);
}
return view;
}
@Override
public boolean hasStableIds() {
return true;
}
public Filter getFilter() {
return mFilter;
}
@Override
public void setFilteredFolders(CharSequence filterText, List<FolderInfoHolder> folders) {
this.filterText = filterText;
mFilteredFolders = folders;
notifyDataSetChanged();
}
void setFolders(List<FolderInfoHolder> folders) {
mFolders = folders;
mFilter = new FolderListFilter(this, folders);
mFilter.filter(filterText);
}
}
static class FolderViewHolder {
TextView folderName;
ImageView folderIcon;
LinearLayout folderListItemLayout;
}
}
|
package org.klomp.snark;
import java.util.*;
import java.io.IOException;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
/**
* Coordinates what peer does what.
*/
public class PeerCoordinator implements PeerListener
{
private final Log _log = new Log(PeerCoordinator.class);
final MetaInfo metainfo;
final Storage storage;
final Snark snark;
// package local for access by CheckDownLoadersTask
final static long CHECK_PERIOD = 40*1000; // 40 seconds
final static int MAX_CONNECTIONS = 24;
final static int MAX_UPLOADERS = 4;
// Approximation of the number of current uploaders.
// Resynced by PeerChecker once in a while.
int uploaders = 0;
int interestedAndChoking = 0;
// final static int MAX_DOWNLOADERS = MAX_CONNECTIONS;
// int downloaders = 0;
private long uploaded;
private long downloaded;
final static int RATE_DEPTH = 6; // make following arrays RATE_DEPTH long
private long uploaded_old[] = {0,0,0,0,0,0};
private long downloaded_old[] = {0,0,0,0,0,0};
// synchronize on this when changing peers or downloaders
final List peers = new ArrayList();
/** estimate of the peers, without requiring any synchronization */
volatile int peerCount;
/** Timer to handle all periodical tasks. */
private final Timer timer = new Timer(true);
private final byte[] id;
// Some random wanted pieces
private List wantedPieces;
private boolean halted = false;
private final CoordinatorListener listener;
public String trackerProblems = null;
public int trackerSeenPeers = 0;
public PeerCoordinator(byte[] id, MetaInfo metainfo, Storage storage,
CoordinatorListener listener, Snark torrent)
{
this.id = id;
this.metainfo = metainfo;
this.storage = storage;
this.listener = listener;
this.snark = torrent;
setWantedPieces();
// Install a timer to check the uploaders.
timer.schedule(new PeerCheckerTask(this), CHECK_PERIOD, CHECK_PERIOD);
}
// only called externally from Storage after the double-check fails
public void setWantedPieces()
{
// Make a list of pieces
wantedPieces = new ArrayList();
BitField bitfield = storage.getBitField();
for(int i = 0; i < metainfo.getPieces(); i++)
if (!bitfield.get(i))
wantedPieces.add(new Piece(i));
Collections.shuffle(wantedPieces);
}
public Storage getStorage() { return storage; }
public CoordinatorListener getListener() { return listener; }
// for web page detailed stats
public List peerList()
{
synchronized(peers)
{
return new ArrayList(peers);
}
}
public byte[] getID()
{
return id;
}
public boolean completed()
{
return storage.complete();
}
public int getPeerCount() { return peerCount; }
public int getPeers()
{
synchronized(peers)
{
int rv = peers.size();
peerCount = rv;
return rv;
}
}
/**
* Returns how many bytes are still needed to get the complete file.
*/
public long getLeft()
{
// XXX - Only an approximation.
return ((long) storage.needed()) * metainfo.getPieceLength(0);
}
/**
* Returns the total number of uploaded bytes of all peers.
*/
public long getUploaded()
{
return uploaded;
}
/**
* Returns the total number of downloaded bytes of all peers.
*/
public long getDownloaded()
{
return downloaded;
}
/**
* Push the total uploaded/downloaded onto a RATE_DEPTH deep stack
*/
public void setRateHistory(long up, long down)
{
setRate(up, uploaded_old);
setRate(down, downloaded_old);
}
private static void setRate(long val, long array[])
{
synchronized(array) {
for (int i = RATE_DEPTH-1; i > 0; i
array[i] = array[i-1];
array[0] = val;
}
}
/**
* Returns the 4-minute-average rate in Bps
*/
public long getDownloadRate()
{
return getRate(downloaded_old);
}
public long getUploadRate()
{
return getRate(uploaded_old);
}
private long getRate(long array[])
{
long rate = 0;
synchronized(array) {
for (int i = 0; i < RATE_DEPTH; i++)
rate += array[i];
}
return rate / (RATE_DEPTH * CHECK_PERIOD / 1000);
}
public MetaInfo getMetaInfo()
{
return metainfo;
}
public boolean needPeers()
{
synchronized(peers)
{
return !halted && peers.size() < MAX_CONNECTIONS;
}
}
public boolean halted() { return halted; }
public void halt()
{
halted = true;
List removed = new ArrayList();
synchronized(peers)
{
// Stop peer checker task.
timer.cancel();
// Stop peers.
removed.addAll(peers);
peers.clear();
peerCount = 0;
}
while (removed.size() > 0) {
Peer peer = (Peer)removed.remove(0);
peer.disconnect();
removePeerFromPieces(peer);
}
// delete any saved orphan partial piece
savedRequest = null;
}
public void connected(Peer peer)
{
if (halted)
{
peer.disconnect(false);
return;
}
Peer toDisconnect = null;
synchronized(peers)
{
Peer old = peerIDInList(peer.getPeerID(), peers);
if ( (old != null) && (old.getInactiveTime() > 4*60*1000) ) {
// idle for 4 minutes, kill the old con (64KB/4min = 273B/sec minimum for one block)
if (_log.shouldLog(Log.WARN))
_log.warn("Remomving old peer: " + peer + ": " + old + ", inactive for " + old.getInactiveTime());
peers.remove(old);
toDisconnect = old;
old = null;
}
if (old != null)
{
if (_log.shouldLog(Log.WARN))
_log.warn("Already connected to: " + peer + ": " + old + ", inactive for " + old.getInactiveTime());
// toDisconnect = peer to get out of synchronized(peers)
peer.disconnect(false); // Don't deregister this connection/peer.
}
else
{
if (_log.shouldLog(Log.INFO))
_log.info("New connection to peer: " + peer + " for " + metainfo.getName());
// Add it to the beginning of the list.
// And try to optimistically make it a uploader.
peers.add(0, peer);
peerCount = peers.size();
unchokePeer();
if (listener != null)
listener.peerChange(this, peer);
}
}
if (toDisconnect != null) {
toDisconnect.disconnect(false);
removePeerFromPieces(toDisconnect);
}
}
private static Peer peerIDInList(PeerID pid, List peers)
{
Iterator it = peers.iterator();
while (it.hasNext()) {
Peer cur = (Peer)it.next();
if (pid.sameID(cur.getPeerID()))
return cur;
}
return null;
}
// returns true if actual attempt to add peer occurs
public boolean addPeer(final Peer peer)
{
if (halted)
{
peer.disconnect(false);
return false;
}
boolean need_more;
synchronized(peers)
{
need_more = !peer.isConnected() && peers.size() < MAX_CONNECTIONS;
}
if (need_more)
{
_log.debug("Adding a peer " + peer.getPeerID().getAddress().calculateHash().toBase64() + " for " + metainfo.getName(), new Exception("add/run"));
// Run the peer with us as listener and the current bitfield.
final PeerListener listener = this;
final BitField bitfield = storage.getBitField();
Runnable r = new Runnable()
{
public void run()
{
peer.runConnection(listener, bitfield);
}
};
String threadName = peer.toString();
new I2PThread(r, threadName).start();
return true;
}
else
if (_log.shouldLog(Log.DEBUG)) {
if (peer.isConnected())
_log.info("Add peer already connected: " + peer);
else
_log.info("MAX_CONNECTIONS = " + MAX_CONNECTIONS
+ " not accepting extra peer: " + peer);
}
return false;
}
// (Optimistically) unchoke. Should be called with peers synchronized
void unchokePeer()
{
// linked list will contain all interested peers that we choke.
// At the start are the peers that have us unchoked at the end the
// other peer that are interested, but are choking us.
List interested = new LinkedList();
synchronized (peers) {
int count = 0;
int unchokedCount = 0;
int maxUploaders = allowedUploaders();
Iterator it = peers.iterator();
while (it.hasNext())
{
Peer peer = (Peer)it.next();
if (peer.isChoking() && peer.isInterested())
{
count++;
if (uploaders < maxUploaders)
{
if (!peer.isChoked())
interested.add(unchokedCount++, peer);
else
interested.add(peer);
}
}
}
while (uploaders < maxUploaders && interested.size() > 0)
{
Peer peer = (Peer)interested.remove(0);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Unchoke: " + peer);
peer.setChoking(false);
uploaders++;
count
// Put peer back at the end of the list.
peers.remove(peer);
peers.add(peer);
peerCount = peers.size();
}
interestedAndChoking = count;
}
}
public byte[] getBitMap()
{
return storage.getBitField().getFieldBytes();
}
/**
* Returns true if we don't have the given piece yet.
*/
public boolean gotHave(Peer peer, int piece)
{
if (listener != null)
listener.peerChange(this, peer);
synchronized(wantedPieces)
{
return wantedPieces.contains(new Piece(piece));
}
}
/**
* Returns true if the given bitfield contains at least one piece we
* are interested in.
*/
public boolean gotBitField(Peer peer, BitField bitfield)
{
if (listener != null)
listener.peerChange(this, peer);
synchronized(wantedPieces)
{
Iterator it = wantedPieces.iterator();
while (it.hasNext())
{
Piece p = (Piece)it.next();
int i = p.getId();
if (bitfield.get(i)) {
p.addPeer(peer);
return true;
}
}
}
return false;
}
/**
* Returns one of pieces in the given BitField that is still wanted or
* -1 if none of the given pieces are wanted.
*/
public int wantPiece(Peer peer, BitField havePieces)
{
if (halted) {
if (_log.shouldLog(Log.WARN))
_log.warn("We don't want anything from the peer, as we are halted! peer=" + peer);
return -1;
}
synchronized(wantedPieces)
{
Piece piece = null;
Collections.sort(wantedPieces); // Sort in order of rarest first.
List requested = new ArrayList();
Iterator it = wantedPieces.iterator();
while (piece == null && it.hasNext())
{
Piece p = (Piece)it.next();
if (havePieces.get(p.getId()) && !p.isRequested())
{
piece = p;
}
else if (p.isRequested())
{
requested.add(p);
}
}
//Only request a piece we've requested before if there's no other choice.
if (piece == null) {
// let's not all get on the same piece
Collections.shuffle(requested);
Iterator it2 = requested.iterator();
while (piece == null && it2.hasNext())
{
Piece p = (Piece)it2.next();
if (havePieces.get(p.getId()))
{
piece = p;
}
}
if (piece == null) {
if (_log.shouldLog(Log.WARN))
_log.warn("nothing to even rerequest from " + peer + ": requested = " + requested);
// _log.warn("nothing to even rerequest from " + peer + ": requested = " + requested
// + " wanted = " + wantedPieces + " peerHas = " + havePieces);
return -1; //If we still can't find a piece we want, so be it.
} else {
// Should be a lot smarter here - limit # of parallel attempts and
// share blocks rather than starting from 0 with each peer.
// This is where the flaws of the snark data model are really exposed.
// Could also randomize within the duplicate set rather than strict rarest-first
if (_log.shouldLog(Log.DEBUG))
_log.debug("parallel request (end game?) for " + peer + ": piece = " + piece);
}
}
piece.setRequested(true);
return piece.getId();
}
}
/**
* Returns a byte array containing the requested piece or null of
* the piece is unknown.
*/
public byte[] gotRequest(Peer peer, int piece, int off, int len)
{
if (halted)
return null;
try
{
return storage.getPiece(piece, off, len);
}
catch (IOException ioe)
{
snark.stopTorrent();
_log.error("Error reading the storage for " + metainfo.getName(), ioe);
throw new RuntimeException("B0rked");
}
}
/**
* Called when a peer has uploaded some bytes of a piece.
*/
public void uploaded(Peer peer, int size)
{
uploaded += size;
if (listener != null)
listener.peerChange(this, peer);
}
/**
* Called when a peer has downloaded some bytes of a piece.
*/
public void downloaded(Peer peer, int size)
{
downloaded += size;
if (listener != null)
listener.peerChange(this, peer);
}
/**
* Returns false if the piece is no good (according to the hash).
* In that case the peer that supplied the piece should probably be
* blacklisted.
*/
public boolean gotPiece(Peer peer, int piece, byte[] bs)
{
if (halted) {
_log.info("Got while-halted piece " + piece + "/" + metainfo.getPieces() +" from " + peer + " for " + metainfo.getName());
return true; // We don't actually care anymore.
}
synchronized(wantedPieces)
{
Piece p = new Piece(piece);
if (!wantedPieces.contains(p))
{
_log.info("Got unwanted piece " + piece + "/" + metainfo.getPieces() +" from " + peer + " for " + metainfo.getName());
// No need to announce have piece to peers.
// Assume we got a good piece, we don't really care anymore.
return true;
}
try
{
if (storage.putPiece(piece, bs))
{
_log.info("Got valid piece " + piece + "/" + metainfo.getPieces() +" from " + peer + " for " + metainfo.getName());
}
else
{
// Oops. We didn't actually download this then... :(
downloaded -= metainfo.getPieceLength(piece);
_log.warn("Got BAD piece " + piece + "/" + metainfo.getPieces() + " from " + peer + " for " + metainfo.getName());
return false; // No need to announce BAD piece to peers.
}
}
catch (IOException ioe)
{
snark.stopTorrent();
_log.error("Error writing storage for " + metainfo.getName(), ioe);
throw new RuntimeException("B0rked");
}
wantedPieces.remove(p);
}
// Announce to the world we have it!
// Disconnect from other seeders when we get the last piece
synchronized(peers)
{
List toDisconnect = new ArrayList();
Iterator it = peers.iterator();
while (it.hasNext())
{
Peer p = (Peer)it.next();
if (p.isConnected())
{
if (completed() && p.isCompleted())
toDisconnect.add(p);
else
p.have(piece);
}
}
it = toDisconnect.iterator();
while (it.hasNext())
{
Peer p = (Peer)it.next();
p.disconnect(true);
}
}
return true;
}
public void gotChoke(Peer peer, boolean choke)
{
if (_log.shouldLog(Log.INFO))
_log.info("Got choke(" + choke + "): " + peer);
if (listener != null)
listener.peerChange(this, peer);
}
public void gotInterest(Peer peer, boolean interest)
{
if (interest)
{
synchronized(peers)
{
if (uploaders < allowedUploaders())
{
if(peer.isChoking())
{
uploaders++;
peer.setChoking(false);
if (_log.shouldLog(Log.INFO))
_log.info("Unchoke: " + peer);
}
}
}
}
if (listener != null)
listener.peerChange(this, peer);
}
public void disconnected(Peer peer)
{
if (_log.shouldLog(Log.INFO))
_log.info("Disconnected " + peer, new Exception("Disconnected by"));
synchronized(peers)
{
// Make sure it is no longer in our lists
if (peers.remove(peer))
{
// Unchoke some random other peer
unchokePeer();
removePeerFromPieces(peer);
}
peerCount = peers.size();
}
if (listener != null)
listener.peerChange(this, peer);
}
/** Called when a peer is removed, to prevent it from being used in
* rarest-first calculations.
*/
public void removePeerFromPieces(Peer peer) {
synchronized(wantedPieces) {
for(Iterator iter = wantedPieces.iterator(); iter.hasNext(); ) {
Piece piece = (Piece)iter.next();
piece.removePeer(peer);
}
}
}
/** Simple method to save a partial piece on peer disconnection
* and hopefully restart it later.
* Only one partial piece is saved at a time.
* Replace it if a new one is bigger or the old one is too old.
* Storage method is private so we can expand to save multiple partials
* if we wish.
*/
private Request savedRequest = null;
private long savedRequestTime = 0;
public void savePeerPartial(PeerState state)
{
if (halted)
return;
Request req = state.getPartialRequest();
if (req == null)
return;
if (savedRequest == null ||
req.off > savedRequest.off ||
System.currentTimeMillis() > savedRequestTime + (15 * 60 * 1000)) {
if (savedRequest == null || (req.piece != savedRequest.piece && req.off != savedRequest.off)) {
if (_log.shouldLog(Log.DEBUG)) {
_log.debug(" Saving orphaned partial piece " + req);
if (savedRequest != null)
_log.debug(" (Discarding previously saved orphan) " + savedRequest);
}
}
savedRequest = req;
savedRequestTime = System.currentTimeMillis();
} else {
if (req.piece != savedRequest.piece)
if (_log.shouldLog(Log.DEBUG))
_log.debug(" Discarding orphaned partial piece " + req);
}
}
/** Return partial piece if it's still wanted and peer has it.
*/
public Request getPeerPartial(BitField havePieces) {
if (savedRequest == null)
return null;
if (! havePieces.get(savedRequest.piece)) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Peer doesn't have orphaned piece " + savedRequest);
return null;
}
synchronized(wantedPieces)
{
for(Iterator iter = wantedPieces.iterator(); iter.hasNext(); ) {
Piece piece = (Piece)iter.next();
if (piece.getId() == savedRequest.piece) {
Request req = savedRequest;
piece.setRequested(true);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Restoring orphaned partial piece " + req);
savedRequest = null;
return req;
}
}
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("We no longer want orphaned piece " + savedRequest);
savedRequest = null;
return null;
}
/** Clear the requested flag for a piece if the peer
** is the only one requesting it
*/
private void markUnrequestedIfOnlyOne(Peer peer, int piece)
{
// see if anybody else is requesting
synchronized (peers)
{
Iterator it = peers.iterator();
while (it.hasNext()) {
Peer p = (Peer)it.next();
if (p.equals(peer))
continue;
if (p.state == null)
continue;
int[] arr = p.state.getRequestedPieces();
for (int i = 0; arr[i] >= 0; i++)
if(arr[i] == piece) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Another peer is requesting piece " + piece);
return;
}
}
}
// nobody is, so mark unrequested
synchronized(wantedPieces)
{
Iterator it = wantedPieces.iterator();
while (it.hasNext()) {
Piece p = (Piece)it.next();
if (p.getId() == piece) {
p.setRequested(false);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Removing from request list piece " + piece);
return;
}
}
}
}
/** Mark a peer's requested pieces unrequested when it is disconnected
** Once for each piece
** This is enough trouble, maybe would be easier just to regenerate
** the requested list from scratch instead.
*/
public void markUnrequested(Peer peer)
{
if (halted || peer.state == null)
return;
int[] arr = peer.state.getRequestedPieces();
for (int i = 0; arr[i] >= 0; i++)
markUnrequestedIfOnlyOne(peer, arr[i]);
}
/** Return number of allowed uploaders for this torrent.
** Check with Snark to see if we are over the total upload limit.
*/
public int allowedUploaders()
{
if (Snark.overUploadLimit(uploaders)) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Over limit, uploaders was: " + uploaders);
return uploaders - 1;
} else if (uploaders < MAX_UPLOADERS)
return uploaders + 1;
else
return MAX_UPLOADERS;
}
}
|
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.util.Arrays;
import javax.imageio.ImageIO;
import javax.swing.*;
public class CameraClient {
private String hostIP;
private int serverPort;
private Socket client;
private OutputStream out;
private InputStream in;
public CameraClient(String hostIP, int serverPort) {
this.hostIP = hostIP;
this.serverPort = serverPort;
}
public CameraClient() {}
public void sethostIP(String hostIP) {
this.hostIP = hostIP;
}
public void setServerPort(int port) {
this.serverPort = port;
}
public String getHostIP() {
return hostIP;
}
public int getServerPort() {
return serverPort;
}
public void initSocket() {
try {
this.client = new Socket(hostIP, serverPort);
this.out = this.client.getOutputStream();
this.in = this.client.getInputStream();
System.out.println("Client socket successfully initialized.");
} catch (IOException e) {
System.out.println("Error Initializing Socket or Input/Output Streams");
}
}
public void writeString(String s) {
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write(s);
bw.close();
} catch (IOException e) {
System.out.println("Error writing string to socket.");
}
}
public String readSocketString() {
String s = null;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
s = br.readLine();
br.close();
} catch (IOException e) {
System.out.println("Error reading string from socket.");
}
return s;
}
private byte[] readSocketBytes() {
ByteArrayOutputStream bs = null;
try {
bs = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int s = 0; (s = in.read(buffer)) != -1; ) {
bs.write(buffer, 0, s);
}
} catch (IOException e) {
System.out.println("Error reading bytes from socket.");
}
return bs.toByteArray();
}
public BufferedImage readImage(int width, int height) {
BufferedImage img = null;
try {
byte[] inBytes = readSocketBytes();
DataBuffer buffer = new DataBufferByte(inBytes, inBytes.length);
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3*width, 3, new int[]{0,1,2}, (Point)null);
ColorModel cm = new ComponentColorModel(ColorModel.getRGBdefault().getColorSpace(), false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
img = new BufferedImage(cm, raster, true, null);
} catch (Exception e) {
e.printStackTrace();
}
return img;
}
public static void main(String[] args) {
CameraClient driveStation = new CameraClient("172.17.125.210", 5439);
driveStation.initSocket();
byte[] bytes = driveStation.readSocketBytes();
System.out.println(Arrays.toString(bytes));
try {
BufferedImage img = driveStation.readImage(10,10);
DisplayImage testImg = new DisplayImage(img);
} catch (Exception e) {
e.printStackTrace();
}
}
private static class DisplayImage {
public DisplayImage(BufferedImage img) throws IOException {
ImageIcon icon = new ImageIcon(img);
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(200,300);
JLabel lbl = new JLabel();
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
}
|
package com.makeramen;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;
@SuppressWarnings("UnusedDeclaration")
public class RoundedImageView extends ImageView {
public static final String TAG = "RoundedImageView";
public static final int DEFAULT_RADIUS = 0;
public static final int DEFAULT_BORDER_WIDTH = 0;
private static final ScaleType[] SCALE_TYPES = {
ScaleType.MATRIX,
ScaleType.FIT_XY,
ScaleType.FIT_START,
ScaleType.FIT_CENTER,
ScaleType.FIT_END,
ScaleType.CENTER,
ScaleType.CENTER_CROP,
ScaleType.CENTER_INSIDE
};
private int mCornerRadius = DEFAULT_RADIUS;
private int mBorderWidth = DEFAULT_BORDER_WIDTH;
private ColorStateList mBorderColor =
ColorStateList.valueOf(RoundedDrawable.DEFAULT_BORDER_COLOR);
private boolean mOval = false;
private boolean mRoundBackground = false;
private int mResource;
private Drawable mDrawable;
private Drawable mBackgroundDrawable;
private ScaleType mScaleType;
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundedImageView, defStyle, 0);
int index = a.getInt(R.styleable.RoundedImageView_android_scaleType, -1);
if (index >= 0) {
setScaleType(SCALE_TYPES[index]);
} else {
// default scaletype to FIT_CENTER
setScaleType(ScaleType.FIT_CENTER);
}
mCornerRadius = a.getDimensionPixelSize(R.styleable.RoundedImageView_corner_radius, -1);
mBorderWidth = a.getDimensionPixelSize(R.styleable.RoundedImageView_border_width, -1);
// don't allow negative values for radius and border
if (mCornerRadius < 0) {
mCornerRadius = DEFAULT_RADIUS;
}
if (mBorderWidth < 0) {
mBorderWidth = DEFAULT_BORDER_WIDTH;
}
mBorderColor = a.getColorStateList(R.styleable.RoundedImageView_border_color);
if (mBorderColor == null) {
mBorderColor = ColorStateList.valueOf(RoundedDrawable.DEFAULT_BORDER_COLOR);
}
mRoundBackground = a.getBoolean(R.styleable.RoundedImageView_round_background, false);
mOval = a.getBoolean(R.styleable.RoundedImageView_is_oval, false);
updateDrawableAttrs();
updateBackgroundDrawableAttrs();
a.recycle();
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
invalidate();
}
/**
* Return the current scale type in use by this ImageView.
*
* @attr ref android.R.styleable#ImageView_scaleType
* @see android.widget.ImageView.ScaleType
*/
@Override
public ScaleType getScaleType() {
return mScaleType;
}
/**
* Controls how the image should be resized or moved to match the size
* of this ImageView.
*
* @param scaleType The desired scaling mode.
* @attr ref android.R.styleable#ImageView_scaleType
*/
@Override
public void setScaleType(ScaleType scaleType) {
if (scaleType == null) {
throw new NullPointerException();
}
if (mScaleType != scaleType) {
mScaleType = scaleType;
switch (scaleType) {
case CENTER:
case CENTER_CROP:
case CENTER_INSIDE:
case FIT_CENTER:
case FIT_START:
case FIT_END:
case FIT_XY:
super.setScaleType(ScaleType.FIT_XY);
break;
default:
super.setScaleType(scaleType);
break;
}
updateDrawableAttrs();
updateBackgroundDrawableAttrs();
invalidate();
}
}
@Override
public void setImageDrawable(Drawable drawable) {
mResource = 0;
mDrawable = RoundedDrawable.fromDrawable(drawable);
updateDrawableAttrs();
super.setImageDrawable(mDrawable);
}
@Override
public void setImageBitmap(Bitmap bm) {
mResource = 0;
mDrawable = RoundedDrawable.fromBitmap(bm);
updateDrawableAttrs();
super.setImageDrawable(mDrawable);
}
@Override
public void setImageResource(int resId) {
if (mResource != resId) {
mResource = resId;
mDrawable = resolveResource();
updateDrawableAttrs();
super.setImageDrawable(mDrawable);
}
}
@Override public void setImageURI(Uri uri) {
super.setImageURI(uri);
setImageDrawable(getDrawable());
}
private Drawable resolveResource() {
Resources rsrc = getResources();
if (rsrc == null) {
return null;
}
Drawable d = null;
if (mResource != 0) {
try {
d = rsrc.getDrawable(mResource);
} catch (Exception e) {
Log.w(TAG, "Unable to find resource: " + mResource, e);
// Don't try again.
mResource = 0;
}
}
return RoundedDrawable.fromDrawable(d);
}
@Override
public void setBackground(Drawable background) {
setBackgroundDrawable(background);
}
private void updateDrawableAttrs() {
updateAttrs(mDrawable, false);
}
private void updateBackgroundDrawableAttrs() {
updateAttrs(mBackgroundDrawable, true);
}
private void updateAttrs(Drawable drawable, boolean background) {
if (drawable == null) {
return;
}
if (drawable instanceof RoundedDrawable) {
((RoundedDrawable) drawable)
.setScaleType(mScaleType)
.setCornerRadius(background && !mRoundBackground ? 0 : mCornerRadius)
.setBorderWidth(background && !mRoundBackground ? 0 : mBorderWidth)
.setBorderColors(mBorderColor)
.setOval(mOval);
} else if (drawable instanceof LayerDrawable) {
// loop through layers to and set drawable attrs
LayerDrawable ld = ((LayerDrawable) drawable);
int layers = ld.getNumberOfLayers();
for (int i = 0; i < layers; i++) {
updateAttrs(ld.getDrawable(i), background);
}
}
}
@Override
@Deprecated
public void setBackgroundDrawable(Drawable background) {
mBackgroundDrawable = RoundedDrawable.fromDrawable(background);
updateBackgroundDrawableAttrs();
super.setBackgroundDrawable(mBackgroundDrawable);
}
public int getCornerRadius() {
return mCornerRadius;
}
public void setCornerRadius(int radius) {
if (mCornerRadius == radius) {
return;
}
mCornerRadius = radius;
updateDrawableAttrs();
updateBackgroundDrawableAttrs();
}
public int getBorderWidth() {
return mBorderWidth;
}
public void setBorderWidth(int width) {
if (mBorderWidth == width) {
return;
}
mBorderWidth = width;
updateDrawableAttrs();
updateBackgroundDrawableAttrs();
invalidate();
}
public int getBorderColor() {
return mBorderColor.getDefaultColor();
}
public void setBorderColor(int color) {
setBorderColors(ColorStateList.valueOf(color));
}
public ColorStateList getBorderColors() {
return mBorderColor;
}
public void setBorderColors(ColorStateList colors) {
if (mBorderColor.equals(colors)) {
return;
}
mBorderColor =
(colors != null) ? colors : ColorStateList.valueOf(RoundedDrawable.DEFAULT_BORDER_COLOR);
updateDrawableAttrs();
updateBackgroundDrawableAttrs();
if (mBorderWidth > 0) {
invalidate();
}
}
public boolean isOval() {
return mOval;
}
public void setOval(boolean oval) {
mOval = oval;
updateDrawableAttrs();
updateBackgroundDrawableAttrs();
invalidate();
}
public boolean isRoundBackground() {
return mRoundBackground;
}
public void setRoundBackground(boolean roundBackground) {
if (mRoundBackground == roundBackground) {
return;
}
mRoundBackground = roundBackground;
updateBackgroundDrawableAttrs();
invalidate();
}
}
|
package com.exedio.cope.util;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import com.exedio.cope.junit.CopeAssert;
public class PropertiesTest extends CopeAssert
{
static class TestProperties extends Properties
{
final BooleanField boolFalse = new BooleanField("boolFalse", false);
final BooleanField boolTrue = new BooleanField("boolTrue", true);
final IntField int10 = new IntField("int10", 10, 5);
final StringField stringMandatory = new StringField("stringMandatory");
final StringField stringOptional = new StringField("stringOptional", "stringOptional.defaultValue");
final StringField stringHidden = new StringField("stringHidden", true);
final FileField file = new FileField("file");
final MapField map = new MapField("map");
TestProperties(final java.util.Properties source, final String sourceDescription)
{
super(getSource(source, sourceDescription), null);
}
TestProperties(final java.util.Properties source, final String sourceDescription, final Source context)
{
super(getSource(source, sourceDescription), context);
}
void assertIt()
{
assertEqualsUnmodifiable(Arrays.asList(new Properties.Field[]{
boolFalse,
boolTrue,
int10,
stringMandatory,
stringOptional,
stringHidden,
file,
map,
}), getFields());
assertEquals("boolFalse", boolFalse.getKey());
assertEquals("boolTrue", boolTrue.getKey());
assertEquals("int10", int10.getKey());
assertEquals("stringMandatory", stringMandatory.getKey());
assertEquals("stringOptional", stringOptional.getKey());
assertEquals("stringHidden", stringHidden.getKey());
assertEquals("file", file.getKey());
assertEquals("map", map.getKey());
assertEquals(Boolean.FALSE, boolFalse.getDefaultValue());
assertEquals(Boolean.TRUE, boolTrue.getDefaultValue());
assertEquals(Integer.valueOf(10), int10.getDefaultValue());
assertEquals(null, stringMandatory.getDefaultValue());
assertEquals("stringOptional.defaultValue", stringOptional.getDefaultValue());
assertEquals(null, stringHidden.getDefaultValue());
assertEquals(null, file.getDefaultValue());
assertEquals(null, map.getDefaultValue());
assertEquals(false, boolFalse.hasHiddenValue());
assertEquals(false, boolTrue.hasHiddenValue());
assertEquals(false, int10.hasHiddenValue());
assertEquals(false, stringMandatory.hasHiddenValue());
assertEquals(false, stringOptional.hasHiddenValue());
assertEquals(true, stringHidden.hasHiddenValue());
assertEquals(false, file.hasHiddenValue());
assertEquals(false, map.hasHiddenValue());
}
}
File file1;
File file2;
@Override
protected void setUp() throws Exception
{
super.setUp();
file1 = File.createTempFile("exedio-cope-PropertiesTest-", ".tmp");
file2 = File.createTempFile("exedio-cope-PropertiesTest-", ".tmp");
}
@Override
protected void tearDown() throws Exception
{
file1.delete();
file2.delete();
super.tearDown();
}
public void testIt()
{
final java.util.Properties pminimal = new java.util.Properties();
pminimal.setProperty("stringMandatory", "stringMandatory.minimalValue");
pminimal.setProperty("stringHidden", "stringHidden.minimalValue");
final TestProperties minimal = new TestProperties(pminimal, "minimal");
minimal.assertIt();
assertEquals("minimal", minimal.getSource());
assertEquals(false, minimal.boolFalse.getBooleanValue());
assertEquals(true, minimal.boolTrue.getBooleanValue());
assertEquals(Boolean.FALSE, minimal.boolFalse.getValue());
assertEquals(Boolean.TRUE, minimal.boolTrue.getValue());
assertEquals(10, minimal.int10.getIntValue());
assertEquals(Integer.valueOf(10), minimal.int10.getValue());
assertEquals("stringMandatory.minimalValue", minimal.stringMandatory.getStringValue());
assertEquals("stringOptional.defaultValue", minimal.stringOptional.getStringValue());
assertEquals("stringHidden.minimalValue", minimal.stringHidden.getStringValue());
assertEquals("stringMandatory.minimalValue", minimal.stringMandatory.getValue());
assertEquals("stringOptional.defaultValue", minimal.stringOptional.getValue());
assertEquals("stringHidden.minimalValue", minimal.stringHidden.getValue());
assertEquals(null, minimal.file.getFileValue());
assertEquals(null, minimal.file.getValue());
assertEquals(new java.util.Properties(), minimal.map.getMapValue());
assertEquals(new java.util.Properties(), minimal.map.getValue());
assertEquals(null, minimal.map.getValue("explicitKey1"));
assertEquals(false, minimal.boolFalse.isSpecified());
assertEquals(false, minimal.boolTrue.isSpecified());
assertEquals(false, minimal.int10.isSpecified());
assertEquals(true, minimal.stringMandatory.isSpecified());
assertEquals(false, minimal.stringOptional.isSpecified());
assertEquals(true, minimal.stringHidden.isSpecified());
assertEquals(false, minimal.file.isSpecified());
assertEquals(false, minimal.map.isSpecified());
minimal.ensureEquality(minimal);
{
final TestProperties minimal1 = new TestProperties(pminimal, "minimal2");
assertEquals("minimal2", minimal1.getSource());
minimal.ensureEquality(minimal1);
minimal1.ensureEquality(minimal);
}
{
final java.util.Properties p = copy(pminimal);
p.setProperty("boolFalse", "true");
p.setProperty("boolTrue", "false");
p.setProperty("int10", "20");
p.setProperty("stringMandatory", "stringMandatory.explicitValue");
p.setProperty("stringOptional", "stringOptional.explicitValue");
p.setProperty("stringHidden", "stringHidden.explicitValue");
p.setProperty("file", file1.getPath());
p.setProperty("map.explicitKey1", "map.explicitValue1");
p.setProperty("map.explicitKey2", "map.explicitValue2");
final TestProperties tp = new TestProperties(p, "maximal");
assertEquals("maximal", tp.getSource());
assertEquals(true, tp.boolFalse.getBooleanValue());
assertEquals(false, tp.boolTrue.getBooleanValue());
assertEquals(Boolean.TRUE, tp.boolFalse.getValue());
assertEquals(Boolean.FALSE, tp.boolTrue.getValue());
assertEquals(20, tp.int10.getIntValue());
assertEquals(Integer.valueOf(20), tp.int10.getValue());
assertEquals("stringMandatory.explicitValue", tp.stringMandatory.getStringValue());
assertEquals("stringOptional.explicitValue", tp.stringOptional.getStringValue());
assertEquals("stringHidden.explicitValue", tp.stringHidden.getStringValue());
assertEquals("stringMandatory.explicitValue", tp.stringMandatory.getValue());
assertEquals("stringOptional.explicitValue", tp.stringOptional.getValue());
assertEquals("stringHidden.explicitValue", tp.stringHidden.getValue());
assertEquals(file1, tp.file.getFileValue());
assertEquals(file1, tp.file.getValue());
java.util.Properties mapExpected = new java.util.Properties();
mapExpected.setProperty("explicitKey1", "map.explicitValue1");
mapExpected.setProperty("explicitKey2", "map.explicitValue2");
assertEquals(mapExpected, tp.map.getMapValue());
assertEquals(mapExpected, tp.map.getValue());
assertEquals("map.explicitValue1", tp.map.getValue("explicitKey1"));
assertEquals("map.explicitValue2", tp.map.getValue("explicitKey2"));
assertEquals(null, tp.map.getValue("explicitKeyNone"));
assertEquals(true, tp.boolFalse.isSpecified());
assertEquals(true, tp.boolTrue.isSpecified());
assertEquals(true, tp.int10.isSpecified());
assertEquals(true, tp.stringMandatory.isSpecified());
assertEquals(true, tp.stringOptional.isSpecified());
assertEquals(true, tp.stringHidden.isSpecified());
assertEquals(true, tp.file.isSpecified());
assertEquals(false, tp.map.isSpecified()); // TODO
}
{
final java.util.Properties p = copy(pminimal);
p.setProperty("wrongKey.zack", "somethingZack");
final TestProperties tp = new TestProperties(p, "wrongkey");
assertEquals("wrongkey", tp.getSource());
tp.ensureValidity("wrongKey");
try
{
tp.ensureValidity();
fail();
}
catch(IllegalArgumentException e)
{
assertEquals(
"property wrongKey.zack in wrongkey is not allowed, but only one of [" +
"boolFalse, " +
"boolTrue, " +
"int10, " +
"stringMandatory, " +
"stringOptional, " +
"stringHidden, " +
"file] " +
"or one starting with [map.].", e.getMessage());
}
}
// boolean
assertWrong(pminimal,
"wrong.bool.true",
"boolFalse", "True",
"property boolFalse in wrong.bool.true has invalid value," +
" expected >true< or >false<, but got >True<.");
assertWrong(pminimal,
"wrong.bool.false",
"boolFalse", "falsE",
"property boolFalse in wrong.bool.false has invalid value," +
" expected >true< or >false<, but got >falsE<.");
assertInconsistent(pminimal,
"inconsistent.bool",
"boolFalse", "true",
"inconsistent initialization for boolFalse between minimal and inconsistent.bool," +
" expected false but got true.",
"inconsistent initialization for boolFalse between inconsistent.bool and minimal," +
" expected true but got false.");
// int
{
// test lowest value
final java.util.Properties p = copy(pminimal);
p.setProperty("int10", "5");
final TestProperties tp = new TestProperties(p, "int.border");
assertEquals(5, tp.int10.getIntValue());
assertEquals(Integer.valueOf(5), tp.int10.getValue());
}
assertWrong(pminimal,
"wrong.int.tooSmall",
"int10", "4",
"property int10 in wrong.int.tooSmall has invalid value," +
" expected an integer greater or equal 5, but got 4.");
assertWrong(pminimal,
"wrong.int.noNumber",
"int10", "10x",
"property int10 in wrong.int.noNumber has invalid value," +
" expected an integer greater or equal 5, but got >10x<.");
assertInconsistent(pminimal,
"inconsistent.int",
"int10", "88",
"inconsistent initialization for int10 between minimal and inconsistent.int," +
" expected 10 but got 88.",
"inconsistent initialization for int10 between inconsistent.int and minimal," +
" expected 88 but got 10.");
// String
assertWrong(pminimal,
"wrong.stringMandatory.missing",
"stringMandatory", null,
"property stringMandatory in wrong.stringMandatory.missing not set and no default value specified.");
assertWrong(pminimal,
"wrong.stringHidden.missing",
"stringHidden", null,
"property stringHidden in wrong.stringHidden.missing not set and no default value specified.");
assertInconsistent(pminimal,
"inconsistent.stringMandatory",
"stringMandatory", "stringMandatory.inconsistentValue",
"inconsistent initialization for stringMandatory between minimal and inconsistent.stringMandatory," +
" expected stringMandatory.minimalValue but got stringMandatory.inconsistentValue.",
"inconsistent initialization for stringMandatory between inconsistent.stringMandatory and minimal," +
" expected stringMandatory.inconsistentValue but got stringMandatory.minimalValue.");
assertInconsistent(pminimal,
"inconsistent.stringOptional",
"stringOptional", "stringOptional.inconsistentValue",
"inconsistent initialization for stringOptional between minimal and inconsistent.stringOptional," +
" expected stringOptional.defaultValue but got stringOptional.inconsistentValue.",
"inconsistent initialization for stringOptional between inconsistent.stringOptional and minimal," +
" expected stringOptional.inconsistentValue but got stringOptional.defaultValue.");
assertInconsistent(pminimal,
"inconsistent.stringHidden",
"stringHidden", "stringHidden.inconsistentValue",
"inconsistent initialization for stringHidden between minimal and inconsistent.stringHidden.",
"inconsistent initialization for stringHidden between inconsistent.stringHidden and minimal.");
// File
assertInconsistent(pminimal,
"inconsistent.file",
"file", file2.getPath(),
"inconsistent initialization for file between minimal and inconsistent.file," +
" expected null but got " + file2.getPath() + ".",
"inconsistent initialization for file between inconsistent.file and minimal," +
" expected " + file2.getPath() + " but got null.");
final java.util.Properties fileInconsistency = copy(pminimal);
fileInconsistency.setProperty("file", file1.getPath());
assertInconsistent(fileInconsistency,
"inconsistent.file",
"file", file2.getPath(),
"inconsistent initialization for file between minimal and inconsistent.file," +
" expected " + file1.getPath() + " but got " + file2.getPath() + ".",
"inconsistent initialization for file between inconsistent.file and minimal," +
" expected " + file2.getPath() + " but got " + file1.getPath() + ".");
// Map
assertInconsistent(pminimal,
"inconsistent.map",
"map.inconsistentKey", "map.inconsistentValue",
"inconsistent initialization for map between minimal and inconsistent.map," +
" expected {} but got {inconsistentKey=map.inconsistentValue}.",
"inconsistent initialization for map between inconsistent.map and minimal," +
" expected {inconsistentKey=map.inconsistentValue} but got {}.");
}
private void assertWrong(
final java.util.Properties template,
final String sourceDescription,
final String key,
final String value,
final String message)
{
final java.util.Properties wrongProps = copy(template);
if(value!=null)
wrongProps.setProperty(key, value);
else
wrongProps.remove(key);
try
{
new TestProperties(wrongProps, sourceDescription);
fail();
}
catch(IllegalArgumentException e)
{
assertEquals(message, e.getMessage());
}
}
private void assertInconsistent(
final java.util.Properties template,
final String sourceDescription,
final String key,
final String value,
final String message1, final String message2)
{
final TestProperties templateProps = new TestProperties(template, "minimal");
templateProps.assertIt();
final java.util.Properties p = copy(template);
p.setProperty(key, value);
final TestProperties inconsistentProps = new TestProperties(p, sourceDescription);
try
{
templateProps.ensureEquality(inconsistentProps);
fail();
}
catch(IllegalArgumentException e)
{
assertEquals(message1, e.getMessage());
}
try
{
inconsistentProps.ensureEquality(templateProps);
fail();
}
catch(IllegalArgumentException e)
{
assertEquals(message2, e.getMessage());
}
}
private static final java.util.Properties copy(final java.util.Properties source)
{
return (java.util.Properties)source.clone();
}
public void testContext()
{
assertContext("y", "${x}");
assertContext("bucket", "${eimer}");
assertContext("bucketpostfix", "${eimer}postfix");
assertContext("prefixbucket", "prefix${eimer}");
assertContext("prefixbucketpostfix", "prefix${eimer}postfix");
assertContext("bucketinfixwater", "${eimer}infix${wasser}");
assertContext("bucketinfixwaterpostfix", "${eimer}infix${wasser}postfix");
assertContext("prefixbucketinfixwater", "prefix${eimer}infix${wasser}");
assertContext("prefixbucketinfixwaterpostfix", "prefix${eimer}infix${wasser}postfix");
assertContext("x$kkk", "x$kkk");
try
{
getContext("${nixus}");
fail();
}
catch(IllegalArgumentException e)
{
assertEquals("key 'nixus' not defined by context TestContextDescription", e.getMessage());
}
try
{
getContext("x${}y");
fail();
}
catch(IllegalArgumentException e)
{
assertEquals("${} not allowed in x${}y", e.getMessage());
}
try
{
getContext("x${kkk");
fail();
}
catch(IllegalArgumentException e)
{
assertEquals("missing '}' in x${kkk", e.getMessage());
}
}
private static final TestProperties getContext(final String raw)
{
final java.util.Properties pminimal = new java.util.Properties();
pminimal.setProperty("stringMandatory", raw);
pminimal.setProperty("stringHidden", "stringHidden.minimalValue");
final TestProperties minimal = new TestProperties(pminimal, "minimal", new Properties.Source(){
public String get(final String key)
{
if("x".equals(key))
return "y";
else if("eimer".equals(key))
return "bucket";
else if("wasser".equals(key))
return "water";
else if("nixus".equals(key))
return null;
else
throw new RuntimeException(key);
}
public Collection<String> keySet()
{
return Collections.unmodifiableList(Arrays.asList("x", "eimer", "wasser"));
}
public String getDescription()
{
return "TestContextDescription";
}
@Override
public String toString()
{
return "TestContextToString";
}
});
return minimal;
}
private static final void assertContext(final String replaced, final String raw)
{
assertEquals(replaced, getContext(raw).stringMandatory.getStringValue());
}
public void testGetContext()
{
final java.util.Properties pcontext = new java.util.Properties();
pcontext.setProperty("stringMandatory", "stringMandatory.minimalValue");
pcontext.setProperty("stringHidden", "stringHidden.minimalValue");
final Properties.Source context = new Properties.Source(){
public String get(final String key)
{
throw new RuntimeException(key);
}
public Collection<String> keySet()
{
throw new RuntimeException();
}
public String getDescription()
{
throw new RuntimeException();
}
@Override
public String toString()
{
throw new RuntimeException();
}
};
final TestProperties properties = new TestProperties(pcontext, "context", context);
assertSame(context, properties.getContext());
final TestProperties none = new TestProperties(pcontext, "none", null);
try
{
none.getContext();
fail();
}
catch(IllegalStateException e)
{
assertEquals("no context available", e.getMessage());
}
}
@Deprecated
public void testGetContextDeprecated()
{
final java.util.Properties pcontext = new java.util.Properties();
pcontext.setProperty("stringMandatory", "stringMandatory.minimalValue");
pcontext.setProperty("stringHidden", "stringHidden.minimalValue");
final TestProperties context = new TestProperties(pcontext, "context", new Properties.Source(){
public String get(final String key)
{
if("a".equals(key))
return "b";
else if("a1".equals(key))
return "b1";
else if("n".equals(key))
return null;
else
throw new RuntimeException(key);
}
public Collection<String> keySet()
{
return Collections.unmodifiableList(Arrays.asList("a", "a1"));
}
public String getDescription()
{
return "TestGetContextDescription";
}
@Override
public String toString()
{
return "TestGetContextToString";
}
});
assertEquals("b", context.getContext("a"));
assertEquals("b1", context.getContext("a1"));
try
{
context.getContext(null);
fail();
}
catch(NullPointerException e)
{
assertEquals("key must not be null", e.getMessage());
}
try
{
context.getContext("n");
fail();
}
catch(IllegalArgumentException e)
{
assertEquals("no value available for key >n< in context TestGetContextDescription", e.getMessage());
}
final TestProperties none = new TestProperties(pcontext, "none", null);
try
{
none.getContext("c");
fail();
}
catch(IllegalStateException e)
{
assertEquals("no context available", e.getMessage());
}
}
static class DuplicateProperties extends Properties
{
final BooleanField duplicate1 = new BooleanField("duplicate", false);
final BooleanField duplicate2 = new BooleanField("duplicate", true);
DuplicateProperties()
{
super(getSource(new java.util.Properties(), "duplicateDescriptin"), null);
}
}
public void testDuplicate()
{
// TODO should throw exception
final DuplicateProperties p = new DuplicateProperties();
assertFalse(p.duplicate1.getBooleanValue());
assertTrue(p.duplicate2.getBooleanValue());
}
}
|
package ru.stqa.pft.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PointTest {
@Test
public void DistanceTestArea () {
Point p1 = new Point(2, 3);
Point p2 = new Point(4, 5);
Assert.assertEquals(p1.distance(p2), 2.8284271247461903);
}
@Test
public void DistanceTest () {
Point p1 = new Point(9, 7);
Point p2 = new Point(5, 4);
double d = p1.distance(p2);
Assert.assertEquals(d, 5.0);
}
@Test
public void NegativeDistanceTest () {
Point p1 = new Point(9, 7);
Point p2 = new Point(5, 4);
assert p1.distance(p2)!=26;
}
}
|
package com.mercadopago.core;
import android.content.Context;
import android.support.annotation.NonNull;
import com.mercadopago.lite.adapters.ErrorHandlingCallAdapter;
import com.mercadopago.lite.callbacks.Callback;
import com.mercadopago.lite.util.HttpClientUtil;
import com.mercadopago.model.Customer;
import com.mercadopago.model.Discount;
import com.mercadopago.model.Payment;
import com.mercadopago.preferences.CheckoutPreference;
import com.mercadopago.services.CustomService;
import com.mercadopago.util.JsonUtil;
import java.util.HashMap;
import java.util.Map;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class CustomServer {
public static void createCheckoutPreference(Context context, String url, String uri, Callback<CheckoutPreference> callback) {
CustomService service = getService(context, url);
service.createPreference(uri, null).enqueue(callback);
}
public static void createCheckoutPreference(Context context, String url, String uri, Map<String, Object> bodyInfo, Callback<CheckoutPreference> callback) {
CustomService service = getService(context, url);
service.createPreference(uri, bodyInfo).enqueue(callback);
}
public static void getCustomer(Context context, String url, String uri, Callback<Customer> callback) {
CustomService service = getService(context, url);
service.getCustomer(uri, null).enqueue(callback);
}
public static void getCustomer(Context context, String url, String uri, @NonNull Map<String, String> additionalInfo, Callback<Customer> callback) {
CustomService service = getService(context, url);
service.getCustomer(uri, additionalInfo).enqueue(callback);
}
public static void createPayment(Context context, String transactionId, String baseUrl, String uri,
Map<String, Object> paymentData, @NonNull Map<String, String> query, Callback<Payment> callback) {
if (query == null) {
query = new HashMap<>();
}
CustomService service = getService(context, baseUrl);
service.createPayment(transactionId, ripFirstSlash(uri), paymentData, query).enqueue(callback);
}
public static void getDirectDiscount(Context context, String transactionAmount, String payerEmail,String url, String uri, @NonNull Map<String, String> discountAdditionalInfo, Callback<Discount> callback) {
CustomService service = getService(context, url);
service.getDirectDiscount(ripFirstSlash(uri), transactionAmount, payerEmail, discountAdditionalInfo).enqueue(callback);
}
public static void getCodeDiscount(String discountCode, String transactionAmount, String payerEmail, Context context, String url, String uri, @NonNull Map<String, String> discountAdditionalInfo, Callback<Discount> callback) {
CustomService service = getService(context, url);
service.getCodeDiscount(ripFirstSlash(uri), transactionAmount, payerEmail, discountCode, discountAdditionalInfo).enqueue(callback);
}
private static CustomService getService(Context context, String baseUrl) {
Retrofit retrofit = getRetrofit(context, baseUrl);
return retrofit.create(CustomService.class);
}
private static Retrofit getRetrofit(Context context, String baseUrl) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.client(HttpClientUtil.getClient(context, 20, 20, 20))
.addConverterFactory(GsonConverterFactory.create(JsonUtil.getInstance().getGson()))
.addCallAdapterFactory(new ErrorHandlingCallAdapter.ErrorHandlingCallAdapterFactory())
.build();
}
private static String ripFirstSlash(String uri) {
return uri.startsWith("/") ? uri.substring(1) : uri;
}
}
|
package com.wonderpush.sdk;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
/**
* Implementation of {@link IWonderPush} that performs the required tasks.
*
* This implementation is used when user consent is either provided or not required.
*/
class WonderPushImpl implements IWonderPush {
@Override
public void _activate() {
}
@Override
public void _deactivate() {
}
@Override
public String getAccessToken() {
String accessToken = null;
try {
accessToken = WonderPushConfiguration.getAccessToken();
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while getting accessToken", e);
}
return accessToken;
}
@Override
public String getDeviceId() {
String deviceId = null;
try {
deviceId = WonderPushConfiguration.getDeviceId();
if (deviceId == null) {
// Read from OpenUDID storage to keep a smooth transition off using OpenUDID
SharedPreferences sharedPrefs = WonderPush.getApplicationContext().getSharedPreferences("openudid_prefs", Context.MODE_PRIVATE);
deviceId = sharedPrefs.getString("openudid", null);
if (deviceId == null) {
// Generate an UUIDv4
deviceId = UUID.randomUUID().toString();
}
// and store it for us
WonderPushConfiguration.setDeviceId(deviceId);
}
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while getting deviceId", e);
}
return deviceId;
}
@Override
public String getInstallationId() {
String installationId = null;
try {
installationId = WonderPushConfiguration.getInstallationId();
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while getting installationId", e);
}
return installationId;
}
@Override
public String getPushToken() {
String pushToken = null;
try {
pushToken = WonderPushConfiguration.getGCMRegistrationId();
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while getting pushToken", e);
}
return pushToken;
}
@Override
public void subscribeToNotifications() {
setNotificationEnabled(true);
}
@Override
public void unsubscribeFromNotifications() {
setNotificationEnabled(false);
}
@Override
public boolean isSubscribedToNotifications() {
return getNotificationEnabled();
}
@Override
@Deprecated
public boolean getNotificationEnabled() {
return WonderPushConfiguration.getNotificationEnabled();
}
@Override
@Deprecated
public void setNotificationEnabled(boolean status) {
try {
WonderPush.logDebug("Set notification enabled: " + status);
boolean previousStatus = WonderPushConfiguration.getNotificationEnabled();
boolean osAreNotificationsEnabled = NotificationManagerCompat.from(WonderPush.getApplicationContext()).areNotificationsEnabled();
boolean cachedOsAreNotificationsEnabled = WonderPushConfiguration.getCachedOsAreNotificationsEnabled();
Set<String> cachedDisabledChannels = WonderPushConfiguration.getCachedDisabledNotificationChannelIds();
Set<String> disabledChannels = WonderPushUserPreferences.getDisabledChannelIds();
String previousValue = previousStatus && cachedOsAreNotificationsEnabled
? WonderPush.INSTALLATION_PREFERENCES_SUBSCRIPTION_STATUS_OPTIN
: WonderPush.INSTALLATION_PREFERENCES_SUBSCRIPTION_STATUS_OPTOUT;
String value = status && osAreNotificationsEnabled
? WonderPush.INSTALLATION_PREFERENCES_SUBSCRIPTION_STATUS_OPTIN
: WonderPush.INSTALLATION_PREFERENCES_SUBSCRIPTION_STATUS_OPTOUT;
if (previousStatus == status
&& value.equals(previousValue)
&& osAreNotificationsEnabled == cachedOsAreNotificationsEnabled
&& disabledChannels.equals(cachedDisabledChannels)
) {
WonderPush.logDebug("Set notification enabled: no change to apply");
return;
}
JSONObject properties = new JSONObject();
JSONObject preferences = new JSONObject();
properties.put("preferences", preferences);
preferences.put("subscriptionStatus", value);
preferences.put("subscribedToNotifications", status);
preferences.put("osNotificationsVisible", osAreNotificationsEnabled);
preferences.put("disabledAndroidChannels", new JSONArray(disabledChannels));
InstallationManager.updateInstallation(properties, false);
WonderPushConfiguration.setNotificationEnabled(status);
WonderPushConfiguration.setCachedOsAreNotificationsEnabled(osAreNotificationsEnabled);
WonderPushConfiguration.setCachedOsAreNotificationsEnabledDate(TimeSync.getTime());
WonderPushConfiguration.setCachedDisabledNotificationChannelIds(disabledChannels);
WonderPushConfiguration.setCachedDisabledNotificationChannelIdsDate(TimeSync.getTime());
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while setting notification enabled to " + status, e);
}
}
@Override
public JSONObject getProperties() {
return getInstallationCustomProperties();
}
@Override
public void putProperties(JSONObject properties) {
putInstallationCustomProperties(properties);
}
@Override
@Deprecated
public JSONObject getInstallationCustomProperties() {
JSONObject rtn = InstallationManager.getInstallationCustomProperties();
WonderPush.logDebug("getInstallationCustomProperties() -> " + rtn);
return rtn;
}
@Override
@Deprecated
public void putInstallationCustomProperties(JSONObject customProperties) {
try {
InstallationManager.putInstallationCustomProperties(customProperties);
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while putting installation custom properties", e);
}
}
@Override
public void trackEvent(String type) {
try {
trackEvent(type, null);
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while tracking user event of type \"" + type + "\"", e);
}
}
@Override
public void trackEvent(String type, JSONObject customData) {
try {
WonderPush.logDebug("trackEvent(" + type + ", " + customData + ")");
WonderPush.trackEvent(type, null, customData);
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while tracking user event of type \"" + type + "\"", e);
}
}
@Override
public void addTag(String... tag) {
try {
InstallationManager.addTag(tag);
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while adding tags " + Arrays.toString(tag), e);
}
}
@Override
public void removeTag(String... tag) {
try {
InstallationManager.removeTag(tag);
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while removing tags " + Arrays.toString(tag), e);
}
}
@Override
public void removeAllTags() {
try {
InstallationManager.removeAllTags();
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while removing all tags", e);
}
}
@Override
public Set<String> getTags() {
try {
return InstallationManager.getTags();
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while getting tags", e);
return new TreeSet<>();
}
}
@Override
public boolean hasTag(String tag) {
try {
return InstallationManager.hasTag(tag);
} catch (Exception e) {
Log.e(WonderPush.TAG, "Unexpected error while testing tag " + tag, e);
return false;
}
}
}
|
package jfxtras.util;
import javafx.scene.Node;
/**
* Utility class that provides methods to simplify node handling. Possible use
* cases are searching for nodes at specific locations, adding/removing nodes
* to/from parents (Parent interface does not give write access to children).
*
* @author Michael Hoffer <info@michaelhoffer.de>
*/
public class NodeUtil {
// no instantiation allowed
private NodeUtil() {
throw new AssertionError(); // not in this class either!
}
/**
*
* @param node
* @return The X screen coordinate of the node.
*/
static public double screenX(Node node) {
return node.localToScene(node.getBoundsInLocal()).getMinX() + node.getScene().getX() + node.getScene().getWindow().getX();
}
/**
*
* @param node
* @return The Y screen coordinate of the node.
*/
static public double screenY(Node node) {
return node.localToScene(node.getBoundsInLocal()).getMinY() + node.getScene().getY() + node.getScene().getWindow().getY();
}
}
|
package com.cloud.agent.manager;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.channels.ClosedChannelException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.agent.AgentManager;
import com.cloud.agent.Listener;
import com.cloud.agent.StartupCommandProcessor;
import com.cloud.agent.api.AgentControlAnswer;
import com.cloud.agent.api.AgentControlCommand;
import com.cloud.agent.api.Answer;
import com.cloud.agent.api.CheckHealthCommand;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.PingAnswer;
import com.cloud.agent.api.PingCommand;
import com.cloud.agent.api.PingRoutingCommand;
import com.cloud.agent.api.ReadyAnswer;
import com.cloud.agent.api.ReadyCommand;
import com.cloud.agent.api.ShutdownCommand;
import com.cloud.agent.api.StartupAnswer;
import com.cloud.agent.api.StartupCommand;
import com.cloud.agent.api.StartupProxyCommand;
import com.cloud.agent.api.StartupRoutingCommand;
import com.cloud.agent.api.StartupSecondaryStorageCommand;
import com.cloud.agent.api.StartupStorageCommand;
import com.cloud.agent.api.UnsupportedAnswer;
import com.cloud.agent.transport.Request;
import com.cloud.agent.transport.Response;
import com.cloud.alert.AlertManager;
import com.cloud.capacity.dao.CapacityDao;
import com.cloud.cluster.ManagementServerNode;
import com.cloud.cluster.StackMaid;
import com.cloud.configuration.Config;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.DataCenterIpAddressDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConnectionException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.UnsupportedVersionException;
import com.cloud.ha.HighAvailabilityManager;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.Status.Event;
import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostTagsDao;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.hypervisor.kvm.resource.KvmDummyResourceBase;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.resource.ResourceManager;
import com.cloud.resource.ResourceState;
import com.cloud.resource.ServerResource;
import com.cloud.storage.StorageManager;
import com.cloud.storage.StorageService;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.StoragePoolHostDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.resource.DummySecondaryStorageResource;
import com.cloud.storage.secondary.SecondaryStorageVmManager;
import com.cloud.user.AccountManager;
import com.cloud.utils.ActionDelegate;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.HypervisorVersionChangedException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.utils.fsm.StateMachine2;
import com.cloud.utils.nio.HandlerFactory;
import com.cloud.utils.nio.Link;
import com.cloud.utils.nio.NioServer;
import com.cloud.utils.nio.Task;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.dao.VMInstanceDao;
import edu.emory.mathcs.backport.java.util.Collections;
/**
* Implementation of the Agent Manager. This class controls the connection to the agents.
*
* @config {@table || Param Name | Description | Values | Default || || port | port to listen on for agent connection. | Integer
* | 8250 || || workers | # of worker threads | Integer | 5 || || router.template.id | default id for template | Integer
* | 1 || || router.ram.size | default ram for router vm in mb | Integer | 128 || || router.ip.address | ip address for
* the router | ip | 10.1.1.1 || || wait | Time to wait for control commands to return | seconds | 1800 || || domain |
* domain for domain routers| String | foo.com || || alert.wait | time to wait before alerting on a disconnected agent |
* seconds | 1800 || || update.wait | time to wait before alerting on a updating agent | seconds | 600 || ||
* ping.interval | ping interval in seconds | seconds | 60 || || instance.name | Name of the deployment String |
* required || || start.retry | Number of times to retry start | Number | 2 || || ping.timeout | multiplier to
* ping.interval before announcing an agent has timed out | float | 2.0x || || router.stats.interval | interval to
* report router statistics | seconds | 300s || * }
**/
@Local(value = { AgentManager.class })
public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager {
private static final Logger s_logger = Logger.getLogger(AgentManagerImpl.class);
private static final Logger status_logger = Logger.getLogger(Status.class);
protected ConcurrentHashMap<Long, AgentAttache> _agents = new ConcurrentHashMap<Long, AgentAttache>(10007);
protected List<Pair<Integer, Listener>> _hostMonitors = new ArrayList<Pair<Integer, Listener>>(17);
protected List<Pair<Integer, Listener>> _cmdMonitors = new ArrayList<Pair<Integer, Listener>>(17);
protected List<Pair<Integer, StartupCommandProcessor>> _creationMonitors = new ArrayList<Pair<Integer, StartupCommandProcessor>>(17);
protected List<Long> _loadingAgents = new ArrayList<Long>();
protected int _monitorId = 0;
private Lock _agentStatusLock = new ReentrantLock();
protected NioServer _connection;
@Inject
protected HostDao _hostDao = null;
@Inject
protected DataCenterDao _dcDao = null;
@Inject
protected DataCenterIpAddressDao _privateIPAddressDao = null;
@Inject
protected IPAddressDao _publicIPAddressDao = null;
@Inject
protected HostPodDao _podDao = null;
@Inject
protected VMInstanceDao _vmDao = null;
@Inject
protected CapacityDao _capacityDao = null;
@Inject
protected ConfigurationDao _configDao = null;
@Inject
protected StoragePoolDao _storagePoolDao = null;
@Inject
protected StoragePoolHostDao _storagePoolHostDao = null;
@Inject
protected ClusterDao _clusterDao = null;
@Inject
protected ClusterDetailsDao _clusterDetailsDao = null;
@Inject
protected HostTagsDao _hostTagsDao = null;
@Inject
protected VolumeDao _volumeDao = null;
protected int _port;
@Inject
protected HighAvailabilityManager _haMgr = null;
@Inject
protected AlertManager _alertMgr = null;
@Inject
protected AccountManager _accountMgr = null;
@Inject
protected VirtualMachineManager _vmMgr = null;
@Inject StorageService _storageSvr = null;
@Inject StorageManager _storageMgr = null;
@Inject
protected HypervisorGuruManager _hvGuruMgr;
@Inject SecondaryStorageVmManager _ssvmMgr;
protected int _retry = 2;
protected String _name;
protected String _instance;
protected int _wait;
protected int _updateWait;
protected int _alertWait;
protected long _nodeId = -1;
protected Random _rand = new Random(System.currentTimeMillis());
protected int _pingInterval;
protected long _pingTimeout;
protected AgentMonitor _monitor = null;
protected ExecutorService _executor;
protected StateMachine2<Status, Status.Event, Host> _statusStateMachine = Status.getStateMachine();
@Inject ResourceManager _resourceMgr;
@Override
public boolean configure(final String name, final Map<String, Object> params) throws ConfigurationException {
_name = name;
final ComponentLocator locator = ComponentLocator.getCurrentLocator();
ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
if (configDao == null) {
throw new ConfigurationException("Unable to get the configuration dao.");
}
final Map<String, String> configs = configDao.getConfiguration("AgentManager", params);
_port = NumbersUtil.parseInt(configs.get("port"), 8250);
final int workers = NumbersUtil.parseInt(configs.get("workers"), 5);
String value = configs.get(Config.PingInterval.toString());
_pingInterval = NumbersUtil.parseInt(value, 60);
value = configs.get(Config.Wait.toString());
_wait = NumbersUtil.parseInt(value, 1800);
value = configs.get(Config.AlertWait.toString());
_alertWait = NumbersUtil.parseInt(value, 1800);
value = configs.get(Config.UpdateWait.toString());
_updateWait = NumbersUtil.parseInt(value, 600);
value = configs.get(Config.PingTimeout.toString());
final float multiplier = value != null ? Float.parseFloat(value) : 2.5f;
_pingTimeout = (long) (multiplier * _pingInterval);
s_logger.info("Ping Timeout is " + _pingTimeout);
value = configs.get(Config.DirectAgentLoadSize.key());
int threads = NumbersUtil.parseInt(value, 16);
_instance = configs.get("instance.name");
if (_instance == null) {
_instance = "DEFAULT";
}
_nodeId = ManagementServerNode.getManagementServerId();
s_logger.info("Configuring AgentManagerImpl. management server node id(msid): " + _nodeId);
long lastPing = (System.currentTimeMillis() >> 10) - _pingTimeout;
_hostDao.markHostsAsDisconnected(_nodeId, lastPing);
_monitor = ComponentLocator.inject(AgentMonitor.class, _nodeId, _hostDao, _vmDao, _dcDao, _podDao, this, _alertMgr, _pingTimeout);
registerForHostEvents(_monitor, true, true, false);
_executor = new ThreadPoolExecutor(threads, threads, 60l, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("AgentTaskPool"));
_connection = new NioServer("AgentManager", _port, workers + 10, this);
s_logger.info("Listening on " + _port + " with " + workers + " workers");
return true;
}
@Override
public Task create(Task.Type type, Link link, byte[] data) {
return new AgentHandler(type, link, data);
}
@Override
public int registerForHostEvents(final Listener listener, boolean connections, boolean commands, boolean priority) {
synchronized (_hostMonitors) {
_monitorId++;
if (connections) {
if (priority) {
_hostMonitors.add(0, new Pair<Integer, Listener>(_monitorId, listener));
} else {
_hostMonitors.add(new Pair<Integer, Listener>(_monitorId, listener));
}
}
if (commands) {
if (priority) {
_cmdMonitors.add(0, new Pair<Integer, Listener>(_monitorId, listener));
} else {
_cmdMonitors.add(new Pair<Integer, Listener>(_monitorId, listener));
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Registering listener " + listener.getClass().getSimpleName() + " with id " + _monitorId);
}
return _monitorId;
}
}
@Override
public int registerForInitialConnects(final StartupCommandProcessor creator,boolean priority) {
synchronized (_hostMonitors) {
_monitorId++;
if (priority) {
_creationMonitors.add(0, new Pair<Integer, StartupCommandProcessor>(
_monitorId, creator));
} else {
_creationMonitors.add(0, new Pair<Integer, StartupCommandProcessor>(
_monitorId, creator));
}
}
return _monitorId;
}
@Override
public void unregisterForHostEvents(final int id) {
s_logger.debug("Deregistering " + id);
_hostMonitors.remove(id);
}
private AgentControlAnswer handleControlCommand(AgentAttache attache, final AgentControlCommand cmd) {
AgentControlAnswer answer = null;
for (Pair<Integer, Listener> listener : _cmdMonitors) {
answer = listener.second().processControlCommand(attache.getId(), cmd);
if (answer != null) {
return answer;
}
}
s_logger.warn("No handling of agent control command: " + cmd + " sent from " + attache.getId());
return new AgentControlAnswer(cmd);
}
public void handleCommands(AgentAttache attache, final long sequence, final Command[] cmds) {
for (Pair<Integer, Listener> listener : _cmdMonitors) {
boolean processed = listener.second().processCommands(attache.getId(), sequence, cmds);
if (s_logger.isTraceEnabled()) {
s_logger.trace("SeqA " + attache.getId() + "-" + sequence + ": " + (processed ? "processed" : "not processed") + " by " + listener.getClass());
}
}
}
public void notifyAnswersToMonitors(long agentId, long seq, Answer[] answers) {
for (Pair<Integer, Listener> listener : _cmdMonitors) {
listener.second().processAnswers(agentId, seq, answers);
}
}
@Override
public AgentAttache findAttache(long hostId) {
AgentAttache attache = null;
synchronized (_agents) {
attache = _agents.get(hostId);
}
return attache;
}
@Override
public Answer sendToSecStorage(HostVO ssHost, Command cmd) {
if( ssHost.getType() == Host.Type.LocalSecondaryStorage ) {
return easySend(ssHost.getId(), cmd);
} else if ( ssHost.getType() == Host.Type.SecondaryStorage) {
return sendToSSVM(ssHost.getDataCenterId(), cmd);
} else {
String msg = "do not support Secondary Storage type " + ssHost.getType();
s_logger.warn(msg);
return new Answer(cmd, false, msg);
}
}
@Override
public void sendToSecStorage(HostVO ssHost, Command cmd, Listener listener) throws AgentUnavailableException {
if( ssHost.getType() == Host.Type.LocalSecondaryStorage ) {
send(ssHost.getId(), new Commands(cmd), listener);
} else if ( ssHost.getType() == Host.Type.SecondaryStorage) {
sendToSSVM(ssHost.getDataCenterId(), cmd, listener);
} else {
String err = "do not support Secondary Storage type " + ssHost.getType();
s_logger.warn(err);
throw new CloudRuntimeException(err);
}
}
private void sendToSSVM(final long dcId, final Command cmd, final Listener listener) throws AgentUnavailableException {
List<HostVO> ssAHosts = _ssvmMgr.listUpAndConnectingSecondaryStorageVmHost(dcId);
if (ssAHosts == null || ssAHosts.isEmpty() ) {
throw new AgentUnavailableException("No ssvm host found", -1);
}
Collections.shuffle(ssAHosts);
HostVO ssAhost = ssAHosts.get(0);
send(ssAhost.getId(), new Commands(cmd), listener);
}
@Override
public Answer sendToSSVM(final Long dcId, final Command cmd) {
List<HostVO> ssAHosts = _ssvmMgr.listUpAndConnectingSecondaryStorageVmHost(dcId);
if (ssAHosts == null || ssAHosts.isEmpty() ) {
return new Answer(cmd, false, "can not find secondary storage VM agent for data center " + dcId);
}
Collections.shuffle(ssAHosts);
HostVO ssAhost = ssAHosts.get(0);
return easySend(ssAhost.getId(), cmd);
}
@Override
public Answer sendTo(Long dcId, HypervisorType type, Command cmd) {
List<ClusterVO> clusters = _clusterDao.listByDcHyType(dcId, type.toString());
int retry = 0;
for (ClusterVO cluster : clusters) {
List<HostVO> hosts = _resourceMgr.listAllUpAndEnabledHosts(Host.Type.Routing, cluster.getId(), null, dcId);
for (HostVO host : hosts) {
retry++;
if (retry > _retry) {
return null;
}
Answer answer = null;
try {
long targetHostId = _hvGuruMgr.getGuruProcessedCommandTargetHost(host.getId(), cmd);
answer = easySend(targetHostId, cmd);
} catch (Exception e) {
}
if (answer != null) {
return answer;
}
}
}
return null;
}
protected int getPingInterval() {
return _pingInterval;
}
@Override
public Answer send(Long hostId, Command cmd) throws AgentUnavailableException, OperationTimedoutException {
Commands cmds = new Commands(OnError.Stop);
cmds.addCommand(cmd);
send(hostId, cmds, cmd.getWait());
Answer[] answers = cmds.getAnswers();
if (answers != null && !(answers[0] instanceof UnsupportedAnswer)) {
return answers[0];
}
if (answers != null && (answers[0] instanceof UnsupportedAnswer)) {
s_logger.warn("Unsupported Command: " + answers[0].getDetails());
return answers[0];
}
return null;
}
@DB
protected boolean noDbTxn() {
Transaction txn = Transaction.currentTxn();
return !txn.dbTxnStarted();
}
@Override
public Answer[] send(Long hostId, Commands commands, int timeout) throws AgentUnavailableException, OperationTimedoutException {
assert hostId != null : "Who's not checking the agent id before sending? ... (finger wagging)";
if (hostId == null) {
throw new AgentUnavailableException(-1);
}
if (timeout <= 0) {
timeout = _wait;
}
assert noDbTxn() : "I know, I know. Why are we so strict as to not allow txn across an agent call? ... Why are we so cruel ... Why are we such a dictator .... Too bad... Sorry...but NO AGENT COMMANDS WRAPPED WITHIN DB TRANSACTIONS!";
Command[] cmds = commands.toCommands();
assert cmds.length > 0 : "Ask yourself this about a hundred times. Why am I sending zero length commands?";
if (cmds.length == 0) {
commands.setAnswers(new Answer[0]);
}
final AgentAttache agent = getAttache(hostId);
if (agent == null || agent.isClosed()) {
throw new AgentUnavailableException("agent not logged into this management server", hostId);
}
Request req = new Request(hostId, _nodeId, cmds, commands.stopOnError(), true);
req.setSequence(agent.getNextSequence());
Answer[] answers = agent.send(req, timeout);
notifyAnswersToMonitors(hostId, req.getSequence(), answers);
commands.setAnswers(answers);
return answers;
}
protected Status investigate(AgentAttache agent) {
Long hostId = agent.getId();
if (s_logger.isDebugEnabled()) {
s_logger.debug("checking if agent (" + hostId + ") is alive");
}
Answer answer = easySend(hostId, new CheckHealthCommand());
if (answer != null && answer.getResult()) {
Status status = Status.Up;
if (s_logger.isDebugEnabled()) {
s_logger.debug("agent (" + hostId + ") responded to checkHeathCommand, reporting that agent is " + status);
}
return status;
}
return _haMgr.investigate(hostId);
}
protected AgentAttache getAttache(final Long hostId) throws AgentUnavailableException {
assert (hostId != null) : "Who didn't check their id value?";
if (hostId == null) {
return null;
}
AgentAttache agent = findAttache(hostId);
if (agent == null) {
s_logger.debug("Unable to find agent for " + hostId);
throw new AgentUnavailableException("Unable to find agent ", hostId);
}
return agent;
}
@Override
public long send(Long hostId, Commands commands, Listener listener) throws AgentUnavailableException {
final AgentAttache agent = getAttache(hostId);
if (agent.isClosed()) {
throw new AgentUnavailableException("Agent " + agent.getId() + " is closed", agent.getId());
}
Command[] cmds = commands.toCommands();
assert cmds.length > 0 : "Why are you sending zero length commands?";
if (cmds.length == 0) {
throw new AgentUnavailableException("Empty command set for agent " + agent.getId(), agent.getId());
}
Request req = new Request(hostId, _nodeId, cmds, commands.stopOnError(), true);
req.setSequence(agent.getNextSequence());
agent.send(req, listener);
return req.getSequence();
}
public void removeAgent(AgentAttache attache, Status nextState) {
if (attache == null) {
return;
}
long hostId = attache.getId();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Remove Agent : " + hostId);
}
AgentAttache removed = null;
boolean conflict = false;
synchronized (_agents) {
removed = _agents.remove(hostId);
if (removed != null && removed != attache) {
conflict = true;
_agents.put(hostId, removed);
removed = attache;
}
}
if (conflict) {
s_logger.debug("Agent for host " + hostId + " is created when it is being disconnected");
}
if (removed != null) {
removed.disconnect(nextState);
}
for (Pair<Integer, Listener> monitor : _hostMonitors) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending Disconnect to listener: " + monitor.second().getClass().getName());
}
monitor.second().processDisconnect(hostId, nextState);
}
}
protected AgentAttache notifyMonitorsOfConnection(AgentAttache attache, final StartupCommand[] cmd, boolean forRebalance) throws ConnectionException {
long hostId = attache.getId();
HostVO host = _hostDao.findById(hostId);
for (Pair<Integer, Listener> monitor : _hostMonitors) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending Connect to listener: " + monitor.second().getClass().getSimpleName());
}
for (int i = 0; i < cmd.length; i++) {
try {
monitor.second().processConnect(host, cmd[i], forRebalance);
} catch (Exception e) {
if (e instanceof ConnectionException) {
ConnectionException ce = (ConnectionException)e;
if (ce.isSetupError()) {
s_logger.warn("Monitor " + monitor.second().getClass().getSimpleName() + " says there is an error in the connect process for " + hostId + " due to " + e.getMessage());
handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected);
throw ce;
} else {
s_logger.info("Monitor " + monitor.second().getClass().getSimpleName() + " says not to continue the connect process for " + hostId + " due to " + e.getMessage());
handleDisconnectWithoutInvestigation(attache, Event.ShutdownRequested);
return attache;
}
} else if (e instanceof HypervisorVersionChangedException) {
handleDisconnectWithoutInvestigation(attache, Event.ShutdownRequested);
throw new CloudRuntimeException("Unable to connect " + attache.getId(), e);
} else {
s_logger.error("Monitor " + monitor.second().getClass().getSimpleName() + " says there is an error in the connect process for " + hostId + " due to " + e.getMessage(), e);
handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected);
throw new CloudRuntimeException("Unable to connect " + attache.getId(), e);
}
}
}
}
Long dcId = host.getDataCenterId();
ReadyCommand ready = new ReadyCommand(dcId);
Answer answer = easySend(hostId, ready);
if (answer == null || !answer.getResult()) {
// this is tricky part for secondary storage
// make it as disconnected, wait for secondary storage VM to be up
// return the attache instead of null, even it is disconnectede
handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected);
}
agentStatusTransitTo(host, Event.Ready, _nodeId);
attache.ready();
return attache;
}
protected boolean notifyCreatorsOfConnection(StartupCommand[] cmd) throws ConnectionException {
boolean handled = false;
for (Pair<Integer, StartupCommandProcessor> monitor : _creationMonitors) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending Connect to creator: "
+ monitor.second().getClass().getSimpleName());
}
handled = monitor.second().processInitialConnect(cmd);
if (handled) {
break;
}
}
return handled;
}
@Override
public boolean start() {
startDirectlyConnectedHosts();
if (_monitor != null) {
_monitor.start();
}
if (_connection != null) {
_connection.start();
}
return true;
}
public void startDirectlyConnectedHosts() {
List<HostVO> hosts = _resourceMgr.findDirectlyConnectedHosts();
for (HostVO host : hosts) {
loadDirectlyConnectedHost(host, false);
}
}
@SuppressWarnings("rawtypes")
protected boolean loadDirectlyConnectedHost(HostVO host, boolean forRebalance) {
boolean initialized = false;
ServerResource resource = null;
try {
String resourceName = host.getResource();
try {
Class<?> clazz = Class.forName(resourceName);
Constructor constructor = clazz.getConstructor();
resource = (ServerResource) constructor.newInstance();
} catch (ClassNotFoundException e) {
s_logger.warn("Unable to find class " + host.getResource(), e);
return false;
} catch (InstantiationException e) {
s_logger.warn("Unablet to instantiate class " + host.getResource(), e);
return false;
} catch (IllegalAccessException e) {
s_logger.warn("Illegal access " + host.getResource(), e);
return false;
} catch (SecurityException e) {
s_logger.warn("Security error on " + host.getResource(), e);
return false;
} catch (NoSuchMethodException e) {
s_logger.warn("NoSuchMethodException error on " + host.getResource(), e);
return false;
} catch (IllegalArgumentException e) {
s_logger.warn("IllegalArgumentException error on " + host.getResource(), e);
return false;
} catch (InvocationTargetException e) {
s_logger.warn("InvocationTargetException error on " + host.getResource(), e);
return false;
}
_hostDao.loadDetails(host);
HashMap<String, Object> params = new HashMap<String, Object>(host.getDetails().size() + 5);
params.putAll(host.getDetails());
params.put("guid", host.getGuid());
params.put("zone", Long.toString(host.getDataCenterId()));
if (host.getPodId() != null) {
params.put("pod", Long.toString(host.getPodId()));
}
if (host.getClusterId() != null) {
params.put("cluster", Long.toString(host.getClusterId()));
String guid = null;
ClusterVO cluster = _clusterDao.findById(host.getClusterId());
if (cluster.getGuid() == null) {
guid = host.getDetail("pool");
} else {
guid = cluster.getGuid();
}
if (guid != null && !guid.isEmpty()) {
params.put("pool", guid);
}
}
params.put("ipaddress", host.getPrivateIpAddress());
params.put("secondary.storage.vm", "false");
params.put("max.template.iso.size", _configDao.getValue(Config.MaxTemplateAndIsoSize.toString()));
params.put("migratewait", _configDao.getValue(Config.MigrateWait.toString()));
try {
resource.configure(host.getName(), params);
} catch (ConfigurationException e) {
s_logger.warn("Unable to configure resource due to " + e.getMessage());
return false;
}
if (!resource.start()) {
s_logger.warn("Unable to start the resource");
return false;
}
initialized = true;
} finally {
if(!initialized) {
if (host != null) {
agentStatusTransitTo(host, Event.AgentDisconnected, _nodeId);
}
}
}
if (forRebalance) {
Host h = _resourceMgr.createHostAndAgent(host.getId(), resource, host.getDetails(), false, null, true);
return (h == null ? false : true);
} else {
_executor.execute(new SimulateStartTask(host.getId(), resource, host.getDetails(), null));
return true;
}
}
protected AgentAttache createAttacheForDirectConnect(HostVO host, ServerResource resource)
throws ConnectionException {
if (resource instanceof DummySecondaryStorageResource || resource instanceof KvmDummyResourceBase) {
return new DummyAttache(this, host.getId(), false);
}
s_logger.debug("create DirectAgentAttache for " + host.getId());
DirectAgentAttache attache = new DirectAgentAttache(this, host.getId(), resource, host.isInMaintenanceStates(), this);
AgentAttache old = null;
synchronized (_agents) {
old = _agents.put(host.getId(), attache);
}
if (old != null) {
old.disconnect(Status.Removed);
}
return attache;
}
@Override
public boolean stop() {
if (_monitor != null) {
_monitor.signalStop();
}
if (_connection != null) {
_connection.stop();
}
s_logger.info("Disconnecting agents: " + _agents.size());
synchronized (_agents) {
for (final AgentAttache agent : _agents.values()) {
final HostVO host = _hostDao.findById(agent.getId());
if (host == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cant not find host " + agent.getId());
}
} else {
agentStatusTransitTo(host, Event.ManagementServerDown, _nodeId);
}
}
}
return true;
}
@Override
public String getName() {
return _name;
}
protected boolean handleDisconnectWithoutInvestigation(AgentAttache attache, Status.Event event) {
long hostId = attache.getId();
s_logger.info("Host " + hostId + " is disconnecting with event " + event);
Status nextStatus = null;
HostVO host = _hostDao.findById(hostId);
if (host == null) {
s_logger.warn("Can't find host with " + hostId);
nextStatus = Status.Removed;
} else {
final Status currentStatus = host.getStatus();
if (currentStatus == Status.Down || currentStatus == Status.Alert || currentStatus == Status.Removed) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Host " + hostId + " is already " + currentStatus);
}
nextStatus = currentStatus;
} else {
try {
nextStatus = currentStatus.getNextStatus(event);
} catch (NoTransitionException e) {
String err = "Cannot find next status for " + event + " as current status is " + currentStatus + " for agent " + hostId;
s_logger.debug(err);
throw new CloudRuntimeException(err);
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("The next status of agent " + hostId + "is " + nextStatus + ", current status is " + currentStatus);
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Deregistering link for " + hostId + " with state " + nextStatus);
}
removeAgent(attache, nextStatus);
if (host != null) {
disconnectAgent(host, event, _nodeId);
}
return true;
}
protected boolean handleDisconnectWithInvestigation(AgentAttache attache, Status.Event event) {
long hostId = attache.getId();
HostVO host = _hostDao.findById(hostId);
if (host != null) {
Status nextStatus = null;
try {
nextStatus = host.getStatus().getNextStatus(event);
} catch (NoTransitionException ne) {
/* Agent may be currently in status of Down, Alert, Removed, namely there is no next status for some events.
* Why this can happen? Ask God not me. I hate there was no piece of comment for code handling race condition.
* God knew what race condition the code dealt with!
*/
}
if (nextStatus == Status.Alert) {
/* OK, we are going to the bad status, let's see what happened */
s_logger.info("Investigating why host " + hostId + " has disconnected with event " + event);
final Status determinedState = investigate(attache);
final Status currentStatus = host.getStatus();
s_logger.info("The state determined is " + determinedState);
if (determinedState == null || determinedState == Status.Down) {
s_logger.error("Host is down: " + host.getId() + "-" + host.getName() + ". Starting HA on the VMs");
event = Status.Event.HostDown;
} else if (determinedState == Status.Up) {
/* Got ping response from host, bring it back*/
s_logger.info("Agent is determined to be up and running");
agentStatusTransitTo(host, Status.Event.Ping, _nodeId);
return false;
} else if (determinedState == Status.Disconnected) {
s_logger.warn("Agent is disconnected but the host is still up: " + host.getId() + "-" + host.getName());
if (currentStatus == Status.Disconnected) {
if (((System.currentTimeMillis() >> 10) - host.getLastPinged()) > _alertWait) {
s_logger.warn("Host " + host.getId() + " has been disconnected pass the time it should be disconnected.");
event = Status.Event.WaitedTooLong;
} else {
s_logger.debug("Host has been determined to be disconnected but it hasn't passed the wait time yet.");
return false;
}
} else if (currentStatus == Status.Up) {
DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
HostPodVO podVO = _podDao.findById(host.getPodId());
String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
if ((host.getType() != Host.Type.SecondaryStorage) && (host.getType() != Host.Type.ConsoleProxy)) {
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host disconnected, " + hostDesc, "If the agent for host [" + hostDesc
+ "] is not restarted within " + _alertWait + " seconds, HA will begin on the VMs");
}
event = Status.Event.AgentDisconnected;
}
} else {
// if we end up here we are in alert state, send an alert
DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
HostPodVO podVO = _podDao.findById(host.getPodId());
String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host in ALERT state, " + hostDesc, "In availability zone " + host.getDataCenterId()
+ ", host is in alert state: " + host.getId() + "-" + host.getName());
}
} else {
s_logger.debug("The next status of Agent " + host.getId() + " is not Alert, no need to investigate what happened");
}
}
handleDisconnectWithoutInvestigation(attache, event);
host = _hostDao.findById(host.getId());
if (host.getStatus() == Status.Alert || host.getStatus() == Status.Down) {
_haMgr.scheduleRestartForVmsOnHost(host, true);
}
return true;
}
protected class DisconnectTask implements Runnable {
AgentAttache _attache;
Status.Event _event;
boolean _investigate;
DisconnectTask(final AgentAttache attache, final Status.Event event, final boolean investigate) {
_attache = attache;
_event = event;
_investigate = investigate;
}
@Override
public void run() {
try {
if (_investigate == true) {
handleDisconnectWithInvestigation(_attache, _event);
} else {
handleDisconnectWithoutInvestigation(_attache, _event);
}
} catch (final Exception e) {
s_logger.error("Exception caught while handling disconnect: ", e);
} finally {
StackMaid.current().exitCleanup();
}
}
}
@Override
public Answer easySend(final Long hostId, final Command cmd) {
try {
Host h = _hostDao.findById(hostId);
if (h == null || h.getRemoved() != null) {
s_logger.debug("Host with id " + hostId + " doesn't exist");
return null;
}
Status status = h.getStatus();
if (!status.equals(Status.Up) && !status.equals(Status.Connecting)) {
s_logger.debug("Can not send command " + cmd + " due to Host " + hostId + " is not up");
return null;
}
final Answer answer = send(hostId, cmd);
if (answer == null) {
s_logger.warn("send returns null answer");
return null;
}
if (s_logger.isDebugEnabled() && answer.getDetails() != null) {
s_logger.debug("Details from executing " + cmd.getClass() + ": " + answer.getDetails());
}
return answer;
} catch (final AgentUnavailableException e) {
s_logger.warn(e.getMessage());
return null;
} catch (final OperationTimedoutException e) {
s_logger.warn("Operation timed out: " + e.getMessage());
return null;
} catch (final Exception e) {
s_logger.warn("Exception while sending", e);
return null;
}
}
@Override
public Answer[] send(final Long hostId, Commands cmds) throws AgentUnavailableException, OperationTimedoutException {
int wait = 0;
for( Command cmd : cmds ) {
if ( cmd.getWait() > wait ) {
wait = cmd.getWait();
}
}
return send(hostId, cmds, wait);
}
@Override
public boolean reconnect(final long hostId) {
HostVO host;
host = _hostDao.findById(hostId);
if (host == null || host.getRemoved() != null) {
s_logger.warn("Unable to find host " + hostId);
return false;
}
if (host.getStatus() != Status.Up && host.getStatus() != Status.Alert && host.getStatus() != Status.Rebalancing) {
s_logger.info("Unable to disconnect host because it is not in the correct state: host=" + hostId + "; Status=" + host.getStatus());
return false;
}
AgentAttache attache = findAttache(hostId);
if (attache == null) {
s_logger.info("Unable to disconnect host because it is not connected to this server: " + hostId);
return false;
}
disconnectWithoutInvestigation(attache, Event.ShutdownRequested);
return true;
}
@Override
public boolean executeUserRequest(long hostId, Event event) throws AgentUnavailableException {
if (event == Event.AgentDisconnected) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Received agent disconnect event for host " + hostId);
}
AgentAttache attache = null;
attache = findAttache(hostId);
if (attache != null) {
handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected);
}
return true;
} else if (event == Event.ShutdownRequested) {
return reconnect(hostId);
}
return false;
}
protected AgentAttache createAttacheForConnect(HostVO host, Link link) throws ConnectionException {
s_logger.debug("create ConnectedAgentAttache for " + host.getId());
AgentAttache attache = new ConnectedAgentAttache(this, host.getId(), link, host.isInMaintenanceStates());
link.attach(attache);
AgentAttache old = null;
synchronized (_agents) {
old = _agents.put(host.getId(), attache);
}
if (old != null) {
old.disconnect(Status.Removed);
}
return attache;
}
//TODO: handle mycloud specific
private AgentAttache handleConnectedAgent(final Link link, final StartupCommand[] startup, Request request) {
AgentAttache attache = null;
StartupAnswer[] answers = new StartupAnswer[startup.length];
try {
HostVO host = _resourceMgr.createHostVOForConnectedAgent(startup);
if (host != null) {
attache = createAttacheForConnect(host, link);
}
Command cmd;
for (int i = 0; i < startup.length; i++) {
cmd = startup[i];
if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) {
answers[i] = new StartupAnswer(startup[i], attache.getId(), getPingInterval());
break;
}
}
}catch (ConnectionException e) {
Command cmd;
for (int i = 0; i < startup.length; i++) {
cmd = startup[i];
if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) {
answers[i] = new StartupAnswer(startup[i], e.toString());
break;
}
}
} catch (IllegalArgumentException e) {
Command cmd;
for (int i = 0; i < startup.length; i++) {
cmd = startup[i];
if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) {
answers[i] = new StartupAnswer(startup[i], e.toString());
break;
}
}
} catch (CloudRuntimeException e) {
Command cmd;
for (int i = 0; i < startup.length; i++) {
cmd = startup[i];
if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) {
answers[i] = new StartupAnswer(startup[i], e.toString());
break;
}
}
}
Response response = null;
if (attache != null) {
response = new Response(request, answers[0], _nodeId, attache.getId());
} else {
response = new Response(request, answers[0], _nodeId, -1);
}
try {
link.send(response.toBytes());
} catch (ClosedChannelException e) {
s_logger.debug("Failed to send startupanswer: " + e.toString());
return null;
}
if (attache == null) {
return null;
}
try {
attache = notifyMonitorsOfConnection(attache, startup, false);
return attache;
} catch (ConnectionException e) {
ReadyCommand ready = new ReadyCommand(null);
ready.setDetails(e.toString());
try {
easySend(attache.getId(), ready);
} catch (Exception e1) {
s_logger.debug("Failed to send readycommand, due to " + e.toString());
}
return null;
} catch (CloudRuntimeException e) {
ReadyCommand ready = new ReadyCommand(null);
ready.setDetails(e.toString());
try {
easySend(attache.getId(), ready);
} catch (Exception e1) {
s_logger.debug("Failed to send readycommand, due to " + e.toString());
}
return null;
}
}
protected class SimulateStartTask implements Runnable {
ServerResource resource;
Map<String, String> details;
long id;
ActionDelegate<Long> actionDelegate;
public SimulateStartTask(long id, ServerResource resource, Map<String, String> details, ActionDelegate<Long> actionDelegate) {
this.id = id;
this.resource = resource;
this.details = details;
this.actionDelegate = actionDelegate;
}
@Override
public void run() {
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Simulating start for resource " + resource.getName() + " id " + id);
}
_resourceMgr.createHostAndAgent(id, resource, details, false, null, false);
} catch (Exception e) {
s_logger.warn("Unable to simulate start on resource " + id + " name " + resource.getName(), e);
} finally {
if (actionDelegate != null) {
actionDelegate.action(new Long(id));
}
StackMaid.current().exitCleanup();
}
}
}
public class AgentHandler extends Task {
public AgentHandler(Task.Type type, Link link, byte[] data) {
super(type, link, data);
}
protected void processRequest(final Link link, final Request request) {
AgentAttache attache = (AgentAttache) link.attachment();
final Command[] cmds = request.getCommands();
Command cmd = cmds[0];
boolean logD = true;
Response response = null;
if (attache == null) {
request.logD("Processing the first command ");
if (!(cmd instanceof StartupCommand)) {
s_logger.warn("Throwing away a request because it came through as the first command on a connect: " + request);
return;
}
StartupCommand[] startups = new StartupCommand[cmds.length];
for (int i = 0; i < cmds.length; i++) {
startups[i] = (StartupCommand) cmds[i];
}
attache = handleConnectedAgent(link, startups, request);
if (attache == null) {
s_logger.warn("Unable to create attache for agent: " + request);
}
return;
}
final long hostId = attache.getId();
if (s_logger.isDebugEnabled()) {
if (cmd instanceof PingRoutingCommand) {
final PingRoutingCommand ping = (PingRoutingCommand) cmd;
if (ping.getNewStates().size() > 0) {
s_logger.debug("SeqA " + hostId + "-" + request.getSequence() + ": Processing " + request);
} else {
logD = false;
s_logger.debug("Ping from " + hostId);
s_logger.trace("SeqA " + hostId + "-" + request.getSequence() + ": Processing " + request);
}
} else if (cmd instanceof PingCommand) {
logD = false;
s_logger.debug("Ping from " + hostId);
s_logger.trace("SeqA " + attache.getId() + "-" + request.getSequence() + ": Processing " + request);
} else {
s_logger.debug("SeqA " + attache.getId() + "-" + request.getSequence() + ": Processing " + request);
}
}
final Answer[] answers = new Answer[cmds.length];
for (int i = 0; i < cmds.length; i++) {
cmd = cmds[i];
Answer answer = null;
try {
if (cmd instanceof StartupRoutingCommand) {
final StartupRoutingCommand startup = (StartupRoutingCommand) cmd;
answer = new StartupAnswer(startup, attache.getId(), getPingInterval());
} else if (cmd instanceof StartupProxyCommand) {
final StartupProxyCommand startup = (StartupProxyCommand) cmd;
answer = new StartupAnswer(startup, attache.getId(), getPingInterval());
} else if (cmd instanceof StartupSecondaryStorageCommand) {
final StartupSecondaryStorageCommand startup = (StartupSecondaryStorageCommand) cmd;
answer = new StartupAnswer(startup, attache.getId(), getPingInterval());
} else if (cmd instanceof StartupStorageCommand) {
final StartupStorageCommand startup = (StartupStorageCommand) cmd;
answer = new StartupAnswer(startup, attache.getId(), getPingInterval());
} else if (cmd instanceof ShutdownCommand) {
final ShutdownCommand shutdown = (ShutdownCommand) cmd;
final String reason = shutdown.getReason();
s_logger.info("Host " + attache.getId() + " has informed us that it is shutting down with reason " + reason + " and detail " + shutdown.getDetail());
if (reason.equals(ShutdownCommand.Update)) {
//disconnectWithoutInvestigation(attache, Event.UpdateNeeded);
throw new CloudRuntimeException("Agent update not implemented");
} else if (reason.equals(ShutdownCommand.Requested)) {
disconnectWithoutInvestigation(attache, Event.ShutdownRequested);
}
return;
} else if (cmd instanceof AgentControlCommand) {
answer = handleControlCommand(attache, (AgentControlCommand) cmd);
} else {
handleCommands(attache, request.getSequence(), new Command[] { cmd });
if (cmd instanceof PingCommand) {
long cmdHostId = ((PingCommand) cmd).getHostId();
// if the router is sending a ping, verify the
// gateway was pingable
if (cmd instanceof PingRoutingCommand) {
boolean gatewayAccessible = ((PingRoutingCommand) cmd).isGatewayAccessible();
HostVO host = _hostDao.findById(Long.valueOf(cmdHostId));
if (!gatewayAccessible) {
// alert that host lost connection to
// gateway (cannot ping the default route)
DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
HostPodVO podVO = _podDao.findById(host.getPodId());
String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_ROUTING, host.getDataCenterId(), host.getPodId(), "Host lost connection to gateway, " + hostDesc, "Host [" + hostDesc
+ "] lost connection to gateway (default route) and is possibly having network connection issues.");
} else {
_alertMgr.clearAlert(AlertManager.ALERT_TYPE_ROUTING, host.getDataCenterId(), host.getPodId());
}
}
answer = new PingAnswer((PingCommand) cmd);
} else if (cmd instanceof ReadyAnswer) {
HostVO host = _hostDao.findById(attache.getId());
if (host == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cant not find host " + attache.getId());
}
}
answer = new Answer(cmd);
} else {
answer = new Answer(cmd);
}
}
} catch (final Throwable th) {
s_logger.warn("Caught: ", th);
answer = new Answer(cmd, false, th.getMessage());
}
answers[i] = answer;
}
response = new Response(request, answers, _nodeId, attache.getId());
if (s_logger.isDebugEnabled()) {
if (logD) {
s_logger.debug("SeqA " + attache.getId() + "-" + response.getSequence() + ": Sending " + response);
} else {
s_logger.trace("SeqA " + attache.getId() + "-" + response.getSequence() + ": Sending " + response);
}
}
try {
link.send(response.toBytes());
} catch (final ClosedChannelException e) {
s_logger.warn("Unable to send response because connection is closed: " + response);
}
}
protected void processResponse(final Link link, final Response response) {
final AgentAttache attache = (AgentAttache) link.attachment();
if (attache == null) {
s_logger.warn("Unable to process: " + response);
}
if (!attache.processAnswers(response.getSequence(), response)) {
s_logger.info("Host " + attache.getId() + " - Seq " + response.getSequence() + ": Response is not processed: " + response);
}
}
@Override
protected void doTask(final Task task) throws Exception {
Transaction txn = Transaction.open(Transaction.CLOUD_DB);
try {
final Type type = task.getType();
if (type == Task.Type.DATA) {
final byte[] data = task.getData();
try {
final Request event = Request.parse(data);
if (event instanceof Response) {
processResponse(task.getLink(), (Response) event);
} else {
processRequest(task.getLink(), event);
}
} catch (final UnsupportedVersionException e) {
s_logger.warn(e.getMessage());
// upgradeAgent(task.getLink(), data, e.getReason());
}
} else if (type == Task.Type.CONNECT) {
} else if (type == Task.Type.DISCONNECT) {
final Link link = task.getLink();
final AgentAttache attache = (AgentAttache) link.attachment();
if (attache != null) {
disconnectWithInvestigation(attache, Event.AgentDisconnected);
} else {
s_logger.info("Connection from " + link.getIpAddress() + " closed but no cleanup was done.");
link.close();
link.terminated();
}
}
} finally {
StackMaid.current().exitCleanup();
txn.close();
}
}
}
protected AgentManagerImpl() {
}
@Override
public boolean tapLoadingAgents(Long hostId, TapAgentsAction action) {
synchronized (_loadingAgents) {
if (action == TapAgentsAction.Add) {
_loadingAgents.add(hostId);
} else if (action == TapAgentsAction.Del) {
_loadingAgents.remove(hostId);
} else if (action == TapAgentsAction.Contains) {
return _loadingAgents.contains(hostId);
} else {
throw new CloudRuntimeException("Unkonwn TapAgentsAction " + action);
}
}
return true;
}
@Override
public boolean agentStatusTransitTo(HostVO host, Status.Event e, long msId) {
try {
_agentStatusLock.lock();
if (status_logger.isDebugEnabled()) {
ResourceState state = host.getResourceState();
StringBuilder msg = new StringBuilder("Transition:");
msg.append("[Resource state = ").append(state);
msg.append(", Agent event = ").append(e.toString());
msg.append(", Host id = ").append(host.getId()).append(", name = " + host.getName()).append("]");
status_logger.debug(msg);
}
host.setManagementServerId(msId);
try {
return _statusStateMachine.transitTo(host, e, host.getId(), _hostDao);
} catch (NoTransitionException e1) {
status_logger.debug("Cannot transit agent status with event " + e + " for host " + host.getId() + ", name=" + host.getName()
+ ", mangement server id is " + msId);
throw new CloudRuntimeException("Cannot transit agent status with event " + e + " for host " + host.getId() + ", mangement server id is "
+ msId + "," + e1.getMessage());
}
} finally {
_agentStatusLock.unlock();
}
}
public boolean disconnectAgent(HostVO host, Status.Event e, long msId) {
host.setDisconnectedOn(new Date());
if (e.equals(Status.Event.Remove)) {
host.setGuid(null);
host.setClusterId(null);
}
return agentStatusTransitTo(host, e, msId);
}
protected void disconnectWithoutInvestigation(AgentAttache attache, final Status.Event event) {
_executor.submit(new DisconnectTask(attache, event, false));
}
protected void disconnectWithInvestigation(AgentAttache attache, final Status.Event event) {
_executor.submit(new DisconnectTask(attache, event, true));
}
private void disconnectInternal(final long hostId, final Status.Event event, boolean invstigate) {
AgentAttache attache = findAttache(hostId);
if (attache != null) {
if (!invstigate) {
disconnectWithoutInvestigation(attache, event);
} else {
disconnectWithInvestigation(attache, event);
}
} else {
/* Agent is still in connecting process, don't allow to disconnect right away */
if (tapLoadingAgents(hostId, TapAgentsAction.Contains)) {
s_logger.info("Host " + hostId + " is being loaded so no disconnects needed.");
return;
}
HostVO host = _hostDao.findById(hostId);
if (host != null && host.getRemoved() == null) {
disconnectAgent(host, event, _nodeId);
}
}
}
public void disconnectWithInvestigation(final long hostId, final Status.Event event) {
disconnectInternal(hostId, event, true);
}
@Override
public void disconnectWithoutInvestigation(final long hostId, final Status.Event event) {
disconnectInternal(hostId, event, false);
}
@Override
public AgentAttache handleDirectConnectAgent(HostVO host, StartupCommand[] cmds, ServerResource resource, boolean forRebalance) throws ConnectionException {
AgentAttache attache;
attache = createAttacheForDirectConnect(host, resource);
StartupAnswer[] answers = new StartupAnswer[cmds.length];
for (int i = 0; i < answers.length; i++) {
answers[i] = new StartupAnswer(cmds[i], attache.getId(), _pingInterval);
}
attache.process(answers);
attache = notifyMonitorsOfConnection(attache, cmds, forRebalance);
return attache;
}
@Override
public void pullAgentToMaintenance(long hostId) {
AgentAttache attache = findAttache(hostId);
if (attache != null) {
attache.setMaintenanceMode(true);
// Now cancel all of the commands except for the active one.
attache.cancelAllCommands(Status.Disconnected, false);
}
}
@Override
public void pullAgentOutMaintenance(long hostId) {
AgentAttache attache = findAttache(hostId);
if (attache != null) {
attache.setMaintenanceMode(false);
}
}
}
|
package com.cloud.ha;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import com.cloud.agent.AgentManager;
import com.cloud.alert.AlertManager;
import com.cloud.cluster.ClusterManagerListener;
import com.cloud.cluster.ManagementServerHostVO;
import com.cloud.cluster.StackMaid;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InsufficientServerCapacityException;
import com.cloud.exception.OperationTimedoutException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.exception.VirtualMachineMigrationException;
import com.cloud.ha.dao.HighAvailabilityDao;
import com.cloud.host.Host;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.dao.HostDao;
import com.cloud.server.ManagementServer;
import com.cloud.storage.StorageManager;
import com.cloud.storage.dao.GuestOSCategoryDao;
import com.cloud.storage.dao.GuestOSDao;
import com.cloud.user.AccountManager;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.component.Adapters;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.component.Inject;
import com.cloud.utils.concurrency.NamedThreadFactory;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.fsm.NoTransitionException;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.Event;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.VirtualMachineProfile;
import com.cloud.vm.dao.VMInstanceDao;
/**
* HighAvailabilityManagerImpl coordinates the HA process. VMs are registered with the HA Manager for HA. The request is stored
* within a database backed work queue. HAManager has a number of workers that pick up these work items to perform HA on the
* VMs.
*
* The HA process goes as follows: 1. Check with the list of Investigators to determine that the VM is no longer running. If a
* Investigator finds the VM is still alive, the HA process is stopped and the state of the VM reverts back to its previous
* state. If a Investigator finds the VM is dead, then HA process is started on the VM, skipping step 2. 2. If the list of
* Investigators can not determine if the VM is dead or alive. The list of FenceBuilders is invoked to fence off the VM so that
* it won't do any damage to the storage and network. 3. The VM is marked as stopped. 4. The VM is started again via the normal
* process of starting VMs. Note that once the VM is marked as stopped, the user may have started the VM himself. 5. VMs that
* have re-started more than the configured number of times are marked as in Error state and the user is not allowed to restart
* the VM.
*
* @config {@table || Param Name | Description | Values | Default || || workers | number of worker threads to spin off to do the
* processing | int | 1 || || time.to.sleep | Time to sleep if no work items are found | seconds | 60 || || max.retries
* | number of times to retry start | int | 5 || || time.between.failure | Time elapsed between failures before we
* consider it as another retry | seconds | 3600 || || time.between.cleanup | Time to wait before the cleanup thread
* runs | seconds | 86400 || || force.ha | Force HA to happen even if the VM says no | boolean | false || ||
* ha.retry.wait | time to wait before retrying the work item | seconds | 120 || || stop.retry.wait | time to wait
* before retrying the stop | seconds | 120 || * }
**/
@Local(value = { HighAvailabilityManager.class })
public class HighAvailabilityManagerImpl implements HighAvailabilityManager, ClusterManagerListener {
protected static final Logger s_logger = Logger.getLogger(HighAvailabilityManagerImpl.class);
String _name;
WorkerThread[] _workers;
boolean _stopped;
long _timeToSleep;
@Inject
HighAvailabilityDao _haDao;
@Inject
VMInstanceDao _instanceDao;
@Inject
HostDao _hostDao;
@Inject
DataCenterDao _dcDao;
@Inject
HostPodDao _podDao;
@Inject
ClusterDetailsDao _clusterDetailsDao;
long _serverId;
@Inject(adapter = Investigator.class)
Adapters<Investigator> _investigators;
@Inject(adapter = FenceBuilder.class)
Adapters<FenceBuilder> _fenceBuilders;
@Inject
AgentManager _agentMgr;
@Inject
AlertManager _alertMgr;
@Inject
StorageManager _storageMgr;
@Inject
GuestOSDao _guestOSDao;
@Inject
GuestOSCategoryDao _guestOSCategoryDao;
@Inject
VirtualMachineManager _itMgr;
@Inject
AccountManager _accountMgr;
String _instance;
ScheduledExecutorService _executor;
int _stopRetryInterval;
int _investigateRetryInterval;
int _migrateRetryInterval;
int _restartRetryInterval;
int _maxRetries;
long _timeBetweenFailures;
long _timeBetweenCleanups;
boolean _forceHA;
protected HighAvailabilityManagerImpl() {
}
@Override
public Status investigate(final long hostId) {
final HostVO host = _hostDao.findById(hostId);
if (host == null) {
return null;
}
final Enumeration<Investigator> en = _investigators.enumeration();
Status hostState = null;
Investigator investigator = null;
while (en.hasMoreElements()) {
investigator = en.nextElement();
hostState = investigator.isAgentAlive(host);
if (hostState != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(investigator.getName() + " was able to determine host " + hostId + " is in " + hostState.toString());
}
return hostState;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug(investigator.getName() + " unable to determine the state of the host. Moving on.");
}
}
return null;
}
@Override
public void scheduleRestartForVmsOnHost(final HostVO host, boolean investigate) {
if (host.getType() != Host.Type.Routing) {
return;
}
// need to wait 60 seconds to make sure storage heartbeat check correct
long begin = System.currentTimeMillis();
while ( true ) {
try {
Thread.sleep(60*1000);
} catch (InterruptedException e) {
}
long now = System.currentTimeMillis();
if( (now - begin) > 60*1000) {
break;
}
}
s_logger.warn("Scheduling restart for VMs on host " + host.getId());
final List<VMInstanceVO> vms = _instanceDao.listByHostId(host.getId());
final DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
// send an email alert that the host is down
StringBuilder sb = null;
if ((vms != null) && !vms.isEmpty()) {
sb = new StringBuilder();
sb.append(" Starting HA on the following VMs: ");
// collect list of vm names for the alert email
VMInstanceVO vm = vms.get(0);
if (vm.isHaEnabled()) {
sb.append(" " + vm);
}
for (int i = 1; i < vms.size(); i++) {
vm = vms.get(i);
if (vm.isHaEnabled()) {
sb.append(" " + vm.getHostName());
}
}
}
// send an email alert that the host is down, include VMs
HostPodVO podVO = _podDao.findById(host.getPodId());
String hostDesc = "name: " + host.getName() + " (id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
_alertMgr.sendAlert(AlertManager.ALERT_TYPE_HOST, host.getDataCenterId(), host.getPodId(), "Host is down, " + hostDesc, "Host [" + hostDesc + "] is down."
+ ((sb != null) ? sb.toString() : ""));
for (final VMInstanceVO vm : vms) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Notifying HA Mgr of to restart vm " + vm.getId() + "-" + vm.getHostName());
}
scheduleRestart(vm, investigate);
}
}
@Override
public void scheduleStop(VMInstanceVO vm, long hostId, WorkType type) {
assert (type == WorkType.CheckStop || type == WorkType.ForceStop || type == WorkType.Stop);
if (_haDao.hasBeenScheduled(vm.getId(), type)) {
s_logger.info("There's already a job scheduled to stop " + vm);
return;
}
HaWorkVO work = new HaWorkVO(vm.getId(), vm.getType(), type, Step.Scheduled, hostId, vm.getState(), 0, vm.getUpdated());
_haDao.persist(work);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Scheduled " + work);
}
wakeupWorkers();
}
protected void wakeupWorkers() {
for (WorkerThread worker : _workers) {
worker.wakup();
}
}
@Override
public boolean scheduleMigration(final VMInstanceVO vm) {
final HaWorkVO work = new HaWorkVO(vm.getId(), vm.getType(), WorkType.Migration, Step.Scheduled, vm.getHostId(), vm.getState(), 0, vm.getUpdated());
_haDao.persist(work);
wakeupWorkers();
return true;
}
@Override
public void scheduleRestart(VMInstanceVO vm, boolean investigate) {
Long hostId = vm.getHostId();
if (hostId == null) {
try {
s_logger.debug("Found a vm that is scheduled to be restarted but has no host id: " + vm);
_itMgr.stateTransitTo(vm, Event.OperationFailed, null);
} catch (NoTransitionException e) {
}
return;
}
if (!investigate) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM does not require investigation so I'm marking it as Stopped: " + vm.toString());
}
short alertType = AlertManager.ALERT_TYPE_USERVM;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY;
}
if (!(_forceHA || vm.isHaEnabled())) {
String hostDesc = "id:" + vm.getHostId() + ", availability zone id:" + vm.getDataCenterIdToDeployIn() + ", pod id:" + vm.getPodIdToDeployIn();
_alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "VM (name: " + vm.getHostName() + ", id: " + vm.getId() + ") stopped unexpectedly on host " + hostDesc,
"Virtual Machine " + vm.getHostName() + " (id: " + vm.getId() + ") running on host [" + vm.getHostId() + "] stopped unexpectedly.");
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not HA enabled so we're done.");
}
}
try {
_itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
} catch (ResourceUnavailableException e) {
// FIXME
} catch (OperationTimedoutException e) {
// FIXME
} catch (ConcurrentOperationException e) {
// FIXME
}
}
List<HaWorkVO> items = _haDao.findPreviousHA(vm.getId());
int maxRetries = 0;
for (HaWorkVO item : items) {
if (maxRetries < item.getTimesTried() && !item.canScheduleNew(_timeBetweenFailures)) {
maxRetries = item.getTimesTried();
break;
}
}
HaWorkVO work = new HaWorkVO(vm.getId(), vm.getType(), WorkType.HA, investigate ? Step.Investigating : Step.Scheduled, hostId, vm.getState(), maxRetries + 1, vm.getUpdated());
_haDao.persist(work);
if (s_logger.isInfoEnabled()) {
s_logger.info("Schedule vm for HA: " + vm);
}
wakeupWorkers();
}
protected Long restart(HaWorkVO work) {
List<HaWorkVO> items = _haDao.listFutureHaWorkForVm(work.getInstanceId(), work.getId());
if (items.size() > 0) {
StringBuilder str = new StringBuilder("Cancelling this work item because newer ones have been scheduled. Work Ids = [");
for (HaWorkVO item : items) {
str.append(item.getId()).append(", ");
}
str.delete(str.length() - 2, str.length()).append("]");
s_logger.info(str.toString());
return null;
}
items = _haDao.listRunningHaWorkForVm(work.getInstanceId());
if (items.size() > 0) {
StringBuilder str = new StringBuilder("Waiting because there's HA work being executed on an item currently. Work Ids =[");
for (HaWorkVO item : items) {
str.append(item.getId()).append(", ");
}
str.delete(str.length() - 2, str.length()).append("]");
s_logger.info(str.toString());
return (System.currentTimeMillis() >> 10) + _investigateRetryInterval;
}
long vmId = work.getInstanceId();
VMInstanceVO vm = _itMgr.findById(work.getType(), work.getInstanceId());
if (vm == null) {
s_logger.info("Unable to find vm: " + vmId);
return null;
}
s_logger.info("HA on " + vm);
if (vm.getState() != work.getPreviousState() || vm.getUpdated() != work.getUpdateTime()) {
s_logger.info("VM " + vm + " has been changed. Current State = " + vm.getState() + " Previous State = " + work.getPreviousState() + " last updated = " + vm.getUpdated()
+ " previous updated = " + work.getUpdateTime());
return null;
}
short alertType = AlertManager.ALERT_TYPE_USERVM;
if (VirtualMachine.Type.DomainRouter.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_DOMAIN_ROUTER;
} else if (VirtualMachine.Type.ConsoleProxy.equals(vm.getType())) {
alertType = AlertManager.ALERT_TYPE_CONSOLE_PROXY;
}
HostVO host = _hostDao.findById(work.getHostId());
boolean isHostRemoved = false;
if (host == null) {
host = _hostDao.findByIdIncludingRemoved(work.getHostId());
if (host != null) {
s_logger.debug("VM " + vm.toString() + " is now no longer on host " + work.getHostId() + " as the host is removed");
isHostRemoved = true;
}
}
DataCenterVO dcVO = _dcDao.findById(host.getDataCenterId());
HostPodVO podVO = _podDao.findById(host.getPodId());
String hostDesc = "name: " + host.getName() + "(id:" + host.getId() + "), availability zone: " + dcVO.getName() + ", pod: " + podVO.getName();
Boolean alive = null;
if (work.getStep() == Step.Investigating) {
if (!isHostRemoved) {
if (vm.getHostId() == null || vm.getHostId() != work.getHostId()) {
s_logger.info("VM " + vm.toString() + " is now no longer on host " + work.getHostId());
return null;
}
Enumeration<Investigator> en = _investigators.enumeration();
Investigator investigator = null;
while (en.hasMoreElements()) {
investigator = en.nextElement();
alive = investigator.isVmAlive(vm, host);
s_logger.info(investigator.getName() + " found " + vm + "to be alive? " + alive);
if (alive != null) {
break;
}
}
boolean fenced = false;
if (alive == null) {
s_logger.debug("Fencing off VM that we don't know the state of");
Enumeration<FenceBuilder> enfb = _fenceBuilders.enumeration();
while (enfb.hasMoreElements()) {
FenceBuilder fb = enfb.nextElement();
Boolean result = fb.fenceOff(vm, host);
s_logger.info("Fencer " + fb.getName() + " returned " + result);
if (result != null && result) {
fenced = true;
break;
}
}
} else if (!alive) {
fenced = true;
} else {
s_logger.debug("VM " + vm.getHostName() + " is found to be alive by " + investigator.getName());
if (host.getStatus() == Status.Up) {
s_logger.info(vm + " is alive and host is up. No need to restart it.");
return null;
} else {
s_logger.debug("Rescheduling because the host is not up but the vm is alive");
return (System.currentTimeMillis() >> 10) + _investigateRetryInterval;
}
}
if (!fenced) {
s_logger.debug("We were unable to fence off the VM " + vm);
_alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
"Insufficient capacity to restart VM, name: " + vm.getHostName() + ", id: " + vmId + " which was running on host " + hostDesc);
return (System.currentTimeMillis() >> 10) + _restartRetryInterval;
}
try {
_itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
} catch (ResourceUnavailableException e) {
assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (OperationTimedoutException e) {
assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
} catch (ConcurrentOperationException e) {
assert false : "How do we hit this when force is true?";
throw new CloudRuntimeException("Caught exception even though it should be handled.", e);
}
work.setStep(Step.Scheduled);
_haDao.update(work.getId(), work);
} else {
assert false : "How come that HA step is Investigating and the host is removed?";
}
}
vm = _itMgr.findById(vm.getType(), vm.getId());
if (!_forceHA && !vm.isHaEnabled()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not HA enabled so we're done.");
}
return null; // VM doesn't require HA
}
if (!_storageMgr.canVmRestartOnAnotherServer(vm.getId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM can not restart on another server.");
}
return null;
}
if (work.getTimesTried() > _maxRetries) {
s_logger.warn("Retried to max times so deleting: " + vmId);
return null;
}
try {
VMInstanceVO started = _itMgr.advanceStart(vm, new HashMap<VirtualMachineProfile.Param, Object>(), _accountMgr.getSystemUser(), _accountMgr.getSystemAccount());
if (started != null) {
s_logger.info("VM is now restarted: " + vmId + " on " + started.getHostId());
return null;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Rescheduling VM " + vm.toString() + " to try again in " + _restartRetryInterval);
}
} catch (final InsufficientCapacityException e) {
s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
_alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
"Insufficient capacity to restart VM, name: " + vm.getHostName() + ", id: " + vmId + " which was running on host " + hostDesc);
} catch (final ResourceUnavailableException e) {
s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
_alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
"The Storage is unavailable for trying to restart VM, name: " + vm.getHostName() + ", id: " + vmId + " which was running on host " + hostDesc);
} catch (ConcurrentOperationException e) {
s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
_alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
"The Storage is unavailable for trying to restart VM, name: " + vm.getHostName() + ", id: " + vmId + " which was running on host " + hostDesc);
} catch (OperationTimedoutException e) {
s_logger.warn("Unable to restart " + vm.toString() + " due to " + e.getMessage());
_alertMgr.sendAlert(alertType, vm.getDataCenterIdToDeployIn(), vm.getPodIdToDeployIn(), "Unable to restart " + vm.getHostName() + " which was running on host " + hostDesc,
"The Storage is unavailable for trying to restart VM, name: " + vm.getHostName() + ", id: " + vmId + " which was running on host " + hostDesc);
}
vm = _itMgr.findById(vm.getType(), vm.getId());
work.setUpdateTime(vm.getUpdated());
work.setPreviousState(vm.getState());
return (System.currentTimeMillis() >> 10) + _restartRetryInterval;
}
public Long migrate(final HaWorkVO work) {
long vmId = work.getInstanceId();
long srcHostId = work.getHostId();
try {
work.setStep(Step.Migrating);
_haDao.update(work.getId(), work);
if (!_itMgr.migrateAway(work.getType(), vmId, srcHostId)) {
s_logger.warn("Unable to migrate vm from " + srcHostId);
_agentMgr.maintenanceFailed(srcHostId);
}
return null;
} catch (InsufficientServerCapacityException e) {
s_logger.warn("Insufficient capacity for migrating a VM.");
_agentMgr.maintenanceFailed(srcHostId);
return (System.currentTimeMillis() >> 10) + _migrateRetryInterval;
} catch (VirtualMachineMigrationException e) {
s_logger.warn("Looks like VM is still starting, we need to retry migrating the VM later.");
_agentMgr.maintenanceFailed(srcHostId);
return (System.currentTimeMillis() >> 10) + _migrateRetryInterval;
}
}
@Override
public void scheduleDestroy(VMInstanceVO vm, long hostId) {
final HaWorkVO work = new HaWorkVO(vm.getId(), vm.getType(), WorkType.Destroy, Step.Scheduled, hostId, vm.getState(), 0, vm.getUpdated());
_haDao.persist(work);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Scheduled " + work.toString());
}
wakeupWorkers();
}
@Override
public void cancelDestroy(VMInstanceVO vm, Long hostId) {
_haDao.delete(vm.getId(), WorkType.Destroy);
}
protected Long destroyVM(HaWorkVO work) {
final VMInstanceVO vm = _itMgr.findById(work.getType(), work.getInstanceId());
s_logger.info("Destroying " + vm.toString());
try {
if (vm.getState() != State.Destroyed) {
s_logger.info("VM is no longer in Destroyed state " + vm.toString());
return null;
}
if (vm.getHostId() != null) {
if (_itMgr.destroy(vm, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount())) {
s_logger.info("Successfully destroy " + vm);
return null;
}
s_logger.debug("Stop for " + vm + " was unsuccessful.");
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm + " has already been stopped");
}
return null;
}
} catch (final AgentUnavailableException e) {
s_logger.debug("Agnet is not available" + e.getMessage());
} catch (OperationTimedoutException e) {
s_logger.debug("operation timed out: " + e.getMessage());
} catch (ConcurrentOperationException e) {
s_logger.debug("concurrent operation: " + e.getMessage());
}
work.setTimesTried(work.getTimesTried() + 1);
return (System.currentTimeMillis() >> 10) + _stopRetryInterval;
}
protected Long stopVM(final HaWorkVO work) throws ConcurrentOperationException {
VMInstanceVO vm = _itMgr.findById(work.getType(), work.getInstanceId());
if (vm == null) {
s_logger.info("No longer can find VM " + work.getInstanceId() + ". Throwing away " + work);
work.setStep(Step.Done);
return null;
}
s_logger.info("Stopping " + vm);
try {
if (work.getWorkType() == WorkType.Stop) {
if (vm.getHostId() == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm.toString() + " has already been stopped");
}
return null;
}
if (_itMgr.advanceStop(vm, false, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount())) {
s_logger.info("Successfully stopped " + vm);
return null;
}
} else if (work.getWorkType() == WorkType.CheckStop) {
if ((vm.getState() != work.getPreviousState()) || vm.getUpdated() != work.getUpdateTime() || vm.getHostId() == null || vm.getHostId().longValue() != work.getHostId()) {
s_logger.info(vm + " is different now. Scheduled Host: " + work.getHostId() + " Current Host: " + (vm.getHostId() != null ? vm.getHostId() : "none") + " State: " + vm.getState());
return null;
}
if (_itMgr.advanceStop(vm, false, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount())) {
s_logger.info("Stop for " + vm + " was successful");
return null;
}
} else if (work.getWorkType() == WorkType.ForceStop) {
if ((vm.getState() != work.getPreviousState()) || vm.getUpdated() != work.getUpdateTime() || vm.getHostId() == null || vm.getHostId().longValue() != work.getHostId()) {
s_logger.info(vm + " is different now. Scheduled Host: " + work.getHostId() + " Current Host: " + (vm.getHostId() != null ? vm.getHostId() : "none") + " State: " + vm.getState());
return null;
}
if (_itMgr.advanceStop(vm, true, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount())) {
s_logger.info("Stop for " + vm + " was successful");
return null;
}
} else {
assert false : "Who decided there's other steps but didn't modify the guy who does the work?";
}
} catch (final ResourceUnavailableException e) {
s_logger.debug("Agnet is not available" + e.getMessage());
} catch (OperationTimedoutException e) {
s_logger.debug("operation timed out: " + e.getMessage());
}
work.setTimesTried(work.getTimesTried() + 1);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Stop was unsuccessful. Rescheduling");
}
return (System.currentTimeMillis() >> 10) + _stopRetryInterval;
}
@Override
public void cancelScheduledMigrations(final HostVO host) {
WorkType type = host.getType() == HostVO.Type.Storage ? WorkType.Stop : WorkType.Migration;
_haDao.deleteMigrationWorkItems(host.getId(), type, _serverId);
}
@Override
public List<VMInstanceVO> findTakenMigrationWork() {
List<HaWorkVO> works = _haDao.findTakenWorkItems(WorkType.Migration);
List<VMInstanceVO> vms = new ArrayList<VMInstanceVO>(works.size());
for (HaWorkVO work : works) {
vms.add(_instanceDao.findById(work.getInstanceId()));
}
return vms;
}
@Override
public boolean configure(final String name, final Map<String, Object> xmlParams) throws ConfigurationException {
_name = name;
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
_serverId = ((ManagementServer) ComponentLocator.getComponent(ManagementServer.Name)).getId();
_investigators = locator.getAdapters(Investigator.class);
_fenceBuilders = locator.getAdapters(FenceBuilder.class);
Map<String, String> params = new HashMap<String, String>();
final ConfigurationDao configDao = locator.getDao(ConfigurationDao.class);
if (configDao != null) {
params = configDao.getConfiguration(Long.toHexString(_serverId), xmlParams);
}
String value = params.get("workers");
final int count = NumbersUtil.parseInt(value, 1);
_workers = new WorkerThread[count];
for (int i = 0; i < _workers.length; i++) {
_workers[i] = new WorkerThread("HA-Worker-" + i);
}
value = params.get("force.ha");
_forceHA = Boolean.parseBoolean(value);
value = params.get("time.to.sleep");
_timeToSleep = NumbersUtil.parseInt(value, 60) * 1000;
value = params.get("max.retries");
_maxRetries = NumbersUtil.parseInt(value, 5);
value = params.get("time.between.failures");
_timeBetweenFailures = NumbersUtil.parseLong(value, 3600) * 1000;
value = params.get("time.between.cleanup");
_timeBetweenCleanups = NumbersUtil.parseLong(value, 3600 * 24);
value = params.get("stop.retry.interval");
_stopRetryInterval = NumbersUtil.parseInt(value, 10 * 60);
value = params.get("restart.retry.interval");
_restartRetryInterval = NumbersUtil.parseInt(value, 10 * 60);
value = params.get("investigate.retry.interval");
_investigateRetryInterval = NumbersUtil.parseInt(value, 1 * 60);
value = params.get("migrate.retry.interval");
_migrateRetryInterval = NumbersUtil.parseInt(value, 2 * 60);
_instance = params.get("instance");
if (_instance == null) {
_instance = "VMOPS";
}
_haDao.releaseWorkItems(_serverId);
_stopped = true;
_executor = Executors.newScheduledThreadPool(count, new NamedThreadFactory("HA"));
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public boolean start() {
_stopped = false;
for (final WorkerThread thread : _workers) {
thread.start();
}
_executor.scheduleAtFixedRate(new CleanupTask(), _timeBetweenCleanups, _timeBetweenCleanups, TimeUnit.SECONDS);
return true;
}
@Override
public boolean stop() {
_stopped = true;
wakeupWorkers();
_executor.shutdown();
return true;
}
protected class CleanupTask implements Runnable {
@Override
public void run() {
s_logger.info("HA Cleanup Thread Running");
try {
_haDao.cleanup(System.currentTimeMillis() - _timeBetweenFailures);
} catch (Exception e) {
s_logger.warn("Error while cleaning up", e);
} finally {
StackMaid.current().exitCleanup();
}
}
}
protected class WorkerThread extends Thread {
public WorkerThread(String name) {
super(name);
}
@Override
public void run() {
s_logger.info("Starting work");
while (!_stopped) {
HaWorkVO work = null;
try {
s_logger.trace("Checking the database");
work = _haDao.take(_serverId);
if (work == null) {
try {
synchronized (this) {
wait(_timeToSleep);
}
continue;
} catch (final InterruptedException e) {
s_logger.info("Interrupted");
continue;
}
}
NDC.push("work-" + work.getId());
s_logger.info("Processing " + work);
try {
final WorkType wt = work.getWorkType();
Long nextTime = null;
if (wt == WorkType.Migration) {
nextTime = migrate(work);
} else if (wt == WorkType.HA) {
nextTime = restart(work);
} else if (wt == WorkType.Stop || wt == WorkType.CheckStop || wt == WorkType.ForceStop) {
nextTime = stopVM(work);
} else if (wt == WorkType.Destroy) {
nextTime = destroyVM(work);
} else {
assert false : "How did we get here with " + wt.toString();
continue;
}
if (nextTime == null) {
s_logger.info("Completed " + work);
work.setStep(Step.Done);
} else {
s_logger.info("Rescheduling " + work + " to try again at " + new Date(nextTime << 10));
work.setTimeToTry(nextTime);
work.setServerId(null);
work.setDateTaken(null);
}
} catch (Exception e) {
s_logger.error("Terminating " + work, e);
work.setStep(Step.Error);
}
_haDao.update(work.getId(), work);
} catch (final Throwable th) {
s_logger.error("Caught this throwable, ", th);
} finally {
StackMaid.current().exitCleanup();
if (work != null) {
NDC.pop();
}
}
}
s_logger.info("Time to go home!");
}
public synchronized void wakup() {
notifyAll();
}
}
@Override
public void onManagementNodeJoined(List<ManagementServerHostVO> nodeList, long selfNodeId) {
}
@Override
public void onManagementNodeLeft(List<ManagementServerHostVO> nodeList, long selfNodeId) {
for (ManagementServerHostVO node : nodeList) {
_haDao.releaseWorkItems(node.getMsid());
}
}
@Override
public void onManagementNodeIsolated() {
}
}
|
package com.cloud.network.rules;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.commands.ListPortForwardingRulesCmd;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventVO;
import com.cloud.event.dao.EventDao;
import com.cloud.event.dao.UsageEventDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.IPAddressVO;
import com.cloud.network.IpAddress;
import com.cloud.network.Network;
import com.cloud.network.Network.GuestIpType;
import com.cloud.network.NetworkManager;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.FirewallRule.State;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.UserContext;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.Ip;
import com.cloud.vm.Nic;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.UserVmDao;
@Local(value={RulesManager.class, RulesService.class})
public class RulesManagerImpl implements RulesManager, RulesService, Manager {
private static final Logger s_logger = Logger.getLogger(RulesManagerImpl.class);
String _name;
@Inject PortForwardingRulesDao _forwardingDao;
@Inject FirewallRulesDao _firewallDao;
@Inject IPAddressDao _ipAddressDao;
@Inject UserVmDao _vmDao;
@Inject AccountManager _accountMgr;
@Inject NetworkManager _networkMgr;
@Inject EventDao _eventDao;
@Inject UsageEventDao _usageEventDao;
@Override
public void detectRulesConflict(FirewallRule newRule, IpAddress ipAddress) throws NetworkRuleConflictException {
assert newRule.getSourceIpAddress().equals(ipAddress.getAddress()) : "You passed in an ip address that doesn't match the address in the new rule";
List<FirewallRuleVO> rules = _firewallDao.listByIpAndNotRevoked(newRule.getSourceIpAddress());
assert (rules.size() >= 1) : "For network rules, we now always first persist the rule and then check for network conflicts so we should at least have one rule at this point.";
for (FirewallRuleVO rule : rules) {
if (rule.getId() == newRule.getId()) {
continue; // Skips my own rule.
}
if (rule.isOneToOneNat() && !newRule.isOneToOneNat()) {
throw new NetworkRuleConflictException("There is already port forwarding rule specified for the " + newRule.getSourceIpAddress());
} else if (!rule.isOneToOneNat() && newRule.isOneToOneNat()) {
throw new NetworkRuleConflictException("There is already 1 to 1 Nat rule specified for the " + newRule.getSourceIpAddress());
}
if (rule.getNetworkId() != newRule.getNetworkId() && rule.getState() != State.Revoke) {
throw new NetworkRuleConflictException("New rule is for a different network than what's specified in rule " + rule.getXid());
}
if ((rule.getSourcePortStart() <= newRule.getSourcePortStart() && rule.getSourcePortEnd() >= newRule.getSourcePortStart()) ||
(rule.getSourcePortStart() <= newRule.getSourcePortEnd() && rule.getSourcePortEnd() >= newRule.getSourcePortEnd()) ||
(newRule.getSourcePortStart() <= rule.getSourcePortStart() && newRule.getSourcePortEnd() >= rule.getSourcePortStart()) ||
(newRule.getSourcePortStart() <= rule.getSourcePortEnd() && newRule.getSourcePortEnd() >= rule.getSourcePortEnd())) {
//we allow port forwarding rules with the same parameters but different protocols
if (!(rule.getPurpose() == Purpose.PortForwarding && newRule.getPurpose() == Purpose.PortForwarding && !newRule.getProtocol().equalsIgnoreCase(rule.getProtocol()))) {
throw new NetworkRuleConflictException("The range specified, " + newRule.getSourcePortStart() + "-" + newRule.getSourcePortEnd() + ", conflicts with rule " + rule.getId() + " which has " + rule.getSourcePortStart() + "-" + rule.getSourcePortEnd());
}
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("No network rule conflicts detected for " + newRule + " against " + (rules.size() - 1) + " existing rules");
}
}
@Override
public void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller) throws InvalidParameterValueException, PermissionDeniedException {
if (ipAddress == null || ipAddress.getAllocatedTime() == null || ipAddress.getAllocatedToAccountId() == null) {
throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified.");
}
if (userVm == null) {
return;
}
if (userVm.getState() == VirtualMachine.State.Destroyed || userVm.getState() == VirtualMachine.State.Expunging) {
throw new InvalidParameterValueException("Invalid user vm: " + userVm.getId());
}
_accountMgr.checkAccess(caller, userVm);
// validate that IP address and userVM belong to the same account
if (ipAddress.getAllocatedToAccountId().longValue() != userVm.getAccountId()) {
throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " owner is not the same as owner of virtual machine " + userVm.toString());
}
// validate that userVM is in the same availability zone as the IP address
if (ipAddress.getDataCenterId() != userVm.getDataCenterId()) {
throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " is not in the same availability zone as virtual machine " + userVm.toString());
}
}
@Override @DB
public PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean isNat) throws NetworkRuleConflictException {
UserContext ctx = UserContext.current();
Account caller = ctx.getCaller();
Ip ipAddr = rule.getSourceIpAddress();
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddr);
Ip dstIp = rule.getDestinationIpAddress();
long networkId;
UserVmVO vm = null;
Network network = null;
if (vmId != null) {
// validate user VM exists
vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + vmId + ").");
}
dstIp = null;
List<? extends Nic> nics = _networkMgr.getNics(vm);
for (Nic nic : nics) {
Network ntwk = _networkMgr.getNetwork(nic.getNetworkId());
if (ntwk.getGuestType() == GuestIpType.Virtual && nic.getIp4Address() != null) {
network = ntwk;
dstIp = new Ip(nic.getIp4Address());
break;
}
}
if (network == null) {
throw new CloudRuntimeException("Unable to find ip address to map to in vm id=" + vmId);
}
} else {
network = _networkMgr.getNetwork(rule.getNetworkId());
if (network == null) {
throw new InvalidParameterValueException("Unable to get the network " + rule.getNetworkId());
}
}
_accountMgr.checkAccess(caller, network);
networkId = network.getId();
long accountId = network.getAccountId();
long domainId = network.getDomainId();
checkIpAndUserVm(ipAddress, vm, caller);
if (isNat && (ipAddress.isSourceNat())) {
throw new NetworkRuleConflictException("Can't do one to one NAT on ip address: " + ipAddress.getAddress());
}
Transaction txn = Transaction.currentTxn();
txn.start();
PortForwardingRuleVO newRule =
new PortForwardingRuleVO(rule.getXid(),
rule.getSourceIpAddress(),
rule.getSourcePortStart(),
rule.getSourcePortEnd(),
dstIp,
rule.getDestinationPortStart(),
rule.getDestinationPortEnd(),
rule.getProtocol(),
networkId,
accountId,
domainId, vmId, isNat);
newRule = _forwardingDao.persist(newRule);
if (isNat && !ipAddress.isOneToOneNat()) {
ipAddress.setOneToOneNat(true);
_ipAddressDao.update(ipAddress.getAddress(), ipAddress);
}
txn.commit();
try {
detectRulesConflict(newRule, ipAddress);
if (!_firewallDao.setStateToAdd(newRule)) {
throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
}
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_ADD, newRule.getAccountId(), 0, newRule.getId(), null);
_usageEventDao.persist(usageEvent);
return newRule;
} catch (Exception e) {
txn.start();
_forwardingDao.remove(newRule.getId());
if (isNat) {
ipAddress.setOneToOneNat(false);
_ipAddressDao.update(ipAddress.getAddress(), ipAddress);
}
txn.commit();
if (e instanceof NetworkRuleConflictException) {
throw (NetworkRuleConflictException)e;
}
throw new CloudRuntimeException("Unable to add rule for " + newRule.getSourceIpAddress(), e);
}
}
protected Pair<Network, Ip> getUserVmGuestIpAddress(UserVm vm) {
Ip dstIp = null;
List<? extends Nic> nics = _networkMgr.getNics(vm);
for (Nic nic : nics) {
Network ntwk = _networkMgr.getNetwork(nic.getNetworkId());
if (ntwk.getGuestType() == GuestIpType.Virtual) {
dstIp = new Ip(nic.getIp4Address());
return new Pair<Network, Ip>(ntwk, dstIp);
}
}
throw new CloudRuntimeException("Unable to find ip address to map to in " + vm.getId());
}
@DB
protected void revokeRule(FirewallRuleVO rule, Account caller, long userId) {
if (caller != null) {
_accountMgr.checkAccess(caller, rule);
}
Transaction txn = Transaction.currentTxn();
txn.start();
if (rule.getState() == State.Staged) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found a rule that is still in stage state so just removing it: " + rule);
}
_firewallDao.remove(rule.getId());
} else if (rule.getState() == State.Add || rule.getState() == State.Active) {
rule.setState(State.Revoke);
_firewallDao.update(rule.getId(), rule);
}
if (rule.isOneToOneNat()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Removing one to one nat so setting the ip back to one to one nat is false: " + rule.getSourceIpAddress());
}
IPAddressVO ipAddress = _ipAddressDao.findById(rule.getSourceIpAddress());
ipAddress.setOneToOneNat(false);
_ipAddressDao.update(ipAddress.getAddress(), ipAddress);
}
// Save and create the event
String ruleName = rule.getPurpose() == Purpose.Firewall ? "Firewall" : (rule.isOneToOneNat() ? "ip forwarding" : "port forwarding");
StringBuilder description = new StringBuilder("deleted ").append(ruleName).append(" rule [").append(rule.getSourceIpAddress()).append(":").append(rule.getSourcePortStart()).append("-").append(rule.getSourcePortEnd()).append("]");
if (rule.getPurpose() == Purpose.PortForwarding) {
PortForwardingRuleVO pfRule = (PortForwardingRuleVO)rule;
description.append("->[").append(pfRule.getDestinationIpAddress()).append(":").append(pfRule.getDestinationPortStart()).append("-").append(pfRule.getDestinationPortEnd()).append("]");
}
description.append(" ").append(rule.getProtocol());
txn.commit();
}
@Override
public boolean revokePortForwardingRule(long ruleId, boolean apply) {
UserContext ctx = UserContext.current();
Account caller = ctx.getCaller();
PortForwardingRuleVO rule = _forwardingDao.findById(ruleId);
if (rule == null) {
throw new InvalidParameterValueException("Unable to find " + ruleId);
}
_accountMgr.checkAccess(caller, rule);
revokeRule(rule, caller, ctx.getCallerUserId());
boolean success = false;
if (apply) {
success = applyPortForwardingRules(rule.getSourceIpAddress(), true);
} else {
success = true;
}
if(success){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_DELETE, rule.getAccountId(), 0, rule.getId(), null);
_usageEventDao.persist(usageEvent);
}
return success;
}
@Override
public boolean revokePortForwardingRule(long vmId) {
UserVmVO vm = _vmDao.findById(vmId);
if (vm == null) {
return false;
}
List<PortForwardingRuleVO> rules = _forwardingDao.listByVm(vmId);
for (PortForwardingRuleVO rule : rules) {
revokePortForwardingRule(rule.getId(), true);
}
return true;
}
public List<? extends FirewallRule> listFirewallRules(Ip ip) {
return _firewallDao.listByIpAndNotRevoked(ip);
}
@Override
public List<? extends PortForwardingRule> listPortForwardingRulesForApplication(Ip ip) {
return _forwardingDao.listForApplication(ip);
}
@Override
public List<? extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd) {
Account caller = UserContext.current().getCaller();
String ip = cmd.getIpAddress();
Pair<String, Long> accountDomainPair = _accountMgr.finalizeAccountDomainForList(caller, cmd.getAccountName(), cmd.getDomainId());
String accountName = accountDomainPair.first();
Long domainId = accountDomainPair.second();
if(cmd.getIpAddress() != null){
Ip ipAddress = new Ip(cmd.getIpAddress());
IPAddressVO ipAddressVO = _ipAddressDao.findById(ipAddress);
if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
throw new InvalidParameterValueException("Ip address not ready for port forwarding rules yet: " + ipAddress);
}
_accountMgr.checkAccess(caller, ipAddressVO);
}
Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<PortForwardingRuleVO> sb = _forwardingDao.createSearchBuilder();
sb.and("ip", sb.entity().getSourceIpAddress(), Op.EQ);
sb.and("accountId", sb.entity().getAccountId(), Op.EQ);
sb.and("domainId", sb.entity().getDomainId(), Op.EQ);
sb.and("oneToOneNat", sb.entity().isOneToOneNat(), Op.EQ);
SearchCriteria<PortForwardingRuleVO> sc = sb.create();
if (ip != null) {
sc.setParameters("ip", ip);
}
if (domainId != null) {
sc.setParameters("domainId", domainId);
if (accountName != null) {
Account account = _accountMgr.getActiveAccount(accountName, domainId);
sc.setParameters("accountId", account.getId());
}
}
sc.setParameters("oneToOneNat", false);
return _forwardingDao.search(sc, filter);
}
@Override
public boolean applyPortForwardingRules(Ip ip, boolean continueOnError) {
try {
return applyPortForwardingRules(ip, continueOnError, null);
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to reapply port forwarding rules for " + ip);
return false;
}
}
protected boolean applyPortForwardingRules(Ip ip, boolean continueOnError, Account caller) throws ResourceUnavailableException {
List<PortForwardingRuleVO> rules = _forwardingDao.listForApplication(ip);
if (rules.size() == 0) {
s_logger.debug("There are no rules to apply for " + ip);
return true;
}
if (caller != null) {
_accountMgr.checkAccess(caller, rules.toArray(new PortForwardingRuleVO[rules.size()]));
}
if (!_networkMgr.applyRules(rules, continueOnError)) {
s_logger.debug("Rules are not completely applied");
return false;
}
for (PortForwardingRuleVO rule : rules) {
if (rule.getState() == FirewallRule.State.Revoke) {
_forwardingDao.remove(rule.getId());
} else if (rule.getState() == FirewallRule.State.Add) {
rule.setState(FirewallRule.State.Active);
_forwardingDao.update(rule.getId(), rule);
}
}
return true;
}
@Override
public List<PortForwardingRuleVO> searchForIpForwardingRules(Ip ip, Long id, Long vmId, Long start, Long size) {
return _forwardingDao.searchNatRules(ip, id, vmId, start, size);
}
@Override
public boolean applyPortForwardingRules(Ip ip, Account caller) throws ResourceUnavailableException {
return applyPortForwardingRules(ip, false, caller);
}
@Override
public boolean revokeAllRules(Ip ip, long userId) throws ResourceUnavailableException {
List<PortForwardingRuleVO> rules = _forwardingDao.listByIpAndNotRevoked(ip);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + rules.size() + " rules for " + ip);
}
for (PortForwardingRuleVO rule : rules) {
revokeRule(rule, null, userId);
}
applyPortForwardingRules(ip, true, null);
// Now we check again in case more rules have been inserted.
rules = _forwardingDao.listByIpAndNotRevoked(ip);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Successfully released rules for " + ip + " and # of rules now = " + rules.size());
}
return rules.size() == 0;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public List<? extends FirewallRule> listFirewallRulesByIp(Ip ip) {
return null;
}
@Override
public boolean releasePorts(Ip ip, String protocol, FirewallRule.Purpose purpose, int... ports) {
return _firewallDao.releasePorts(ip, protocol, purpose, ports);
}
@Override @DB
public FirewallRuleVO[] reservePorts(IpAddress ip, String protocol, FirewallRule.Purpose purpose, int... ports) throws NetworkRuleConflictException {
FirewallRuleVO[] rules = new FirewallRuleVO[ports.length];
Transaction txn = Transaction.currentTxn();
txn.start();
for (int i = 0; i < ports.length; i++) {
rules[i] =
new FirewallRuleVO(null,
ip.getAddress(),
ports[i],
protocol,
ip.getAssociatedWithNetworkId(),
ip.getAllocatedToAccountId(),
ip.getAllocatedInDomainId(),
purpose, ip.isOneToOneNat());
rules[i] = _firewallDao.persist(rules[i]);
}
txn.commit();
boolean success = false;
try {
for (FirewallRuleVO newRule : rules) {
detectRulesConflict(newRule, ip);
}
success = true;
return rules;
} finally {
if (!success) {
txn.start();
for (FirewallRuleVO newRule : rules) {
_forwardingDao.remove(newRule.getId());
}
txn.commit();
}
}
}
@Override
public List<? extends PortForwardingRule> gatherPortForwardingRulesForApplication(List<? extends IpAddress> addrs) {
List<PortForwardingRuleVO> allRules = new ArrayList<PortForwardingRuleVO>();
for (IpAddress addr : addrs) {
if (!addr.readyToUse()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Skipping " + addr + " because it is not ready for propation yet.");
}
continue;
}
allRules.addAll(_forwardingDao.listForApplication(addr.getAddress()));
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found " + allRules.size() + " rules to apply for the addresses.");
}
return allRules;
}
@Override
public List<? extends PortForwardingRule> listByNetworkId(long networkId) {
return _forwardingDao.listByNetworkId(networkId);
}
}
|
package com.cloud.server;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Pattern;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.Resource;
import com.cloud.configuration.Resource.ResourceOwnerType;
import com.cloud.configuration.Resource.ResourceType;
import com.cloud.configuration.ResourceCountVO;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.configuration.dao.ResourceCountDao;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.domain.DomainVO;
import com.cloud.domain.dao.DomainDao;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.Network;
import com.cloud.network.Network.Provider;
import com.cloud.network.Network.Service;
import com.cloud.network.Network.State;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.guru.ControlNetworkGuru;
import com.cloud.network.guru.DirectPodBasedNetworkGuru;
import com.cloud.network.guru.PodBasedNetworkGuru;
import com.cloud.network.guru.PublicNetworkGuru;
import com.cloud.network.guru.StorageNetworkGuru;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.Availability;
import com.cloud.offerings.NetworkOfferingServiceMapVO;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.offerings.dao.NetworkOfferingServiceMapDao;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.test.IPRangeConfig;
import com.cloud.user.Account;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.dao.AccountDao;
import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.crypt.DBEncryptionUtil;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.Script;
import com.cloud.uuididentity.dao.IdentityDao;
public class ConfigurationServerImpl implements ConfigurationServer {
public static final Logger s_logger = Logger.getLogger(ConfigurationServerImpl.class.getName());
private final ConfigurationDao _configDao;
private final DataCenterDao _zoneDao;
private final HostPodDao _podDao;
private final DiskOfferingDao _diskOfferingDao;
private final ServiceOfferingDao _serviceOfferingDao;
private final NetworkOfferingDao _networkOfferingDao;
private final DataCenterDao _dataCenterDao;
private final NetworkDao _networkDao;
private final VlanDao _vlanDao;
private String _domainSuffix;
private final DomainDao _domainDao;
private final AccountDao _accountDao;
private final ResourceCountDao _resourceCountDao;
private final NetworkOfferingServiceMapDao _ntwkOfferingServiceMapDao;
private final IdentityDao _identityDao;
public ConfigurationServerImpl() {
ComponentLocator locator = ComponentLocator.getLocator(Name);
_configDao = locator.getDao(ConfigurationDao.class);
_zoneDao = locator.getDao(DataCenterDao.class);
_podDao = locator.getDao(HostPodDao.class);
_diskOfferingDao = locator.getDao(DiskOfferingDao.class);
_serviceOfferingDao = locator.getDao(ServiceOfferingDao.class);
_networkOfferingDao = locator.getDao(NetworkOfferingDao.class);
_dataCenterDao = locator.getDao(DataCenterDao.class);
_networkDao = locator.getDao(NetworkDao.class);
_vlanDao = locator.getDao(VlanDao.class);
_domainDao = locator.getDao(DomainDao.class);
_accountDao = locator.getDao(AccountDao.class);
_resourceCountDao = locator.getDao(ResourceCountDao.class);
_ntwkOfferingServiceMapDao = locator.getDao(NetworkOfferingServiceMapDao.class);
_identityDao = locator.getDao(IdentityDao.class);
}
@Override @DB
public void persistDefaultValues() throws InternalErrorException {
// Create system user and admin user
saveUser();
// Get init
String init = _configDao.getValue("init");
// Get domain suffix - needed for network creation
_domainSuffix = _configDao.getValue("guest.domain.suffix");
if (init == null || init.equals("false")) {
s_logger.debug("ConfigurationServer is saving default values to the database.");
// Save default Configuration Table values
List<String> categories = Config.getCategories();
for (String category : categories) {
// If this is not a premium environment, don't insert premium configuration values
if (!_configDao.isPremium() && category.equals("Premium")) {
continue;
}
List<Config> configs = Config.getConfigs(category);
for (Config c : configs) {
String name = c.key();
//if the config value already present in the db, don't insert it again
if (_configDao.findByName(name) != null) {
continue;
}
String instance = "DEFAULT";
String component = c.getComponent();
String value = c.getDefaultValue();
value = ("Hidden".equals(category)) ? DBEncryptionUtil.encrypt(value) : value;
String description = c.getDescription();
ConfigurationVO configVO = new ConfigurationVO(category, instance, component, name, value, description);
_configDao.persist(configVO);
}
}
_configDao.update(Config.UseSecondaryStorageVm.key(), Config.UseSecondaryStorageVm.getCategory(), "true");
s_logger.debug("ConfigurationServer made secondary storage vm required.");
_configDao.update(Config.SecStorageEncryptCopy.key(), Config.SecStorageEncryptCopy.getCategory(), "true");
s_logger.debug("ConfigurationServer made secondary storage copy encrypted.");
_configDao.update("secstorage.secure.copy.cert", "realhostip");
s_logger.debug("ConfigurationServer made secondary storage copy use realhostip.");
// Save default service offerings
createServiceOffering(User.UID_SYSTEM, "Small Instance", 1, 512, 500, "Small Instance", false, false, null);
createServiceOffering(User.UID_SYSTEM, "Medium Instance", 1, 1024, 1000, "Medium Instance", false, false, null);
// Save default disk offerings
createdefaultDiskOffering(null, "Small", "Small Disk, 5 GB", 5, null);
createdefaultDiskOffering(null, "Medium", "Medium Disk, 20 GB", 20, null);
createdefaultDiskOffering(null, "Large", "Large Disk, 100 GB", 100, null);
// Save the mount parent to the configuration table
String mountParent = getMountParent();
if (mountParent != null) {
_configDao.update(Config.MountParent.key(), Config.MountParent.getCategory(), mountParent);
s_logger.debug("ConfigurationServer saved \"" + mountParent + "\" as mount.parent.");
} else {
s_logger.debug("ConfigurationServer could not detect mount.parent.");
}
String hostIpAdr = NetUtils.getDefaultHostIp();
if (hostIpAdr != null) {
_configDao.update(Config.ManagementHostIPAdr.key(), Config.ManagementHostIPAdr.getCategory(), hostIpAdr);
s_logger.debug("ConfigurationServer saved \"" + hostIpAdr + "\" as host.");
}
// generate a single sign-on key
updateSSOKey();
//Create default network offerings
createDefaultNetworkOfferings();
//Create default networks
createDefaultNetworks();
//Create userIpAddress ranges
//Update existing vlans with networkId
Transaction txn = Transaction.currentTxn();
List<VlanVO> vlans = _vlanDao.listAll();
if (vlans != null && !vlans.isEmpty()) {
for (VlanVO vlan : vlans) {
if (vlan.getNetworkId().longValue() == 0) {
updateVlanWithNetworkId(vlan);
}
//Create vlan user_ip_address range
String ipPange = vlan.getIpRange();
String[] range = ipPange.split("-");
String startIp = range[0];
String endIp = range[1];
txn.start();
IPRangeConfig config = new IPRangeConfig();
long startIPLong = NetUtils.ip2Long(startIp);
long endIPLong = NetUtils.ip2Long(endIp);
config.savePublicIPRange(txn, startIPLong, endIPLong, vlan.getDataCenterId(), vlan.getId(), vlan.getNetworkId(), vlan.getPhysicalNetworkId());
txn.commit();
}
}
}
//Update resource count if needed
updateResourceCount();
// keystore for SSL/TLS connection
updateSSLKeystore();
// store the public and private keys in the database
updateKeyPairs();
// generate a random password used to authenticate zone-to-zone copy
generateSecStorageVmCopyPassword();
// Update the cloud identifier
updateCloudIdentifier();
updateUuids();
// Set init to true
_configDao.update("init", "Hidden", "true");
}
private void updateUuids() {
_identityDao.initializeDefaultUuid("disk_offering");
_identityDao.initializeDefaultUuid("network_offerings");
_identityDao.initializeDefaultUuid("vm_template");
_identityDao.initializeDefaultUuid("user");
_identityDao.initializeDefaultUuid("domain");
_identityDao.initializeDefaultUuid("account");
_identityDao.initializeDefaultUuid("guest_os");
_identityDao.initializeDefaultUuid("guest_os_category");
_identityDao.initializeDefaultUuid("hypervisor_capabilities");
_identityDao.initializeDefaultUuid("snapshot_policy");
_identityDao.initializeDefaultUuid("security_group");
_identityDao.initializeDefaultUuid("security_group_rule");
_identityDao.initializeDefaultUuid("physical_network");
_identityDao.initializeDefaultUuid("physical_network_traffic_types");
_identityDao.initializeDefaultUuid("physical_network_service_providers");
_identityDao.initializeDefaultUuid("virtual_router_providers");
_identityDao.initializeDefaultUuid("networks");
_identityDao.initializeDefaultUuid("user_ip_address");
}
private String getMountParent() {
return getEnvironmentProperty("mount.parent");
}
private String getEnvironmentProperty(String name) {
try {
final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
if (propsFile == null) {
return null;
} else {
final FileInputStream finputstream = new FileInputStream(propsFile);
final Properties props = new Properties();
props.load(finputstream);
finputstream.close();
return props.getProperty("mount.parent");
}
} catch (IOException e) {
return null;
}
}
@DB
protected void saveUser() {
// insert system account
String insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (1, 'system', '1', '1')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
}
// insert system user
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) VALUES (1, 'system', '', 1, 'system', 'cloud', now())";
txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
}
// insert admin user
long id = 2;
String username = "admin";
String firstname = "admin";
String lastname = "cloud";
String password = "password";
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return;
}
md5.reset();
BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes()));
String pwStr = pwInt.toString(16);
int padding = 32 - pwStr.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < padding; i++) {
sb.append('0'); // make sure the MD5 password is 32 digits long
}
sb.append(pwStr);
// create an account for the admin user first
insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (" + id + ", '" + username + "', '1', '1')";
txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
}
// now insert the user
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) " +
"VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())";
txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
}
try {
String tableName = "security_group";
try {
String checkSql = "SELECT * from network_group";
PreparedStatement stmt = txn.prepareAutoCloseStatement(checkSql);
stmt.executeQuery();
tableName = "network_group";
} catch (Exception ex) {
// if network_groups table exists, create the default security group there
}
insertSql = "SELECT * FROM " + tableName + " where account_id=2 and name='default'";
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
//save default security group
if (tableName.equals("security_group")) {
insertSql = "INSERT INTO " + tableName +" (name, description, account_id, domain_id) " +
"VALUES ('default', 'Default Security Group', 2, 1)";
} else {
insertSql = "INSERT INTO " + tableName +" (name, description, account_id, domain_id, account_name) " +
"VALUES ('default', 'Default Security Group', 2, 1, 'admin')";
}
txn = Transaction.currentTxn();
try {
stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
s_logger.warn("Failed to create default security group for default admin account due to ", ex);
}
}
rs.close();
} catch (Exception ex) {
s_logger.warn("Failed to create default security group for default admin account due to ", ex);
}
}
protected void updateCloudIdentifier() {
// Creates and saves a UUID as the cloud identifier
String currentCloudIdentifier = _configDao.getValue("cloud.identifier");
if (currentCloudIdentifier == null || currentCloudIdentifier.isEmpty()) {
String uuid = UUID.randomUUID().toString();
_configDao.update(Config.CloudIdentifier.key(),Config.CloudIdentifier.getCategory(), uuid);
}
}
private String getBase64Keystore(String keystorePath) throws IOException {
byte[] storeBytes = new byte[4094];
int len = 0;
try {
len = new FileInputStream(keystorePath).read(storeBytes);
} catch (EOFException e) {
} catch (Exception e) {
throw new IOException("Cannot read the generated keystore file");
}
if (len > 3000) { // Base64 codec would enlarge data by 1/3, and we have 4094 bytes in database entry at most
throw new IOException("KeyStore is too big for database! Length " + len);
}
byte[] encodeBytes = new byte[len];
System.arraycopy(storeBytes, 0, encodeBytes, 0, len);
return new String(Base64.encodeBase64(encodeBytes));
}
private void generateDefaultKeystore(String keystorePath) throws IOException {
String cn = "Cloudstack User";
String ou;
try {
ou = InetAddress.getLocalHost().getCanonicalHostName();
String[] group = ou.split("\\.");
// Simple check to see if we got IP Address...
boolean isIPAddress = Pattern.matches("[0-9]$", group[group.length - 1]);
if (isIPAddress) {
ou = "cloud.com";
} else {
ou = group[group.length - 1];
for (int i = group.length - 2; i >= 0 && i >= group.length - 3; i
ou = group[i] + "." + ou;
}
} catch (UnknownHostException ex) {
s_logger.info("Fail to get user's domain name. Would use cloud.com. ", ex);
ou = "cloud.com";
}
String o = ou;
String c = "Unknown";
String dname = "cn=\"" + cn + "\",ou=\"" + ou +"\",o=\"" + o + "\",c=\"" + c + "\"";
Script script = new Script(true, "keytool", 5000, null);
script.add("-genkey");
script.add("-keystore", keystorePath);
script.add("-storepass", "vmops.com");
script.add("-keypass", "vmops.com");
script.add("-keyalg", "RSA");
script.add("-validity", "3650");
script.add("-dname", dname);
String result = script.execute();
if (result != null) {
throw new IOException("Fail to generate certificate!");
}
}
protected void updateSSLKeystore() {
if (s_logger.isInfoEnabled()) {
s_logger.info("Processing updateSSLKeyStore");
}
String dbString = _configDao.getValue("ssl.keystore");
File confFile= PropertiesUtil.findConfigFile("db.properties");
/* This line may throw a NPE, but that's due to fail to find db.properities, meant some bugs in the other places */
String confPath = confFile.getParent();
String keystorePath = confPath + "/cloud.keystore";
File keystoreFile = new File(keystorePath);
boolean dbExisted = (dbString != null && !dbString.isEmpty());
s_logger.info("SSL keystore located at " + keystorePath);
try {
if (!dbExisted) {
if (!keystoreFile.exists()) {
generateDefaultKeystore(keystorePath);
s_logger.info("Generated SSL keystore.");
}
String base64Keystore = getBase64Keystore(keystorePath);
ConfigurationVO configVO = new ConfigurationVO("Hidden", "DEFAULT", "management-server", "ssl.keystore", DBEncryptionUtil.encrypt(base64Keystore), "SSL Keystore for the management servers");
_configDao.persist(configVO);
s_logger.info("Stored SSL keystore to database.");
} else if (keystoreFile.exists()) { // and dbExisted
// Check if they are the same one, otherwise override with local keystore
String base64Keystore = getBase64Keystore(keystorePath);
if (base64Keystore.compareTo(dbString) != 0) {
_configDao.update("ssl.keystore", "Hidden", base64Keystore);
s_logger.info("Updated database keystore with local one.");
}
} else { // !keystoreFile.exists() and dbExisted
// Export keystore to local file
byte[] storeBytes = Base64.decodeBase64(dbString);
try {
String tmpKeystorePath = "/tmp/tmpkey";
FileOutputStream fo = new FileOutputStream(tmpKeystorePath);
fo.write(storeBytes);
fo.close();
Script script = new Script(true, "cp", 5000, null);
script.add(tmpKeystorePath);
script.add(keystorePath);
String result = script.execute();
if (result != null) {
throw new IOException();
}
} catch (Exception e) {
throw new IOException("Fail to create keystore file!", e);
}
s_logger.info("Stored database keystore to local.");
}
} catch (Exception ex) {
s_logger.warn("Would use fail-safe keystore to continue.", ex);
}
}
@DB
protected void updateKeyPairs() {
// Grab the SSH key pair and insert it into the database, if it is not present
String userid = System.getProperty("user.name");
if (!userid.startsWith("cloud")){
return;
}
String already = _configDao.getValue("ssh.privatekey");
String homeDir = Script.runSimpleBashScript("echo ~");
if (s_logger.isInfoEnabled()) {
s_logger.info("Processing updateKeyPairs");
}
if (homeDir != null && homeDir.equalsIgnoreCase("~")) {
s_logger.error("No home directory was detected. Set the HOME environment variable to point to your user profile or home directory.");
throw new CloudRuntimeException("No home directory was detected. Set the HOME environment variable to point to your user profile or home directory.");
}
File privkeyfile = new File(homeDir + "/.ssh/id_rsa");
File pubkeyfile = new File(homeDir + "/.ssh/id_rsa.pub");
if (already == null || already.isEmpty()) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Systemvm keypairs not found in database. Need to store them in the database");
}
//FIXME: take a global database lock here for safety.
Script.runSimpleBashScript("if [ -f ~/.ssh/id_rsa ] ; then rm -f ~/.ssh/id_rsa ; fi; ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa -q");
byte[] arr1 = new byte[4094]; // configuration table column value size
try {
new DataInputStream(new FileInputStream(privkeyfile)).readFully(arr1);
} catch (EOFException e) {
} catch (Exception e) {
s_logger.error("Cannot read the private key file",e);
throw new CloudRuntimeException("Cannot read the private key file");
}
String privateKey = new String(arr1).trim();
byte[] arr2 = new byte[4094]; // configuration table column value size
try {
new DataInputStream(new FileInputStream(pubkeyfile)).readFully(arr2);
} catch (EOFException e) {
} catch (Exception e) {
s_logger.warn("Cannot read the public key file",e);
throw new CloudRuntimeException("Cannot read the public key file");
}
String publicKey = new String(arr2).trim();
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '"+DBEncryptionUtil.encrypt(privateKey)+"','Private key for the entire CloudStack')";
String insertSql2 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '"+DBEncryptionUtil.encrypt(publicKey)+"','Public key for the entire CloudStack')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt1 = txn.prepareAutoCloseStatement(insertSql1);
stmt1.executeUpdate();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Private key inserted into database");
}
} catch (SQLException ex) {
s_logger.error("SQL of the private key failed",ex);
throw new CloudRuntimeException("SQL of the private key failed");
}
try {
PreparedStatement stmt2 = txn.prepareAutoCloseStatement(insertSql2);
stmt2.executeUpdate();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Public key inserted into database");
}
} catch (SQLException ex) {
s_logger.error("SQL of the public key failed",ex);
throw new CloudRuntimeException("SQL of the public key failed");
}
} else {
s_logger.info("Keypairs already in database");
if (userid.startsWith("cloud")) {
s_logger.info("Keypairs already in database, updating local copy");
updateKeyPairsOnDisk(homeDir);
} else {
s_logger.info("Keypairs already in database, skip updating local copy (not running as cloud user)");
}
}
s_logger.info("Going to update systemvm iso with generated keypairs if needed");
injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath());
}
private void writeKeyToDisk(String key, String keyPath) {
Script.runSimpleBashScript("mkdir -p ~/.ssh");
File keyfile = new File( keyPath);
if (!keyfile.exists()) {
try {
keyfile.createNewFile();
} catch (IOException e) {
s_logger.warn("Failed to create file: " + e.toString());
throw new CloudRuntimeException("Failed to update keypairs on disk: cannot create key file " + keyPath);
}
}
if (keyfile.exists()) {
try {
FileOutputStream kStream = new FileOutputStream(keyfile);
kStream.write(key.getBytes());
kStream.close();
} catch (FileNotFoundException e) {
s_logger.warn("Failed to write key to " + keyfile.getAbsolutePath());
throw new CloudRuntimeException("Failed to update keypairs on disk: cannot find key file " + keyPath);
} catch (IOException e) {
s_logger.warn("Failed to write key to " + keyfile.getAbsolutePath());
throw new CloudRuntimeException("Failed to update keypairs on disk: cannot write to key file " + keyPath);
}
}
}
private void updateKeyPairsOnDisk(String homeDir ) {
String pubKey = _configDao.getValue("ssh.publickey");
String prvKey = _configDao.getValue("ssh.privatekey");
writeKeyToDisk(prvKey, homeDir + "/.ssh/id_rsa");
writeKeyToDisk(pubKey, homeDir + "/.ssh/id_rsa.pub");
}
protected void injectSshKeysIntoSystemVmIsoPatch(String publicKeyPath, String privKeyPath) {
String injectScript = "scripts/vm/systemvm/injectkeys.sh";
String scriptPath = Script.findScript("" , injectScript);
String systemVmIsoPath = Script.findScript("", "vms/systemvm.iso");
if ( scriptPath == null ) {
throw new CloudRuntimeException("Unable to find key inject script " + injectScript);
}
if (systemVmIsoPath == null) {
throw new CloudRuntimeException("Unable to find systemvm iso vms/systemvm.iso");
}
final Script command = new Script(scriptPath, s_logger);
command.add(publicKeyPath);
command.add(privKeyPath);
command.add(systemVmIsoPath);
final String result = command.execute();
if (result != null) {
s_logger.warn("Failed to inject generated public key into systemvm iso " + result);
throw new CloudRuntimeException("Failed to inject generated public key into systemvm iso " + result);
}
}
@DB
protected void generateSecStorageVmCopyPassword() {
String already = _configDao.getValue("secstorage.copy.password");
if (already == null) {
s_logger.info("Need to store secondary storage vm copy password in the database");
String password = PasswordGenerator.generateRandomPassword(12);
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt1 = txn.prepareAutoCloseStatement(insertSql1);
stmt1.executeUpdate();
s_logger.debug("secondary storage vm copy password inserted into database");
} catch (SQLException ex) {
s_logger.warn("Failed to insert secondary storage vm copy password",ex);
}
}
}
private void updateSSOKey() {
try {
String encodedKey = null;
// Algorithm for SSO Keys is SHA1, should this be configurable?
KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
SecretKey key = generator.generateKey();
encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());
_configDao.update(Config.SSOKey.key(), Config.SSOKey.getCategory(), encodedKey);
} catch (NoSuchAlgorithmException ex) {
s_logger.error("error generating sso key", ex);
}
}
@DB
protected HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp) throws InternalErrorException {
String[] cidrPair = cidr.split("\\/");
String cidrAddress = cidrPair[0];
int cidrSize = Integer.parseInt(cidrPair[1]);
if (startIp != null) {
if (endIp == null) {
endIp = NetUtils.getIpRangeEndIpFromCidr(cidrAddress, cidrSize);
}
}
// Create the new pod in the database
String ipRange;
if (startIp != null) {
ipRange = startIp + "-";
if (endIp != null) {
ipRange += endIp;
}
} else {
ipRange = "";
}
HostPodVO pod = new HostPodVO(podName, zoneId, gateway, cidrAddress, cidrSize, ipRange);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
if (_podDao.persist(pod) == null) {
txn.rollback();
throw new InternalErrorException("Failed to create new pod. Please contact Cloud Support.");
}
if (startIp != null) {
_zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIp);
}
String ipNums = _configDao.getValue("linkLocalIp.nums");
int nums = Integer.parseInt(ipNums);
if (nums > 16 || nums <= 0) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16");
}
/*local link ip address starts from 169.254.0.2 - 169.254.(nums)*/
String[] linkLocalIpRanges = NetUtils.getLinkLocalIPRange(nums);
if (linkLocalIpRanges == null) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16");
} else {
_zoneDao.addLinkLocalIpAddress(zoneId, pod.getId(), linkLocalIpRanges[0], linkLocalIpRanges[1]);
}
txn.commit();
} catch(Exception e) {
txn.rollback();
s_logger.error("Unable to create new pod due to " + e.getMessage(), e);
throw new InternalErrorException("Failed to create new pod. Please contact Cloud Support.");
}
return pod;
}
private DiskOfferingVO createdefaultDiskOffering(Long domainId, String name, String description, int numGibibytes, String tags) {
long diskSize = numGibibytes;
diskSize = diskSize * 1024 * 1024 * 1024;
tags = cleanupTags(tags);
DiskOfferingVO newDiskOffering = new DiskOfferingVO(domainId, name, description, diskSize,tags,false);
newDiskOffering.setUniqueName("Cloud.Com-" + name);
newDiskOffering = _diskOfferingDao.persistDeafultDiskOffering(newDiskOffering);
return newDiskOffering;
}
private ServiceOfferingVO createServiceOffering(long userId, String name, int cpu, int ramSize, int speed, String displayText, boolean localStorageRequired, boolean offerHA, String tags) {
tags = cleanupTags(tags);
ServiceOfferingVO offering = new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, offerHA, displayText, localStorageRequired, false, tags, false, null, false);
offering.setUniqueName("Cloud.Com-" + name);
offering = _serviceOfferingDao.persistSystemServiceOffering(offering);
return offering;
}
private String cleanupTags(String tags) {
if (tags != null) {
String[] tokens = tags.split(",");
StringBuilder t = new StringBuilder();
for (int i = 0; i < tokens.length; i++) {
t.append(tokens[i].trim()).append(",");
}
t.delete(t.length() - 1, t.length());
tags = t.toString();
}
return tags;
}
@DB
protected void createDefaultNetworkOfferings() {
NetworkOfferingVO publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPublicNetwork, TrafficType.Public);
publicNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(publicNetworkOffering);
NetworkOfferingVO managementNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemManagementNetwork, TrafficType.Management);
managementNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(managementNetworkOffering);
NetworkOfferingVO controlNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemControlNetwork, TrafficType.Control);
controlNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(controlNetworkOffering);
NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage);
storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering);
//populate providers
Map<Network.Service, Network.Provider> defaultSharedNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
defaultSharedNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter);
defaultSharedNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter);
defaultSharedNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter);
Map<Network.Service, Network.Provider> defaultIsolatedNetworkOfferingProviders = defaultSharedNetworkOfferingProviders;
Map<Network.Service, Network.Provider> defaultSharedSGNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
defaultSharedSGNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter);
defaultSharedSGNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter);
defaultSharedSGNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter);
defaultSharedSGNetworkOfferingProviders.put(Service.SecurityGroup, Provider.SecurityGroupProvider);
Map<Network.Service, Network.Provider> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap<Network.Service, Network.Provider>();
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dhcp, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dns, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.UserData, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Firewall, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Gateway, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Lb, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.SourceNat, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.StaticNat, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.PortForwarding, Provider.VirtualRouter);
defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, Provider.VirtualRouter);
//The only one diff between 1 and 2 network offerings is that the first one has SG enabled. In Basic zone only first network offering has to be enabled, in Advance zone - the second one
Transaction txn = Transaction.currentTxn();
txn.start();
//Offering
NetworkOfferingVO deafultSharedSGNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultSharedNetworkOfferingWithSGService,
"Offering for Shared Security group enabled networks",
TrafficType.Guest,
false, true, null, null, true, Availability.Optional,
null, Network.GuestType.Shared, true);
deafultSharedSGNetworkOffering.setState(NetworkOffering.State.Enabled);
deafultSharedSGNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(deafultSharedSGNetworkOffering);
for (Service service : defaultSharedSGNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(deafultSharedSGNetworkOffering.getId(), service, defaultSharedSGNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
//Offering
NetworkOfferingVO defaultSharedNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultSharedNetworkOffering,
"Offering for Shared networks",
TrafficType.Guest,
false, true, null, null, true, Availability.Optional,
null, Network.GuestType.Shared, true);
defaultSharedNetworkOffering.setState(NetworkOffering.State.Enabled);
defaultSharedNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultSharedNetworkOffering);
for (Service service : defaultSharedNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultSharedNetworkOffering.getId(), service, defaultSharedNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
//Offering
NetworkOfferingVO defaultIsolatedSourceNatEnabledNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService,
"Offering for Isolated networks with Source Nat service enabled",
TrafficType.Guest,
false, false, null, null, true, Availability.Required,
null, Network.GuestType.Isolated, true);
defaultIsolatedSourceNatEnabledNetworkOffering.setState(NetworkOffering.State.Enabled);
defaultIsolatedSourceNatEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedSourceNatEnabledNetworkOffering);
for (Service service : defaultIsolatedSourceNatEnabledNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultIsolatedSourceNatEnabledNetworkOffering.getId(), service, defaultIsolatedSourceNatEnabledNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
//Offering
NetworkOfferingVO defaultIsolatedEnabledNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultIsolatedNetworkOffering,
"Offering for Isolated networks with no Source Nat service",
TrafficType.Guest,
false, true, null, null, true, Availability.Optional,
null, Network.GuestType.Isolated, true);
defaultIsolatedEnabledNetworkOffering.setState(NetworkOffering.State.Enabled);
defaultIsolatedEnabledNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultIsolatedEnabledNetworkOffering);
for (Service service : defaultIsolatedNetworkOfferingProviders.keySet()) {
NetworkOfferingServiceMapVO offService = new NetworkOfferingServiceMapVO(defaultIsolatedEnabledNetworkOffering.getId(), service, defaultIsolatedNetworkOfferingProviders.get(service));
_ntwkOfferingServiceMapDao.persist(offService);
s_logger.trace("Added service for the network offering: " + offService);
}
txn.commit();
}
private void createDefaultNetworks() {
List<DataCenterVO> zones = _dataCenterDao.listAll();
long id = 1;
HashMap<TrafficType, String> guruNames = new HashMap<TrafficType, String>();
guruNames.put(TrafficType.Public, PublicNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Management, PodBasedNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Control, ControlNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Storage, StorageNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Guest, DirectPodBasedNetworkGuru.class.getSimpleName());
for (DataCenterVO zone : zones) {
long zoneId = zone.getId();
long accountId = 1L;
Long domainId = zone.getDomainId();
if (domainId == null) {
domainId = 1L;
}
//Create default networks - system only
List<NetworkOfferingVO> ntwkOff = _networkOfferingDao.listSystemNetworkOfferings();
for (NetworkOfferingVO offering : ntwkOff) {
if (offering.isSystemOnly()) {
long related = id;
long networkOfferingId = offering.getId();
Mode mode = Mode.Static;
String networkDomain = null;
BroadcastDomainType broadcastDomainType = null;
TrafficType trafficType= offering.getTrafficType();
boolean isNetworkDefault = false;
if (trafficType == TrafficType.Management) {
broadcastDomainType = BroadcastDomainType.Native;
} else if (trafficType == TrafficType.Control) {
broadcastDomainType = BroadcastDomainType.LinkLocal;
} else if (offering.getTrafficType() == TrafficType.Public) {
if ((zone.getNetworkType() == NetworkType.Advanced && !zone.isSecurityGroupEnabled()) || zone.getNetworkType() == NetworkType.Basic) {
broadcastDomainType = BroadcastDomainType.Vlan;
} else {
continue;
}
} else if (offering.getTrafficType() == TrafficType.Guest) {
if (zone.getNetworkType() == NetworkType.Basic) {
isNetworkDefault = true;
broadcastDomainType = BroadcastDomainType.Native;
} else {
continue;
}
networkDomain = "cs" + Long.toHexString(Account.ACCOUNT_ID_SYSTEM) + _domainSuffix;
} else if (offering.getTrafficType() == TrafficType.Storage) {
broadcastDomainType = BroadcastDomainType.Storage;
}
if (broadcastDomainType != null) {
NetworkVO network = new NetworkVO(id, trafficType, mode, broadcastDomainType, networkOfferingId, domainId, accountId, related, null, null, networkDomain, Network.GuestType.Shared, zoneId, null, null);
network.setGuruName(guruNames.get(network.getTrafficType()));
network.setDns1(zone.getDns1());
network.setDns2(zone.getDns2());
network.setState(State.Implemented);
_networkDao.persist(network, false, getServicesAndProvidersForNetwork(networkOfferingId));
id++;
}
}
}
}
}
private void updateVlanWithNetworkId(VlanVO vlan) {
long zoneId = vlan.getDataCenterId();
long networkId = 0L;
DataCenterVO zone = _zoneDao.findById(zoneId);
if (zone.getNetworkType() == NetworkType.Advanced) {
networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Public);
} else {
networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Guest);
}
vlan.setNetworkId(networkId);
_vlanDao.update(vlan.getId(), vlan);
}
private long getSystemNetworkIdByZoneAndTrafficType(long zoneId, TrafficType trafficType) {
//find system public network offering
Long networkOfferingId = null;
List<NetworkOfferingVO> offerings = _networkOfferingDao.listSystemNetworkOfferings();
for (NetworkOfferingVO offering: offerings) {
if (offering.getTrafficType() == trafficType) {
networkOfferingId = offering.getId();
break;
}
}
if (networkOfferingId == null) {
throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType);
}
List<NetworkVO> networks = _networkDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId);
if (networks == null || networks.isEmpty()) {
throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId);
}
return networks.get(0).getId();
}
@DB
public void updateResourceCount() {
ResourceType[] resourceTypes = Resource.ResourceType.values();
List<AccountVO> accounts = _accountDao.listAllIncludingRemoved();
List<DomainVO> domains = _domainDao.listAllIncludingRemoved();
List<ResourceCountVO> domainResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Domain);
List<ResourceCountVO> accountResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Account);
List<ResourceType> accountSupportedResourceTypes = new ArrayList<ResourceType>();
List<ResourceType> domainSupportedResourceTypes = new ArrayList<ResourceType>();
for (ResourceType resourceType : resourceTypes) {
if (resourceType.supportsOwner(ResourceOwnerType.Account)) {
accountSupportedResourceTypes.add(resourceType);
}
if (resourceType.supportsOwner(ResourceOwnerType.Domain)) {
domainSupportedResourceTypes.add(resourceType);
}
}
int accountExpectedCount = accountSupportedResourceTypes.size();
int domainExpectedCount = domainSupportedResourceTypes.size();
if ((domainResourceCount.size() < domainExpectedCount * domains.size())) {
s_logger.debug("resource_count table has records missing for some domains...going to insert them");
for (DomainVO domain : domains) {
//Lock domain
Transaction txn = Transaction.currentTxn();
txn.start();
_domainDao.lockRow(domain.getId(), true);
List<ResourceCountVO> domainCounts = _resourceCountDao.listByOwnerId(domain.getId(), ResourceOwnerType.Domain);
List<String> domainCountStr = new ArrayList<String>();
for (ResourceCountVO domainCount : domainCounts) {
domainCountStr.add(domainCount.getType().toString());
}
if (domainCountStr.size() < domainExpectedCount) {
for (ResourceType resourceType : domainSupportedResourceTypes) {
if (!domainCountStr.contains(resourceType.toString())) {
ResourceCountVO resourceCountVO = new ResourceCountVO(resourceType, 0, domain.getId(), ResourceOwnerType.Domain);
s_logger.debug("Inserting resource count of type " + resourceType + " for domain id=" + domain.getId());
_resourceCountDao.persist(resourceCountVO);
}
}
}
txn.commit();
}
}
if ((accountResourceCount.size() < accountExpectedCount * accounts.size())) {
s_logger.debug("resource_count table has records missing for some accounts...going to insert them");
for (AccountVO account : accounts) {
//lock account
Transaction txn = Transaction.currentTxn();
txn.start();
_accountDao.lockRow(account.getId(), true);
List<ResourceCountVO> accountCounts = _resourceCountDao.listByOwnerId(account.getId(), ResourceOwnerType.Account);
List<String> accountCountStr = new ArrayList<String>();
for (ResourceCountVO accountCount : accountCounts) {
accountCountStr.add(accountCount.getType().toString());
}
if (accountCountStr.size() < accountExpectedCount) {
for (ResourceType resourceType : accountSupportedResourceTypes) {
if (!accountCountStr.contains(resourceType.toString())) {
ResourceCountVO resourceCountVO = new ResourceCountVO(resourceType, 0, account.getId(), ResourceOwnerType.Account);
s_logger.debug("Inserting resource count of type " + resourceType + " for account id=" + account.getId());
_resourceCountDao.persist(resourceCountVO);
}
}
}
txn.commit();
}
}
}
public Map<String, String> getServicesAndProvidersForNetwork(long networkOfferingId) {
Map<String, String> svcProviders = new HashMap<String, String>();
List<NetworkOfferingServiceMapVO> servicesMap = _ntwkOfferingServiceMapDao.listByNetworkOfferingId(networkOfferingId);
for (NetworkOfferingServiceMapVO serviceMap : servicesMap) {
if (svcProviders.containsKey(serviceMap.getService())) {
continue;
}
svcProviders.put(serviceMap.getService(), serviceMap.getProvider());
}
return svcProviders;
}
}
|
package com.cloud.server;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import com.cloud.configuration.Config;
import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.dao.ConfigurationDao;
import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.HostPodVO;
import com.cloud.dc.VlanVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.VlanDao;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.network.Network.GuestIpType;
import com.cloud.network.Network.State;
import com.cloud.network.NetworkVO;
import com.cloud.network.Networks.BroadcastDomainType;
import com.cloud.network.Networks.Mode;
import com.cloud.network.Networks.TrafficType;
import com.cloud.network.dao.NetworkDao;
import com.cloud.network.guru.ControlNetworkGuru;
import com.cloud.network.guru.DirectPodBasedNetworkGuru;
import com.cloud.network.guru.PodBasedNetworkGuru;
import com.cloud.network.guru.PublicNetworkGuru;
import com.cloud.offering.NetworkOffering;
import com.cloud.offering.NetworkOffering.Availability;
import com.cloud.offerings.NetworkOfferingVO;
import com.cloud.offerings.dao.NetworkOfferingDao;
import com.cloud.service.ServiceOfferingVO;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.test.IPRangeConfig;
import com.cloud.user.Account;
import com.cloud.user.User;
import com.cloud.utils.PasswordGenerator;
import com.cloud.utils.PropertiesUtil;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.Script;
public class ConfigurationServerImpl implements ConfigurationServer {
public static final Logger s_logger = Logger.getLogger(ConfigurationServerImpl.class.getName());
private final ConfigurationDao _configDao;
private final DataCenterDao _zoneDao;
private final HostPodDao _podDao;
private final DiskOfferingDao _diskOfferingDao;
private final ServiceOfferingDao _serviceOfferingDao;
private final NetworkOfferingDao _networkOfferingDao;
private final DataCenterDao _dataCenterDao;
private final NetworkDao _networkDao;
private final VlanDao _vlanDao;
public ConfigurationServerImpl() {
ComponentLocator locator = ComponentLocator.getLocator(Name);
_configDao = locator.getDao(ConfigurationDao.class);
_zoneDao = locator.getDao(DataCenterDao.class);
_podDao = locator.getDao(HostPodDao.class);
_diskOfferingDao = locator.getDao(DiskOfferingDao.class);
_serviceOfferingDao = locator.getDao(ServiceOfferingDao.class);
_networkOfferingDao = locator.getDao(NetworkOfferingDao.class);
_dataCenterDao = locator.getDao(DataCenterDao.class);
_networkDao = locator.getDao(NetworkDao.class);
_vlanDao = locator.getDao(VlanDao.class);
}
@Override @DB
public void persistDefaultValues() throws InvalidParameterValueException, InternalErrorException {
// Create system user and admin user
saveUser();
// Get init
String init = _configDao.getValue("init");
if (init.equals("false")) {
s_logger.debug("ConfigurationServer is saving default values to the database.");
// Save default Configuration Table values
List<String> categories = Config.getCategories();
for (String category : categories) {
// If this is not a premium environment, don't insert premium configuration values
if (!_configDao.isPremium() && category.equals("Premium")) {
continue;
}
List<Config> configs = Config.getConfigs(category);
for (Config c : configs) {
String name = c.key();
//if the config value already present in the db, don't insert it again
if (_configDao.findByName(name) != null) {
continue;
}
String instance = "DEFAULT";
String component = c.getComponent();
String value = c.getDefaultValue();
String description = c.getDescription();
ConfigurationVO configVO = new ConfigurationVO(category, instance, component, name, value, description);
_configDao.persist(configVO);
}
}
_configDao.update("secondary.storage.vm", "true");
s_logger.debug("ConfigurationServer made secondary storage vm required.");
_configDao.update("secstorage.encrypt.copy", "true");
s_logger.debug("ConfigurationServer made secondary storage copy encrypted.");
_configDao.update("secstorage.secure.copy.cert", "realhostip");
s_logger.debug("ConfigurationServer made secondary storage copy use realhostip.");
// Save default service offerings
createServiceOffering(User.UID_SYSTEM, "Small Instance", 1, 512, 500, "Small Instance, $0.05 per hour", false, false, null);
createServiceOffering(User.UID_SYSTEM, "Medium Instance", 1, 1024, 1000, "Medium Instance, $0.10 per hour", false, false, null);
// Save default disk offerings
createDiskOffering(null, "Small", "Small Disk, 5 GB", 5, null);
createDiskOffering(null, "Medium", "Medium Disk, 20 GB", 20, null);
createDiskOffering(null, "Large", "Large Disk, 100 GB", 100, null);
// Save the mount parent to the configuration table
String mountParent = getMountParent();
if (mountParent != null) {
_configDao.update("mount.parent", mountParent);
s_logger.debug("ConfigurationServer saved \"" + mountParent + "\" as mount.parent.");
} else {
s_logger.debug("ConfigurationServer could not detect mount.parent.");
}
String hostIpAdr = getHost();
if (hostIpAdr != null) {
_configDao.update("host", hostIpAdr);
s_logger.debug("ConfigurationServer saved \"" + hostIpAdr + "\" as host.");
}
// generate a single sign-on key
updateSSOKey();
//Create default network offerings
createDefaultNetworkOfferings();
//Create default networks
createDefaultNetworks();
//Create userIpAddress ranges
//Update existing vlans with networkId
Transaction txn = Transaction.currentTxn();
List<VlanVO> vlans = _vlanDao.listAll();
if (vlans != null && !vlans.isEmpty()) {
for (VlanVO vlan : vlans) {
if (vlan.getNetworkId().longValue() == 0) {
updateVlanWithNetworkId(vlan);
}
//Create vlan user_ip_address range
String ipPange = vlan.getIpRange();
String[] range = ipPange.split("-");
String startIp = range[0];
String endIp = range[1];
txn.start();
IPRangeConfig config = new IPRangeConfig();
long startIPLong = NetUtils.ip2Long(startIp);
long endIPLong = NetUtils.ip2Long(endIp);
config.savePublicIPRange(txn, startIPLong, endIPLong, vlan.getDataCenterId(), vlan.getId(), vlan.getNetworkId());
txn.commit();
}
}
}
// store the public and private keys in the database
updateKeyPairs();
// generate a random password used to authenticate zone-to-zone copy
generateSecStorageVmCopyPassword();
// Update the cloud identifier
updateCloudIdentifier();
// Set init to true
_configDao.update("init", "true");
}
private String getEthDevice() {
String defaultRoute = Script.runSimpleBashScript("/sbin/route | grep default");
if (defaultRoute == null) {
return null;
}
String[] defaultRouteList = defaultRoute.split("\\s+");
if (defaultRouteList.length != 8) {
return null;
}
return defaultRouteList[7];
}
private String getMountParent() {
return getEnvironmentProperty("mount.parent");
}
private String getEnvironmentProperty(String name) {
try {
final File propsFile = PropertiesUtil.findConfigFile("environment.properties");
if (propsFile == null) {
return null;
} else {
final FileInputStream finputstream = new FileInputStream(propsFile);
final Properties props = new Properties();
props.load(finputstream);
finputstream.close();
return props.getProperty("mount.parent");
}
} catch (IOException e) {
return null;
}
}
@DB
protected String getHost() {
NetworkInterface nic = null;
String pubNic = getEthDevice();
if (pubNic == null) {
return null;
}
try {
nic = NetworkInterface.getByName(pubNic);
} catch (final SocketException e) {
return null;
}
String[] info = NetUtils.getNetworkParams(nic);
return info[0];
}
@DB
protected void saveUser() {
// insert system account
String insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (1, 'system', '1', '1')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
}
// insert system user
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) VALUES (1, 'system', '', 1, 'system', 'cloud', now())";
txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
}
// insert admin user
long id = 2;
String username = "admin";
String firstname = "admin";
String lastname = "cloud";
String password = "password";
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return;
}
md5.reset();
BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes()));
String pwStr = pwInt.toString(16);
int padding = 32 - pwStr.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < padding; i++) {
sb.append('0'); // make sure the MD5 password is 32 digits long
}
sb.append(pwStr);
// create an account for the admin user first
insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (" + id + ", '" + username + "', '1', '1')";
txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
}
// now insert the user
insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) " +
"VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())";
txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql);
stmt.executeUpdate();
} catch (SQLException ex) {
}
}
protected void updateCloudIdentifier() {
// Creates and saves a UUID as the cloud identifier
String currentCloudIdentifier = _configDao.getValue("cloud.identifier");
if (currentCloudIdentifier == null || currentCloudIdentifier.isEmpty()) {
String uuid = UUID.randomUUID().toString();
_configDao.update("cloud.identifier", uuid);
}
}
@DB
protected void updateKeyPairs() {
// Grab the SSH key pair and insert it into the database, if it is not present
if (s_logger.isInfoEnabled()) {
s_logger.info("Processing updateKeyPairs");
}
String already = _configDao.getValue("ssh.privatekey");
String homeDir = Script.runSimpleBashScript("echo ~");
String userid = System.getProperty("user.name");
if (homeDir == "~") {
s_logger.error("No home directory was detected. Set the HOME environment variable to point to your user profile or home directory.");
throw new CloudRuntimeException("No home directory was detected. Set the HOME environment variable to point to your user profile or home directory.");
}
File privkeyfile = new File(homeDir + "/.ssh/id_rsa");
File pubkeyfile = new File(homeDir + "/.ssh/id_rsa.pub");
if (already == null || already.isEmpty()) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Systemvm keypairs not found in database. Need to store them in the database");
}
//FIXME: take a global database lock here for safety.
Script.runSimpleBashScript("if [ -f ~/.ssh/id_rsa ] ; then true ; else yes '' | ssh-keygen -t rsa -q ; fi");
byte[] arr1 = new byte[4094]; // configuration table column value size
try {
new DataInputStream(new FileInputStream(privkeyfile)).readFully(arr1);
} catch (EOFException e) {
} catch (Exception e) {
s_logger.error("Cannot read the private key file",e);
throw new CloudRuntimeException("Cannot read the private key file");
}
String privateKey = new String(arr1).trim();
byte[] arr2 = new byte[4094]; // configuration table column value size
try {
new DataInputStream(new FileInputStream(pubkeyfile)).readFully(arr2);
} catch (EOFException e) {
} catch (Exception e) {
s_logger.warn("Cannot read the public key file",e);
throw new CloudRuntimeException("Cannot read the public key file");
}
String publicKey = new String(arr2).trim();
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.privatekey', '"+privateKey+"','Private key for the entire CloudStack')";
String insertSql2 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','ssh.publickey', '"+publicKey+"','Public key for the entire CloudStack')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt1 = txn.prepareAutoCloseStatement(insertSql1);
stmt1.executeUpdate();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Private key inserted into database");
}
} catch (SQLException ex) {
s_logger.error("SQL of the private key failed",ex);
throw new CloudRuntimeException("SQL of the private key failed");
}
try {
PreparedStatement stmt2 = txn.prepareAutoCloseStatement(insertSql2);
stmt2.executeUpdate();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Public key inserted into database");
}
} catch (SQLException ex) {
s_logger.error("SQL of the public key failed",ex);
throw new CloudRuntimeException("SQL of the public key failed");
}
} else {
s_logger.info("Keypairs already in database");
if (userid.startsWith("cloud")) {
s_logger.info("Keypairs already in database, updating local copy");
updateKeyPairsOnDisk(homeDir);
} else {
s_logger.info("Keypairs already in database, skip updating local copy (not running as cloud user)");
}
}
if (userid.startsWith("cloud")){
s_logger.info("Going to update systemvm iso with generated keypairs if needed");
injectSshKeysIntoSystemVmIsoPatch(pubkeyfile.getAbsolutePath(), privkeyfile.getAbsolutePath());
} else {
s_logger.info("Skip updating keypairs on systemvm iso (not running as cloud user)");
}
}
private void writeKeyToDisk(String key, String keyPath) {
Script.runSimpleBashScript("mkdir -p ~/.ssh");
File keyfile = new File( keyPath);
if (!keyfile.exists()) {
try {
keyfile.createNewFile();
} catch (IOException e) {
s_logger.warn("Failed to create file: " + e.toString());
throw new CloudRuntimeException("Failed to update keypairs on disk: cannot create key file " + keyPath);
}
}
if (keyfile.exists()) {
try {
FileOutputStream kStream = new FileOutputStream(keyfile);
kStream.write(key.getBytes());
kStream.close();
} catch (FileNotFoundException e) {
s_logger.warn("Failed to write key to " + keyfile.getAbsolutePath());
throw new CloudRuntimeException("Failed to update keypairs on disk: cannot find key file " + keyPath);
} catch (IOException e) {
s_logger.warn("Failed to write key to " + keyfile.getAbsolutePath());
throw new CloudRuntimeException("Failed to update keypairs on disk: cannot write to key file " + keyPath);
}
}
}
private void updateKeyPairsOnDisk(String homeDir ) {
String pubKey = _configDao.getValue("ssh.publickey");
String prvKey = _configDao.getValue("ssh.privatekey");
writeKeyToDisk(prvKey, homeDir + "/.ssh/id_rsa");
writeKeyToDisk(pubKey, homeDir + "/.ssh/id_rsa.pub");
}
protected void injectSshKeysIntoSystemVmIsoPatch(String publicKeyPath, String privKeyPath) {
String injectScript = "scripts/vm/systemvm/injectkeys.sh";
String scriptPath = Script.findScript("" , injectScript);
String systemVmIsoPath = Script.findScript("", "vms/systemvm.iso");
if ( scriptPath == null ) {
throw new CloudRuntimeException("Unable to find key inject script " + injectScript);
}
if (systemVmIsoPath == null) {
throw new CloudRuntimeException("Unable to find systemvm iso vms/systemvm.iso");
}
final Script command = new Script(scriptPath, s_logger);
command.add(publicKeyPath);
command.add(privKeyPath);
command.add(systemVmIsoPath);
final String result = command.execute();
if (result != null) {
s_logger.warn("Failed to inject generated public key into systemvm iso " + result);
throw new CloudRuntimeException("Failed to inject generated public key into systemvm iso " + result);
}
}
@DB
protected void generateSecStorageVmCopyPassword() {
String already = _configDao.getValue("secstorage.copy.password");
if (already == null) {
s_logger.info("Need to store secondary storage vm copy password in the database");
String password = PasswordGenerator.generateRandomPassword(12);
String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " +
"VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + password + "','Password used to authenticate zone-to-zone template copy requests')";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt1 = txn.prepareAutoCloseStatement(insertSql1);
stmt1.executeUpdate();
s_logger.debug("secondary storage vm copy password inserted into database");
} catch (SQLException ex) {
s_logger.warn("Failed to insert secondary storage vm copy password",ex);
}
}
}
private void updateSSOKey() {
try {
String encodedKey = null;
// Algorithm for SSO Keys is SHA1, should this be configurable?
KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
SecretKey key = generator.generateKey();
encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());
_configDao.update("security.singlesignon.key", encodedKey);
} catch (NoSuchAlgorithmException ex) {
s_logger.error("error generating sso key", ex);
}
}
@DB
protected HostPodVO createPod(long userId, String podName, long zoneId, String gateway, String cidr, String startIp, String endIp) throws InvalidParameterValueException, InternalErrorException {
String[] cidrPair = cidr.split("\\/");
String cidrAddress = cidrPair[0];
int cidrSize = Integer.parseInt(cidrPair[1]);
if (startIp != null) {
if (endIp == null) {
endIp = NetUtils.getIpRangeEndIpFromCidr(cidrAddress, cidrSize);
}
}
// Create the new pod in the database
String ipRange;
if (startIp != null) {
ipRange = startIp + "-";
if (endIp != null) {
ipRange += endIp;
}
} else {
ipRange = "";
}
HostPodVO pod = new HostPodVO(podName, zoneId, gateway, cidrAddress, cidrSize, ipRange);
Transaction txn = Transaction.currentTxn();
try {
txn.start();
if (_podDao.persist(pod) == null) {
txn.rollback();
throw new InternalErrorException("Failed to create new pod. Please contact Cloud Support.");
}
if (startIp != null) {
_zoneDao.addPrivateIpAddress(zoneId, pod.getId(), startIp, endIp);
}
String ipNums = _configDao.getValue("linkLocalIp.nums");
int nums = Integer.parseInt(ipNums);
if (nums > 16 || nums <= 0) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "is wrong, should be 1~16");
}
/*local link ip address starts from 169.254.0.2 - 169.254.(nums)*/
String[] linkLocalIpRanges = NetUtils.getLinkLocalIPRange(nums);
if (linkLocalIpRanges == null) {
throw new InvalidParameterValueException("The linkLocalIp.nums: " + nums + "may be wrong, should be 1~16");
} else {
_zoneDao.addLinkLocalIpAddress(zoneId, pod.getId(), linkLocalIpRanges[0], linkLocalIpRanges[1]);
}
txn.commit();
} catch(Exception e) {
txn.rollback();
s_logger.error("Unable to create new pod due to " + e.getMessage(), e);
throw new InternalErrorException("Failed to create new pod. Please contact Cloud Support.");
}
return pod;
}
private DiskOfferingVO createDiskOffering(Long domainId, String name, String description, int numGibibytes, String tags) throws InvalidParameterValueException {
long diskSize = numGibibytes * 1024;
tags = cleanupTags(tags);
DiskOfferingVO newDiskOffering = new DiskOfferingVO(domainId, name, description, diskSize,tags,false);
return _diskOfferingDao.persist(newDiskOffering);
}
private ServiceOfferingVO createServiceOffering(long userId, String name, int cpu, int ramSize, int speed, String displayText, boolean localStorageRequired, boolean offerHA, String tags) {
tags = cleanupTags(tags);
ServiceOfferingVO offering = new ServiceOfferingVO(name, cpu, ramSize, speed, null, null, offerHA, displayText, localStorageRequired, false, tags, false);
if ((offering = _serviceOfferingDao.persist(offering)) != null) {
return offering;
} else {
return null;
}
}
private String cleanupTags(String tags) {
if (tags != null) {
String[] tokens = tags.split(",");
StringBuilder t = new StringBuilder();
for (int i = 0; i < tokens.length; i++) {
t.append(tokens[i].trim()).append(",");
}
t.delete(t.length() - 1, t.length());
tags = t.toString();
}
return tags;
}
private void createDefaultNetworkOfferings() {
NetworkOfferingVO publicNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemPublicNetwork, TrafficType.Public);
publicNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(publicNetworkOffering);
NetworkOfferingVO managementNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemManagementNetwork, TrafficType.Management);
managementNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(managementNetworkOffering);
NetworkOfferingVO controlNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemControlNetwork, TrafficType.Control);
controlNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(controlNetworkOffering);
NetworkOfferingVO storageNetworkOffering = new NetworkOfferingVO(NetworkOfferingVO.SystemStorageNetwork, TrafficType.Storage);
storageNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(storageNetworkOffering);
NetworkOfferingVO guestNetworkOffering = new NetworkOfferingVO(
NetworkOffering.SystemGuestNetwork,
"System-Guest-Network",
TrafficType.Guest,
true, false, null, null, null, true,
Availability.Required,
true, true, true, //services - all true except for firewall/lb/vpn and gateway
false, false, false, false, GuestIpType.Direct);
guestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(guestNetworkOffering);
NetworkOfferingVO defaultGuestNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultVirtualizedNetworkOffering,
"Virtual Vlan",
TrafficType.Guest,
false, false, null, null, null, true,
Availability.Required,
true, true, true, //services
true, true, true, true, GuestIpType.Virtual);
defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestNetworkOffering);
NetworkOfferingVO defaultGuestDirectNetworkOffering = new NetworkOfferingVO(
NetworkOffering.DefaultDirectNetworkOffering,
"Direct",
TrafficType.Guest,
false, true, null, null, null, true,
Availability.Optional,
true, true, true, //services - all true except for firewall/lb/vpn and gateway
false, false, false, false, GuestIpType.Direct);
defaultGuestNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultGuestDirectNetworkOffering);
}
private void createDefaultNetworks() {
List<DataCenterVO> zones = _dataCenterDao.listAll();
long id = 1;
HashMap<TrafficType, String> guruNames = new HashMap<TrafficType, String>();
guruNames.put(TrafficType.Public, PublicNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Management, PodBasedNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Control, ControlNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Storage, PodBasedNetworkGuru.class.getSimpleName());
guruNames.put(TrafficType.Guest, DirectPodBasedNetworkGuru.class.getSimpleName());
for (DataCenterVO zone : zones) {
long zoneId = zone.getId();
long accountId = 1L;
Long domainId = zone.getDomainId();
if (domainId == null) {
domainId = 1L;
}
//Create default networks - system only
List<NetworkOfferingVO> ntwkOff = _networkOfferingDao.listSystemNetworkOfferings();
for (NetworkOfferingVO offering : ntwkOff) {
if (offering.isSystemOnly()) {
long related = id;
long networkOfferingId = offering.getId();
Mode mode = Mode.Static;
BroadcastDomainType broadcastDomainType = null;
TrafficType trafficType= offering.getTrafficType();
boolean isNetworkDefault = false;
if (trafficType == TrafficType.Management || trafficType == TrafficType.Storage) {
broadcastDomainType = BroadcastDomainType.Native;
} else if (trafficType == TrafficType.Control) {
broadcastDomainType = BroadcastDomainType.LinkLocal;
} else if (offering.getTrafficType() == TrafficType.Public) {
if (zone.getNetworkType() == NetworkType.Advanced) {
broadcastDomainType = BroadcastDomainType.Vlan;
} else {
continue;
}
} else if (offering.getTrafficType() == TrafficType.Guest) {
if (zone.getNetworkType() == NetworkType.Basic) {
isNetworkDefault = true;
broadcastDomainType = BroadcastDomainType.Native;
} else {
continue;
}
}
if (broadcastDomainType != null) {
NetworkVO network = new NetworkVO(id, trafficType, null, mode, broadcastDomainType, networkOfferingId, zoneId, domainId, accountId, related, null, null, true, isNetworkDefault);
network.setGuruName(guruNames.get(network.getTrafficType()));
network.setDns1(zone.getDns1());
network.setDns2(zone.getDns2());
network.setState(State.Implemented);
_networkDao.persist(network, false);
id++;
}
}
}
}
}
private void updateVlanWithNetworkId(VlanVO vlan) {
long zoneId = vlan.getDataCenterId();
long networkId = 0L;
DataCenterVO zone = _zoneDao.findById(zoneId);
if (zone.getNetworkType() == NetworkType.Advanced) {
networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Public);
} else {
networkId = getSystemNetworkIdByZoneAndTrafficType(zoneId, TrafficType.Guest);
}
vlan.setNetworkId(networkId);
_vlanDao.update(vlan.getId(), vlan);
}
private long getSystemNetworkIdByZoneAndTrafficType(long zoneId, TrafficType trafficType) {
//find system public network offering
Long networkOfferingId = null;
List<NetworkOfferingVO> offerings = _networkOfferingDao.listSystemNetworkOfferings();
for (NetworkOfferingVO offering: offerings) {
if (offering.getTrafficType() == trafficType) {
networkOfferingId = offering.getId();
break;
}
}
if (networkOfferingId == null) {
throw new InvalidParameterValueException("Unable to find system network offering with traffic type " + trafficType);
}
List<NetworkVO> networks = _networkDao.listBy(Account.ACCOUNT_ID_SYSTEM, networkOfferingId, zoneId);
if (networks == null || networks.isEmpty()) {
throw new InvalidParameterValueException("Unable to find network with traffic type " + trafficType + " in zone " + zoneId);
}
return networks.get(0).getId();
}
}
|
package org.mg.server;
import static org.jboss.netty.channel.Channels.pipeline;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.util.CharsetUtil;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.littleshoot.proxy.Launcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultXmppProxy implements XmppProxy {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ClientSocketChannelFactory channelFactory =
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
private static final String MAC_ADDRESS;
static {
String tempMac;
try {
tempMac = getMacAddress();
} catch (final SocketException e) {
e.printStackTrace();
tempMac = String.valueOf(RandomUtils.nextLong());
}
MAC_ADDRESS = tempMac.trim();
}
public DefaultXmppProxy() {
// Start the HTTP proxy server that we relay data to. It has more
// developed logic for handling different types of requests, and we'd
// otherwise have to duplicate that here.
Launcher.main("7777");
}
public void start() throws XMPPException, IOException {
final Properties props = new Properties();
final File propsDir = new File(System.getProperty("user.home"), ".mg");
final File propsFile = new File(propsDir, "mg.properties");
if (!propsFile.isFile()) {
System.err.println("No properties file found at "+propsFile+
". That file is required and must contain a property for " +
"'user' and 'pass'.");
System.exit(0);
}
props.load(new FileInputStream(propsFile));
final String user = props.getProperty("google.server.user");
final String pass = props.getProperty("google.server.pwd");
final Collection<XMPPConnection> xmppConnections =
new ArrayList<XMPPConnection>();
for (int i = 0; i < 10; i++) {
// We create a bunch of connections to allow us to process as much
// incoming data as possible.
final XMPPConnection xmpp = newConnection(user, pass);
xmppConnections.add(xmpp);
log.info("Created connection for user: {}", xmpp.getUser());
}
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
for (final XMPPConnection conn : xmppConnections) {
log.info("Disconnecting user: {}", conn.getUser());
conn.disconnect();
}
}
}, "XMPP-Disconnect-On-Shutdown"));
}
private XMPPConnection newConnection(final String user, final String pass) {
for (int i = 0; i < 10; i++) {
try {
return newSingleConnection(user, pass);
} catch (final XMPPException e) {
log.error("Could not create XMPP connection", e);
}
}
throw new RuntimeException("Could not connect to XMPP server");
}
private XMPPConnection newSingleConnection(final String user,
final String pass) throws XMPPException {
final ConnectionConfiguration config =
new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
config.setCompressionEnabled(true);
final XMPPConnection conn = new XMPPConnection(config);
conn.connect();
conn.login(user, pass, "MG");
final Roster roster = conn.getRoster();
roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
final ChatManager cm = conn.getChatManager();
final ChatManagerListener listener = new ChatManagerListener() {
public void chatCreated(final Chat chat,
final boolean createdLocally) {
log.info("Created a chat!!");
final ConcurrentHashMap<String, ChannelFuture> proxyConnections =
new ConcurrentHashMap<String, ChannelFuture>();
final Collection<String> removedConnections =
new HashSet<String>();
final Collection<ChannelFuture> chatChannels =
new HashSet<ChannelFuture>();
// We need to listen for the unavailability of clients we're
// chatting with so we can disconnect from their associated
// remote servers.
final PacketListener pl = new PacketListener() {
public void processPacket(final Packet pack) {
if (!(pack instanceof Presence)) return;
final Presence pres = (Presence) pack;
final String from = pres.getFrom();
final String participant = chat.getParticipant();
log.info("Comparing presence packet from "+from+
" to particant "+participant);
if (from.equals(participant) && !pres.isAvailable()) {
log.info("Closing all channels for this chat");
synchronized(chatChannels) {
for (final ChannelFuture cf : chatChannels) {
log.info("Closing channel to local proxy");
cf.getChannel().close();
}
}
}
}
};
// Register the listener.
conn.addPacketListener(pl, null);
final MessageListener ml = new MessageListener() {
public void processMessage(final Chat ch, final Message msg) {
log.info("Got message!!");
log.info("Property names: {}", msg.getPropertyNames());
log.info("SEQUENCE #: {}", msg.getProperty("SEQ"));
log.info("FROM: {}",msg.getFrom());
log.info("TO: {}",msg.getTo());
final String smac = (String) msg.getProperty("SMAC");
log.info("SMAC: {}", smac);
if (StringUtils.isNotBlank(smac) &&
smac.trim().equals(MAC_ADDRESS)) {
log.warn("IGNORING MESSAGE FROM OURSELVES!!");
return;
}
final String closeString =
(String) msg.getProperty("CLOSE");
log.info("Close value: {}", closeString);
final boolean close;
if (StringUtils.isNotBlank(closeString) &&
closeString.trim().equalsIgnoreCase("true")) {
log.info("Got close true");
close = true;
}
else {
close = false;
final String data = (String) msg.getProperty("HTTP");
if (StringUtils.isBlank(data)) {
log.warn("HTTP IS BLANK?? IGNORING...");
return;
}
}
log.info("Getting channel future...");
final ChannelFuture cf =
getChannelFuture(msg, chat, close,
proxyConnections, removedConnections, conn);
log.info("Got channel: {}", cf);
if (cf == null) {
log.info("Null channel future! Returning");
return;
}
if (close) {
log.info("Received close from client...closing " +
"connection to the proxy");
cf.getChannel().close();
// This will get added to the removed connections
// in the close listener.
chatChannels.remove(cf);
return;
}
chatChannels.add(cf);
// TODO: Check the sequence number??
final ChannelBuffer cb = xmppToHttpChannelBuffer(msg);
if (cf.getChannel().isConnected()) {
cf.getChannel().write(cb);
}
else {
cf.addListener(new ChannelFutureListener() {
public void operationComplete(
final ChannelFuture future)
throws Exception {
cf.getChannel().write(cb);
}
});
}
}
};
chat.addMessageListener(ml);
}
};
cm.addChatListener(listener);
return conn;
}
private ChannelBuffer xmppToHttpChannelBuffer(final Message msg) {
final String data = (String) msg.getProperty("HTTP");
final byte[] raw =
Base64.decodeBase64(data.getBytes(CharsetUtil.UTF_8));
return ChannelBuffers.wrappedBuffer(raw);
}
/**
* This gets a channel to connect to the local HTTP proxy on. This is
* slightly complex, as we're trying to mimic the state as if this HTTP
* request is coming in to a "normal" LittleProxy instance instead of
* having the traffic tunneled through XMPP. So we create a separate
* connection to the proxy just as those separate connections were made
* from the browser to the proxy originally on the remote end.
*
* If there's already an existing connection mimicking the original
* connection, we use that.
*
* @param key The key for the remote IP/port pair.
* @param chat The chat session across Google Talk -- we need this to
* send responses back to the original caller.
* @param close Whether or not this is a message to close the connection -
* we don't want to open a new connection if it is.
* @param connections The connections to the local proxy that are
* associated with this chat.
* @param removedConnections Keeps track of connections we've removed --
* for debugging.
* @param conn The XMPP connection.
* @return The {@link ChannelFuture} that will connect to the local
* LittleProxy instance.
*/
private ChannelFuture getChannelFuture(final Message message,
final Chat chat, final boolean close,
final Map<String,ChannelFuture> connections,
final Collection<String> removedConnections,
final XMPPConnection conn) {
// The other side will also need to know where the
// request came from to differentiate incoming HTTP
// connections.
log.info("Getting properties...");
// Note these will fail if the original properties were not set as
// strings.
final String mac = (String) message.getProperty("MAC");
final String hc = (String) message.getProperty("HASHCODE");
// We can sometimes get messages back that were not intended for us.
// Just ignore them.
if (mac == null || hc == null) {
log.error("Message not intended for us?!?!?\n" +
"Null MAC and/or HASH and to: "+message.getTo());
return null;
}
final String key = mac + hc;
log.info("Getting channel future for key: {}", key);
synchronized (connections) {
if (connections.containsKey(key)) {
log.info("Using existing connection");
return connections.get(key);
}
if (close) {
// We've likely already closed the connection in this case.
log.warn("Returning null channel on close call");
return null;
}
if (removedConnections.contains(key)) {
log.warn("KEY IS IN REMOVED CONNECTIONS: "+key);
}
// Configure the client.
final ClientBootstrap cb = new ClientBootstrap(this.channelFactory);
final ChannelPipelineFactory cpf = new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
final ChannelPipeline pipeline = pipeline();
final class HttpChatRelay extends SimpleChannelUpstreamHandler {
private long sequenceNumber = 0L;
@Override
public void messageReceived(
final ChannelHandlerContext ctx,
final MessageEvent me) throws Exception {
//log.info("HTTP message received from proxy on " +
// "relayer: {}", me.getMessage());
final Message msg = new Message();
final ByteBuffer buf =
((ChannelBuffer) me.getMessage()).toByteBuffer();
final byte[] raw = toRawBytes(buf);
final String base64 =
Base64.encodeBase64URLSafeString(raw);
log.info("Connection ID: {}", conn.getConnectionID());
log.info("Connection host: {}", conn.getHost());
log.info("Connection service name: {}", conn.getServiceName());
log.info("Connection user: {}", conn.getUser());
msg.setTo(chat.getParticipant());
msg.setFrom(conn.getUser());
msg.setProperty("HTTP", base64);
msg.setProperty("MD5", toMd5(raw));
msg.setProperty("SEQ", sequenceNumber);
msg.setProperty("HASHCODE", hc);
msg.setProperty("MAC", mac);
// This is the server-side MAC address. This is
// useful because there are odd cases where XMPP
// servers echo back our own messages, and we
// want to ignore them.
log.info("Setting SMAC to: {}", MAC_ADDRESS);
msg.setProperty("SMAC", MAC_ADDRESS);
log.info("Sending to: {}", chat.getParticipant());
log.info("Sending SEQUENCE #: "+sequenceNumber);
chat.sendMessage(msg);
sequenceNumber++;
}
@Override
public void channelClosed(final ChannelHandlerContext ctx,
final ChannelStateEvent cse) {
// We need to send the CLOSE directive to the other
// side VIA google talk to simulate the proxy
// closing the connection to the browser.
log.info("Got channel closed on C in A->B->C->D chain...");
log.info("Sending close message");
final Message msg = new Message();
msg.setProperty("HASHCODE", hc);
msg.setProperty("MAC", mac);
msg.setFrom(conn.getUser());
// We set the sequence number so the client knows
// how many total messages to expect. This is
// necessary because the XMPP server can deliver
// messages out of order.
msg.setProperty("SEQ", sequenceNumber);
msg.setProperty("CLOSE", "true");
// This is the server-side MAC address. This is
// useful because there are odd cases where XMPP
// servers echo back our own messages, and we
// want to ignore them.
log.info("Setting SMAC to: {}", MAC_ADDRESS);
msg.setProperty("SMAC", MAC_ADDRESS);
try {
chat.sendMessage(msg);
} catch (final XMPPException e) {
log.warn("Error sending close message", e);
}
removedConnections.add(key);
connections.remove(key);
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx,
final ExceptionEvent e) throws Exception {
log.warn("Caught exception on C in A->B->C->D " +
"chain...", e.getCause());
if (e.getChannel().isOpen()) {
log.warn("Closing open connection");
closeOnFlush(e.getChannel());
}
else {
// We've seen odd cases where channels seem to
// continually attempt connections. Make sure
// we explicitly close the connection here.
log.warn("Closing connection even though " +
"isOpen is false");
e.getChannel().close();
}
}
}
pipeline.addLast("handler", new HttpChatRelay());
return pipeline;
}
};
// Set up the event pipeline factory.
cb.setPipelineFactory(cpf);
cb.setOption("connectTimeoutMillis", 40*1000);
log.info("Connecting to localhost proxy");
final ChannelFuture future =
cb.connect(new InetSocketAddress("127.0.0.1", 7777));
connections.put(key, future);
return future;
}
}
private String toMd5(final byte[] raw) {
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
final byte[] digest = md.digest(raw);
return Base64.encodeBase64URLSafeString(digest);
} catch (final NoSuchAlgorithmException e) {
log.error("No MD5 -- will never happen", e);
return "NO MD5";
}
}
public static byte[] toRawBytes(final ByteBuffer buf) {
final int mark = buf.position();
final byte[] bytes = new byte[buf.remaining()];
buf.get(bytes);
buf.position(mark);
return bytes;
}
/**
* Closes the specified channel after all queued write requests are flushed.
*/
private void closeOnFlush(final Channel ch) {
log.info("Closing channel on flush: {}", ch);
if (ch.isConnected()) {
ch.write(ChannelBuffers.EMPTY_BUFFER).addListener(
ChannelFutureListener.CLOSE);
}
}
private static String getMacAddress() throws SocketException {
final Enumeration<NetworkInterface> nis =
NetworkInterface.getNetworkInterfaces();
while (nis.hasMoreElements()) {
final NetworkInterface ni = nis.nextElement();
try {
final byte[] mac = ni.getHardwareAddress();
if (mac.length > 0) {
return Base64.encodeBase64String(mac);
}
} catch (final SocketException e) {
}
}
try {
return Base64.encodeBase64String(
InetAddress.getLocalHost().getAddress()) +
System.currentTimeMillis();
} catch (final UnknownHostException e) {
final byte[] bytes = new byte[24];
new Random().nextBytes(bytes);
return Base64.encodeBase64String(bytes);
}
}
}
|
package placebooks.client.ui;
import placebooks.client.AbstractCallback;
import placebooks.client.PlaceBookService;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
public class CreateEverytrailAccount extends Composite
{
interface CreateEverytrailAccountUiBinder extends UiBinder<Widget, CreateEverytrailAccount>
{
}
private static CreateEverytrailAccountUiBinder uiBinder = GWT.create(CreateEverytrailAccountUiBinder.class);
@UiField
Button createAccount;
@UiField
PasswordTextBox password;
@UiField
TextBox username;
private AbstractCallback callback;
public CreateEverytrailAccount()
{
initWidget(uiBinder.createAndBindUi(this));
createAccount.setEnabled(false);
}
public String getPassword()
{
return password.getText();
}
public String getUsername()
{
return username.getText();
}
public void setCallback(final AbstractCallback callback)
{
this.callback = callback;
}
@UiHandler(value = { "username", "password" })
void checkValid(final KeyPressEvent event)
{
if (username.getText().trim().equals(""))
{
createAccount.setEnabled(false);
return;
}
if (password.getText().trim().equals(""))
{
createAccount.setEnabled(false);
return;
}
createAccount.setEnabled(true);
}
@UiHandler("createAccount")
void createAccount(final ClickEvent event)
{
createAccount.setEnabled(false);
PlaceBookService.linkAccount(username.getText(), password.getText(), "Everytrail", callback);
}
}
|
package com.intellij.execution;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.CapturingProcessHandler;
import com.intellij.execution.process.ProcessOutput;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.testFramework.UsefulTestCase;
import org.jetbrains.annotations.NotNull;
import java.io.File;
public class WSLUtilTest extends UsefulTestCase {
@Override
protected boolean shouldRunTest() {
return super.shouldRunTest() && WSLUtil.hasWSL();
}
public void testWslToWinPath() throws Exception {
assertWslPath("/usr/something/include", "%LOCALAPPDATA%\\lxss\\rootfs\\usr\\something\\include");
assertWslPath("/usr/something/bin/gcc", "%LOCALAPPDATA%\\lxss\\rootfs\\usr\\something\\bin\\gcc");
assertWslPath("/mnt/c", "c:\\");
assertWslPath("/mnt/x/", "x:\\");
assertWslPath("/mnt/c/temp/foo", "c:\\temp\\foo");
assertWslPath("/mnt/c/temp/KeepCase", "c:\\temp\\KeepCase");
assertWslPath("/mnt/c/name with spaces/another name with spaces", "c:\\name with spaces\\another name with spaces");
assertWslPath("/mnt/c/юникод", "c:\\юникод");
}
public void testWinToWslPath() {
assertWinPath("c:\\foo", "/mnt/c/foo");
assertWinPath("c:\\temp\\KeepCase", "/mnt/c/temp/KeepCase");
assertWinPath("%LOCALAPPDATA%\\lxss\\rootfs\\usr\\something\\include", "/usr/something/include");
assertWinPath("%LOCALAPPDATA%\\lxss\\rootfs\\usr\\something\\bin\\gcc", "/usr/something/bin/gcc");
}
public void testPaths() {
final String originalWinPath = "c:\\usr\\something\\bin\\gcc";
final String winPath = WSLUtil.getWindowsPath(WSLUtil.getWslPath(originalWinPath));
assertEquals(originalWinPath, winPath);
final String originalWslPath = "/usr/bin/gcc";
final String wslPath = WSLUtil.getWslPath(WSLUtil.getWindowsPath(originalWslPath));
assertEquals(originalWslPath, wslPath);
}
public void testVersion() {
final String version = WSLUtil.getWslVersion();
assertTrue(WSLUtil.hasWSL() ? version != null : version == null);
}
public void testResolveSymlink() throws Exception {
if (!WSLUtil.hasWSL()) return;
final File winFile = FileUtil.createTempFile("the_file.txt", null);
final File winSymlink = new File(new File(FileUtil.getTempDirectory()), "sym_link");
try {
final String file = WSLUtil.getWslPath(winFile.getPath());
final String symlink = WSLUtil.getWslPath(winSymlink.getPath());
mkSymlink(file, symlink);
final String resolved = WSLUtil.getWindowsPath(WSLUtil.resolveSymlink(symlink));
assertTrue(FileUtil.exists(resolved));
assertTrue(winFile.getPath().equalsIgnoreCase(resolved));
}
finally {
FileUtil.delete(winFile);
FileUtil.delete(winSymlink);
}
}
private static void assertWinPath(@NotNull String winPath, @NotNull String wslPath) {
assertEquals(wslPath, WSLUtil.getWslPath(prepare(winPath)));
}
private static void assertWslPath(@NotNull String wslPath, @NotNull String winPath) {
assertEquals(prepare(winPath), WSLUtil.getWindowsPath(wslPath));
}
private static String prepare(@NotNull String path) {
if (path.startsWith("%LOCALAPPDATA%")) {
final String localappdata = System.getenv().get("LOCALAPPDATA");
path = localappdata + path.substring("%LOCALAPPDATA%".length());
}
return path;
}
private static void mkSymlink(@NotNull String file, @NotNull String symlink) throws Exception {
final GeneralCommandLine cl = new GeneralCommandLine();
cl.setExePath("ln");
cl.addParameters("-s", file, symlink);
final GeneralCommandLine cmd = WSLUtil.patchCommandLine(cl, null, null, false);
final CapturingProcessHandler process = new CapturingProcessHandler(cmd);
final ProcessOutput output = process.runProcess(10_000);
assertFalse(output.isTimeout());
assertEquals(0, output.getExitCode());
}
}
|
package com.intellij.execution;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.CapturingProcessHandler;
import com.intellij.execution.process.ProcessOutput;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
public class WSLUtilTest {
@Test
public void testWslToWinPath() {
assumeTrue(WSLUtil.hasWSL());
assertWslPath("/usr/something/include", "%LOCALAPPDATA%\\lxss\\rootfs\\usr\\something\\include");
assertWslPath("/usr/something/bin/gcc", "%LOCALAPPDATA%\\lxss\\rootfs\\usr\\something\\bin\\gcc");
assertWslPath("/mnt/c", "c:\\");
assertWslPath("/mnt/x/", "x:\\");
assertWslPath("/mnt/c/temp/foo", "c:\\temp\\foo");
assertWslPath("/mnt/c/temp/KeepCase", "c:\\temp\\KeepCase");
assertWslPath("/mnt/c/name with spaces/another name with spaces", "c:\\name with spaces\\another name with spaces");
assertWslPath("/mnt/c/юникод", "c:\\юникод");
}
@Test
public void testWinToWslPath() {
assumeTrue(WSLUtil.hasWSL());
assertWinPath("c:\\foo", "/mnt/c/foo");
assertWinPath("c:\\temp\\KeepCase", "/mnt/c/temp/KeepCase");
assertWinPath("%LOCALAPPDATA%\\lxss\\rootfs\\usr\\something\\include", "/usr/something/include");
assertWinPath("%LOCALAPPDATA%\\lxss\\rootfs\\usr\\something\\bin\\gcc", "/usr/something/bin/gcc");
}
@Test
public void testPaths() {
assumeTrue(WSLUtil.hasWSL());
final String originalWinPath = "c:\\usr\\something\\bin\\gcc";
final String winPath = WSLUtil.getWindowsPath(WSLUtil.getWslPath(originalWinPath));
assertEquals(originalWinPath, winPath);
final String originalWslPath = "/usr/bin/gcc";
final String wslPath = WSLUtil.getWslPath(WSLUtil.getWindowsPath(originalWslPath));
assertEquals(originalWslPath, wslPath);
}
@Test
public void testVersion() {
final String version = WSLUtil.getWslVersion();
assertTrue(WSLUtil.hasWSL() ? version != null : version == null);
}
@Test
public void testResolveSymlink() throws Exception {
assumeTrue(WSLUtil.hasWSL());
final File winFile = FileUtil.createTempFile("the_file.txt", null);
final File winSymlink = new File(new File(FileUtil.getTempDirectory()), "sym_link");
try {
final String file = WSLUtil.getWslPath(winFile.getPath());
final String symlink = WSLUtil.getWslPath(winSymlink.getPath());
mkSymlink(file, symlink);
final String resolved = WSLUtil.getWindowsPath(WSLUtil.resolveSymlink(symlink));
assertTrue(FileUtil.exists(resolved));
assertTrue(winFile.getPath().equalsIgnoreCase(resolved));
}
finally {
FileUtil.delete(winFile);
FileUtil.delete(winSymlink);
}
}
private static void assertWinPath(@NotNull String winPath, @NotNull String wslPath) {
assertEquals(wslPath, WSLUtil.getWslPath(prepare(winPath)));
}
private static void assertWslPath(@NotNull String wslPath, @NotNull String winPath) {
assertEquals(prepare(winPath), WSLUtil.getWindowsPath(wslPath));
}
private static String prepare(@NotNull String path) {
if (path.startsWith("%LOCALAPPDATA%")) {
final String localappdata = System.getenv().get("LOCALAPPDATA");
path = localappdata + path.substring("%LOCALAPPDATA%".length());
}
return path;
}
private static void mkSymlink(@NotNull String file, @NotNull String symlink) throws Exception {
final GeneralCommandLine cl = new GeneralCommandLine();
cl.setExePath("ln");
cl.addParameters("-s", file, symlink);
final GeneralCommandLine cmd = WSLUtil.patchCommandLine(cl, null, null, false);
final CapturingProcessHandler process = new CapturingProcessHandler(cmd);
final ProcessOutput output = process.runProcess(10_000);
assertFalse(output.isTimeout());
assertEquals(0, output.getExitCode());
}
}
|
package edu.valelab.GaussianFit;
import edu.ucsf.tsf.TaggedSpotsProtos.FitMode;
import edu.ucsf.tsf.TaggedSpotsProtos.IntensityUnits;
import edu.ucsf.tsf.TaggedSpotsProtos.LocationUnits;
import edu.ucsf.tsf.TaggedSpotsProtos.Spot;
import edu.ucsf.tsf.TaggedSpotsProtos.SpotList;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import ij.gui.Arrow;
import ij.gui.ImageWindow;
import ij.gui.MessageDialog;
import ij.gui.Roi;
import ij.gui.StackWindow;
import ij.gui.YesNoCancelDialog;
import ij.measure.ResultsTable;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import ij.text.TextPanel;
import ij.text.TextWindow;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.geom.Point2D;
import java.io.*;
import java.nio.channels.FileChannel;
import java.text.ParseException;
import java.util.*;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import org.apache.commons.math.stat.StatUtils;
import org.jfree.data.xy.XYSeries;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.utils.FileDialogs;
import org.micromanager.utils.FileDialogs.FileType;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.ReportingUtils;
/**
*
* @author Nico Stuurman
*/
public class DataCollectionForm extends javax.swing.JFrame {
AbstractTableModel myTableModel_;
private final String[] columnNames_ = {"ID", "Image", "Nr of spots",
"2C Reference", "stdX", "stdY", "nrPhotons"};
private final String[] plotModes_ = {"t-X", "t-Y", "X-Y", "t-Int"};
private final String[] renderModes_ = {"Points", "Gaussian", "Norm. Gaussian"};
private final String[] renderSizes_ = {"1x", "2x", "4x", "8x", "16x", "32x", "64x", "128x"};
public final static String extension_ = ".tsf";
// Prefs
private static final String FRAMEXPOS = "DCXPos";
private static final String FRAMEYPOS = "DCYPos";
private static final String FRAMEWIDTH = "DCWidth";
private static final String FRAMEHEIGHT = "DCHeight";
private static final String USESIGMA = "DCSigma";
private static final String SIGMAMIN = "DCSigmaMin";
private static final String SIGMAMAX = "DCSigmaMax";
private static final String USEINT = "DCIntensity";
private static final String INTMIN = "DCIntMin";
private static final String INTMAX = "DCIntMax";
private static final String LOADTSFDIR = "TSFDir";
private static final String RENDERMAG = "VisualizationMagnification";
private static final String PAIRSMAXDISTANCE = "PairsMaxDistance";
private static final String METHOD2C = "MethodFor2CCorrection";
private static final String COL0Width = "Col0Width";
private static final String COL1Width = "Col1Width";
private static final String COL2Width = "Col2Width";
private static final String COL3Width = "Col3Width";
private static final String COL4Width = "Col4Width";
private static final String COL5Width = "Col5Width";
private static final int OK = 0;
private static final int FAILEDDONOTINFORM = 1;
private static final int FAILEDDOINFORM = 2;
private Preferences prefs_;
private static FileType TSF_FILE = new FileType("TSF File",
"Tagged Spot Format file",
"./data.tsf",
false, new String[]{"txt", "tsf"});
/*
* Switch between clojure and Java code here
* LWM is Java, LocalWeightedMean is Clojure
* Currently, LocalWeightedMean gives great results, LWM does not
*/
//private static LocalWeightedMean lwm_;
private static CoordinateMapper c2t_;
private static String loadTSFDir_ = "";
private static int rowDataID_ = 1;
private int jitterMethod_ = 1;
private int jitterMaxSpots_ = 40000;
private int jitterMaxFrames_ = 500;
public static ZCalibrator zc_ = new ZCalibrator();
/**
* Method to allow scripts to tune the jitter corrector
* @param jm
*/
public void setJitterMethod(int jm) {
if (jm == 0 || jm == 1)
jitterMethod_ = jm;
}
/**
* Method to allow scripts to tune the jitter corrector
* Sets the maximum number of frames that will be used to produce one
* "time-point" in the de-jitter process. Defaults to 500, set higher if you
* have few data-points, lower if you have many spots per frame.
* @param jm - max number of frames that will be used per de-jitter cycle
*/
public void setJitterMaxFrames(int jm) {
jitterMaxFrames_ = jm;
}
/**
* Method to allow scripts to tune the jitter corrector
* Sets the maximum number of spots that will be used to produce one
* "timepoint" in the de-jitter process. Defaults to 40000.
* @param jm
*/
public void setJitterMaxSpots(int jm) {
jitterMaxSpots_ = jm;
}
public static DataCollectionForm instance_ = null;
// public since it is used in MathForm.
// TODO: make this private
public ArrayList<MyRowData> rowData_;
public enum Coordinates {NM, PIXELS};
public enum PlotMode {X, Y, INT};
/**
* Data structure for spotlists
*/
public class MyRowData {
public final List<GaussianSpotData> spotList_;
public Map<Integer, List<GaussianSpotData>> frameIndexSpotList_;
public final ArrayList<Double> timePoints_;
public String name_;
public final String title_;
public final String colCorrRef_;
public final int width_;
public final int height_;
public final float pixelSizeNm_;
public final float zStackStepSizeNm_;
public final int shape_;
public final int halfSize_;
public final int nrChannels_;
public final int nrFrames_;
public final int nrSlices_;
public final int nrPositions_;
public final int maxNrSpots_;
public final boolean isTrack_;
public final double stdX_;
public final double stdY_;
public final int ID_;
public final Coordinates coordinate_;
public final boolean hasZ_;
public final double minZ_;
public final double maxZ_;
public final double totalNrPhotons_;
public MyRowData(String name,
String title,
String colCorrRef,
int width,
int height,
float pixelSizeUm,
float zStackStepSizeNm,
int shape,
int halfSize,
int nrChannels,
int nrFrames,
int nrSlices,
int nrPositions,
int maxNrSpots,
List<GaussianSpotData> spotList,
ArrayList<Double> timePoints,
boolean isTrack,
Coordinates coordinate,
boolean hasZ,
double minZ,
double maxZ) {
name_ = name;
title_ = title;
colCorrRef_ = colCorrRef;
width_ = width;
height_ = height;
pixelSizeNm_ = pixelSizeUm;
zStackStepSizeNm_ = zStackStepSizeNm;
spotList_ = spotList;
shape_ = shape;
halfSize_ = halfSize;
nrChannels_ = nrChannels;
nrFrames_ = nrFrames;
nrSlices_ = nrSlices;
nrPositions_ = nrPositions;
maxNrSpots_ = maxNrSpots;
timePoints_ = timePoints;
isTrack_ = isTrack;
double stdX = 0.0;
double stdY = 0.0;
double nrPhotons = 0.0;
if (isTrack_) {
ArrayList<Point2D.Double> xyList = spotListToPointList(spotList_);
Point2D.Double avgPoint = avgXYList(xyList);
Point2D.Double stdPoint = stdDevXYList(xyList, avgPoint);
stdX = stdPoint.x;
stdY = stdPoint.y;
for (GaussianSpotData spot : spotList_) {
nrPhotons += spot.getIntensity();
}
}
stdX_ = stdX;
stdY_ = stdY;
totalNrPhotons_ = nrPhotons;
coordinate_ = coordinate;
hasZ_ = hasZ;
minZ_ = minZ;
maxZ_ = maxZ;
ID_ = rowDataID_;
rowDataID_++;
}
/**
* Populates the list frameIndexSpotList which gives access to spots by frame
*/
public void index() {
boolean useFrames = nrFrames_ > nrSlices_;
int nr = nrSlices_;
if (useFrames)
nr = nrFrames_;
frameIndexSpotList_ = new HashMap<Integer, List<GaussianSpotData>>(nr);
for (GaussianSpotData spot : spotList_) {
int index = spot.getSlice();
if (useFrames)
index = spot.getFrame();
if (frameIndexSpotList_.get(index) == null)
frameIndexSpotList_.put(index, new ArrayList<GaussianSpotData>());
frameIndexSpotList_.get(index).add(spot);
}
}
}
/**
* Implement this class as a singleton
*
* @return the form
*/
public static DataCollectionForm getInstance() {
if (instance_ == null)
instance_ = new DataCollectionForm();
return instance_;
}
/**
* Creates new form DataCollectionForm
*/
private DataCollectionForm() {
rowData_ = new ArrayList<MyRowData>();
myTableModel_ = new AbstractTableModel() {
@Override
public String getColumnName(int col) {
return columnNames_[col].toString();
}
@Override
public int getRowCount() {
if (rowData_ == null)
return 0;
return rowData_.size();
}
@Override
public int getColumnCount() {
return columnNames_.length;
}
@Override
public Object getValueAt(int row, int col) {
if (col == 0 && rowData_ != null)
return rowData_.get(row).ID_;
else if (col == 1 && rowData_ != null)
return rowData_.get(row).name_;
else if (col == 2)
return rowData_.get(row).spotList_.size();
else if (col == 3)
return rowData_.get(row).colCorrRef_;
else if (col == 4)
if (rowData_.get(row).isTrack_)
return String.format("%.2f", rowData_.get(row).stdX_);
else return null;
else if (col == 5)
if (rowData_.get(row).isTrack_)
return String.format("%.2f", rowData_.get(row).stdY_);
else
return null;
else if (col == 6)
if (rowData_.get(row).isTrack_)
return String.format("%.2f", rowData_.get(row).totalNrPhotons_);
else
return null;
else
return getColumnName(col);
}
@Override
public boolean isCellEditable(int row, int col) {
if (col == 1)
return true;
return false;
}
@Override
public void setValueAt(Object value, int row, int col) {
if (col == 1)
rowData_.get(row).name_ = (String) value;
fireTableCellUpdated(row, col);
}
};
initComponents();
referenceName_.setText(" ");
plotComboBox_.setModel(new javax.swing.DefaultComboBoxModel(plotModes_));
visualizationModel_.setModel(new javax.swing.DefaultComboBoxModel(renderModes_));
visualizationMagnification_.setModel(new javax.swing.DefaultComboBoxModel(renderSizes_));
jScrollPane1_.setName("Gaussian Spot Fitting Data Sets");
setBackground(MMStudioMainFrame.getInstance().getBackgroundColor());
MMStudioMainFrame.getInstance().addMMBackgroundListener(this);
if (prefs_ == null)
prefs_ = Preferences.userNodeForPackage(this.getClass());
setBounds(prefs_.getInt(FRAMEXPOS, 50), prefs_.getInt(FRAMEYPOS, 100),
prefs_.getInt(FRAMEWIDTH, 800), prefs_.getInt(FRAMEHEIGHT, 250));
filterSigmaCheckBox_.setSelected(prefs_.getBoolean(USESIGMA, false));
sigmaMin_.setText(prefs_.get(SIGMAMIN, "0.0"));
sigmaMax_.setText(prefs_.get(SIGMAMAX, "20.0"));
filterIntensityCheckBox_.setSelected(prefs_.getBoolean(USEINT, false));
intensityMin_.setText(prefs_.get(INTMIN, "0.0"));
intensityMax_.setText(prefs_.get(INTMAX, "20000"));
loadTSFDir_ = prefs_.get(LOADTSFDIR, "");
visualizationMagnification_.setSelectedIndex(prefs_.getInt(RENDERMAG, 0));
pairsMaxDistanceField_.setText(prefs_.get(PAIRSMAXDISTANCE, "500"));
method2CBox_.setSelectedItem(prefs_.get(METHOD2C, "LWM"));
jTable1_.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnModel cm = jTable1_.getColumnModel();
cm.getColumn(0).setPreferredWidth(prefs_.getInt(COL0Width, 25));
cm.getColumn(1).setPreferredWidth(prefs_.getInt(COL1Width, 300));
cm.getColumn(2).setPreferredWidth(prefs_.getInt(COL2Width, 150));
cm.getColumn(3).setPreferredWidth(prefs_.getInt(COL3Width, 75));
cm.getColumn(4).setPreferredWidth(prefs_.getInt(COL4Width, 75));
cm.getColumn(5).setPreferredWidth(prefs_.getInt(COL5Width, 75));
// Drag and Drop support for file loading
this.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
return true;
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (!canImport(support)) {
return false;
}
Transferable t = support.getTransferable();
try {
java.util.List<File> l =
(java.util.List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
loadFiles((File[]) l.toArray());
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
});
setVisible(true);
}
/**
* Adds a spot data set to the form
*
*
* @param name
* @param title
* @param width
* @param height
* @param pixelSizeUm
* @param shape
* @param halfSize
* @param nrChannels
* @param nrFrames
* @param nrSlices
* @param nrPositions
* @param maxNrSpots
* @param spotList
* @param isTrack
*/
public void addSpotData(
String name,
String title,
String colCorrRef,
int width,
int height,
float pixelSizeUm,
float zStackStepSizeNm,
int shape,
int halfSize,
int nrChannels,
int nrFrames,
int nrSlices,
int nrPositions,
int maxNrSpots,
List<GaussianSpotData> spotList,
ArrayList<Double> timePoints,
boolean isTrack,
Coordinates coordinate,
boolean hasZ,
double minZ,
double maxZ) {
MyRowData newRow = new MyRowData(name, title, colCorrRef, width, height,
pixelSizeUm, zStackStepSizeNm,
shape, halfSize, nrChannels, nrFrames, nrSlices, nrPositions,
maxNrSpots, spotList, timePoints, isTrack, coordinate,
hasZ, minZ, maxZ);
rowData_.add(newRow);
myTableModel_.fireTableRowsInserted(rowData_.size()-1, rowData_.size());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
formComponentResized(null);
}
} );
}
/**
* Return a dataset with requested ID.
*/
public MyRowData getDataSet(int ID) {
int i=0;
while (i < rowData_.size()) {
if (rowData_.get(i).ID_ == ID)
return rowData_.get(i);
}
return null;
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
loadButton = new javax.swing.JButton();
jScrollPane1_ = new javax.swing.JScrollPane();
jTable1_ = new javax.swing.JTable();
plotComboBox_ = new javax.swing.JComboBox();
visualizationMagnification_ = new javax.swing.JComboBox();
visualizationModel_ = new javax.swing.JComboBox();
saveButton = new javax.swing.JButton();
removeButton = new javax.swing.JButton();
showButton_ = new javax.swing.JButton();
c2StandardButton = new javax.swing.JButton();
pairsButton = new javax.swing.JButton();
c2CorrectButton = new javax.swing.JButton();
referenceName_ = new javax.swing.JLabel();
unjitterButton_ = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
filterSigmaCheckBox_ = new javax.swing.JCheckBox();
filterIntensityCheckBox_ = new javax.swing.JCheckBox();
sigmaMin_ = new javax.swing.JTextField();
intensityMin_ = new javax.swing.JTextField();
sigmaMax_ = new javax.swing.JTextField();
intensityMax_ = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
SigmaLabel2 = new javax.swing.JLabel();
IntLabel2 = new javax.swing.JLabel();
infoButton_ = new javax.swing.JButton();
plotButton_ = new javax.swing.JButton();
renderButton_ = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
jSeparator3 = new javax.swing.JSeparator();
saveFormatBox_ = new javax.swing.JComboBox();
jSeparator4 = new javax.swing.JSeparator();
averageTrackButton_ = new javax.swing.JButton();
mathButton_ = new javax.swing.JButton();
pairsMaxDistanceField_ = new javax.swing.JTextField();
SigmaLabel3 = new javax.swing.JLabel();
linkButton_ = new javax.swing.JButton();
straightenTrackButton_ = new javax.swing.JButton();
centerTrackButton_ = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
powerSpectrumCheckBox_ = new javax.swing.JCheckBox();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
logLogCheckBox_ = new javax.swing.JCheckBox();
zCalibrateButton_ = new javax.swing.JButton();
zCalibrationLabel_ = new javax.swing.JLabel();
listButton_ = new javax.swing.JButton();
method2CBox_ = new javax.swing.JComboBox();
SubRange = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Gaussian tracking data");
setMinimumSize(new java.awt.Dimension(450, 80));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
loadButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
loadButton.setText("Load");
loadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadButtonActionPerformed(evt);
}
});
jScrollPane1_.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane1_.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jTable1_.setModel(myTableModel_);
jScrollPane1_.setViewportView(jTable1_);
plotComboBox_.setFont(new java.awt.Font("Lucida Grande", 0, 10)); // NOI18N
plotComboBox_.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "t-X", "t-Y", "X-Y", "t-Int.", " " }));
visualizationMagnification_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
visualizationMagnification_.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1x", "2x", "4x", "8x", "16x", "32x", "64x", "128x" }));
visualizationModel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
visualizationModel_.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gaussian" }));
saveButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
saveButton.setText("Save");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
}
});
removeButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
removeButton.setText("Remove");
removeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeButtonActionPerformed(evt);
}
});
showButton_.setFont(new java.awt.Font("Lucida Grande", 0, 10)); // NOI18N
showButton_.setText("Show");
showButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showButton_ActionPerformed(evt);
}
});
c2StandardButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
c2StandardButton.setText("2C Reference");
c2StandardButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
c2StandardButtonActionPerformed(evt);
}
});
pairsButton.setFont(new java.awt.Font("Lucida Grande", 0, 10)); // NOI18N
pairsButton.setText("Pairs");
pairsButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pairsButtonActionPerformed(evt);
}
});
c2CorrectButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
c2CorrectButton.setText("2C Correct");
c2CorrectButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
c2CorrectButtonActionPerformed(evt);
}
});
referenceName_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
referenceName_.setText("JLabel1");
unjitterButton_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
unjitterButton_.setText("Drift Correct");
unjitterButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
unjitterButton_ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 11));
jLabel1.setText("Filters:");
filterSigmaCheckBox_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
filterSigmaCheckBox_.setText("Sigma");
filterSigmaCheckBox_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
filterSigmaCheckBox_ActionPerformed(evt);
}
});
filterIntensityCheckBox_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
filterIntensityCheckBox_.setText("Intensity");
filterIntensityCheckBox_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
filterIntensityCheckBox_ActionPerformed(evt);
}
});
sigmaMin_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
sigmaMin_.setText("0");
intensityMin_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
intensityMin_.setText("0");
sigmaMax_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
sigmaMax_.setText("0");
intensityMax_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
intensityMax_.setText("0");
jLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 11));
jLabel2.setText("< spot <");
jLabel3.setFont(new java.awt.Font("Lucida Grande", 0, 11));
jLabel3.setText("< spot <");
SigmaLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 11)); // NOI18N
SigmaLabel2.setText("nm");
IntLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 11));
IntLabel2.setText("
infoButton_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
infoButton_.setText("Info");
infoButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
infoButton_ActionPerformed(evt);
}
});
plotButton_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
plotButton_.setText("Plot");
plotButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
plotButton_ActionPerformed(evt);
}
});
renderButton_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
renderButton_.setText("Render");
renderButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
renderButton_ActionPerformed(evt);
}
});
jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL);
saveFormatBox_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
saveFormatBox_.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Binary", "Text" }));
jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL);
averageTrackButton_.setFont(new java.awt.Font("Lucida Grande", 0, 11)); // NOI18N
averageTrackButton_.setText("Average");
averageTrackButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
averageTrackButton_ActionPerformed(evt);
}
});
mathButton_.setFont(new java.awt.Font("Lucida Grande", 0, 11)); // NOI18N
mathButton_.setText("Math");
mathButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mathButton_ActionPerformed(evt);
}
});
pairsMaxDistanceField_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
pairsMaxDistanceField_.setText("500");
SigmaLabel3.setFont(new java.awt.Font("Lucida Grande", 0, 11));
SigmaLabel3.setText("nm");
linkButton_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
linkButton_.setText("Link");
linkButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
linkButton_ActionPerformed(evt);
}
});
straightenTrackButton_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
straightenTrackButton_.setText("Straighten");
straightenTrackButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
straightenTrackButton_ActionPerformed(evt);
}
});
centerTrackButton_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
centerTrackButton_.setText("Center");
centerTrackButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
centerTrackButton_ActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Lucida Grande", 0, 11));
jLabel4.setText("Localization Microscopy");
jLabel5.setFont(new java.awt.Font("Lucida Grande", 0, 11));
jLabel5.setText("2-Color");
powerSpectrumCheckBox_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
powerSpectrumCheckBox_.setText("PSD");
powerSpectrumCheckBox_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
powerSpectrumCheckBox_ActionPerformed(evt);
}
});
jLabel6.setFont(new java.awt.Font("Lucida Grande", 0, 11)); // NOI18N
jLabel6.setText("Tracks");
jLabel7.setFont(new java.awt.Font("Lucida Grande", 0, 11));
jLabel7.setText("General");
logLogCheckBox_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
logLogCheckBox_.setText("log-log");
logLogCheckBox_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
logLogCheckBox_ActionPerformed(evt);
}
});
zCalibrateButton_.setFont(new java.awt.Font("Lucida Grande", 0, 10)); // NOI18N
zCalibrateButton_.setText("Z Calibration");
zCalibrateButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zCalibrateButton_ActionPerformed(evt);
}
});
zCalibrationLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
zCalibrationLabel_.setText("UnCalibrated");
listButton_.setFont(new java.awt.Font("Lucida Grande", 0, 10)); // NOI18N
listButton_.setText("List");
listButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
listButton_ActionPerformed(evt);
}
});
method2CBox_.setFont(new java.awt.Font("Lucida Grande", 0, 11));
method2CBox_.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NR-Similarity", "Affine", "LWM" }));
method2CBox_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
method2CBox_ActionPerformed(evt);
}
});
SubRange.setFont(new java.awt.Font("Lucida Grande", 0, 11)); // NOI18N
SubRange.setText("SubRange");
SubRange.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SubRangeActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(12, 12, 12)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(50, 50, 50)
.add(jLabel7))
.add(layout.createSequentialGroup()
.add(saveButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 70, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(saveFormatBox_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(loadButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 70, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(10, 10, 10)
.add(removeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(showButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 70, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(10, 10, 10)
.add(infoButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 81, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jSeparator3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(8, 8, 8)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(70, 70, 70)
.add(jLabel5))
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(c2StandardButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 82, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(method2CBox_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 90, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(18, 18, 18)
.add(referenceName_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 60, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(9, 9, 9)
.add(pairsMaxDistanceField_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 44, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(SigmaLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
.add(layout.createSequentialGroup()
.add(10, 10, 10)
.add(c2CorrectButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 72, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(8, 8, 8)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, listButton_, 0, 0, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, pairsButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 70, Short.MAX_VALUE))))
.add(18, 18, 18)
.add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(plotButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createSequentialGroup()
.add(2, 2, 2)
.add(powerSpectrumCheckBox_))
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(mathButton_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, averageTrackButton_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, SubRange, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 88, Short.MAX_VALUE))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(6, 6, 6)
.add(straightenTrackButton_))
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(plotComboBox_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(logLogCheckBox_)
.add(centerTrackButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 101, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(jLabel6)
.add(80, 80, 80)))
.add(9, 9, 9)
.add(jSeparator4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(unjitterButton_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.add(linkButton_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.add(layout.createSequentialGroup()
.add(20, 20, 20)
.add(zCalibrationLabel_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 75, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(zCalibrateButton_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(60, 60, 60)
.add(jLabel4))
.add(layout.createSequentialGroup()
.add(renderButton_)
.add(3, 3, 3)
.add(visualizationModel_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 110, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(6, 6, 6)
.add(visualizationMagnification_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 70, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(jLabel1)
.add(4, 4, 4)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(filterSigmaCheckBox_)
.add(layout.createSequentialGroup()
.add(1, 1, 1)
.add(filterIntensityCheckBox_)))
.add(1, 1, 1)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(sigmaMin_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 47, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createSequentialGroup()
.add(1, 1, 1)
.add(intensityMin_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(3, 3, 3)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel3)
.add(jLabel2))
.add(4, 4, 4)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(sigmaMax_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(intensityMax_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(10, 10, 10)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(SigmaLabel3)
.add(layout.createSequentialGroup()
.add(1, 1, 1)
.add(IntLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
.add(114, 114, 114))
.add(jScrollPane1_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1168, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(30, 30, 30)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 120, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jSeparator3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 120, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jSeparator4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 120, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(jLabel7)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(saveButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(saveFormatBox_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(21, 21, 21)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(loadButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(removeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(1, 1, 1)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(showButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(infoButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(layout.createSequentialGroup()
.add(jLabel5)
.add(5, 5, 5)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(c2StandardButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(method2CBox_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(pairsMaxDistanceField_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(SigmaLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(referenceName_))
.add(4, 4, 4)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(pairsButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(c2CorrectButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(listButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(jLabel6)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(17, 17, 17)
.add(logLogCheckBox_))
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, plotComboBox_, 0, 0, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, plotButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 18, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(2, 2, 2)
.add(powerSpectrumCheckBox_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(averageTrackButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(straightenTrackButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(mathButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(centerTrackButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(SubRange, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(19, 19, 19)
.add(zCalibrateButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(1, 1, 1)
.add(zCalibrationLabel_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(3, 3, 3)
.add(unjitterButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(20, 20, 20)
.add(linkButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
.add(layout.createSequentialGroup()
.add(60, 60, 60)
.add(SigmaLabel3)
.add(6, 6, 6)
.add(IntLabel2))
.add(layout.createSequentialGroup()
.add(jLabel4)
.add(6, 6, 6)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(3, 3, 3)
.add(renderButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 19, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(visualizationModel_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(visualizationMagnification_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(16, 16, 16)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(3, 3, 3)
.add(jLabel1))
.add(layout.createSequentialGroup()
.add(filterSigmaCheckBox_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(0, 0, 0)
.add(filterIntensityCheckBox_))
.add(layout.createSequentialGroup()
.add(sigmaMin_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(0, 0, 0)
.add(intensityMin_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(jLabel3)
.add(3, 3, 3)
.add(jLabel2))
.add(layout.createSequentialGroup()
.add(sigmaMax_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 17, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(3, 3, 3)
.add(intensityMax_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 17, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jScrollPane1_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1149, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Loads data saved in TSF format (Tagged Spot File Format)
* Opens awt file select dialog which lets you select only a single file
* If you want to open multiple files, press the ctrl key while clicking
* the button. This will open the swing file opener.
*
* @evt
*/
private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
int modifiers = evt.getModifiers();
final File[] selectedFiles;
if ((modifiers & java.awt.event.InputEvent.META_MASK) > 0) {
// The Swing fileopener looks ugly but allows for selection of multiple files
final JFileChooser jfc = new JFileChooser(loadTSFDir_);
jfc.setMultiSelectionEnabled(true);
jfc.setDialogTitle("Load Spot Data");
int ret = jfc.showOpenDialog(this);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
selectedFiles = jfc.getSelectedFiles();
} else {
File f = FileDialogs.openFile(this, "Open tsf data set", TSF_FILE);
selectedFiles = new File[] {f};
}
if (selectedFiles == null || selectedFiles.length < 1) {
return;
} else {
// Thread doing file import
Runnable loadFile = new Runnable() {
@Override
public void run() {
loadFiles(selectedFiles);
}
};
(new Thread(loadFile)).start();
}
}//GEN-LAST:event_loadButtonActionPerformed
/**
* Given an array of files, tries to import them all
* Uses .txt import for text files, and tsf importer for .tsf files.
* @param selectedFiles - Array of files to be imported
*/
private void loadFiles(File[] selectedFiles) {
for (File selectedFile : selectedFiles) {
loadTSFDir_ = selectedFile.getParent();
if (selectedFile.getName().endsWith(".txt")) {
loadText(selectedFile);
} else if (selectedFile.getName().endsWith(".tsf")) {
loadTSF(selectedFile);
} else if (selectedFile.getName().endsWith(".bin")) {
loadBin(selectedFile);
} else {
JOptionPane.showMessageDialog(getInstance(), "Unrecognized file extension");
}
}
}
private void loadBin(File selectedFile) {
try {
ij.IJ.showStatus ("Loading data..");
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
List<GaussianSpotData> spotList = new ArrayList<GaussianSpotData>();
float pixelSize = (float) 160.0; // how do we get this from the file?
LittleEndianDataInputStream fin = new LittleEndianDataInputStream(
new BufferedInputStream(new FileInputStream(selectedFile)));
byte[] m425 = {77, 52, 50, 53};
for (int i = 0; i < 4; i++) {
if (fin.readByte() != m425[i])
throw (new IOException("Not a .bin file"));
}
boolean nStorm = true;
byte[] ns = new byte[4];
byte[] guid = {71, 85, 73, 68};
for (int i = 0; i < 4; i++) {
ns[i] = fin.readByte();
if (ns[i] != guid[i])
nStorm = false;
}
if (nStorm) { // read away 57 bytes
fin.skipBytes(53);
} else {
// there may be a more elegant way to go back 4 bytes
fin.close();
fin = new LittleEndianDataInputStream (
new BufferedInputStream(new FileInputStream(selectedFile)));
fin.skipBytes(4);
}
int nrFrames = fin.readInt();
int molType = fin.readInt();
int nr = 0;
boolean hasZ = false;
double maxZ = Double.NEGATIVE_INFINITY;
double minZ = Double.POSITIVE_INFINITY;
for (int i = 0; i <= nrFrames; i++) {
int nrMolecules = fin.readInt();
for (int j = 0; j < nrMolecules; j++) {
// total size of data on disk is 17 bytes
float x = fin.readFloat();
float y = fin.readFloat();
float xc = fin.readFloat();
float yc = fin.readFloat();
float h = fin.readFloat();
float a = fin.readFloat(); // integrated dens. based on fitting
float w = fin.readFloat();
float phi = fin.readFloat();
float ax = fin.readFloat();
float b = fin.readFloat();
float intensity = fin.readFloat();
int c = fin.readInt();
int union = fin.readInt();
int frame = fin.readInt();
int union2 = fin.readInt();
int link = fin.readInt();
float z = fin.readFloat();
float zc = fin.readFloat();
if (zc != 0.0)
hasZ = true;
if (zc > maxZ)
maxZ = zc;
if (zc < minZ)
minZ = zc;
GaussianSpotData gsd = new GaussianSpotData(null, 0, 0, i,
0, nr, (int) xc, (int) yc);
gsd.setData(intensity, b, pixelSize * xc, pixelSize * yc, 0.0, w, ax, phi, c);
gsd.setZCenter(zc);
gsd.setOriginalPosition(x, y, z);
spotList.add(gsd);
nr++;
}
}
String name = selectedFile.getName();
addSpotData(name, name, "", 256, 256, pixelSize, (float) 0.0, 3, 2, 1, 1, 1, 1,
nr, spotList, null, false, Coordinates.NM, hasZ, minZ, maxZ);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(getInstance(), "File not found");
} catch (IOException ex) {
JOptionPane.showMessageDialog(getInstance(), "Error while reading file");
} catch (OutOfMemoryError ome) {
JOptionPane.showMessageDialog(getInstance(), "Out Of Memory");
} finally {
setCursor(Cursor.getDefaultCursor());
ij.IJ.showStatus("");
ij.IJ.showProgress(1.0);
}
}
/**
* Loads a text file saved from this application back into memory
* @param selectedFile
*/
private void loadText(File selectedFile) {
try {
ij.IJ.showStatus("Loading data..");
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
BufferedReader fr = new BufferedReader( new FileReader(selectedFile));
String info = fr.readLine();
String[] infos = info.split("\t");
HashMap<String, String> infoMap = new HashMap<String, String>();
for (int i = 0; i < infos.length; i++) {
String[] keyValue = infos[i].split(": ");
if (keyValue.length == 2)
infoMap.put(keyValue[0], keyValue[1]);
}
String test = infoMap.get("has_Z");
boolean hasZ = false;
if (test != null && test.equals("true")) {
hasZ = true;
}
String head = fr.readLine();
String[] headers = head.split("\t");
String spot;
List<GaussianSpotData> spotList = new ArrayList<GaussianSpotData>();
double maxZ = Double.NEGATIVE_INFINITY;
double minZ = Double.POSITIVE_INFINITY;
while ( (spot = fr.readLine()) != null) {
String[] spotTags = spot.split("\t");
HashMap<String, String> k = new HashMap<String, String>();
for (int i = 0; i < headers.length; i ++)
k.put(headers[i], spotTags[i]);
GaussianSpotData gsd = new GaussianSpotData(null,
Integer.parseInt(k.get("channel")),
Integer.parseInt(k.get("slice")),
Integer.parseInt(k.get("frame")),
Integer.parseInt(k.get("pos")),
Integer.parseInt(k.get("molecule")),
Integer.parseInt(k.get("x_position")),
Integer.parseInt(k.get("y_position"))
);
gsd.setData(Double.parseDouble(k.get("intensity")),
Double.parseDouble(k.get("background")),
Double.parseDouble(k.get("x")),
Double.parseDouble(k.get("y")), 0.0,
Double.parseDouble(k.get("width")),
Double.parseDouble(k.get("a")),
Double.parseDouble(k.get("theta")),
Double.parseDouble(k.get("x_precision"))
);
if (hasZ) {
double zc = Double.parseDouble(k.get("z"));
gsd.setZCenter(zc);
if (zc > maxZ)
maxZ = zc;
if (zc < minZ)
minZ = zc;
}
spotList.add(gsd);
}
// Add transformed data to data overview window
float zStepSize = (float) 0.0;
if (infoMap.containsKey("z_step_size"))
zStepSize = (float) (Double.parseDouble(infoMap.get("z_step_size")));
addSpotData(infoMap.get("name"), infoMap.get("name"),
referenceName_.getText(), Integer.parseInt(infoMap.get("nr_pixels_x")),
Integer.parseInt(infoMap.get("nr_pixels_y")),
Math.round(Double.parseDouble(infoMap.get("pixel_size"))),
zStepSize,
Integer.parseInt(infoMap.get("fit_mode")),
Integer.parseInt(infoMap.get("box_size")),
Integer.parseInt(infoMap.get("nr_channels")),
Integer.parseInt(infoMap.get("nr_frames")),
Integer.parseInt(infoMap.get("nr_slices")),
Integer.parseInt(infoMap.get("nr_pos")),
spotList.size(),
spotList,
null,
Boolean.parseBoolean(infoMap.get("is_track")),
Coordinates.NM,
hasZ,
minZ,
maxZ
);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(getInstance(), "File format did not meet expectations");
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(getInstance(), "File not found");
} catch (IOException ex) {
JOptionPane.showMessageDialog(getInstance(), "Error while reading file");
} finally {
setCursor(Cursor.getDefaultCursor());
ij.IJ.showStatus("");
ij.IJ.showProgress(1.0);
}
}
/**
* Load a .tsf file
* @param selectedFile - File to be loaded
*/
private void loadTSF(File selectedFile) {
SpotList psl = null;
try {
ij.IJ.showStatus("Loading data..");
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
FileInputStream fi = new FileInputStream(selectedFile);
DataInputStream di = new DataInputStream(fi);
// the new file format has an initial 0, then the offset (in long)
// to the position of spotList
int magic = di.readInt();
if (magic != 0) {
// reset and mark do not seem to work on my computer
fi.close();
fi = new FileInputStream(selectedFile);
psl = SpotList.parseDelimitedFrom(fi);
} else {
// TODO: evaluate after creating code writing this formt
long offset = di.readLong();
fi.skip(offset);
psl = SpotList.parseDelimitedFrom(fi);
fi.close();
fi = new FileInputStream(selectedFile);
fi.skip(12); // size of int + size of long
}
String name = psl.getName();
String title = psl.getName();
int width = psl.getNrPixelsX();
int height = psl.getNrPixelsY();
float pixelSizeUm = psl.getPixelSize();
int shape = 1;
if (psl.getFitMode() == FitMode.TWOAXIS) {
shape = 2;
} else if (psl.getFitMode() == FitMode.TWOAXISANDTHETA) {
shape = 3;
}
int halfSize = psl.getBoxSize() / 2;
int nrChannels = psl.getNrChannels();
int nrFrames = psl.getNrFrames();
int nrSlices = psl.getNrSlices();
int nrPositions = psl.getNrPos();
boolean isTrack = psl.getIsTrack();
long expectedSpots = psl.getNrSpots();
long esf = expectedSpots / 100;
long maxNrSpots = 0;
boolean hasZ = false;
double maxZ = Double.NEGATIVE_INFINITY;
double minZ = Double.POSITIVE_INFINITY;
ArrayList<GaussianSpotData> spotList = new ArrayList<GaussianSpotData>();
Spot pSpot;
while (fi.available() > 0 && (expectedSpots == 0 || maxNrSpots < expectedSpots)) {
pSpot = Spot.parseDelimitedFrom(fi);
GaussianSpotData gSpot = new GaussianSpotData((ImageProcessor) null, pSpot.getChannel(),
pSpot.getSlice(), pSpot.getFrame(), pSpot.getPos(),
pSpot.getMolecule(), pSpot.getXPosition(), pSpot.getYPosition());
gSpot.setData(pSpot.getIntensity(), pSpot.getBackground(), pSpot.getX(),
pSpot.getY(), 0.0, pSpot.getWidth(), pSpot.getA(), pSpot.getTheta(),
pSpot.getXPrecision());
if (pSpot.hasZ()) {
double zc = pSpot.getZ();
gSpot.setZCenter(zc);
hasZ = true;
if (zc > maxZ)
maxZ = zc;
if (zc < minZ)
minZ = zc;
}
maxNrSpots++;
if ((esf > 0) && ((maxNrSpots % esf) == 0)) {
ij.IJ.showProgress((double) maxNrSpots / (double) expectedSpots);
}
spotList.add(gSpot);
}
addSpotData(name, title, "", width, height, pixelSizeUm, (float) 0.0, shape, halfSize,
nrChannels, nrFrames, nrSlices, nrPositions, (int) maxNrSpots,
spotList, null, isTrack, Coordinates.NM, hasZ, minZ, maxZ);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(getInstance(),"File not found");
} catch (IOException ex) {
JOptionPane.showMessageDialog(getInstance(),"Error while reading file");
} finally {
setCursor(Cursor.getDefaultCursor());
ij.IJ.showStatus("");
ij.IJ.showProgress(1.0);
}
}
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
int rows[] = jTable1_.getSelectedRows();
if (rows.length > 0) {
for (int row : rows) {
if (saveFormatBox_.getSelectedIndex() == 0) {
saveData(rowData_.get(row));
} else {
saveDataAsText(rowData_.get(row));
}
}
} else {
JOptionPane.showMessageDialog(getInstance(), "Please select a dataset to save");
}
}//GEN-LAST:event_saveButtonActionPerformed
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed
int rows[] = jTable1_.getSelectedRows();
if (rows.length > 0) {
for (int row = rows.length - 1; row >= 0; row
rowData_.remove(rows[row]);
myTableModel_.fireTableRowsDeleted(rows[row], rows[row]);
}
} else {
JOptionPane.showMessageDialog(getInstance(), "No dataset selected");
}
}//GEN-LAST:event_removeButtonActionPerformed
private void showButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showButton_ActionPerformed
int row = jTable1_.getSelectedRow();
if (row > -1) {
try {
showResults(rowData_.get(row));
} catch (OutOfMemoryError ome) {
JOptionPane.showMessageDialog(getInstance(), "Not enough memory to show data");
}
} else {
JOptionPane.showMessageDialog(getInstance(), "Please select a dataset to show");
}
}//GEN-LAST:event_showButton_ActionPerformed
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
//jScrollPane1.setSize(this.getSize());
Dimension d = getSize();
d.height -= 155;
jScrollPane1_.setSize(d);
jScrollPane1_.getViewport().setViewSize(d);
}//GEN-LAST:event_formComponentResized
/**
* Use the selected data set as the reference for 2-channel color correction
* @param evt
*/
private void c2StandardButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_c2StandardButtonActionPerformed
int rows[] = jTable1_.getSelectedRows();
if (rows.length < 1) {
JOptionPane.showMessageDialog(getInstance(), "Please select one or more datasets as color reference");
} else {
CoordinateMapper.PointMap points = new CoordinateMapper.PointMap();
for (int row : rows) {
// Get points from both channels in first frame as ArrayLists
ArrayList<Point2D.Double> xyPointsCh1 = new ArrayList<Point2D.Double>();
ArrayList<Point2D.Double> xyPointsCh2 = new ArrayList<Point2D.Double>();
Iterator it = rowData_.get(row).spotList_.iterator();
while (it.hasNext()) {
GaussianSpotData gs = (GaussianSpotData) it.next();
if (gs.getFrame() == 1) {
Point2D.Double point = new Point2D.Double(gs.getXCenter(), gs.getYCenter());
if (gs.getChannel() == 1) {
xyPointsCh1.add(point);
} else if (gs.getChannel() == 2) {
xyPointsCh2.add(point);
}
}
}
if (xyPointsCh2.isEmpty()) {
JOptionPane.showMessageDialog(getInstance(), "No points found in second channel. Is this a dual channel dataset?");
return;
}
// Find matching points in the two ArrayLists
Iterator it2 = xyPointsCh1.iterator();
//HashMap<Point2D.Double, Point2D.Double> points = new HashMap<Point2D.Double, Point2D.Double>();
NearestPoint2D np;
try {
np = new NearestPoint2D(xyPointsCh2,
NumberUtils.displayStringToDouble(pairsMaxDistanceField_.getText()));
} catch (ParseException ex) {
ReportingUtils.showError("Problem parsing Pairs max distance number");
return;
}
while (it2.hasNext()) {
Point2D.Double pCh1 = (Point2D.Double) it2.next();
Point2D.Double pCh2 = np.findKDWSE(pCh1);
if (pCh2 != null) {
points.put(pCh1, pCh2);
}
}
if (points.size() < 4) {
ReportingUtils.showError("Fewer than 4 matching points found. Not enough to set as 2C reference");
return;
}
}
// we have pairs from all images, construct the coordinate mapper
try {
c2t_ = new CoordinateMapper(points, 2, 1);
String name = "ID: " + rowData_.get(rows[0]).ID_;
if (rows.length > 1) {
for (int i = 1; i < rows.length; i++) {
name += "," + rowData_.get(rows[i]).ID_;
}
}
referenceName_.setText(name);
} catch (Exception ex) {
JOptionPane.showMessageDialog(getInstance(), "Error setting color reference. Did you have enough input points?");
return;
}
}
}//GEN-LAST:event_c2StandardButtonActionPerformed
/**
* Cycles through the spots of the selected data set and finds the most nearby
* spot in channel 2. It will list this as a pair if the two spots are within
* MAXMATCHDISTANCE nm of each other.
* In addition, it will list the average distance, and average distance
* in x and y for each frame.
*
* spots in channel 2
* that are within MAXMATCHDISTANCE of
*
* @param evt
*/
private void pairsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pairsButtonActionPerformed
final int row = jTable1_.getSelectedRow();
if (row < 0) {
JOptionPane.showMessageDialog(getInstance(), "Please select a dataset for the Pair function");
return;
}
if (row > -1) {
Runnable doWorkRunnable = new Runnable() {
@Override
public void run() {
ResultsTable rt = new ResultsTable();
rt.reset();
rt.setPrecision(2);
ResultsTable rt2 = new ResultsTable();
rt2.reset();
rt2.setPrecision(2);
int width = rowData_.get(row).width_;
int height = rowData_.get(row).height_;
double factor = rowData_.get(row).pixelSizeNm_;
boolean useS = useSeconds(rowData_.get(row));
ij.ImageStack stack = new ij.ImageStack(width, height);
ImagePlus sp = new ImagePlus("Errors in pairs");
XYSeries xData = new XYSeries("XError");
XYSeries yData = new XYSeries("YError");
ij.IJ.showStatus("Creating Pairs...");
for (int frame = 1; frame <= rowData_.get(row).nrFrames_; frame++) {
ij.IJ.showProgress(frame, rowData_.get(row).nrFrames_);
ImageProcessor ip = new ShortProcessor(width, height);
short pixels[] = new short[width * height];
ip.setPixels(pixels);
// Get points from both channels in each frame as ArrayLists
ArrayList<GaussianSpotData> gsCh1 = new ArrayList<GaussianSpotData>();
ArrayList<Point2D.Double> xyPointsCh2 = new ArrayList<Point2D.Double>();
Iterator it = rowData_.get(row).spotList_.iterator();
while (it.hasNext()) {
GaussianSpotData gs = (GaussianSpotData) it.next();
if (gs.getFrame() == frame) {
if (gs.getChannel() == 1) {
gsCh1.add(gs);
} else if (gs.getChannel() == 2) {
Point2D.Double point = new Point2D.Double(gs.getXCenter(), gs.getYCenter());
xyPointsCh2.add(point);
}
}
}
if (xyPointsCh2.isEmpty()) {
ReportingUtils.logError("Pairs function in Localization plugin: no points found in second channel in frame " + frame);
continue;
}
// Find matching points in the two ArrayLists
Iterator it2 = gsCh1.iterator();
try {
NearestPoint2D np = new NearestPoint2D(xyPointsCh2,
NumberUtils.displayStringToDouble(pairsMaxDistanceField_.getText()));
ArrayList<Double> distances = new ArrayList<Double>();
ArrayList<Double> errorX = new ArrayList<Double>();
ArrayList<Double> errorY = new ArrayList<Double>();
while (it2.hasNext()) {
GaussianSpotData gs = (GaussianSpotData) it2.next();
Point2D.Double pCh1 = new Point2D.Double(gs.getXCenter(), gs.getYCenter());
Point2D.Double pCh2 = np.findKDWSE(pCh1);
if (pCh2 != null) {
rt.incrementCounter();
rt.addValue(Terms.POSITION, gs.getPosition());
rt.addValue(Terms.FRAME, gs.getFrame());
rt.addValue(Terms.SLICE, gs.getSlice());
rt.addValue(Terms.CHANNEL, gs.getSlice());
rt.addValue(Terms.XPIX, gs.getX());
rt.addValue(Terms.YPIX, gs.getY());
rt.addValue("X1", pCh1.getX());
rt.addValue("Y1", pCh1.getY());
rt.addValue("X2", pCh2.getX());
rt.addValue("Y2", pCh2.getY());
double d2 = NearestPoint2D.distance2(pCh1, pCh2);
double d = Math.sqrt(d2);
rt.addValue("Distance", d);
rt.addValue("Orientation (sine)",
NearestPoint2D.orientation(pCh1, pCh2));
distances.add(d);
ip.putPixel((int) (pCh1.x / factor), (int) (pCh1.y / factor), (int) d);
double ex = pCh2.getX() - pCh1.getX();
//double ex = (pCh1.getX() - pCh2.getX()) * (pCh1.getX() - pCh2.getX());
//ex = Math.sqrt(ex);
errorX.add(ex);
//double ey = (pCh1.getY() - pCh2.getY()) * (pCh1.getY() - pCh2.getY());
//ey = Math.sqrt(ey);
double ey = pCh2.getY() - pCh1.getY();
errorY.add(ey);
}
}
Double avg = listAvg(distances);
Double stdDev = listStdDev(distances, avg);
Double avgX = listAvg(errorX);
Double stdDevX = listStdDev(errorX, avgX);
Double avgY = listAvg(errorY);
Double stdDevY = listStdDev(errorY, avgY);
rt2.incrementCounter();
rt2.addValue("Frame Nr.", frame);
rt2.addValue("Avg. distance", avg);
rt2.addValue("StdDev distance", stdDev);
rt2.addValue("X", avgX);
rt2.addValue("StdDev X", stdDevX);
rt2.addValue("Y", avgY);
rt2.addValue("StdDevY", stdDevY);
stack.addSlice("frame: " + frame, ip);
double timePoint = frame;
if (rowData_.get(row).timePoints_ != null) {
timePoint = rowData_.get(row).timePoints_.get(frame);
if (useS) {
timePoint /= 1000;
}
}
xData.add(timePoint, avgX);
yData.add(timePoint, avgY);
} catch (ParseException ex) {
JOptionPane.showMessageDialog(getInstance(), "Error in Pairs input");
return;
}
}
if (rt.getCounter() == 0) {
MessageDialog md = new MessageDialog(DataCollectionForm.getInstance(),
"No Pairs found", "No Pairs found");
return;
}
// show summary in resultstable
rt2.show("Summary of Pairs found in " + rowData_.get(row).name_);
// show Pairs panel and attach listener
TextPanel tp;
TextWindow win;
String rtName = "Pairs found in " + rowData_.get(row).name_;
rt.show(rtName);
ImagePlus siPlus = ij.WindowManager.getImage(rowData_.get(row).title_);
Frame frame = WindowManager.getFrame(rtName);
if (frame != null && frame instanceof TextWindow && siPlus != null) {
win = (TextWindow) frame;
tp = win.getTextPanel();
// TODO: the following does not work, there is some voodoo going on here
for (MouseListener ms : tp.getMouseListeners()) {
tp.removeMouseListener(ms);
}
for (KeyListener ks : tp.getKeyListeners()) {
tp.removeKeyListener(ks);
}
ResultsTableListener myk = new ResultsTableListener(siPlus, rt, win, rowData_.get(row).halfSize_);
tp.addKeyListener(myk);
tp.addMouseListener(myk);
frame.toFront();
}
String xAxis = "Time (frameNr)";
if (rowData_.get(row).timePoints_ != null) {
xAxis = "Time (ms)";
if (useS) {
xAxis = "Time (s)";
}
}
GaussianUtils.plotData2("Error in " + rowData_.get(row).name_, xData, yData, xAxis, "Error(nm)", 0, 400);
ij.IJ.showStatus("");
sp.setOpenAsHyperStack(true);
sp.setStack(stack, 1, 1, rowData_.get(row).nrFrames_);
sp.setDisplayRange(0, 20);
sp.setTitle(rowData_.get(row).title_);
ImageWindow w = new StackWindow(sp);
w.setTitle("Error in " + rowData_.get(row).name_);
w.setImage(sp);
w.setVisible(true);
}
};
(new Thread(doWorkRunnable)).start();
}
}//GEN-LAST:event_pairsButtonActionPerformed
/**
* Helper function for function listParticels
* Finds a spot within MAXMatchDistance in the frame following the frame
* of the given spot.
* Only looks at Channel 1
*
* @param input - look for a spot close to this one
* @param spotPairs - List with spotPairs
* @return spotPair found or null if none
*/
private GsSpotPair findNextSpotPair(GsSpotPair input,
ArrayList<ArrayList<GsSpotPair>> spotPairsByFrame,
NearestPointGsSpotPair npsp, int frame) {
final double maxDistance;
try {
maxDistance = NumberUtils.displayStringToDouble(pairsMaxDistanceField_.getText());
} catch (ParseException ex) {
ReportingUtils.logError("Error parsing pairs max distance field");
return null;
}
final double maxDistance2 = maxDistance * maxDistance;
Iterator<GsSpotPair> it = (spotPairsByFrame.get(frame - 1)).iterator();
while (it.hasNext()) {
GsSpotPair nextSpot = it.next();
if (nextSpot.getGSD().getFrame() == frame) {
if (NearestPoint2D.distance2(input.getfp(), nextSpot.getfp())
< maxDistance2) {
return nextSpot;
}
}
// optimization that is only valid if the ArrayList is properly sorted
if (nextSpot.getGSD().getFrame() > frame) {
return null;
}
}
return null;
}
/**
* Cycles through the spots of the selected data set and finds the most nearby
* spot in channel 2. It will list this as a pair if the two spots are within
* MAXMATCHDISTANCE nm of each other.
*
* Once all pairs are found, it will go through all frames and try to build up
* tracks. If the spot is within MAXMATCHDISTANCE between frames, the code
* will consider the particle to be identical.
*
* All "tracks" of particles will be listed
*
* In addition, it will list the average distance, and average distance
* in x and y for each frame.
*
* spots in channel 2
* that are within MAXMATCHDISTANCE of
*
* @param evt
*/
public void listParticles(java.awt.event.ActionEvent evt) {
final int[] rows = jTable1_.getSelectedRows();
if (rows.length < 1) {
JOptionPane.showMessageDialog(getInstance(), "Please select a dataset for the List Particles function");
return;
}
// if (row > -1) {
Runnable doWorkRunnable = new Runnable() {
@Override
public void run() {
// Show Particle List as linked Results Table
ResultsTable rt = new ResultsTable();
rt.reset();
rt.setPrecision(2);
// Show Particle Summary as Linked Results Table
ResultsTable rt2 = new ResultsTable();
rt2.reset();
rt2.setPrecision(1);
final double maxDistance;
try {
maxDistance = NumberUtils.displayStringToDouble(pairsMaxDistanceField_.getText());
} catch (ParseException ex) {
ReportingUtils.logError("Error parsing pairs max distance field");
return;
}
for (int row : rows) {
ArrayList<ArrayList<GsSpotPair>> spotPairsByFrame =
new ArrayList<ArrayList<GsSpotPair>>();
ij.IJ.showStatus("Creating Pairs...");
// First go through all frames to find all pairs
int nrSpotPairsInFrame1 = 0;
for (int frame = 1; frame <= rowData_.get(row).nrFrames_; frame++) {
ij.IJ.showProgress(frame, rowData_.get(row).nrFrames_);
spotPairsByFrame.add(new ArrayList<GsSpotPair>());
// Get points from both channels in each frame as ArrayLists
ArrayList<GaussianSpotData> gsCh1 = new ArrayList<GaussianSpotData>();
ArrayList<Point2D.Double> xyPointsCh2 = new ArrayList<Point2D.Double>();
Iterator it = rowData_.get(row).spotList_.iterator();
while (it.hasNext()) {
GaussianSpotData gs = (GaussianSpotData) it.next();
if (gs.getFrame() == frame) {
if (gs.getChannel() == 1) {
gsCh1.add(gs);
} else if (gs.getChannel() == 2) {
Point2D.Double point = new Point2D.Double(gs.getXCenter(), gs.getYCenter());
xyPointsCh2.add(point);
}
}
}
if (xyPointsCh2.isEmpty()) {
ReportingUtils.logError("Pairs function in Localization plugin: no points found in second channel in frame " + frame);
continue;
}
// Find matching points in the two ArrayLists
Iterator it2 = gsCh1.iterator();
try {
NearestPoint2D np = new NearestPoint2D(xyPointsCh2,
NumberUtils.displayStringToDouble(pairsMaxDistanceField_.getText()));
while (it2.hasNext()) {
GaussianSpotData gs = (GaussianSpotData) it2.next();
Point2D.Double pCh1 = new Point2D.Double(gs.getXCenter(), gs.getYCenter());
Point2D.Double pCh2 = np.findKDWSE(pCh1);
if (pCh2 != null) {
GsSpotPair pair = new GsSpotPair(gs, pCh1, pCh2);
//spotPairs.add(pair);
spotPairsByFrame.get(frame - 1).add(pair);
}
}
} catch (ParseException ex) {
JOptionPane.showMessageDialog(getInstance(), "Error in Pairs input");
return;
}
}
// We have all pairs, assemble in tracks
ij.IJ.showStatus("Assembling tracks...");
// prepare NearestPoint objects to speed up finding closest pair
ArrayList<NearestPointGsSpotPair> npsp = new ArrayList<NearestPointGsSpotPair>();
for (int frame = 1; frame <= rowData_.get(row).nrFrames_; frame++) {
npsp.add(new NearestPointGsSpotPair(spotPairsByFrame.get(frame - 1), maxDistance));
}
ArrayList<ArrayList<GsSpotPair>> tracks = new ArrayList<ArrayList<GsSpotPair>>();
Iterator<GsSpotPair> iSpotPairs = spotPairsByFrame.get(0).iterator();
int i = 0;
while (iSpotPairs.hasNext()) {
ij.IJ.showProgress(i++, nrSpotPairsInFrame1);
GsSpotPair spotPair = iSpotPairs.next();
// for now, we only start tracks at frame number 1
if (spotPair.getGSD().getFrame() == 1) {
ArrayList<GsSpotPair> track = new ArrayList<GsSpotPair>();
track.add(spotPair);
int frame = 2;
while (frame <= rowData_.get(row).nrFrames_) {
GsSpotPair newSpotPair = npsp.get(frame - 1).findKDWSE(
new Point2D.Double(spotPair.getfp().getX(), spotPair.getfp().getY()));
if (newSpotPair != null) {
spotPair = newSpotPair;
track.add(spotPair);
}
frame++;
}
tracks.add(track);
}
}
if (tracks.isEmpty()) {
MessageDialog md = new MessageDialog(DataCollectionForm.getInstance(),
"No Pairs found", "No Pairs found");
continue;
}
Iterator<ArrayList<GsSpotPair>> itTracks = tracks.iterator();
int spotId = 0;
while (itTracks.hasNext()) {
ArrayList<GsSpotPair> track = itTracks.next();
Iterator<GsSpotPair> itTrack = track.iterator();
while (itTrack.hasNext()) {
GsSpotPair spot = itTrack.next();
rt.incrementCounter();
rt.addValue("Spot ID", spotId);
rt.addValue(Terms.FRAME, spot.getGSD().getFrame());
rt.addValue(Terms.SLICE, spot.getGSD().getSlice());
rt.addValue(Terms.CHANNEL, spot.getGSD().getSlice());
rt.addValue(Terms.XPIX, spot.getGSD().getX());
rt.addValue(Terms.YPIX, spot.getGSD().getY());
rt.addValue("Distance", Math.sqrt(
NearestPoint2D.distance2(spot.getfp(), spot.getsp())));
rt.addValue("Orientation (sine)",
NearestPoint2D.orientation(spot.getfp(), spot.getsp()));
}
spotId++;
}
TextPanel tp;
TextWindow win;
String rtName = rowData_.get(row).name_ + " Particle List";
rt.show(rtName);
ImagePlus siPlus = ij.WindowManager.getImage(rowData_.get(row).title_);
Frame frame = WindowManager.getFrame(rtName);
if (frame != null && frame instanceof TextWindow && siPlus != null) {
win = (TextWindow) frame;
tp = win.getTextPanel();
// TODO: the following does not work, there is some voodoo going on here
for (MouseListener ms : tp.getMouseListeners()) {
tp.removeMouseListener(ms);
}
for (KeyListener ks : tp.getKeyListeners()) {
tp.removeKeyListener(ks);
}
ResultsTableListener myk = new ResultsTableListener(siPlus, rt, win, rowData_.get(row).halfSize_);
tp.addKeyListener(myk);
tp.addMouseListener(myk);
frame.toFront();
}
siPlus = ij.WindowManager.getImage(rowData_.get(row).title_);
if (siPlus != null && siPlus.getOverlay() != null) {
siPlus.getOverlay().clear();
}
Arrow.setDefaultWidth(0.5);
itTracks = tracks.iterator();
spotId = 0;
while (itTracks.hasNext()) {
ArrayList<GsSpotPair> track = itTracks.next();
ArrayList<Double> distances = new ArrayList<Double>();
ArrayList<Double> orientations = new ArrayList<Double>();
ArrayList<Double> xDiff = new ArrayList<Double>();
ArrayList<Double> yDiff = new ArrayList<Double>();
for (GsSpotPair pair : track) {
distances.add(Math.sqrt(
NearestPoint2D.distance2(pair.getfp(), pair.getsp())));
orientations.add(NearestPoint2D.orientation(pair.getfp(),
pair.getsp()));
xDiff.add(pair.getfp().getX() - pair.getsp().getX());
yDiff.add(pair.getfp().getY() - pair.getsp().getY());
}
GsSpotPair pair = track.get(0);
rt2.incrementCounter();
rt2.addValue("Row ID", rowData_.get(row).ID_);
rt2.addValue("Spot ID", spotId);
rt2.addValue(Terms.FRAME, pair.getGSD().getFrame());
rt2.addValue(Terms.SLICE, pair.getGSD().getSlice());
rt2.addValue(Terms.CHANNEL, pair.getGSD().getSlice());
rt2.addValue(Terms.XPIX, pair.getGSD().getX());
rt2.addValue(Terms.YPIX, pair.getGSD().getY());
rt2.addValue("n", track.size());
double avg = avgList(distances);
rt2.addValue("Distance-Avg", avg);
rt2.addValue("Distance-StdDev", stdDevList(distances, avg));
double oAvg = avgList(orientations);
rt2.addValue("Orientation-Avg", oAvg);
rt2.addValue("Orientation-StdDev",
stdDevList(orientations, oAvg));
double xDiffAvg = avgList(xDiff);
double yDiffAvg = avgList(yDiff);
double xDiffAvgStdDev = stdDevList(xDiff, xDiffAvg);
double yDiffAvgStdDev = stdDevList(yDiff, yDiffAvg);
rt2.addValue("Dist.Vect.Avg", Math.sqrt(
(xDiffAvg * xDiffAvg) + (yDiffAvg * yDiffAvg)));
rt2.addValue("Dist.Vect.StdDev", Math.sqrt(
(xDiffAvgStdDev * xDiffAvgStdDev)
+ (yDiffAvgStdDev * yDiffAvgStdDev)));
/* draw arrows in overlay */
double mag = 100.0; // factor that sets magnification of the arrow
double factor = mag * 1 / rowData_.get(row).pixelSizeNm_; // factor relating mad and pixelSize
int xStart = track.get(0).getGSD().getX();
int yStart = track.get(0).getGSD().getY();
Arrow arrow = new Arrow(xStart, yStart,
xStart + (factor * xDiffAvg),
yStart + (factor * yDiffAvg));
arrow.setHeadSize(3);
arrow.setOutline(false);
if (siPlus != null && siPlus.getOverlay() == null) {
siPlus.setOverlay(arrow, Color.yellow, 1, Color.yellow);
} else if (siPlus != null && siPlus.getOverlay() != null) {
siPlus.getOverlay().add(arrow);
}
spotId++;
}
if (siPlus != null) {
siPlus.setHideOverlay(false);
}
rtName = rowData_.get(row).name_ + " Particle Summary";
rt2.show(rtName);
siPlus = ij.WindowManager.getImage(rowData_.get(row).title_);
frame = WindowManager.getFrame(rtName);
if (frame != null && frame instanceof TextWindow && siPlus != null) {
win = (TextWindow) frame;
tp = win.getTextPanel();
// TODO: the following does not work, there is some voodoo going on here
for (MouseListener ms : tp.getMouseListeners()) {
tp.removeMouseListener(ms);
}
for (KeyListener ks : tp.getKeyListeners()) {
tp.removeKeyListener(ks);
}
ResultsTableListener myk = new ResultsTableListener(siPlus, rt2, win, rowData_.get(row).halfSize_);
tp.addKeyListener(myk);
tp.addMouseListener(myk);
frame.toFront();
}
ij.IJ.showStatus("");
}
}
};
(new Thread(doWorkRunnable)).start();
}
/**
* Calculates the average of a list of doubles
*
* @param list
* @return average
*/
private static double listAvg (ArrayList<Double> list) {
double total = 0.0;
Iterator it = list.iterator();
while (it.hasNext()) {
total += (Double) it.next();
}
return total / list.size();
}
/**
* Returns the Standard Deviation as sqrt( 1/(n-1) sum( square(value - avg)) )
* Feeding in parameter avg is just increase performance
*
* @param list ArrayList<Double>
* @param avg average of the list
* @return standard deviation as defined above
*/
private static double listStdDev (ArrayList<Double> list, double avg) {
double errorsSquared = 0;
Iterator it = list.iterator();
while (it.hasNext()) {
double error = (Double) it.next() - avg;
errorsSquared += (error * error);
}
return Math.sqrt(errorsSquared / (list.size() - 1) ) ;
}
/**
* Utility function to calculate Standard Deviation
* @param list
* @return
*/
private static double listStdDev (ArrayList<Double> list) {
double avg = listAvg(list);
return listStdDev(list, avg);
}
private void c2CorrectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_c2CorrectButtonActionPerformed
int[] rows = jTable1_.getSelectedRows();
if (rows.length > 0) {
try {
for (int row : rows) {
correct2C(rowData_.get(row));
}
} catch (InterruptedException ex) {
ReportingUtils.showError(ex);
}
} else
JOptionPane.showMessageDialog(getInstance(), "Please select a dataset to color correct");
}//GEN-LAST:event_c2CorrectButtonActionPerformed
private void unjitterButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unjitterButton_ActionPerformed
final int row = jTable1_.getSelectedRow();
if (row > -1) {
Runnable doWorkRunnable = new Runnable() {
public void run() {
if (jitterMethod_ == 0)
unJitter(rowData_.get(row));
else
new DriftCorrector().unJitter(rowData_.get(row), jitterMaxFrames_, jitterMaxSpots_);
}
};
(new Thread(doWorkRunnable)).start();
} else {
JOptionPane.showMessageDialog(getInstance(), "Please select a dataset to unjitter");
}
}//GEN-LAST:event_unjitterButton_ActionPerformed
private void filterSigmaCheckBox_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterSigmaCheckBox_ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_filterSigmaCheckBox_ActionPerformed
private void filterIntensityCheckBox_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filterIntensityCheckBox_ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_filterIntensityCheckBox_ActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
prefs_.putInt(FRAMEXPOS, getX());
prefs_.putInt(FRAMEYPOS, getY());
prefs_.putInt(FRAMEWIDTH, getWidth());
prefs_.putInt(FRAMEHEIGHT, getHeight());
prefs_.putBoolean(USESIGMA, filterSigmaCheckBox_.isSelected());
prefs_.put(SIGMAMIN, sigmaMin_.getText());
prefs_.put(SIGMAMAX, sigmaMax_.getText());
prefs_.putBoolean(USEINT, filterIntensityCheckBox_.isSelected());
prefs_.put(INTMIN, intensityMin_.getText());
prefs_.put(INTMAX, intensityMax_.getText());
prefs_.put(LOADTSFDIR, loadTSFDir_);
prefs_.putInt(RENDERMAG, visualizationMagnification_.getSelectedIndex());
prefs_.put(PAIRSMAXDISTANCE, pairsMaxDistanceField_.getText());
TableColumnModel cm = jTable1_.getColumnModel();
prefs_.putInt(COL0Width, cm.getColumn(0).getWidth());
prefs_.putInt(COL1Width, cm.getColumn(1).getWidth());
prefs_.putInt(COL2Width, cm.getColumn(2).getWidth());
prefs_.putInt(COL3Width, cm.getColumn(3).getWidth());
prefs_.putInt(COL4Width, cm.getColumn(4).getWidth());
setVisible(false);
}//GEN-LAST:event_formWindowClosing
/**
* Present user with summary data of this dataset.
*
* @param evt
*/
private void infoButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_infoButton_ActionPerformed
int row = jTable1_.getSelectedRow();
if (row > -1) {
MyRowData rowData = rowData_.get(row);
String data = "Name: " + rowData.name_ + "\n" +
"Title: " + rowData.title_ + "\n" +
"BoxSize: " + 2*rowData.halfSize_ + "\n" +
"Image Height (pixels): " + rowData.height_ + "\n" +
"Image Width (pixels): " + rowData.width_ + "\n" +
"Nr. of Spots: " + rowData.maxNrSpots_ + "\n" +
"Pixel Size (nm): " + rowData.pixelSizeNm_ + "\n" +
"Z Stack Step Size (nm): " + rowData.zStackStepSizeNm_ + "\n" +
"Nr. of Channels: " + rowData.nrChannels_ + "\n" +
"Nr. of Frames: " + rowData.nrFrames_ + "\n" +
"Nr. of Slices: " + rowData.nrSlices_ + "\n" +
"Nr. of Positions: " + rowData.nrPositions_ + "\n" +
"Is a Track: " + rowData.isTrack_;
if (!rowData.isTrack_)
data += "\nHas Z info: " + rowData.hasZ_;
if (rowData.hasZ_) {
data += "\nMinZ: " + String.format("%.2f",rowData.minZ_) + "\n";
data += "MaxZ: " + String.format("%.2f",rowData.maxZ_);
}
if (rowData.isTrack_) {
ArrayList<Point2D.Double> xyList = spotListToPointList(rowData.spotList_);
Point2D.Double avg = DataCollectionForm.avgXYList(xyList);
Point2D.Double stdDev = DataCollectionForm.stdDevXYList(xyList, avg);
data += "\n" +
"Average X: " + avg.x + "\n" +
"StdDev X: " + stdDev.x + "\n" +
"Average Y: " + avg.y + "\n" +
"StdDev Y: " + stdDev.y;
}
TextWindow tw = new TextWindow("Info for " + rowData.name_, data, 300, 300);
tw.setVisible(true);
}
else
JOptionPane.showMessageDialog(getInstance(), "Please select a dataset first");
}//GEN-LAST:event_infoButton_ActionPerformed
/**
* Renders dataset
*
* @param evt
*/
private void renderButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_renderButton_ActionPerformed
final int row = jTable1_.getSelectedRow();
if (row < 0) {
JOptionPane.showMessageDialog(getInstance(), "Please select a dataset to render");
} else {
Runnable doWorkRunnable = new Runnable() {
@Override
public void run() {
try {
int mag = 1 << visualizationMagnification_.getSelectedIndex();
SpotDataFilter sf = new SpotDataFilter();
if (filterSigmaCheckBox_.isSelected()) {
sf.setSigma(true, Double.parseDouble(sigmaMin_.getText()),
Double.parseDouble(sigmaMax_.getText()));
}
if (filterIntensityCheckBox_.isSelected()) {
sf.setIntensity(true, Double.parseDouble(intensityMin_.getText()),
Double.parseDouble(intensityMax_.getText()));
}
MyRowData rowData = rowData_.get(row);
String fsep = System.getProperty("file.separator");
String ttmp = rowData.name_;
if (rowData.name_.contains(fsep)) {
ttmp = rowData.name_.substring(rowData.name_.lastIndexOf(fsep) + 1);
}
ttmp += mag + "x";
final String title = ttmp;
ImagePlus sp = null;
if (rowData.hasZ_) {
ImageStack is = ImageRenderer.renderData3D(rowData,
visualizationModel_.getSelectedIndex(), mag, null, sf);
sp = new ImagePlus(title, is);
DisplayUtils.AutoStretch(sp);
DisplayUtils.SetCalibration(sp, (float) (rowData.pixelSizeNm_ / mag));
sp.show();
} else {
ImageProcessor ip = ImageRenderer.renderData(rowData,
visualizationModel_.getSelectedIndex(), mag, null, sf);
sp = new ImagePlus(title, ip);
GaussCanvas gs = new GaussCanvas(sp, rowData_.get(row),
visualizationModel_.getSelectedIndex(), mag, sf);
DisplayUtils.AutoStretch(sp);
DisplayUtils.SetCalibration(sp, (float) (rowData.pixelSizeNm_ / mag));
ImageWindow w = new ImageWindow(sp, gs);
w.setVisible(true);
}
} catch (OutOfMemoryError ome) {
ReportingUtils.showError("Out of Memory");
}
}
};
(new Thread(doWorkRunnable)).start();
}
}//GEN-LAST:event_renderButton_ActionPerformed
private void plotButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_plotButton_ActionPerformed
int rows[] = jTable1_.getSelectedRows();
if (rows.length < 1) {
JOptionPane.showMessageDialog(getInstance(), "Please select one or more datasets to plot");
} else {
MyRowData[] myRows = new MyRowData[rows.length];
// TODO: check that these are tracks
for (int i = 0; i < rows.length; i++)
myRows[i] = rowData_.get(rows[i]);
plotData(myRows, plotComboBox_.getSelectedIndex());
}
}//GEN-LAST:event_plotButton_ActionPerformed
public static ArrayList<Point2D.Double> spotListToPointList(List<GaussianSpotData> spotList){
ArrayList<Point2D.Double> xyPoints = new ArrayList<Point2D.Double>();
Iterator it = spotList.iterator();
while (it.hasNext()) {
GaussianSpotData gs = (GaussianSpotData) it.next();
Point2D.Double point = new Point2D.Double(gs.getXCenter(), gs.getYCenter());
xyPoints.add(point);
}
return xyPoints;
}
public static Point2D.Double avgXYList(ArrayList<Point2D.Double> xyPoints) {
Point2D.Double myAvg = new Point2D.Double(0.0, 0.0);
for (Point2D.Double point : xyPoints) {
myAvg.x += point.x;
myAvg.y += point.y;
}
myAvg.x = myAvg.x / xyPoints.size();
myAvg.y = myAvg.y / xyPoints.size();
return myAvg;
}
public static Point2D.Double stdDevXYList(ArrayList<Point2D.Double> xyPoints,
Point2D.Double avg) {
Point2D.Double myStdDev = new Point2D.Double(0.0, 0.0);
for (Point2D.Double point : xyPoints) {
myStdDev.x += (point.x - avg.x) * (point.x - avg.x);
myStdDev.y += (point.y - avg.y) * (point.y - avg.y);
}
myStdDev.x = Math.sqrt(myStdDev.x / (xyPoints.size() - 1) ) ;
myStdDev.y = Math.sqrt(myStdDev.y / (xyPoints.size() - 1) ) ;
return myStdDev;
}
public static double avgList(ArrayList<Double> vals) {
double result = 0;
for (Double val : vals) {
result += val;
}
return result / vals.size();
}
public static double stdDevList(ArrayList<Double> vals, double avg) {
double result = 0;
for (Double val: vals) {
result += (val - avg) * (val - avg);
}
if (vals.size() < 2)
return 0.0;
result = result / (vals.size() - 1);
return Math.sqrt(result);
}
public class TrackAnalysisData {
public int frame;
public int n;
public double xAvg;
public double xStdDev;
public double yAvg;
public double yStdDev;
}
/**
* Centers all selected tracks (subtracts the average position)
* and then calculates the average position of all tracks.
* Can take multiple tracks of varied lengths as input
*
* @param evt
*/
private void averageTrackButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_averageTrackButton_ActionPerformed
int rows[] = jTable1_.getSelectedRows();
if (rows.length < 1) {
JOptionPane.showMessageDialog(getInstance(),
"Please select one or more datasets to average");
} else {
MyRowData[] myRows = new MyRowData[rows.length];
ArrayList<Point2D.Double> listAvgs = new ArrayList<Point2D.Double>();
for (int i = 0; i < rows.length; i++) {
myRows[i] = rowData_.get(rows[i]);
ArrayList<Point2D.Double> xyPoints = spotListToPointList(myRows[i].spotList_);
Point2D.Double listAvg = avgXYList(xyPoints);
listAvgs.add(listAvg);
}
// organize all spots in selected rows in a Hashmap keyed by frame number
// while doing so, also subtract the average (i.e. center around 0)
HashMap<Integer, List<GaussianSpotData>> allData =
new HashMap<Integer, List<GaussianSpotData>>();
for (int i=0; i < myRows.length; i++) {
for (GaussianSpotData spotData : myRows[i].spotList_) {
GaussianSpotData spotCopy = new GaussianSpotData(spotData);
spotCopy.setXCenter(spotData.getXCenter() - listAvgs.get(i).x);
spotCopy.setYCenter(spotData.getYCenter() - listAvgs.get(i).y);
int frame = spotData.getFrame();
if (!allData.containsKey(frame)) {
List<GaussianSpotData> thisFrame = new ArrayList<GaussianSpotData>();
thisFrame.add(spotCopy);
allData.put(frame, thisFrame);
} else {
allData.get(frame).add(spotCopy);
}
}
}
List<GaussianSpotData> transformedResultList =
Collections.synchronizedList(new ArrayList<GaussianSpotData>());
List<TrackAnalysisData> avgTrackData = new ArrayList<TrackAnalysisData>();
// for each frame in the collection, calculate the average
for (int i = 1; i <= allData.size(); i++) {
List<GaussianSpotData> frameList = allData.get(i);
TrackAnalysisData tad = new TrackAnalysisData();
tad.frame = i;
tad.n = frameList.size();
GaussianSpotData avgFrame = new GaussianSpotData(frameList.get(0));
ArrayList<Point2D.Double> xyPoints = spotListToPointList(frameList);
Point2D.Double listAvg = avgXYList(xyPoints);
Point2D.Double stdDev = stdDevXYList(xyPoints, listAvg);
tad.xAvg = listAvg.x;
tad.yAvg = listAvg.y;
tad.xStdDev = stdDev.x;
tad.yStdDev = stdDev.y;
avgTrackData.add(tad);
avgFrame.setXCenter(listAvg.x);
avgFrame.setYCenter(listAvg.y);
transformedResultList.add(avgFrame);
}
// Add transformed data to data overview window
MyRowData rowData = myRows[0];
addSpotData(rowData.name_ + " Average", rowData.title_, "", rowData.width_,
rowData.height_, rowData.pixelSizeNm_, rowData.zStackStepSizeNm_, rowData.shape_,
rowData.halfSize_, rowData.nrChannels_, rowData.nrFrames_,
rowData.nrSlices_, 1, rowData.maxNrSpots_, transformedResultList,
rowData.timePoints_, true, Coordinates.NM, false, 0.0, 0.0);
// show resultsTable
ResultsTable rt = new ResultsTable();
for (int i = 0; i < avgTrackData.size(); i++) {
rt.incrementCounter();
TrackAnalysisData trackData = avgTrackData.get(i);
rt.addValue("Frame", trackData.frame);
rt.addValue("n", trackData.n);
rt.addValue("XAvg", trackData.xAvg);
rt.addValue("XStdev", trackData.xStdDev);
rt.addValue("YAvg", trackData.yAvg);
rt.addValue("YStdev", trackData.yStdDev);
}
rt.show("Averaged Tracks");
}
}//GEN-LAST:event_averageTrackButton_ActionPerformed
public void doMathOnRows(MyRowData source, MyRowData operand, int action) {
// create a copy of the dataset and copy in the corrected data
List<GaussianSpotData> transformedResultList =
Collections.synchronizedList(new ArrayList<GaussianSpotData>());
try {
for (int i = 0; i < source.spotList_.size(); i++) {
GaussianSpotData spotSource = source.spotList_.get(i);
boolean found = false;
int j = 0;
GaussianSpotData spotOperand = null;
while (!found && j < operand.spotList_.size()) {
spotOperand = operand.spotList_.get(j);
if (spotSource.getChannel() == spotOperand.getChannel() &&
spotSource.getFrame() == spotOperand.getFrame() &&
spotSource.getPosition() == spotOperand.getPosition() &&
spotSource.getSlice() == spotOperand.getSlice() ) {
found = true;
}
j++;
}
if (found) {
double x = 0.0;
double y = 0.0;
if (action == 0) {
x = spotSource.getXCenter() - spotOperand.getXCenter();
y = spotSource.getYCenter() - spotOperand.getYCenter();
}
GaussianSpotData newSpot = new GaussianSpotData(spotSource);
newSpot.setXCenter(x);
newSpot.setYCenter(y);
transformedResultList.add(newSpot);
}
}
MyRowData rowData = source;
// TODO: feed in better data
addSpotData(rowData.name_ + " Subtracted", rowData.title_, "", rowData.width_,
rowData.height_, rowData.pixelSizeNm_, rowData.zStackStepSizeNm_,
rowData.shape_, rowData.halfSize_, rowData.nrChannels_,
rowData.nrFrames_, rowData.nrSlices_, 1, rowData.maxNrSpots_,
transformedResultList,
rowData.timePoints_, true, Coordinates.NM, false, 0.0, 0.0);
} catch (IndexOutOfBoundsException iobe) {
JOptionPane.showMessageDialog(getInstance(), "Data sets differ in Size");
}
}
private void mathButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mathButton_ActionPerformed
int[] rows = new int[jTable1_.getRowCount()];
for (int i = 0; i < rows.length; i++) {
rows[i] = (Integer) jTable1_.getValueAt(i, 0);
}
MathForm mf = new MathForm(rows, rows);
mf.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor());
MMStudioMainFrame.getInstance().addMMBackgroundListener(mf);
mf.setVisible(true);
}//GEN-LAST:event_mathButton_ActionPerformed
/**
* Links spots by checking in consecutive frames whether the spot is still present
* If it is, add it to a list
* Once a frame has been found in which it is not present, calculate the average spot position
* and add this averaged spot to the list with linked spots
* The Frame number of the linked spot list will be 0
* @param evt - ignored...
*/
private void linkButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_linkButton_ActionPerformed
final int row = jTable1_.getSelectedRow();
final MyRowData rowData = rowData_.get(row);
if (rowData.frameIndexSpotList_ == null) {
rowData.index();
}
Runnable doWorkRunnable = new Runnable() {
@Override
public void run() {
try {
ij.IJ.showStatus("Linking spotData...");
boolean useFrames = rowData.nrFrames_ > rowData.nrSlices_;
int nr = rowData.nrSlices_;
if (useFrames) {
nr = rowData.nrFrames_;
}
// linked spots go here:
List<GaussianSpotData> destList = new ArrayList<GaussianSpotData>();
// build a 2D array of lists with gaussian spots
List<GaussianSpotData>[][] spotImage =
new ArrayList[rowData.width_][rowData.height_];
for (int i = 1; i < nr; i++) {
ij.IJ.showStatus("Linking spotData...");
ij.IJ.showProgress(i, nr);
List<GaussianSpotData> frameSpots = rowData.frameIndexSpotList_.get(i);
if (frameSpots != null) {
for (GaussianSpotData spot : frameSpots) {
if (spotImage[spot.getX()][spot.getY()] == null) {
spotImage[spot.getX()][spot.getY()] = new ArrayList<GaussianSpotData>();
} else {
List<GaussianSpotData> prevSpotList = spotImage[spot.getX()][spot.getY()];
GaussianSpotData lastSpot = prevSpotList.get(prevSpotList.size() - 1);
int lastFrame = lastSpot.getFrame();
if (!useFrames) {
lastFrame = lastSpot.getSlice();
}
if (lastFrame != i - 1) {
linkSpots(prevSpotList, destList, useFrames);
spotImage[spot.getX()][spot.getY()] = new ArrayList<GaussianSpotData>();
}
}
spotImage[spot.getX()][spot.getY()].add(spot);
}
} else {
System.out.println("Empty row: " + i);
}
}
// Finish links of all remaining spots
ij.IJ.showStatus("Finishing linking spotData...");
for (int w = 0; w < rowData.width_; w++) {
for (int h = 0; h < rowData.height_; h++) {
if (spotImage[w][h] != null) {
linkSpots(spotImage[w][h], destList, useFrames);
}
}
}
ij.IJ.showStatus("");
ij.IJ.showProgress(1);
// Add destList to rowData
addSpotData(rowData.name_ + " Linked", rowData.title_, "", rowData.width_,
rowData.height_, rowData.pixelSizeNm_, rowData.zStackStepSizeNm_,
rowData.shape_, rowData.halfSize_, rowData.nrChannels_, 0,
0, 1, rowData.maxNrSpots_, destList,
rowData.timePoints_, false, Coordinates.NM, false, 0.0, 0.0);
} catch (OutOfMemoryError oome) {
JOptionPane.showMessageDialog(getInstance(), "Out of memory");
}
}
};
(new Thread(doWorkRunnable)).start();
}//GEN-LAST:event_linkButton_ActionPerformed
private void straightenTrackButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_straightenTrackButton_ActionPerformed
int rows[] = jTable1_.getSelectedRows();
if (rows.length < 1) {
JOptionPane.showMessageDialog(getInstance(),
"Please select one or more datasets to straighten");
} else {
for (int row : rows) {
MyRowData r = rowData_.get(row);
if (evt.getModifiers() > 0) {
if (r.title_.equals(ij.IJ.getImage().getTitle()) ) {
ImagePlus ip = ij.IJ.getImage();
Roi roi = ip.getRoi();
if (roi.isLine()) {
Polygon pol = roi.getPolygon();
}
}
}
straightenTrack(r);
}
}
}//GEN-LAST:event_straightenTrackButton_ActionPerformed
private void centerTrackButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_centerTrackButton_ActionPerformed
int rows[] = jTable1_.getSelectedRows();
if (rows.length < 1) {
JOptionPane.showMessageDialog(getInstance(),
"Please select one or more datasets to center");
} else {
for (int row : rows) {
centerTrack(rowData_.get(row));
}
}
}//GEN-LAST:event_centerTrackButton_ActionPerformed
private void powerSpectrumCheckBox_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_powerSpectrumCheckBox_ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_powerSpectrumCheckBox_ActionPerformed
private void logLogCheckBox_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logLogCheckBox_ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_logLogCheckBox_ActionPerformed
private void zCalibrateButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zCalibrateButton_ActionPerformed
int rows[] = jTable1_.getSelectedRows();
if (rows.length != 1) {
JOptionPane.showMessageDialog(getInstance(),
"Please select one datasets for Z Calibration");
} else {
int result = zCalibrate(rows[0]);
if (result == OK ) {
zCalibrationLabel_.setText("Calibrated");
} else if (result == FAILEDDOINFORM) {
ReportingUtils.showError("Z-Calibration failed");
}
}
}//GEN-LAST:event_zCalibrateButton_ActionPerformed
private void listButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listButton_ActionPerformed
listParticles(evt);
}//GEN-LAST:event_listButton_ActionPerformed
private void method2CBox_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_method2CBox_ActionPerformed
prefs_.put(METHOD2C, (String) method2CBox_.getSelectedItem());
}//GEN-LAST:event_method2CBox_ActionPerformed
private void SubRangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SubRangeActionPerformed
String range = (String) JOptionPane.showInputDialog(this, "Provide desired subrange\n" +
"e.g. \"7-50\"", "SubRange", JOptionPane.PLAIN_MESSAGE, null, null, "");
ReportingUtils.showMessage("Range chosed: " + range);
}//GEN-LAST:event_SubRangeActionPerformed
/**
* Given a list of linked spots, create a single spot entry that will be added
* to the destination list
* @param source - list of spots that all occur around the same pixel and in linked frames
* @param dest - list spots in which each entry represents multiple linked spots
*/
private void linkSpots(List<GaussianSpotData> source, List<GaussianSpotData> dest,
boolean useFrames) {
if (source == null)
return;
if (dest == null)
return;
GaussianSpotData sp = new GaussianSpotData(source.get(0));
double intensity = 0.0;
double background = 0.0;
double xCenter = 0.0;
double yCenter = 0.0;
double width = 0.0;
double a = 0.0;
double theta = 0.0;
double sigma = 0.0;
for (GaussianSpotData spot : source) {
intensity += spot.getIntensity();
background += spot.getBackground();
xCenter += spot.getXCenter();
yCenter += spot.getYCenter();
width += spot.getWidth();
a += spot.getA();
theta += spot.getTheta();
sigma += spot.getSigma();
}
background /= source.size();
xCenter /= source.size();
yCenter /= source.size();
width /= source.size();
a /= source.size();
theta /= source.size();
sigma /= source.size();
// not sure if this is correct:
sigma /= Math.sqrt(source.size());
sp.setData(intensity, background, xCenter, yCenter, 0.0, width, a, theta, sigma);
sp.originalFrame_ = source.get(0).getFrame();
if (!useFrames)
sp.originalFrame_ = source.get(0).getSlice();
sp.nrLinks_ = source.size();
dest.add(sp);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel IntLabel2;
private javax.swing.JLabel SigmaLabel2;
private javax.swing.JLabel SigmaLabel3;
private javax.swing.JButton SubRange;
private javax.swing.JButton averageTrackButton_;
private javax.swing.JButton c2CorrectButton;
private javax.swing.JButton c2StandardButton;
private javax.swing.JButton centerTrackButton_;
private javax.swing.JCheckBox filterIntensityCheckBox_;
private javax.swing.JCheckBox filterSigmaCheckBox_;
private javax.swing.JButton infoButton_;
private javax.swing.JTextField intensityMax_;
private javax.swing.JTextField intensityMin_;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1_;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JTable jTable1_;
private javax.swing.JButton linkButton_;
private javax.swing.JButton listButton_;
private javax.swing.JButton loadButton;
private javax.swing.JCheckBox logLogCheckBox_;
private javax.swing.JButton mathButton_;
private javax.swing.JComboBox method2CBox_;
private javax.swing.JButton pairsButton;
private javax.swing.JTextField pairsMaxDistanceField_;
private javax.swing.JButton plotButton_;
private javax.swing.JComboBox plotComboBox_;
private javax.swing.JCheckBox powerSpectrumCheckBox_;
private javax.swing.JLabel referenceName_;
private javax.swing.JButton removeButton;
private javax.swing.JButton renderButton_;
private javax.swing.JButton saveButton;
private javax.swing.JComboBox saveFormatBox_;
private javax.swing.JButton showButton_;
private javax.swing.JTextField sigmaMax_;
private javax.swing.JTextField sigmaMin_;
private javax.swing.JButton straightenTrackButton_;
private javax.swing.JButton unjitterButton_;
private javax.swing.JComboBox visualizationMagnification_;
private javax.swing.JComboBox visualizationModel_;
private javax.swing.JButton zCalibrateButton_;
private javax.swing.JLabel zCalibrationLabel_;
// End of variables declaration//GEN-END:variables
/**
* Renders button with appropriate names
*/
class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
setForeground(table.getForeground());
setBackground(UIManager.getColor("Button.background"));
if (rowData_.get(row).isTrack_) {
if (column == 4)
setText((value == null ? "" : "Center"));
else {
if (column == 5)
setText((value == null ? "" : "Straighten"));
else
setText((value == null ? "" : value.toString()));
}
} else {
return null;
//if (column == 4)
// setText((value == null ? "" : "Render"));
//if (column == 5)
// return null;
}
return this;
}
}
/**
* Shows dataset in ImageJ Results Table
*
* @rowData
*/
private void showResults(MyRowData rowData) {
// Copy data to results table
ResultsTable rt = new ResultsTable();
rt.reset();
rt.setPrecision(1);
int shape = rowData.shape_;
for (GaussianSpotData gd : rowData.spotList_) {
if (gd != null) {
rt.incrementCounter();
rt.addValue(Terms.FRAME, gd.getFrame());
rt.addValue(Terms.SLICE, gd.getSlice());
rt.addValue(Terms.CHANNEL, gd.getChannel());
rt.addValue(Terms.POSITION, gd.getPosition());
rt.addValue(Terms.INT, gd.getIntensity());
rt.addValue(Terms.BACKGROUND, gd.getBackground());
if (rowData.coordinate_ == Coordinates.NM) {
rt.addValue(Terms.XNM, gd.getXCenter());
rt.addValue(Terms.YNM, gd.getYCenter());
if (rowData.hasZ_)
rt.addValue(Terms.ZNM, gd.getZCenter());
} else if (rowData.coordinate_ == Coordinates.PIXELS) {
rt.addValue(Terms.XFITPIX, gd.getXCenter());
rt.addValue(Terms.YFITPIX, gd.getYCenter());
}
rt.addValue(Terms.SIGMA, gd.getSigma());
if (shape >= 1) {
rt.addValue(Terms.WIDTH, gd.getWidth());
}
if (shape >= 2) {
rt.addValue(Terms.A, gd.getA());
}
if (shape == 3) {
rt.addValue(Terms.THETA, gd.getTheta());
}
rt.addValue(Terms.XPIX, gd.getX());
rt.addValue(Terms.YPIX, gd.getY());
}
}
TextPanel tp;
TextWindow win;
String name = "Spots from: " + rowData.name_;
rt.show(name);
ImagePlus siPlus = ij.WindowManager.getImage(rowData.title_);
// Attach listener to TextPanel
Frame frame = WindowManager.getFrame(name);
if (frame != null && frame instanceof TextWindow && siPlus != null) {
win = (TextWindow) frame;
tp = win.getTextPanel();
// TODO: the following does not work, there is some voodoo going on here
for (MouseListener ms : tp.getMouseListeners()) {
tp.removeMouseListener(ms);
}
for (KeyListener ks : tp.getKeyListeners()) {
tp.removeKeyListener(ks);
}
ResultsTableListener myk = new ResultsTableListener(siPlus, rt, win, rowData.halfSize_);
tp.addKeyListener(myk);
tp.addMouseListener(myk);
frame.toFront();
}
}
/**
* Save data set in TSF (Tagged Spot File) format
*
* @rowData - row with spot data to be saved
*/
private void saveData(final MyRowData rowData) {
FileDialog fd = new FileDialog(this, "Save Spot Data", FileDialog.SAVE);
fd.setFile(rowData.name_ + ".tsf");
fd.setVisible(true);
String selectedItem = fd.getFile();
if (selectedItem == null) {
return;
} else {
String fn = fd.getFile();
if (!fn.contains(".")) {
fn = fn + extension_;
}
final File selectedFile = new File(fd.getDirectory() + File.separator + fn);
if (selectedFile.exists()) {
// this may be superfluous
YesNoCancelDialog y = new YesNoCancelDialog(this, "File " + fn + "Exists...", "File exists. Overwrite?");
if (y.cancelPressed()) {
return;
}
if (!y.yesPressed()) {
saveData(rowData);
return;
}
}
Runnable doWorkRunnable = new Runnable() {
@Override
public void run() {
SpotList.Builder tspBuilder = SpotList.newBuilder();
tspBuilder.setApplicationId(1).
setName(rowData.name_).
setFilepath(rowData.title_).
setNrPixelsX(rowData.width_).
setNrPixelsY(rowData.height_).
setNrSpots(rowData.spotList_.size()).
setPixelSize(rowData.pixelSizeNm_).
setBoxSize(rowData.halfSize_ * 2).
setNrChannels(rowData.nrChannels_).
setNrSlices(rowData.nrSlices_).
setIsTrack(rowData.isTrack_).
setNrPos(rowData.nrPositions_).
setNrFrames(rowData.nrFrames_).
setLocationUnits(LocationUnits.NM).
setIntensityUnits(IntensityUnits.PHOTONS).
setNrSpots(rowData.maxNrSpots_);
switch (rowData.shape_) {
case (1):
tspBuilder.setFitMode(FitMode.ONEAXIS);
break;
case (2):
tspBuilder.setFitMode(FitMode.TWOAXIS);
break;
case (3):
tspBuilder.setFitMode(FitMode.TWOAXISANDTHETA);
break;
}
SpotList spotList = tspBuilder.build();
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
FileOutputStream fo = new FileOutputStream(selectedFile);
// write space for magic nr and offset to spotList
for (int i = 0; i < 12; i++) {
fo.write(0);
}
int counter = 0;
for (GaussianSpotData gd : rowData.spotList_) {
if ((counter % 1000) == 0) {
ij.IJ.showStatus("Saving spotData...");
ij.IJ.showProgress(counter, rowData.spotList_.size());
}
if (gd != null) {
Spot.Builder spotBuilder = Spot.newBuilder();
// TODO: precede all these calls with check for presence of member
// or be OK with default values?
spotBuilder.setMolecule(counter).
setFrame(gd.getFrame()).
setChannel(gd.getChannel()).
setPos(gd.getPosition()).
setSlice(gd.getSlice()).
setX((float) gd.getXCenter()).
setY((float) gd.getYCenter()).
setIntensity((float) gd.getIntensity()).
setBackground((float) gd.getBackground()).
setXPosition(gd.getX()).
setYPosition(gd.getY()).
setWidth((float) gd.getWidth()).
setA((float) gd.getA()).
setTheta((float) gd.getTheta()).
setXPrecision((float) gd.getSigma());
if (rowData.hasZ_) {
spotBuilder.setZ((float) gd.getZCenter());
}
double width = gd.getWidth();
double xPrec = gd.getSigma();
Spot spot = spotBuilder.build();
// write message size and message
spot.writeDelimitedTo(fo);
counter++;
}
}
FileChannel fc = fo.getChannel();
long offset = fc.position();
spotList.writeDelimitedTo(fo);
// now go back to write offset to the stream
fc.position(4);
DataOutputStream dos = new DataOutputStream(fo);
dos.writeLong(offset - 12);
fo.close();
ij.IJ.showProgress(1);
ij.IJ.showStatus("Finished saving spotData...");
} catch (IOException ex) {
Logger.getLogger(DataCollectionForm.class.getName()).log(Level.SEVERE, null, ex);
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
};
(new Thread(doWorkRunnable)).start();
}
}
/**
* Save data set in as a text file
*
* @rowData - row with spot data to be saved
*/
private void saveDataAsText(final MyRowData rowData) {
FileDialog fd = new FileDialog(this, "Save Spot Data", FileDialog.SAVE);
fd.setFile(rowData.name_ + ".txt");
FilenameFilter fnf = new FilenameFilter() {
@Override
public boolean accept(File file, String string) {
if (string.endsWith(".txt"))
return true;
return false;
}
};
fd.setFilenameFilter(fnf);
fd.setVisible(true);
String selectedItem = fd.getFile();
if (selectedItem == null) {
return;
} else {
String fn = fd.getFile();
if (!fn.contains(".")) {
fn = fn + ".txt";
}
final File selectedFile = new File(fd.getDirectory() + File.separator + fn);
if (selectedFile.exists()) {
// this may be superfluous
YesNoCancelDialog y = new YesNoCancelDialog(this, "File " + fn + "Exists...", "File exists. Overwrite?");
if (y.cancelPressed()) {
return;
}
if (!y.yesPressed()) {
saveDataAsText(rowData);
return;
}
}
Runnable doWorkRunnable = new Runnable() {
@Override
public void run() {
try {
String tab = "\t";
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
FileWriter fw = new FileWriter(selectedFile);
fw.write( "" +
"application_id: " + 1 + tab +
"name: " + rowData.name_ + tab +
"filepath: " + rowData.title_ + tab +
"nr_pixels_x: " + rowData.width_ + tab +
"nr_pixels_y: " + rowData.height_ + tab +
"pixel_size: " + rowData.pixelSizeNm_ + tab +
"nr_spots: " + rowData.maxNrSpots_ + tab +
"box_size: " + rowData.halfSize_ * 2 + tab +
"nr_channels: " + rowData.nrChannels_ + tab +
"nr_frames: " + rowData.nrFrames_ + tab +
"nr_slices: " + rowData.nrSlices_ + tab +
"nr_pos: " + rowData.nrPositions_ + tab +
"location_units: " + LocationUnits.NM + tab +
"intensity_units: " + IntensityUnits.PHOTONS + tab +
"fit_mode: " + rowData.shape_ + tab +
"is_track: " + rowData.isTrack_ + tab +
"has_Z: " + rowData.hasZ_ + "\n") ;
fw.write("molecule\tchannel\tframe\tslice\tpos\tx\ty\tintensity\t" +
"background\twidth\ta\ttheta\tx_position\ty_position\t" +
"x_precision");
if (rowData.hasZ_) {
fw.write("\tz");
}
fw.write("\n");
int counter = 0;
for (GaussianSpotData gd : rowData.spotList_) {
if ((counter % 1000) == 0) {
ij.IJ.showStatus("Saving spotData...");
ij.IJ.showProgress(counter, rowData.spotList_.size());
}
if (gd != null) {
fw.write("" + gd.getFrame() + tab +
gd.getChannel() + tab +
gd.getFrame() + tab +
gd.getSlice() + tab +
gd.getPosition() + tab +
String.format("%.2f", gd.getXCenter()) + tab +
String.format("%.2f", gd.getYCenter()) + tab +
String.format("%.2f", gd.getIntensity()) + tab +
String.format("%.2f", gd.getBackground()) + tab +
String.format("%.2f",gd.getWidth()) + tab +
String.format("%.3f", gd.getA()) + tab +
String.format("%.3f",gd.getTheta()) + tab +
gd.getX() + tab +
gd.getY() + tab +
String.format("%.3f", gd.getSigma()) );
if (rowData.hasZ_) {
fw.write(tab + String.format("%.2f", gd.getZCenter()));
}
fw.write("\n");
counter++;
}
}
fw.close();
ij.IJ.showProgress(1);
ij.IJ.showStatus("Finished saving spotData to text file...");
} catch (IOException ex) {
JOptionPane.showMessageDialog(getInstance(), "Error while saving data in text format");
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
};
(new Thread(doWorkRunnable)).start();
}
}
/**
* Calculates the axis of motion of a given dataset and normalizes the data
* to that axis.
*
* @rowData
*/
private void straightenTrack(MyRowData rowData) {
if (rowData.spotList_.size() <= 1) {
return;
}
ArrayList<Point2D.Double> xyPoints = new ArrayList<Point2D.Double>();
Iterator it = rowData.spotList_.iterator();
while (it.hasNext()) {
GaussianSpotData gs = (GaussianSpotData) it.next();
Point2D.Double point = new Point2D.Double(gs.getXCenter(), gs.getYCenter());
xyPoints.add(point);
}
// Calculate direction of travel and transform data set along this axis
ArrayList<Point2D.Double> xyCorrPoints = GaussianUtils.pcaRotate(xyPoints);
List<GaussianSpotData> transformedResultList =
Collections.synchronizedList(new ArrayList<GaussianSpotData>());
for (int i = 0; i < xyPoints.size(); i++) {
GaussianSpotData oriSpot = rowData.spotList_.get(i);
GaussianSpotData spot = new GaussianSpotData(oriSpot);
spot.setData(oriSpot.getIntensity(), oriSpot.getBackground(),
xyCorrPoints.get(i).getX(), xyCorrPoints.get(i).getY(), 0.0, oriSpot.getWidth(),
oriSpot.getA(), oriSpot.getTheta(), oriSpot.getSigma());
transformedResultList.add(spot);
}
// Add transformed data to data overview window
addSpotData(rowData.name_ + "Straightened", rowData.title_, "", rowData.width_,
rowData.height_, rowData.pixelSizeNm_, rowData.zStackStepSizeNm_,
rowData.shape_, rowData.halfSize_, rowData.nrChannels_, rowData.nrFrames_,
rowData.nrSlices_, 1, rowData.maxNrSpots_, transformedResultList,
rowData.timePoints_, true, Coordinates.NM, false, 0.0, 0.0);
}
/**
* Creates a new dataset that is centered around the average of the X and Y data.
* In other words, the average of both X and Y is calculated and subtracted from each datapoint
*
* @rowData
*/
private void centerTrack(MyRowData rowData) {
if (rowData.spotList_.size() <= 1) {
return;
}
ArrayList<Point2D.Double> xyPoints = spotListToPointList(rowData.spotList_);
Point2D.Double avgPoint = avgXYList(xyPoints);
/*ArrayList<Point2D.Double> xyPoints = new ArrayList<Point2D.Double>();
Iterator it = rowData.spotList_.iterator();
double totalX = 0.0;
double totalY = 0.0;
while (it.hasNext()) {
GaussianSpotData gs = (GaussianSpotData) it.next();
Point2D.Double point = new Point2D.Double(gs.getXCenter(), gs.getYCenter());
totalX += gs.getXCenter();
totalY += gs.getYCenter();
xyPoints.add(point);
}
double avgX = totalX / rowData.spotList_.size();
double avgY = totalY / rowData.spotList_.size();
*
*/
for (Point2D.Double xy : xyPoints) {
xy.x = xy.x - avgPoint.x;
xy.y = xy.y - avgPoint.y;
}
// create a copy of the dataset and copy in the corrected data
List<GaussianSpotData> transformedResultList =
Collections.synchronizedList(new ArrayList<GaussianSpotData>());
for (int i = 0; i < xyPoints.size(); i++) {
GaussianSpotData oriSpot = rowData.spotList_.get(i);
GaussianSpotData spot = new GaussianSpotData(oriSpot);
spot.setData(oriSpot.getIntensity(), oriSpot.getBackground(),
xyPoints.get(i).getX(), xyPoints.get(i).getY(), 0.0, oriSpot.getWidth(),
oriSpot.getA(), oriSpot.getTheta(), oriSpot.getSigma());
transformedResultList.add(spot);
}
// Add transformed data to data overview window
addSpotData(rowData.name_ + " Centered", rowData.title_, "", rowData.width_,
rowData.height_, rowData.pixelSizeNm_, rowData.zStackStepSizeNm_,
rowData.shape_, rowData.halfSize_, rowData.nrChannels_,
rowData.nrFrames_, rowData.nrSlices_, 1, rowData.maxNrSpots_,
transformedResultList, rowData.timePoints_, true, Coordinates.NM,
false, 0.0, 0.0);
}
/**
* Creates a new data set that is corrected for motion blur
* Correction is performed by projecting a number of images onto a
* 2D scattergram and using cross-correlation between them to find
* the displacement
*
* @param rowData
*/
private void unJitter(final MyRowData rowData) {
// TODO: instead of a fixed number of frames, go for a certain number of spots
// Number of frames could be limited as well
final int framesToCombine = 200;
if (rowData.spotList_.size() <= 1) {
return;
}
ij.IJ.showStatus("Executing jitter correction");
Runnable doWorkRunnable = new Runnable() {
public void run() {
int mag = (int) (rowData.pixelSizeNm_ / 40.0);
while (mag % 2 != 0)
mag += 1;
int width = mag * rowData.width_;
int height = mag * rowData.height_;
int size = width * height;
// TODO: add 0 padding to deal with aberrant image sizes
if ( (width != height) || ( (width & (width - 1)) != 0) ) {
JOptionPane.showMessageDialog(getInstance(),
"Magnified image is not a square with a size that is a power of 2");
ij.IJ.showStatus(" ");
return;
}
// TODO: what if we should go through nrSlices instead of nrFrames?
boolean useSlices = false;
int nrOfTests = rowData.nrFrames_ / framesToCombine;
if (nrOfTests == 0) {
useSlices = true;
nrOfTests = rowData.nrSlices_ / framesToCombine;
if (rowData.nrSlices_ % framesToCombine > 0) {
nrOfTests++;
}
} else {
if (rowData.nrFrames_ % framesToCombine > 0) {
nrOfTests++;
}
}
// storage of stage movement data
class StageMovementData {
Point2D.Double pos_;
Point frameRange_;
StageMovementData(Point2D.Double pos, Point frameRange) {
pos_ = pos;
frameRange_ = frameRange;
}
}
ArrayList<StageMovementData> stagePos = new ArrayList<StageMovementData>();
try {
// make imageprocessors for all the images that we will generate
ImageProcessor[] ip = new ImageProcessor[nrOfTests];
byte[][] pixels = new byte[nrOfTests][width * height];
for (int i = 0; i < nrOfTests; i++) {
ip[i] = new ByteProcessor(width, height);
ip[i].setPixels(pixels[i]);
}
double factor = (double) mag / rowData.pixelSizeNm_;
// make 2D scattergrams of all pixelData
for (GaussianSpotData spot : rowData.spotList_) {
int j = 0;
if (useSlices) {
j = (spot.getSlice() - 1) / framesToCombine;
} else {
j = (spot.getFrame() - 1) / framesToCombine;
}
int x = (int) (factor * spot.getXCenter());
int y = (int) (factor * spot.getYCenter());
int index = (y * width) + x;
if (index < size && index > 0) {
if (pixels[j][index] != -1) {
pixels[j][index] += 1;
}
}
}
JitterDetector jd = new JitterDetector(ip[0]);
Point2D.Double fp = new Point2D.Double(0.0, 0.0);
Point2D.Double com = new Point2D.Double(0.0, 0.0);
jd.getJitter(ip[0], fp);
for (int i = 1; i < ip.length; i++) {
ij.IJ.showStatus("Executing jitter correction..." + i);
ij.IJ.showProgress(i, ip.length);
int spotCount = 0;
for (int j=0; j < ip[i].getPixelCount(); j++)
spotCount += ip[i].get(j);
jd.getJitter(ip[i], com);
double x = (fp.x - com.x) / factor;
double y = (fp.y - com.y) / factor;
if (rowData.timePoints_ != null) {
rowData.timePoints_.get(i);
}
stagePos.add(new StageMovementData(new Point2D.Double(x, y),
new Point(i * framesToCombine, ((i + 1) * framesToCombine - 1))));
System.out.println("i: " + i + " nSpots: " + spotCount + " X: " + x + " Y: " + y);
}
} catch (OutOfMemoryError ex) {
// not enough memory to allocate all images in one go
// we need to cycle through all gaussian spots cycle by cycle
double factor = (double) mag / rowData.pixelSizeNm_;
ImageProcessor ipRef = new ByteProcessor(width, height);
byte[] pixelsRef = new byte[width * height];
ipRef.setPixels(pixelsRef);
// take the first image as reference
for (GaussianSpotData spot : rowData.spotList_) {
int j = 0;
if (useSlices) {
j = (spot.getSlice() - 1) / framesToCombine;
} else {
j = (spot.getFrame() - 1) / framesToCombine;
}
if (j == 0) {
int x = (int) (factor * spot.getXCenter());
int y = (int) (factor * spot.getYCenter());
int index = (y * width) + x;
if (index < size && index > 0) {
if (pixelsRef[index] != -1) {
pixelsRef[index] += 1;
}
}
}
}
JitterDetector jd = new JitterDetector(ipRef);
Point2D.Double fp = new Point2D.Double(0.0, 0.0);
jd.getJitter(ipRef, fp);
Point2D.Double com = new Point2D.Double(0.0, 0.0);
ImageProcessor ipTest = new ByteProcessor(width, height);
byte[] pixelsTest = new byte[width * height];
ipTest.setPixels(pixelsTest);
for (int i = 1; i < nrOfTests; i++) {
ij.IJ.showStatus("Executing jitter correction..." + i);
ij.IJ.showProgress(i, nrOfTests);
for (int p = 0; p < size; p++) {
ipTest.set(p, 0);
}
for (GaussianSpotData spot : rowData.spotList_) {
int j = 0;
if (useSlices) {
j = (spot.getSlice() - 1) / framesToCombine;
} else {
j = (spot.getFrame() - 1) / framesToCombine;
}
if (j == i) {
int x = (int) (factor * spot.getXCenter());
int y = (int) (factor * spot.getYCenter());
int index = (y * width) + x;
if (index < size && index > 0) {
if (pixelsTest[index] != -1) {
pixelsTest[index] += 1;
}
}
}
}
jd.getJitter(ipTest, com);
double x = (fp.x - com.x) / factor;
double y = (fp.y - com.y) / factor;
double timePoint = i;
if (rowData.timePoints_ != null) {
rowData.timePoints_.get(i);
}
stagePos.add(new StageMovementData(new Point2D.Double(x, y),
new Point(i * framesToCombine, ((i + 1) * framesToCombine - 1))));
System.out.println("X: " + x + " Y: " + y);
}
}
try {
// Assemble stage movement data into a track
List<GaussianSpotData> stageMovementData = new ArrayList<GaussianSpotData>();
GaussianSpotData sm = new GaussianSpotData(null, 1, 1, 1, 1, 1, 1, 1);
sm.setData(0, 0, 0, 0, 0.0, 0, 0, 0, 0);
stageMovementData.add(sm);
// calculate moving average for stageposition
ArrayList<StageMovementData> stagePosMA = new ArrayList<StageMovementData>();
int windowSize = 5;
for (int i = 0; i < stagePos.size() - windowSize; i++) {
Point2D.Double avg = new Point2D.Double(0.0, 0.0);
for (int j = 0; j < windowSize; j++) {
avg.x += stagePos.get(i + j).pos_.x;
avg.y += stagePos.get(i + j).pos_.y;
}
avg.x /= windowSize;
avg.y /= windowSize;
stagePosMA.add(new StageMovementData(avg, stagePos.get(i).frameRange_));
}
for (int i = 0; i < stagePosMA.size(); i++) {
StageMovementData smd = stagePosMA.get(i);
GaussianSpotData s =
new GaussianSpotData(null, 1, 1, i + 2, 1, 1, 1, 1);
s.setData(0, 0, smd.pos_.x, smd.pos_.y, 0.0, 0, 0, 0, 0);
stageMovementData.add(s);
}
// Add stage movement data to overview window
// First try to copy the time points
ArrayList<Double> timePoints = null;
if (rowData.timePoints_ != null) {
timePoints = new ArrayList<Double>();
int tp = framesToCombine;
while (tp < rowData.timePoints_.size()) {
timePoints.add(rowData.timePoints_.get(tp));
tp += framesToCombine;
}
}
MyRowData newRow = new MyRowData(rowData.name_ + "-Jitter",
rowData.title_, "", rowData.width_,rowData.height_,
rowData.pixelSizeNm_, rowData.zStackStepSizeNm_,
rowData.shape_, rowData.halfSize_, rowData.nrChannels_,
stageMovementData.size(),1, 1, stageMovementData.size(),
stageMovementData, timePoints, true, Coordinates.NM,
false, 0.0, 0.0);
rowData_.add(newRow);
myTableModel_.fireTableRowsInserted(rowData_.size() - 1, rowData_.size());
ij.IJ.showStatus("Assembling jitter corrected dataset...");
ij.IJ.showProgress(1);
List<GaussianSpotData> correctedData = new ArrayList<GaussianSpotData>();
Iterator it = rowData.spotList_.iterator();
int testNr = 0;
StageMovementData smd = stagePosMA.get(0);
int counter = 0;
while (it.hasNext()) {
counter++;
GaussianSpotData gs = (GaussianSpotData) it.next();
int test = 0;
if (useSlices) {
test = gs.getSlice();
} else {
test = gs.getFrame();
}
if (test != testNr) {
testNr = test - 1;
}
boolean found = false;
if (testNr >= smd.frameRange_.x && testNr <= smd.frameRange_.y) {
found = true;
}
if (!found) {
for (int i = 0; i < stagePosMA.size() && !found; i++) {
smd = stagePosMA.get(i);
if (testNr >= smd.frameRange_.x && testNr <= smd.frameRange_.y) {
found = true;
}
}
}
if (found) {
Point2D.Double point = new Point2D.Double(gs.getXCenter() - smd.pos_.x,
gs.getYCenter() - smd.pos_.y);
GaussianSpotData gsn = new GaussianSpotData(gs);
gsn.setXCenter(point.x);
gsn.setYCenter(point.y);
correctedData.add(gsn);
} else {
correctedData.add(gs);
}
}
// Add transformed data to data overview window
addSpotData(rowData.name_ + "-Jitter-Correct", rowData.title_, "",
rowData.width_, rowData.height_, rowData.pixelSizeNm_,
rowData.zStackStepSizeNm_, rowData.shape_,
rowData.halfSize_, rowData.nrChannels_, rowData.nrFrames_,
rowData.nrSlices_, 1, rowData.maxNrSpots_, correctedData,
null, false, Coordinates.NM, false, 0.0, 0.0);
ij.IJ.showStatus("Finished jitter correction");
} catch (OutOfMemoryError oom) {
System.gc();
ij.IJ.error("Out of Memory");
}
}
};
(new Thread(doWorkRunnable)).start();
}
// Used to avoid multiple instances of correct2C at the same time
private final Semaphore semaphore_ = new Semaphore(1, true);
/**
* Use the 2Channel calibration to create a new, corrected data set
*
* @param rowData
*/
private void correct2C(final MyRowData rowData) throws InterruptedException
{
if (rowData.spotList_.size() <= 1) {
JOptionPane.showMessageDialog(getInstance(), "Please select a dataset to Color correct");
return;
}
if (c2t_ == null) {
JOptionPane.showMessageDialog(getInstance(), "No calibration data available. First Calibrate using 2C Reference");
return;
}
semaphore_.acquire();
int method = CoordinateMapper.LWM;
if (method2CBox_.getSelectedItem().equals("Affine"))
method = CoordinateMapper.AFFINE;
if (method2CBox_.getSelectedItem().equals("NR-Similarity"))
method = CoordinateMapper.NONRFEFLECTIVESIMILARITY;
c2t_.setMethod(method);
ij.IJ.showStatus("Executing color correction");
Runnable doWorkRunnable = new Runnable() {
@Override
public void run() {
List<GaussianSpotData> correctedData =
Collections.synchronizedList(new ArrayList<GaussianSpotData>());
Iterator it = rowData.spotList_.iterator();
int frameNr = 0;
while (it.hasNext()) {
GaussianSpotData gs = (GaussianSpotData) it.next();
if (gs.getFrame() != frameNr) {
frameNr = gs.getFrame();
ij.IJ.showStatus("Executing color correction...");
ij.IJ.showProgress(frameNr, rowData.nrFrames_);
}
if (gs.getChannel() == 1) {
Point2D.Double point = new Point2D.Double(gs.getXCenter(), gs.getYCenter());
try {
Point2D.Double corPoint = c2t_.transform(point);
GaussianSpotData gsn = new GaussianSpotData(gs);
gsn.setXCenter(corPoint.x);
gsn.setYCenter(corPoint.y);
correctedData.add(gsn);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
} else if (gs.getChannel() == 2) {
correctedData.add(gs);
}
}
// Add transformed data to data overview window
addSpotData(rowData.name_ + "-CC-" +referenceName_.getText() + "-" +
method2CBox_.getSelectedItem(),
rowData.title_,
referenceName_.getText(), rowData.width_,
rowData.height_, rowData.pixelSizeNm_,
rowData.zStackStepSizeNm_, rowData.shape_,
rowData.halfSize_, rowData.nrChannels_, rowData.nrFrames_,
rowData.nrSlices_, 1, rowData.maxNrSpots_, correctedData,
rowData.timePoints_,
false, Coordinates.NM, false, 0.0, 0.0);
semaphore_.release();
}
};
(new Thread(doWorkRunnable)).start();
}
/**
* Plots Tracks using JFreeChart
*
* @rowData
* @plotMode - Index of plotMode in array {"t-X", "t-Y", "X-Y", "t-Int"};
*/
private void plotData(MyRowData[] rowDatas, int plotMode) {
String title = plotModes_[plotMode];
boolean logLog = logLogCheckBox_.isSelected();
boolean doPSD = powerSpectrumCheckBox_.isSelected();
boolean useShapes = true;
if (logLog || doPSD)
useShapes = false;
if (rowDatas.length == 1) {
title = rowDatas[0].name_ + " " + plotModes_[plotMode];
}
XYSeries[] datas = new XYSeries[rowDatas.length];
boolean useS;
String xAxis = null;
switch (plotMode) {
case (0): {
if (doPSD) {
FFTUtils.calculatePSDs(rowDatas, datas, PlotMode.X);
xAxis = "Freq (Hz)";
GaussianUtils.plotDataN(title + " PSD", datas, xAxis, "Strength",
0, 400, useShapes, logLog);
} else {
for (int index = 0; index < rowDatas.length; index++) {
datas[index] = new XYSeries(rowDatas[index].ID_);
for (int i = 0; i < rowDatas[index].spotList_.size(); i++) {
GaussianSpotData spot = rowDatas[index].spotList_.get(i);
if (rowDatas[index].timePoints_ != null) {
double timePoint = rowDatas[index].timePoints_.get(i);
datas[index].add(timePoint, spot.getXCenter());
} else {
datas[index].add(i, spot.getXCenter());
}
}
xAxis = "Time (frameNr)";
if (rowDatas[index].timePoints_ != null) {
xAxis = "Time (ms)";
}
}
GaussianUtils.plotDataN(title, datas, xAxis, "X(nm)", 0, 400, useShapes, logLog);
}
}
break;
case (1): {
if (doPSD) {
FFTUtils.calculatePSDs(rowDatas, datas, PlotMode.Y);
xAxis = "Freq (Hz)";
GaussianUtils.plotDataN(title + " PSD", datas, xAxis, "Strength",
0, 400, useShapes, logLog);
} else {
for (int index = 0; index < rowDatas.length; index++) {
datas[index] = new XYSeries(rowDatas[index].ID_);
for (int i = 0; i < rowDatas[index].spotList_.size(); i++) {
GaussianSpotData spot = rowDatas[index].spotList_.get(i);
if (rowDatas[index].timePoints_ != null) {
double timePoint = rowDatas[index].timePoints_.get(i);
datas[index].add(timePoint, spot.getYCenter());
} else {
datas[index].add(i, spot.getYCenter());
}
}
xAxis = "Time (frameNr)";
if (rowDatas[index].timePoints_ != null) {
xAxis = "Time (s)";
}
}
GaussianUtils.plotDataN(title, datas, xAxis, "Y(nm)", 0, 400, useShapes, logLog);
}
}
break;
case (2): {
if (doPSD) {
JOptionPane.showMessageDialog(this, "Function is not implemented");
} else {
for (int index = 0; index < rowDatas.length; index++) {
datas[index] = new XYSeries(rowDatas[index].ID_, false, true);
for (int i = 0; i < rowDatas[index].spotList_.size(); i++) {
GaussianSpotData spot = rowDatas[index].spotList_.get(i);
datas[index].add(spot.getXCenter(), spot.getYCenter());
}
}
GaussianUtils.plotDataN(title, datas, "X(nm)", "Y(nm)", 0, 400, useShapes, logLog);
}
}
break;
case (3): {
if (doPSD) {
FFTUtils.calculatePSDs(rowDatas, datas, PlotMode.INT);
xAxis = "Freq (Hz)";
GaussianUtils.plotDataN(title + " PSD", datas, xAxis, "Strength",
0, 400, useShapes, logLog);
} else {
for (int index = 0; index < rowDatas.length; index++) {
datas[index] = new XYSeries(rowDatas[index].ID_);
useS = useSeconds(rowDatas[index]);
for (int i = 0; i < rowDatas[index].spotList_.size(); i++) {
GaussianSpotData spot = rowDatas[index].spotList_.get(i);
if (rowDatas[index].timePoints_ != null) {
double timePoint = rowDatas[index].timePoints_.get(i);
if (useS) {
timePoint /= 1000;
}
datas[index].add(timePoint, spot.getIntensity());
} else {
datas[index].add(i, spot.getIntensity());
}
}
xAxis = "Time (frameNr)";
if (rowDatas[index].timePoints_ != null) {
xAxis = "Time (ms)";
if (useS) {
xAxis = "Time (s)";
}
}
}
GaussianUtils.plotDataN(title, datas, xAxis, "Intensity (#photons)",
0, 400, useShapes, logLog);
}
}
break;
}
}
private boolean useSeconds(MyRowData row) {
boolean useS = false;
if (row.timePoints_ != null) {
if (row.timePoints_.get(row.timePoints_.size() - 1)
- row.timePoints_.get(0) > 10000) {
useS = true;
}
}
return useS;
}
/**
* Performs Z-calibration
*
*
* @param rowNr
* @return 0 indicates success, 1 indicates failure and calling code should inform user, 2 indicates failure but calling code should not inform user
*/
public int zCalibrate(int rowNr) {
final double widthCutoff = 1000.0;
final double maxVariance = 100000.0;
final int minNrSpots = 1;
zc_.clearDataPoints();
MyRowData rd = rowData_.get(rowNr);
if (rd.shape_ < 2) {
JOptionPane.showMessageDialog(getInstance(), "Use Fit Parameters Dimension 2 or 3 for Z-calibration");
return FAILEDDONOTINFORM;
}
List<GaussianSpotData> sl = rd.spotList_;
for (GaussianSpotData gsd : sl) {
double xw = gsd.getWidth();
double xy = xw / gsd.getA();
if (xw < widthCutoff && xy < widthCutoff && xw > 0 && xy > 0) {
zc_.addDataPoint(gsd.getWidth(), gsd.getWidth() / gsd.getA(),
gsd.getSlice() /* * rd.zStackStepSizeNm_*/);
}
}
zc_.plotDataPoints();
zc_.clearDataPoints();
// calculate average and stdev per frame
if (rd.frameIndexSpotList_ == null) {
rd.index();
}
final int nrImages = rd.nrSlices_;
int frameNr = 0;
while (frameNr < nrImages) {
List<GaussianSpotData> frameSpots = rd.frameIndexSpotList_.get(frameNr);
if (frameSpots != null) {
double[] xws = new double[frameSpots.size()];
double[] yws = new double[frameSpots.size()];
int i = 0;
for (GaussianSpotData gsd : frameSpots) {
xws[i] = gsd.getWidth();
yws[i] = (gsd.getWidth() / gsd.getA());
i++;
}
double meanX = StatUtils.mean(xws);
double meanY = StatUtils.mean(yws);
double varX = StatUtils.variance(xws, meanX);
double varY = StatUtils.variance(yws, meanY);
//System.out.println("Frame: " + frameNr + ", X: " + (int) meanX + ", " + (int) varX +
// ", Y: " + (int) meanY + ", " + (int) varY);
if (frameSpots.size() >= minNrSpots &&
meanX < widthCutoff &&
meanY < widthCutoff &&
varX < maxVariance &&
varY < maxVariance &&
meanX > 0 &&
meanY > 0) {
zc_.addDataPoint(meanX, meanY, frameNr /* * rd.zStackStepSizeNm_ */);
}
}
frameNr++;
}
if (zc_.nrDataPoints() < 6) {
ReportingUtils.showError("Not enough particles found for 3D calibration");
return FAILEDDONOTINFORM;
}
zc_.plotDataPoints();
try {
zc_.fitFunction();
} catch (Exception ex) {
ReportingUtils.showError("Error while fitting data");
return FAILEDDONOTINFORM;
}
return OK;
}
}
|
package org.nohope.rpc;
import org.nohope.rpc.protocol.RPC;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelUpstreamHandler;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder;
import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder;
public class PipelineFactory implements ChannelPipelineFactory {
private static final int MAX_FRAME_BYTES_LENGTH = Integer.MAX_VALUE;
private static final int HEADER_BYTES = 4;
private final ChannelUpstreamHandler handler;
public PipelineFactory(final ChannelUpstreamHandler handler) {
this.handler = handler;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
final ChannelPipeline p = Channels.pipeline();
p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_BYTES_LENGTH, 0, HEADER_BYTES, 0, HEADER_BYTES));
p.addLast("protobufDecoder", new ProtobufDecoder(RPC.RpcRequest.getDefaultInstance()));
p.addLast("frameEncoder", new LengthFieldPrepender(HEADER_BYTES));
p.addLast("protobufEncoder", new ProtobufEncoder());
p.addLast("handler", handler);
return p;
}
}
|
package org.jfree.chart.annotations;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.jfree.chart.HashUtilities;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.io.SerialUtilities;
import org.jfree.text.TextUtilities;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.TextAnchor;
import org.jfree.util.PaintUtilities;
import org.jfree.util.PublicCloneable;
/**
* A text annotation that can be placed at a particular (x, y) location on an
* {@link XYPlot}.
*/
public class XYTextAnnotation extends AbstractXYAnnotation
implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -2946063342782506328L;
/** The default font. */
public static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN,
10);
/** The default paint. */
public static final Paint DEFAULT_PAINT = Color.black;
/** The default text anchor. */
public static final TextAnchor DEFAULT_TEXT_ANCHOR = TextAnchor.CENTER;
/** The default rotation anchor. */
public static final TextAnchor DEFAULT_ROTATION_ANCHOR = TextAnchor.CENTER;
/** The default rotation angle. */
public static final double DEFAULT_ROTATION_ANGLE = 0.0;
/** The text. */
private String text;
/** The font. */
private Font font;
/** The paint. */
private transient Paint paint;
/** The x-coordinate. */
private double x;
/** The y-coordinate. */
private double y;
/** The text anchor (to be aligned with (x, y)). */
private TextAnchor textAnchor;
/** The rotation anchor. */
private TextAnchor rotationAnchor;
/** The rotation angle. */
private double rotationAngle;
/**
* The background paint (possibly null).
*
* @since 1.0.13
*/
private transient Paint backgroundPaint;
/**
* The flag that controls the visibility of the outline.
*
* @since 1.0.13
*/
private boolean outlineVisible;
/**
* The outline paint (never null).
*
* @since 1.0.13
*/
private transient Paint outlinePaint;
/**
* The outline stroke (never null).
*
* @since 1.0.13
*/
private transient Stroke outlineStroke;
/**
* Creates a new annotation to be displayed at the given coordinates. The
* coordinates are specified in data space (they will be converted to
* Java2D space for display).
*
* @param text the text (<code>null</code> not permitted).
* @param x the x-coordinate (in data space).
* @param y the y-coordinate (in data space).
*/
public XYTextAnnotation(String text, double x, double y) {
if (text == null) {
throw new IllegalArgumentException("Null 'text' argument.");
}
this.text = text;
this.font = DEFAULT_FONT;
this.paint = DEFAULT_PAINT;
this.x = x;
this.y = y;
this.textAnchor = DEFAULT_TEXT_ANCHOR;
this.rotationAnchor = DEFAULT_ROTATION_ANCHOR;
this.rotationAngle = DEFAULT_ROTATION_ANGLE;
// by default the outline and background won't be visible
this.backgroundPaint = null;
this.outlineVisible = false;
this.outlinePaint = Color.black;
this.outlineStroke = new BasicStroke(0.5f);
}
/**
* Returns the text for the annotation.
*
* @return The text (never <code>null</code>).
*
* @see #setText(String)
*/
public String getText() {
return this.text;
}
/**
* Sets the text for the annotation.
*
* @param text the text (<code>null</code> not permitted).
*
* @see #getText()
*/
public void setText(String text) {
if (text == null) {
throw new IllegalArgumentException("Null 'text' argument.");
}
this.text = text;
}
/**
* Returns the font for the annotation.
*
* @return The font (never <code>null</code>).
*
* @see #setFont(Font)
*/
public Font getFont() {
return this.font;
}
/**
* Sets the font for the annotation.
*
* @param font the font (<code>null</code> not permitted).
*
* @see #getFont()
*/
public void setFont(Font font) {
if (font == null) {
throw new IllegalArgumentException("Null 'font' argument.");
}
this.font = font;
}
/**
* Returns the paint for the annotation.
*
* @return The paint (never <code>null</code>).
*
* @see #setPaint(Paint)
*/
public Paint getPaint() {
return this.paint;
}
/**
* Sets the paint for the annotation.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getPaint()
*/
public void setPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.paint = paint;
}
/**
* Returns the text anchor.
*
* @return The text anchor (never <code>null</code>).
*
* @see #setTextAnchor(TextAnchor)
*/
public TextAnchor getTextAnchor() {
return this.textAnchor;
}
/**
* Sets the text anchor (the point on the text bounding rectangle that is
* aligned to the (x, y) coordinate of the annotation).
*
* @param anchor the anchor point (<code>null</code> not permitted).
*
* @see #getTextAnchor()
*/
public void setTextAnchor(TextAnchor anchor) {
if (anchor == null) {
throw new IllegalArgumentException("Null 'anchor' argument.");
}
this.textAnchor = anchor;
}
/**
* Returns the rotation anchor.
*
* @return The rotation anchor point (never <code>null</code>).
*
* @see #setRotationAnchor(TextAnchor)
*/
public TextAnchor getRotationAnchor() {
return this.rotationAnchor;
}
/**
* Sets the rotation anchor point.
*
* @param anchor the anchor (<code>null</code> not permitted).
*
* @see #getRotationAnchor()
*/
public void setRotationAnchor(TextAnchor anchor) {
if (anchor == null) {
throw new IllegalArgumentException("Null 'anchor' argument.");
}
this.rotationAnchor = anchor;
}
/**
* Returns the rotation angle.
*
* @return The rotation angle.
*
* @see #setRotationAngle(double)
*/
public double getRotationAngle() {
return this.rotationAngle;
}
/**
* Sets the rotation angle. The angle is measured clockwise in radians.
*
* @param angle the angle (in radians).
*
* @see #getRotationAngle()
*/
public void setRotationAngle(double angle) {
this.rotationAngle = angle;
}
/**
* Returns the x coordinate for the text anchor point (measured against the
* domain axis).
*
* @return The x coordinate (in data space).
*
* @see #setX(double)
*/
public double getX() {
return this.x;
}
/**
* Sets the x coordinate for the text anchor point (measured against the
* domain axis).
*
* @param x the x coordinate (in data space).
*
* @see #getX()
*/
public void setX(double x) {
this.x = x;
}
/**
* Returns the y coordinate for the text anchor point (measured against the
* range axis).
*
* @return The y coordinate (in data space).
*
* @see #setY(double)
*/
public double getY() {
return this.y;
}
/**
* Sets the y coordinate for the text anchor point (measured against the
* range axis).
*
* @param y the y coordinate.
*
* @see #getY()
*/
public void setY(double y) {
this.y = y;
}
/**
* Returns the background paint for the annotation.
*
* @return The background paint (possibly <code>null</code>).
*
* @see #setBackgroundPaint(Paint)
*
* @since 1.0.13
*/
public Paint getBackgroundPaint() {
return this.backgroundPaint;
}
/**
* Sets the background paint for the annotation.
*
* @param paint the paint (<code>null</code> permitted).
*
* @see #getBackgroundPaint()
*
* @since 1.0.13
*/
public void setBackgroundPaint(Paint paint) {
this.backgroundPaint = paint;
}
/**
* Returns the outline paint for the annotation.
*
* @return The outline paint (never <code>null</code>).
*
* @see #setOutlinePaint(Paint)
*
* @since 1.0.13
*/
public Paint getOutlinePaint() {
return this.outlinePaint;
}
/**
* Sets the outline paint for the annotation.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getOutlinePaint()
*
* @since 1.0.13
*/
public void setOutlinePaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.outlinePaint = paint;
}
/**
* Returns the outline stroke for the annotation.
*
* @return The outline stroke (never <code>null</code>).
*
* @see #setOutlineStroke(Stroke)
*
* @since 1.0.13
*/
public Stroke getOutlineStroke() {
return this.outlineStroke;
}
/**
* Sets the outline stroke for the annotation.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getOutlineStroke()
*
* @since 1.0.13
*/
public void setOutlineStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' argument.");
}
this.outlineStroke = stroke;
}
/**
* Returns the flag that controls whether or not the outline is drawn.
*
* @return A boolean.
*
* @since 1.0.13
*/
public boolean isOutlineVisible() {
return this.outlineVisible;
}
/**
* Sets the flag that controls whether or not the outline is drawn.
*
* @param visible the new flag value.
*
* @since 1.0.13
*/
public void setOutlineVisible(boolean visible) {
this.outlineVisible = visible;
}
/**
* Draws the annotation.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param dataArea the data area.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param rendererIndex the renderer index.
* @param info an optional info object that will be populated with
* entity information.
*/
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea,
ValueAxis domainAxis, ValueAxis rangeAxis,
int rendererIndex,
PlotRenderingInfo info) {
PlotOrientation orientation = plot.getOrientation();
RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(
plot.getDomainAxisLocation(), orientation);
RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(
plot.getRangeAxisLocation(), orientation);
float anchorX = (float) domainAxis.valueToJava2D(
this.x, dataArea, domainEdge);
float anchorY = (float) rangeAxis.valueToJava2D(
this.y, dataArea, rangeEdge);
if (orientation == PlotOrientation.HORIZONTAL) {
float tempAnchor = anchorX;
anchorX = anchorY;
anchorY = tempAnchor;
}
Shape hotspot = TextUtilities.calculateRotatedStringBounds(
getText(), g2, anchorX, anchorY, getTextAnchor(),
getRotationAngle(), getRotationAnchor());
if (this.backgroundPaint != null) {
g2.setPaint(this.backgroundPaint);
g2.fill(hotspot);
}
g2.setFont(getFont());
g2.setPaint(getPaint());
TextUtilities.drawRotatedString(getText(), g2, anchorX, anchorY,
getTextAnchor(), getRotationAngle(), getRotationAnchor());
if (this.outlineVisible) {
g2.setStroke(this.outlineStroke);
g2.setPaint(this.outlinePaint);
g2.draw(hotspot);
}
String toolTip = getToolTipText();
String url = getURL();
if (toolTip != null || url != null) {
addEntity(info, hotspot, rendererIndex, toolTip, url);
}
}
/**
* Tests this annotation for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof XYTextAnnotation)) {
return false;
}
XYTextAnnotation that = (XYTextAnnotation) obj;
if (!this.text.equals(that.text)) {
return false;
}
if (this.x != that.x) {
return false;
}
if (this.y != that.y) {
return false;
}
if (!this.font.equals(that.font)) {
return false;
}
if (!PaintUtilities.equal(this.paint, that.paint)) {
return false;
}
if (!this.rotationAnchor.equals(that.rotationAnchor)) {
return false;
}
if (this.rotationAngle != that.rotationAngle) {
return false;
}
if (!this.textAnchor.equals(that.textAnchor)) {
return false;
}
if (this.outlineVisible != that.outlineVisible) {
return false;
}
if (!PaintUtilities.equal(this.backgroundPaint, that.backgroundPaint)) {
return false;
}
if (!PaintUtilities.equal(this.outlinePaint, that.outlinePaint)) {
return false;
}
if (!(this.outlineStroke.equals(that.outlineStroke))) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for the object.
*
* @return A hash code.
*/
public int hashCode() {
int result = 193;
result = 37 * this.text.hashCode();
result = 37 * this.font.hashCode();
result = 37 * result + HashUtilities.hashCodeForPaint(this.paint);
long temp = Double.doubleToLongBits(this.x);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.y);
result = 37 * result + (int) (temp ^ (temp >>> 32));
result = 37 * result + this.textAnchor.hashCode();
result = 37 * result + this.rotationAnchor.hashCode();
temp = Double.doubleToLongBits(this.rotationAngle);
result = 37 * result + (int) (temp ^ (temp >>> 32));
return result;
}
/**
* Returns a clone of the annotation.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the annotation can't be cloned.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.paint, stream);
SerialUtilities.writePaint(this.backgroundPaint, stream);
SerialUtilities.writePaint(this.outlinePaint, stream);
SerialUtilities.writeStroke(this.outlineStroke, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.paint = SerialUtilities.readPaint(stream);
this.backgroundPaint = SerialUtilities.readPaint(stream);
this.outlinePaint = SerialUtilities.readPaint(stream);
this.outlineStroke = SerialUtilities.readStroke(stream);
}
}
|
package org.jfree.chart.urls;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.jfree.chart.util.ParamChecks;
import org.jfree.data.general.PieDataset;
import org.jfree.util.ObjectUtilities;
/**
* A URL generator for pie charts. Instances of this class are immutable.
*/
public class StandardPieURLGenerator implements PieURLGenerator, Serializable {
/** For serialization. */
private static final long serialVersionUID = 1626966402065883419L;
/** The prefix. */
private String prefix = "index.html";
/** The category parameter name. */
private String categoryParamName = "category";
/** The pie index parameter name. */
private String indexParamName = "pieIndex";
/**
* Default constructor.
*/
public StandardPieURLGenerator() {
this("index.html");
}
/**
* Creates a new generator.
*
* @param prefix the prefix ({@code null} not permitted).
*/
public StandardPieURLGenerator(String prefix) {
this(prefix, "category");
}
/**
* Creates a new generator.
*
* @param prefix the prefix ({@code null} not permitted).
* @param categoryParamName the category parameter name ({@code null} not
* permitted).
*/
public StandardPieURLGenerator(String prefix, String categoryParamName) {
this(prefix, categoryParamName, "pieIndex");
}
/**
* Creates a new generator.
*
* @param prefix the prefix ({@code null} not permitted).
* @param categoryParamName the category parameter name ({@code null} not
* permitted).
* @param indexParamName the index parameter name ({@code null} permitted).
*/
public StandardPieURLGenerator(String prefix, String categoryParamName,
String indexParamName) {
ParamChecks.nullNotPermitted(prefix, "prefix");
ParamChecks.nullNotPermitted(categoryParamName, "categoryParamName");
this.prefix = prefix;
this.categoryParamName = categoryParamName;
this.indexParamName = indexParamName;
}
/**
* Generates a URL.
*
* @param dataset the dataset (ignored).
* @param key the item key ({@code null} not permitted).
* @param pieIndex the pie index.
*
* @return A string containing the generated URL.
*/
@Override
public String generateURL(PieDataset dataset, Comparable key,
int pieIndex) {
String url = this.prefix;
try {
if (url.contains("?")) {
url += "&" + this.categoryParamName + "="
+ URLEncoder.encode(key.toString(), "UTF-8");
} else {
url += "?" + this.categoryParamName + "="
+ URLEncoder.encode(key.toString(), "UTF-8");
}
if (this.indexParamName != null) {
url += "&" + this.indexParamName + "=" + pieIndex;
}
} catch (UnsupportedEncodingException e) { // this won't happen :)
throw new RuntimeException(e);
}
return url;
}
/**
* Tests if this object is equal to another.
*
* @param obj the object ({@code null} permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof StandardPieURLGenerator)) {
return false;
}
StandardPieURLGenerator that = (StandardPieURLGenerator) obj;
if (!this.prefix.equals(that.prefix)) {
return false;
}
if (!this.categoryParamName.equals(that.categoryParamName)) {
return false;
}
if (!ObjectUtilities.equal(this.indexParamName, that.indexParamName)) {
return false;
}
return true;
}
}
|
package com.squareup.spoon;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Pattern;
import static android.content.Context.MODE_WORLD_READABLE;
import static android.graphics.Bitmap.CompressFormat.PNG;
import static android.graphics.Bitmap.Config.ARGB_8888;
import static com.squareup.spoon.Chmod.chmodPlusR;
import static com.squareup.spoon.Chmod.chmodPlusRWX;
/** Utility class for capturing screenshots for Spoon. */
public final class Spoon {
static final String SPOON_SCREENSHOTS = "spoon-screenshots";
static final String NAME_SEPARATOR = "_";
static final String TEST_CASE_CLASS = "android.test.InstrumentationTestCase";
static final String TEST_CASE_METHOD = "runMethod";
private static final String EXTENSION = ".png";
private static final String TAG = "SpoonScreenshot";
private static final Object LOCK = new Object();
private static final Pattern TAG_VALIDATION = Pattern.compile("[a-zA-Z0-9_-]+");
/** Whether or not the screenshot output directory needs cleared. */
private static boolean outputNeedsClear = true;
/**
* Take a screenshot with the specified tag.
*
* @param activity Activity with which to capture a screenshot.
* @param tag Unique tag to further identify the screenshot. Must match [a-zA-Z0-9_-]+.
*/
public static void screenshot(Activity activity, String tag) {
if (!TAG_VALIDATION.matcher(tag).matches()) {
throw new IllegalArgumentException("Tag must match " + TAG_VALIDATION.pattern() + ".");
}
try {
File screenshotDirectory = obtainScreenshotDirectory(activity);
String screenshotName = System.currentTimeMillis() + NAME_SEPARATOR + tag + EXTENSION;
takeScreenshot(new File(screenshotDirectory, screenshotName), activity);
} catch (Exception e) {
throw new RuntimeException("Unable to capture screenshot.", e);
}
}
private static void takeScreenshot(File file, final Activity activity) throws IOException {
DisplayMetrics dm = activity.getResources().getDisplayMetrics();
final Bitmap bitmap = Bitmap.createBitmap(dm.widthPixels, dm.heightPixels, ARGB_8888);
if (Looper.myLooper() == Looper.getMainLooper()) {
drawDecorViewToBitmap(activity, bitmap);
} else {
// On a background thread, post to main.
final CountDownLatch latch = new CountDownLatch(1);
activity.runOnUiThread(new Runnable() {
@Override public void run() {
try {
drawDecorViewToBitmap(activity, bitmap);
} finally {
latch.countDown();
}
}
});
try {
latch.await();
} catch (InterruptedException e) {
String msg = "Unable to get screenshot " + file.getAbsolutePath();
Log.e(TAG, msg, e);
throw new RuntimeException(msg, e);
}
}
OutputStream fos = null;
try {
fos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(PNG, 100 /* quality */, fos);
bitmap.recycle();
chmodPlusR(file);
} finally {
if (fos != null) {
fos.close();
}
}
}
private static void drawDecorViewToBitmap(Activity activity, Bitmap bitmap) {
Canvas canvas = new Canvas(bitmap);
activity.getWindow().getDecorView().draw(canvas);
}
private static File obtainScreenshotDirectory(Context context) throws IllegalAccessException {
File screenshotsDir = context.getDir(SPOON_SCREENSHOTS, MODE_WORLD_READABLE);
synchronized (LOCK) {
if (outputNeedsClear) {
deletePath(screenshotsDir, false);
outputNeedsClear = false;
}
}
StackTraceElement testClass = findTestClassTraceElement(Thread.currentThread().getStackTrace());
String className = testClass.getClassName().replaceAll("[^A-Za-z0-9._-]", "_");
File dirClass = new File(screenshotsDir, className);
File dirMethod = new File(dirClass, testClass.getMethodName());
createDir(dirMethod);
return dirMethod;
}
/** Returns the test class element by looking at the method InstrumentationTestCase invokes. */
static StackTraceElement findTestClassTraceElement(StackTraceElement[] trace) {
for (int i = trace.length - 1; i >= 0; i
StackTraceElement element = trace[i];
if (TEST_CASE_CLASS.equals(element.getClassName())
&& TEST_CASE_METHOD.equals(element.getMethodName())) {
return trace[i - 3];
}
}
throw new IllegalArgumentException("Could not find test class!");
}
private static void createDir(File dir) throws IllegalAccessException {
File parent = dir.getParentFile();
if (!parent.exists()) {
createDir(parent);
}
if (!dir.exists() && !dir.mkdirs()) {
throw new IllegalAccessException("Unable to create output dir: " + dir.getAbsolutePath());
}
chmodPlusRWX(dir);
}
private static void deletePath(File path, boolean inclusive) {
if (path.isDirectory()) {
File[] children = path.listFiles();
if (children != null) {
for (File child : children) {
deletePath(child, true);
}
}
}
if (inclusive) {
path.delete();
}
}
private Spoon() {
// No instances.
}
}
|
package org.objectweb.proactive.core.body;
import java.io.IOException;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.ProActiveInternalObject;
import org.objectweb.proactive.annotation.ImmediateService;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.benchmarks.timit.util.CoreTimersContainer;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.UniqueID;
import org.objectweb.proactive.core.body.exceptions.InactiveBodyException;
import org.objectweb.proactive.core.body.ft.protocols.FTManager;
import org.objectweb.proactive.core.body.ft.service.FaultToleranceTechnicalService;
import org.objectweb.proactive.core.body.future.Future;
import org.objectweb.proactive.core.body.future.FuturePool;
import org.objectweb.proactive.core.body.future.MethodCallResult;
import org.objectweb.proactive.core.body.reply.Reply;
import org.objectweb.proactive.core.body.reply.ReplyImpl;
import org.objectweb.proactive.core.body.reply.ReplyReceiver;
import org.objectweb.proactive.core.body.request.BlockingRequestQueue;
import org.objectweb.proactive.core.body.request.Request;
import org.objectweb.proactive.core.body.request.RequestFactory;
import org.objectweb.proactive.core.body.request.RequestQueue;
import org.objectweb.proactive.core.body.request.RequestReceiver;
import org.objectweb.proactive.core.body.request.RequestReceiverImpl;
import org.objectweb.proactive.core.body.tags.MessageTags;
import org.objectweb.proactive.core.body.tags.Tag;
import org.objectweb.proactive.core.body.tags.tag.DsiTag;
import org.objectweb.proactive.core.component.body.ComponentBodyImpl;
import org.objectweb.proactive.core.component.request.ComponentRequestImpl;
import org.objectweb.proactive.core.config.CentralPAPropertyRepository;
import org.objectweb.proactive.core.debug.debugger.BreakpointType;
import org.objectweb.proactive.core.gc.GarbageCollector;
import org.objectweb.proactive.core.jmx.mbean.BodyWrapper;
import org.objectweb.proactive.core.jmx.naming.FactoryName;
import org.objectweb.proactive.core.jmx.notification.NotificationType;
import org.objectweb.proactive.core.jmx.notification.RequestNotificationData;
import org.objectweb.proactive.core.jmx.server.ServerConnector;
import org.objectweb.proactive.core.mop.MOP;
import org.objectweb.proactive.core.mop.MOPException;
import org.objectweb.proactive.core.mop.MethodCall;
import org.objectweb.proactive.core.mop.ObjectReferenceReplacer;
import org.objectweb.proactive.core.mop.ObjectReplacer;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeFactory;
import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
import org.objectweb.proactive.core.security.exceptions.CommunicationForbiddenException;
import org.objectweb.proactive.core.security.exceptions.RenegotiateSessionException;
import org.objectweb.proactive.core.util.profiling.Profiling;
import org.objectweb.proactive.core.util.profiling.TimerWarehouse;
/**
* <i><font size="-1" color="#FF0000">**For internal use only** </font></i><br>
* <p>
* This class gives a common implementation of the Body interface. It provides
* all the non specific behavior allowing sub-class to write the detail
* implementation.
* </p>
* <p>
* Each body is identify by an unique identifier.
* </p>
* <p>
* All active bodies that get created in one JVM register themselves into a
* table that allows to tack them done. The registering and deregistering is
* done by the AbstractBody and the table is managed here as well using some
* static methods.
* </p>
* <p>
* In order to let somebody customize the body of an active object without
* subclassing it, AbstractBody delegates lot of tasks to satellite objects that
* implements a given interface. Abstract protected methods instantiate those
* objects allowing subclasses to create them as they want (using customizable
* factories or instance).
* </p>
*
* @author The ProActive Team
* @version 1.0, 2001/10/23
* @since ProActive 0.9
* @see org.objectweb.proactive.Body
* @see UniqueID
*
*/
public abstract class BodyImpl extends AbstractBody implements java.io.Serializable, BodyImplMBean {
/** The component in charge of receiving reply */
protected ReplyReceiver replyReceiver;
/** The component in charge of receiving request */
protected RequestReceiver requestReceiver;
// already checked methods
private HashMap<String, HashSet<List<Class<?>>>> checkedMethodNames;
/**
* Creates a new AbstractBody. Used for serialization.
*/
public BodyImpl() {
}
/**
* Creates a new AbstractBody for an active object attached to a given node.
*
* @param reifiedObject the active object that body is for
*
* @param nodeURL the URL of the node that body is attached to
*
* @param factory the factory able to construct new factories for each type of meta objects
* needed by this body
*/
public BodyImpl(Object reifiedObject, String nodeURL, MetaObjectFactory factory)
throws ActiveObjectCreationException {
super(reifiedObject, nodeURL, factory);
super.isProActiveInternalObject = reifiedObject instanceof ProActiveInternalObject;
// TIMING
if (!super.isProActiveInternalObject) {
super.timersContainer = CoreTimersContainer.create(super.bodyID, reifiedObject, factory, nodeURL);
if (super.timersContainer != null) {
TimerWarehouse.enableTimers();
// START TOTAL TIMER
TimerWarehouse.startTimer(super.bodyID, TimerWarehouse.TOTAL);
}
}
this.checkedMethodNames = new HashMap<String, HashSet<List<Class<?>>>>();
this.requestReceiver = factory.newRequestReceiverFactory().newRequestReceiver();
this.replyReceiver = factory.newReplyReceiverFactory().newReplyReceiver();
setLocalBodyImpl(new ActiveLocalBodyStrategy(reifiedObject, factory.newRequestQueueFactory()
.newRequestQueue(this.bodyID), factory.newRequestFactory()));
this.localBodyStrategy.getFuturePool().setOwnerBody(this);
// FAULT TOLERANCE=
try {
Node node = NodeFactory.getNode(this.getNodeURL());
if ("true".equals(node.getProperty(FaultToleranceTechnicalService.FT_ENABLED))) {
// if the object is a ProActive internal object, FT is disabled
if (!super.isProActiveInternalObject) {
// if the object is not serializable or instance of non static enclosing class (PROACTIVE-277), FT is disabled
Class reifiedClass = this.localBodyStrategy.getReifiedObject().getClass();
if ((this.localBodyStrategy.getReifiedObject() instanceof Serializable) ||
(reifiedClass.isMemberClass() && !Modifier.isStatic(reifiedClass.getModifiers()))) {
try {
// create the fault tolerance manager
int protocolSelector = FTManager.getProtoSelector(node
.getProperty(FaultToleranceTechnicalService.PROTOCOL));
this.ftmanager = factory.newFTManagerFactory().newFTManager(protocolSelector);
this.ftmanager.init(this);
if (bodyLogger.isDebugEnabled()) {
bodyLogger.debug("Init FTManager on " + this.getNodeURL());
}
} catch (ProActiveException e) {
bodyLogger
.error("**ERROR** Unable to init FTManager. Fault-tolerance is disabled " +
e);
this.ftmanager = null;
}
} else {
// target body is not serilizable
bodyLogger
.error("**WARNING** Activated object is not serializable or instance of non static member class (" +
this.localBodyStrategy.getReifiedObject().getClass() +
"). Fault-tolerance is disabled for this active object");
this.ftmanager = null;
}
}
} else {
this.ftmanager = null;
}
} catch (ProActiveException e) {
bodyLogger.error("**ERROR** Unable to read node configuration. Fault-tolerance is disabled");
this.ftmanager = null;
}
this.gc = new GarbageCollector(this);
// JMX registration
if (!super.isProActiveInternalObject) {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName oname = FactoryName.createActiveObjectName(this.bodyID);
if (!mbs.isRegistered(oname)) {
super.mbean = new BodyWrapper(oname, this);
try {
mbs.registerMBean(mbean, oname);
} catch (InstanceAlreadyExistsException e) {
bodyLogger.error("A MBean with the object name " + oname + " already exists", e);
} catch (MBeanRegistrationException e) {
bodyLogger.error("Can't register the MBean of the body", e);
} catch (NotCompliantMBeanException e) {
bodyLogger.error("The MBean of the body is not JMX compliant", e);
}
}
}
// ImmediateService
initializeImmediateService(reifiedObject);
}
/**
* Receives a request for later processing. The call to this method is non blocking unless the
* body cannot temporary receive the request.
*
* @param request the request to process
*
* @exception java.io.IOException if the request cannot be accepted
*/
@Override
protected int internalReceiveRequest(Request request) throws java.io.IOException,
RenegotiateSessionException {
// JMX Notification
if (!isProActiveInternalObject && (this.mbean != null)) {
String tagNotification = createTagNotification(request.getTags());
RequestNotificationData requestNotificationData = new RequestNotificationData(request
.getSourceBodyID(), request.getSenderNodeURL(), this.bodyID, this.nodeURL, request
.getMethodName(), getRequestQueue().size() + 1, request.getSequenceNumber(),
tagNotification);
this.mbean.sendNotification(NotificationType.requestReceived, requestNotificationData);
}
// END JMX Notification
// request queue length = number of requests in queue
// + the one to add now
try {
return this.requestReceiver.receiveRequest(request, this);
} catch (CommunicationForbiddenException e) {
e.printStackTrace();
}
return 0;
}
/**
* Receives a reply in response to a former request.
*
* @param reply the reply received
*
* @exception java.io.IOException if the reply cannot be accepted
*/
@Override
protected int internalReceiveReply(Reply reply) throws java.io.IOException {
// JMX Notification
if (!isProActiveInternalObject && (this.mbean != null) && reply.getResult().getException() == null) {
String tagNotification = createTagNotification(reply.getTags());
RequestNotificationData requestNotificationData = new RequestNotificationData(
BodyImpl.this.bodyID, BodyImpl.this.getNodeURL(), reply.getSourceBodyID(), this.nodeURL,
reply.getMethodName(), getRequestQueue().size() + 1, reply.getSequenceNumber(),
tagNotification);
this.mbean.sendNotification(NotificationType.replyReceived, requestNotificationData);
}
// END JMX Notification
return replyReceiver.receiveReply(reply, this, getFuturePool());
}
/**
* Signals that the activity of this body, managed by the active thread has just stopped.
*
* @param completeACs if true, and if there are remaining AC in the futurepool, the AC thread is
* not killed now; it will be killed after the sending of the last remaining AC.
*/
@Override
protected void activityStopped(boolean completeACs) {
super.activityStopped(completeACs);
try {
this.localBodyStrategy.getRequestQueue().destroy();
} catch (ProActiveRuntimeException e) {
// this method can be called twos times if the automatic
// continuation thread
// is killed *after* the activity thread.
bodyLogger.debug("Terminating already terminated body " + this.getID());
}
this.getFuturePool().terminateAC(completeACs);
if (!completeACs) {
setLocalBodyImpl(new InactiveLocalBodyStrategy());
} else {
// the futurepool is still needed for remaining ACs
setLocalBodyImpl(new InactiveLocalBodyStrategy(this.getFuturePool()));
}
// terminate request receiver
this.requestReceiver.terminate();
}
public boolean checkMethod(String methodName) {
return checkMethod(methodName, null);
}
@Deprecated
public void setImmediateService(String methodName) {
setImmediateService(methodName, false);
}
public void setImmediateService(String methodName, boolean uniqueThread) {
checkImmediateServiceMode(methodName, null, uniqueThread);
((RequestReceiverImpl) this.requestReceiver).setImmediateService(methodName, uniqueThread);
}
public void setImmediateService(String methodName, Class<?>[] parametersTypes, boolean uniqueThread) {
checkImmediateServiceMode(methodName, parametersTypes, uniqueThread);
((RequestReceiverImpl) this.requestReceiver).setImmediateService(methodName, parametersTypes,
uniqueThread);
}
protected void initializeImmediateService(Object reifiedObject) {
Method[] methods = reifiedObject.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method m = methods[i];
ImmediateService is = m.getAnnotation(ImmediateService.class);
if (is != null) {
setImmediateService(m.getName(), m.getParameterTypes(), is.uniqueThread());
}
}
}
private void checkImmediateServiceMode(String methodName, Class<?>[] parametersTypes, boolean uniqueThread) {
// see PROACTIVE-309
if (!((ComponentBodyImpl) this).isComponent()) {
if (parametersTypes == null) { // all args
if (!((ComponentBodyImpl) this).isComponent()) {
if (!checkMethod(methodName)) {
throw new NoSuchMethodError(methodName + " is not defined in " +
getReifiedObject().getClass().getName());
}
}
} else { // args are specified
if (!checkMethod(methodName, parametersTypes)) {
String signature = methodName + "(";
for (int i = 0; i < parametersTypes.length; i++) {
signature += parametersTypes[i] + ((i < parametersTypes.length - 1) ? "," : "");
}
signature += " is not defined in " + getReifiedObject().getClass().getName();
throw new NoSuchMethodError(signature);
}
}
}
// cannot use IS with unique thread with fault-tolerant active object
if (uniqueThread && this.ftmanager != null) {
throw new ProActiveRuntimeException("The method " + methodName +
" cannot be set as immediate service with unique thread since the active object " +
this.getID() + " has enabled fault-tolerance.");
}
}
public void removeImmediateService(String methodName) {
((RequestReceiverImpl) this.requestReceiver).removeImmediateService(methodName);
}
public void removeImmediateService(String methodName, Class<?>[] parametersTypes) {
((RequestReceiverImpl) this.requestReceiver).removeImmediateService(methodName, parametersTypes);
}
public void updateNodeURL(String newNodeURL) {
this.nodeURL = newNodeURL;
}
@Override
public boolean isInImmediateService() throws IOException {
return this.requestReceiver.isInImmediateService();
}
public boolean checkMethod(String methodName, Class<?>[] parametersTypes) {
if (this.checkedMethodNames.containsKey(methodName)) {
if (parametersTypes != null) {
// the method name with the right signature has already been
// checked
List<Class<?>> parameterTlist = Arrays.asList(parametersTypes);
HashSet<List<Class<?>>> signatures = this.checkedMethodNames.get(methodName);
if (signatures.contains(parameterTlist)) {
return true;
}
} else {
// the method name has already been checked
return true;
}
}
// check if the method is defined as public
Class<?> reifiedClass = getReifiedObject().getClass();
boolean exists = org.objectweb.proactive.core.mop.Utils.checkMethodExistence(reifiedClass,
methodName, parametersTypes);
if (exists) {
storeInMethodCache(methodName, parametersTypes);
return true;
}
return false;
}
/**
* Stores the given method name with the given parameters types inside our method signature
* cache to avoid re-testing them
*
* @param methodName name of the method
*
* @param parametersTypes parameter type list
*/
private void storeInMethodCache(String methodName, Class<?>[] parametersTypes) {
List<Class<?>> parameterTlist = null;
if (parametersTypes != null) {
parameterTlist = Arrays.asList(parametersTypes);
}
// if we already know a version of this method, we store the new version
// in the existing set
if (this.checkedMethodNames.containsKey(methodName) && (parameterTlist != null)) {
HashSet<List<Class<?>>> signatures = this.checkedMethodNames.get(methodName);
signatures.add(parameterTlist);
}
// otherwise, we create a set containing a single element
else {
HashSet<List<Class<?>>> signatures = new HashSet<List<Class<?>>>();
if (parameterTlist != null) {
signatures.add(parameterTlist);
}
checkedMethodNames.put(methodName, signatures);
}
}
// Create the string from tag data for the notification
private String createTagNotification(MessageTags tags) {
String result = "";
if (tags != null) {
for (Tag tag : tags.getTags()) {
result += tag.getNotificationMessage();
}
}
return result;
}
private class ActiveLocalBodyStrategy implements LocalBodyStrategy, java.io.Serializable {
/** A pool future that contains the pending future objects */
protected FuturePool futures;
/** The reified object target of the request processed by this body */
protected Object reifiedObject;
protected BlockingRequestQueue requestQueue;
protected RequestFactory internalRequestFactory;
private long absoluteSequenceID;
public ActiveLocalBodyStrategy(Object reifiedObject, BlockingRequestQueue requestQueue,
RequestFactory requestFactory) {
this.reifiedObject = reifiedObject;
this.futures = new FuturePool();
this.requestQueue = requestQueue;
this.internalRequestFactory = requestFactory;
}
// -- implements LocalBody
public FuturePool getFuturePool() {
return this.futures;
}
public BlockingRequestQueue getRequestQueue() {
return this.requestQueue;
}
public Object getReifiedObject() {
return this.reifiedObject;
}
public String getName() {
return this.reifiedObject.getClass().getName();
}
/**
* Serves the request. The request should be removed from the request queue before serving,
* which is correctly done by all methods of the Service class. However, this condition is
* not ensured for custom calls on serve.
*/
public void serve(Request request) {
if (Profiling.TIMERS_COMPILED) {
TimerWarehouse.startServeTimer(bodyID, request.getMethodCall().getReifiedMethod());
}
// push the new context
LocalBodyStore.getInstance().pushContext(new Context(BodyImpl.this, request));
try {
serveInternal(request);
} finally {
LocalBodyStore.getInstance().popContext();
}
if (Profiling.TIMERS_COMPILED) {
TimerWarehouse.stopServeTimer(BodyImpl.this.bodyID);
}
}
private void serveInternal(Request request) {
if (request == null) {
return;
}
if (!isProActiveInternalObject) {
if (((RequestReceiverImpl) requestReceiver).immediateExecution(request)) {
debugger.breakpoint(BreakpointType.NewImmediateService, request);
} else {
debugger.breakpoint(BreakpointType.NewService, request);
}
}
// JMX Notification
if (!isProActiveInternalObject && (mbean != null)) {
String tagNotification = createTagNotification(request.getTags());
RequestNotificationData data = new RequestNotificationData(request.getSourceBodyID(), request
.getSenderNodeURL(), BodyImpl.this.bodyID, BodyImpl.this.nodeURL, request
.getMethodName(), getRequestQueue().size(), request.getSequenceNumber(),
tagNotification);
mbean.sendNotification(NotificationType.servingStarted, data);
}
// END JMX Notification
Reply reply = null;
// If the request is not a "terminate Active Object" request,
// it is served normally.
if (!isTerminateAORequest(request)) {
reply = request.serve(BodyImpl.this);
}
if (!isProActiveInternalObject) {
try {
if (isInImmediateService())
debugger.breakpoint(BreakpointType.EndImmediateService, request);
else
debugger.breakpoint(BreakpointType.EndService, request);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (reply == null) {
if (!isActive()) {
return; // test if active in case of terminate() method
// otherwise eventProducer would be null
}
// JMX Notification
if (!isProActiveInternalObject && (mbean != null)) {
String tagNotification = createTagNotification(request.getTags());
RequestNotificationData data = new RequestNotificationData(request.getSourceBodyID(),
request.getSenderNodeURL(), BodyImpl.this.bodyID, BodyImpl.this.nodeURL, request
.getMethodName(), getRequestQueue().size(), request.getSequenceNumber(),
tagNotification);
mbean.sendNotification(NotificationType.voidRequestServed, data);
}
// END JMX Notification
return;
}
if (Profiling.TIMERS_COMPILED) {
TimerWarehouse.startTimer(BodyImpl.this.bodyID, TimerWarehouse.SEND_REPLY);
}
// JMX Notification
if (!isProActiveInternalObject && (mbean != null) && reply.getResult().getException() == null) {
String tagNotification = createTagNotification(request.getTags());
RequestNotificationData data = new RequestNotificationData(request.getSourceBodyID(), request
.getSenderNodeURL(), BodyImpl.this.bodyID, BodyImpl.this.nodeURL, request
.getMethodName(), getRequestQueue().size(), request.getSequenceNumber(),
tagNotification);
mbean.sendNotification(NotificationType.replySent, data);
}
// END JMX Notification
ArrayList<UniversalBody> destinations = new ArrayList<UniversalBody>();
destinations.add(request.getSender());
this.getFuturePool().registerDestinations(destinations);
// Modify result object
Object initialObject = null;
Object stubOnActiveObject = null;
Object modifiedObject = null;
ObjectReplacer objectReplacer = null;
if (CentralPAPropertyRepository.PA_IMPLICITGETSTUBONTHIS.isTrue()) {
initialObject = reply.getResult().getResultObjet();
try {
PAActiveObject.getStubOnThis();
stubOnActiveObject = (Object) MOP.createStubObject(BodyImpl.this.getReifiedObject()
.getClass().getName(), BodyImpl.this.getRemoteAdapter());
objectReplacer = new ObjectReferenceReplacer(BodyImpl.this.getReifiedObject(),
stubOnActiveObject);
modifiedObject = objectReplacer.replaceObject(initialObject);
reply.getResult().setResult(modifiedObject);
} catch (InactiveBodyException e) {
e.printStackTrace();
} catch (MOPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// FAULT-TOLERANCE
if (BodyImpl.this.ftmanager != null) {
BodyImpl.this.ftmanager.sendReply(reply, request.getSender());
} else {
// if the reply cannot be sent, try to sent the thrown exception
// as result
// Useful if the exception is due to the content of the result
// (e.g. InvalidClassException)
try {
reply.send(request.getSender());
} catch (Throwable e1) {
// see PROACTIVE-1172
// previously only IOException were caught but now that new communication protocols
// can be added dynamically (remote objects) we can no longer suppose that only IOException
// will be thrown i.e. a runtime exception sent by the protocol can go through the stack and
// kill the service thread if not caught here.
// We do not want the AO to be killed if he cannot send the result.
try {
// trying to send the exception as result to fill the future.
// we want to inform the caller that the result cannot be set in
// the future for any reason. let's see if we can put the exception instead.
// works only if the exception is not due to a communication issue.
this.retrySendReplyWithException(reply, e1, request.getSender());
} catch (Throwable retryException1) {
// log the issue on the AO side for debugging purpose
// the initial exception must be the one to appear in the log.
sendReplyExceptionsLogger.error("Failed to send reply to " + request, e1);
}
}
}
if (Profiling.TIMERS_COMPILED) {
TimerWarehouse.stopTimer(BodyImpl.this.bodyID, TimerWarehouse.SEND_REPLY);
}
this.getFuturePool().removeDestinations();
// Restore Result Object
if (CentralPAPropertyRepository.PA_IMPLICITGETSTUBONTHIS.isTrue() && (objectReplacer != null)) {
try {
objectReplacer.restoreObject();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// If a reply sending has failed, try to send the exception as reply
private void retrySendReplyWithException(Reply reply, Throwable e, UniversalBody destination)
throws Exception {
// Get current request TAGs from current context
// Request currentreq = LocalBodyStore.getInstance().getContext().getCurrentRequest();
// MessageTags tags = null;
// if (currentreq != null)
// tags = currentreq.getTags();
Reply exceptionReply = new ReplyImpl(reply.getSourceBodyID(), reply.getSequenceNumber(), reply
.getMethodName(), new MethodCallResult(null, e), BodyImpl.this.securityManager/*, tags*/);
exceptionReply.send(destination);
}
public void sendRequest(MethodCall methodCall, Future future, UniversalBody destinationBody)
throws IOException, RenegotiateSessionException, CommunicationForbiddenException {
long sequenceID = getNextSequenceID();
MessageTags tags = applyTags(sequenceID);
Request request = this.internalRequestFactory.newRequest(methodCall, BodyImpl.this,
future == null, sequenceID, tags);
// COMPONENTS : generate ComponentRequest for component messages
if (methodCall.getComponentMetadata() != null) {
request = new ComponentRequestImpl(request);
}
if (future != null) {
future.setID(sequenceID);
this.futures.receiveFuture(future);
}
// JMX Notification
// TODO Write this section, after the commit of Arnaud
// TODO Send a notification only if the destination doesn't
// implement ProActiveInternalObject
if (!isProActiveInternalObject && (mbean != null)) {
ServerConnector serverConnector = ProActiveRuntimeImpl.getProActiveRuntime()
.getJMXServerConnector();
// If the connector server is not active the connectorID can be
// null
if ((serverConnector != null) && serverConnector.getConnectorServer().isActive()) {
UniqueID connectorID = serverConnector.getUniqueID();
if (!connectorID.equals(destinationBody.getID())) {
String tagNotification = createTagNotification(tags);
mbean.sendNotification(NotificationType.requestSent, new RequestNotificationData(
BodyImpl.this.bodyID, BodyImpl.this.getNodeURL(), destinationBody.getID(),
destinationBody.getNodeURL(), methodCall.getName(), -1, request
.getSequenceNumber(), tagNotification));
}
}
}
// END JMX Notification
// FAULT TOLERANCE
if (BodyImpl.this.ftmanager != null) {
BodyImpl.this.ftmanager.sendRequest(request, destinationBody);
} else {
request.send(destinationBody);
}
}
/**
* Returns a unique identifier that can be used to tag a future, a request
*
* @return a unique identifier that can be used to tag a future, a request.
*/
public synchronized long getNextSequenceID() {
return BodyImpl.this.bodyID.toString().hashCode() + ++this.absoluteSequenceID;
}
/**
* Test if the MethodName of the request is "terminateAO" or "terminateAOImmediately". If
* true, AbstractBody.terminate() is called
*
* @param request The request to serve
*
* @return true if the name of the method is "terminateAO" or "terminateAOImmediately".
*/
private boolean isTerminateAORequest(Request request) {
boolean terminateRequest = (request.getMethodName()).startsWith("_terminateAO");
if (terminateRequest) {
terminate();
}
return terminateRequest;
}
/**
* Propagate all tags attached to the current served request.
* @return The MessageTags for the propagation
*/
private MessageTags applyTags(long sequenceID) {
// apply the code of all message TAGs from current context
Request currentreq = LocalBodyStore.getInstance().getContext().getCurrentRequest();
MessageTags currentMessagetags = null;
MessageTags nextTags = messageTagsFactory.newMessageTags();
if (currentreq != null && (currentMessagetags = currentreq.getTags()) != null) {
// there is a request with a MessageTags object in the current context
for (Tag t : currentMessagetags.getTags()) {
Tag newTag = t.apply();
if (newTag != null)
nextTags.addTag(newTag);
}
}
// Check the presence of the DSI Tag if enabled
// Ohterwise add it
if (CentralPAPropertyRepository.PA_TAG_DSF.isTrue()) {
if (!nextTags.check(DsiTag.IDENTIFIER)) {
nextTags.addTag(new DsiTag(bodyID, sequenceID));
}
}
return nextTags;
}
}
// end inner class LocalBodyImpl
private class InactiveLocalBodyStrategy implements LocalBodyStrategy, java.io.Serializable {
// An inactive body strategy can have a futurepool if some ACs to do
// remain after the termination of the active object
private FuturePool futures;
public InactiveLocalBodyStrategy() {
}
public InactiveLocalBodyStrategy(FuturePool remainingsACs) {
this.futures = remainingsACs;
}
// -- implements LocalBody
public FuturePool getFuturePool() {
return this.futures;
}
public BlockingRequestQueue getRequestQueue() {
throw new InactiveBodyException(BodyImpl.this);
}
public RequestQueue getHighPriorityRequestQueue() {
throw new InactiveBodyException(BodyImpl.this);
}
public Object getReifiedObject() {
throw new InactiveBodyException(BodyImpl.this);
}
public String getName() {
return "inactive body";
}
public void serve(Request request) {
throw new InactiveBodyException(BodyImpl.this, (request != null) ? request.getMethodName()
: "null request");
}
public void sendRequest(MethodCall methodCall, Future future, UniversalBody destinationBody)
throws java.io.IOException {
throw new InactiveBodyException(BodyImpl.this, destinationBody.getNodeURL(), destinationBody
.getID(), methodCall.getName());
}
/*
* @see org.objectweb.proactive.core.body.LocalBodyStrategy#getNextSequenceID()
*/
public long getNextSequenceID() {
return 0;
}
}
// end inner class InactiveBodyException
}
|
/*
* Cordova WebSocket Server Plugin
*
* WebSocket Server plugin for Cordova/Phonegap
* by Sylvain Brejeon
*/
package net.becvert.cordova;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.exceptions.InvalidDataException;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.ServerHandshakeBuilder;
import org.java_websocket.server.WebSocketServer;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class WebSocketServerImpl extends WebSocketServer {
protected boolean active = true;
private CallbackContext callbackContext;
private List<String> origins;
private List<String> protocols;
private Map<String, WebSocket> UUIDSockets = new HashMap<String, WebSocket>();
private Map<WebSocket, String> socketsUUID = new HashMap<WebSocket, String>();
public WebSocketServerImpl(int port) {
super(new InetSocketAddress(port));
}
public CallbackContext getCallbackContext() {
return this.callbackContext;
}
public void setCallbackContext(CallbackContext callbackContext) {
this.callbackContext = callbackContext;
}
public void setOrigins(List<String> origins) {
this.origins = origins;
}
public void setProtocols(List<String> protocols) {
this.protocols = protocols;
}
private String getAcceptedProtocol(ClientHandshake clientHandshake) {
String acceptedProtocol = null;
String secWebSocketProtocol = clientHandshake.getFieldValue("Sec-WebSocket-Protocol");
if (secWebSocketProtocol != null && !secWebSocketProtocol.equals("")) {
String[] requestedProtocols = secWebSocketProtocol.split(", ");
for (int i = 0, l = requestedProtocols.length; i < l; i++) {
if (protocols.indexOf(requestedProtocols[i]) > -1) {
// returns first matching protocol.
// assumes in order of preference.
acceptedProtocol = requestedProtocols[i];
break;
}
}
}
return acceptedProtocol;
}
@Override
public ServerHandshakeBuilder onWebsocketHandshakeReceivedAsServer(WebSocket conn, Draft draft,
ClientHandshake request) throws InvalidDataException {
ServerHandshakeBuilder serverHandshakeBuilder = super.onWebsocketHandshakeReceivedAsServer(conn, draft,
request);
if (origins != null) {
String origin = request.getFieldValue("Origin");
if (origins.indexOf(origin) == -1) {
Log.w(WebSocketServerPlugin.TAG, "handshake: origin denied: " + origin);
throw new InvalidDataException(CloseFrame.REFUSE);
}
}
if (protocols != null) {
String acceptedProtocol = getAcceptedProtocol(request);
if (acceptedProtocol == null) {
String secWebSocketProtocol = request.getFieldValue("Sec-WebSocket-Protocol");
Log.w(WebSocketServerPlugin.TAG, "handshake: protocol denied: " + secWebSocketProtocol);
throw new InvalidDataException(CloseFrame.PROTOCOL_ERROR);
} else {
serverHandshakeBuilder.put("Sec-WebSocket-Protocol", acceptedProtocol);
}
}
return serverHandshakeBuilder;
}
@Override
public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
Log.v(WebSocketServerPlugin.TAG, "onopen");
String uuid = null;
while (uuid == null || UUIDSockets.containsKey(uuid)) {
// prevent collision
uuid = UUID.randomUUID().toString();
}
UUIDSockets.put(uuid, webSocket);
socketsUUID.put(webSocket, uuid);
try {
JSONObject httpFields = new JSONObject();
Iterator<String> iterator = clientHandshake.iterateHttpFields();
while (iterator.hasNext()) {
String httpField = iterator.next();
httpFields.put(httpField, clientHandshake.getFieldValue(httpField));
}
JSONObject conn = new JSONObject();
conn.put("uuid", uuid);
conn.put("remoteAddr", webSocket.getRemoteSocketAddress().getAddress().getHostAddress());
String acceptedProtocol = "";
if (protocols != null) {
acceptedProtocol = getAcceptedProtocol(clientHandshake);
}
conn.put("acceptedProtocol", acceptedProtocol);
conn.put("httpFields", httpFields);
conn.put("resource", clientHandshake.getResourceDescriptor());
JSONObject status = new JSONObject();
status.put("action", "onOpen");
status.put("conn", conn);
Log.d(WebSocketServerPlugin.TAG, "onopen result: " + status.toString());
PluginResult result = new PluginResult(PluginResult.Status.OK, status);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
} catch (JSONException e) {
e.printStackTrace();
callbackContext.error("Error: " + e.getMessage());
}
}
@Override
public void onMessage(WebSocket webSocket, String msg) {
Log.v(WebSocketServerPlugin.TAG, "onmessage");
String uuid = socketsUUID.get(webSocket);
if (uuid != null) {
try {
JSONObject conn = new JSONObject();
conn.put("uuid", uuid);
conn.put("remoteAddr", webSocket.getRemoteSocketAddress().getAddress().getHostAddress());
JSONObject status = new JSONObject();
status.put("action", "onMessage");
status.put("conn", conn);
status.put("msg", msg);
Log.d(WebSocketServerPlugin.TAG, "onmessage result: " + status.toString());
PluginResult result = new PluginResult(PluginResult.Status.OK, status);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
} catch (JSONException e) {
e.printStackTrace();
callbackContext.error("Error: " + e.getMessage());
}
} else {
Log.d(WebSocketServerPlugin.TAG, "onmessage: unknown websocket");
}
}
@Override
public void onClose(WebSocket webSocket, int code, String reason, boolean remote) {
Log.v(WebSocketServerPlugin.TAG, "onclose");
if (webSocket != null) {
String uuid = socketsUUID.get(webSocket);
if (uuid != null) {
try {
JSONObject conn = new JSONObject();
conn.put("uuid", uuid);
conn.put("remoteAddr", webSocket.getRemoteSocketAddress().getAddress().getHostAddress());
JSONObject status = new JSONObject();
status.put("action", "onClose");
status.put("conn", conn);
status.put("code", code);
status.put("reason", reason);
status.put("wasClean", remote);
Log.d(WebSocketServerPlugin.TAG, "onclose result: " + status.toString());
PluginResult result = new PluginResult(PluginResult.Status.OK, status);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
} catch (JSONException e) {
e.printStackTrace();
callbackContext.error("Error: " + e.getMessage());
} finally {
socketsUUID.remove(webSocket);
UUIDSockets.remove(uuid);
}
} else {
Log.d(WebSocketServerPlugin.TAG, "onclose: unknown websocket");
}
}
}
@Override
public void onError(WebSocket webSocket, Exception exception) {
Log.v(WebSocketServerPlugin.TAG, "onerror");
if (webSocket == null) {
// server error
if (exception != null) {
exception.printStackTrace();
if (exception instanceof IOException) {
try {
JSONObject status = new JSONObject();
status.put("action", "onDidNotStart");
status.put("addr", this.getAddress().getAddress().getHostAddress());
status.put("port", this.getPort());
Log.d(WebSocketServerPlugin.TAG, "onerror result: " + status.toString());
PluginResult result = new PluginResult(PluginResult.Status.OK, status);
result.setKeepCallback(false);
this.callbackContext.sendPluginResult(result);
} catch (JSONException e) {
e.printStackTrace();
callbackContext.error("Error: " + e.getMessage());
}
} else {
callbackContext.error("Error: " + exception.getMessage());
}
}
this.active = false;
this.callbackContext = null;
this.UUIDSockets = null;
this.socketsUUID = null;
}
}
public void send(String uuid, String msg) {
Log.v(WebSocketServerPlugin.TAG, "send");
WebSocket webSocket = UUIDSockets.get(uuid);
if (webSocket != null) {
webSocket.send(msg);
} else {
Log.d(WebSocketServerPlugin.TAG, "send: unknown websocket");
}
}
public void close(String uuid, int code, String reason) {
Log.v(WebSocketServerPlugin.TAG, "close");
WebSocket webSocket = UUIDSockets.get(uuid);
if (webSocket != null) {
if (code == -1) {
webSocket.close(CloseFrame.NORMAL);
} else {
webSocket.close(code, reason);
}
UUIDSockets.remove(uuid);
socketsUUID.remove(webSocket);
} else {
Log.d(WebSocketServerPlugin.TAG, "close: unknown websocket");
}
}
}
|
package assettocorsa.servermanager;
import assettocorsa.servermanager.model.*;
import assettocorsa.servermanager.ui.listview.DriverOnRosterNameConverter;
import assettocorsa.servermanager.ui.listview.RaceSettingsNameConverter;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Window;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
public class MainWindowController implements Initializable {
public ListView<DriverOnRoster> driverRosterListView;
public TextField driverInfoNameTextField;
public TextField driverInfoGuidTextField;
public TextField outputLocationTextField;
public TextField acLocationTextField;
/**
* Added the rootPane in order to get access to it's parent, the Stage.
*/
public BorderPane rootPane;
/**
* List of all the races that have been configured.
*/
public ListView<RaceSettings> raceListView;
/* Service config panel fields */
public TextField serverNameTextField;
public TextField serverPasswordTextField;
public TextField adminPasswordTextField;
/**
* Data storage handler for the driver roster.
* Injecting this would be best.
*/
private DriverRoster driverRoster;
private DriverOnRoster selectedDriverOnDriverRoster;
/**
* Driver info panel text field enable status.
* javafx.scene.control.TextField Both text fields enableProperty shall be bound to this property.
*/
private SimpleBooleanProperty driverInfoInputsEnabled;
private AppSettings appSettings;
private RaceUIModel raceUIModel;
@Override
public void initialize(URL location, ResourceBundle resources) {
initialisePropertiesAndBindings();
driverRoster = new DriverRosterImpl();
driverRoster.load();
// TODO Try catch IOException on failed load should go into the driverRoster
ObservableList<DriverOnRoster> driverList = driverRoster.getListOfDrivers();
// TODO inject this
appSettings = new AppSettingsImpl();
appSettings.loadAppSettings();
// TODO inject this
raceUIModel = new RaceUIModelImpl();
initiliseBindingToRaceUIModel();
intialiseDriverRosterListView(driverList);
initaliseBindingsToAppSettings(appSettings);
}
private void initiliseBindingToRaceUIModel() {
raceListView.setCellFactory(TextFieldListCell.forListView(new RaceSettingsNameConverter()));
raceListView.setItems(raceUIModel.raceSettingsListProperty());
raceListView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
RaceSettings raceSettings = raceUIModel.selectedRaceSettingsProperty();
serverNameTextField.textProperty().bindBidirectional(raceSettings.serverNameProperty());
// And the rest...
}
/**
* Bindings to the AppSettings Property to the UI
*
* @param appSettings
*/
private void initaliseBindingsToAppSettings(AppSettings appSettings) {
acLocationTextField.textProperty().bindBidirectional(appSettings.assettoCorsaDirectoryProperty());
outputLocationTextField.textProperty().bindBidirectional(appSettings.exportDirectoryProperty());
}
/**
* Bindings between UI Components
*/
private void initialisePropertiesAndBindings() {
selectedDriverOnDriverRoster = null;
driverInfoInputsEnabled = new SimpleBooleanProperty(true);
driverInfoNameTextField.editableProperty().bindBidirectional(driverInfoInputsEnabled);
driverInfoGuidTextField.editableProperty().bindBidirectional(driverInfoInputsEnabled);
}
/**
* Initialised the driver roster as multi select. With a custom cell factory which shall render the driver name.
*
* @param driverList
*/
private void intialiseDriverRosterListView(ObservableList<DriverOnRoster> driverList) {
driverRosterListView.setCellFactory(TextFieldListCell.forListView(new DriverOnRosterNameConverter()));
driverRosterListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
driverRosterListView.setItems(driverList);
}
/**
* Acivated from new button in driver roster
*
* @param actionEvent
*/
public void newDriverInRosterAction(ActionEvent actionEvent) {
unbindDriverSelectedOnRoster();
selectedDriverOnDriverRoster = driverRoster.createNewDriver();
driverRosterListView.getSelectionModel().clearSelection();
driverRosterListView.getSelectionModel().select(selectedDriverOnDriverRoster);
bindFirstDriverSelectedOnRoster();
}
/**
* Activated from delete button in driver roster.
*
* @param actionEvent
*/
public void deleteDriverInRoster(ActionEvent actionEvent) {
driverRosterListView.getSelectionModel().getSelectedItems().forEach(driver -> driverRoster.removeDriver(driver));
}
public void saveDriverRoster(ActionEvent actionEvent) {
driverRoster.store();
}
/**
* Executed on selection of driverRosterListView
*
* @param event
*/
public void updateDriverInfoFromRoster(Event event) {
ObservableList<DriverOnRoster> selectedDrivers = driverRosterListView.getSelectionModel().getSelectedItems();
unbindDriverSelectedOnRoster();
if (selectedDrivers.size() == 1) {
bindFirstDriverSelectedOnRoster();
} else {
disableDriverInfo();
}
}
private void disableDriverInfo() {
driverInfoInputsEnabled.setValue(false);
selectedDriverOnDriverRoster = null;
}
private void bindFirstDriverSelectedOnRoster() {
ObservableList<DriverOnRoster> selectedDrivers = driverRosterListView.getSelectionModel().getSelectedItems();
driverInfoInputsEnabled.setValue(true);
selectedDriverOnDriverRoster = selectedDrivers.get(0);
driverInfoNameTextField.textProperty().bindBidirectional(selectedDriverOnDriverRoster.driverNameProperty());
driverInfoGuidTextField.textProperty().bindBidirectional(selectedDriverOnDriverRoster.guidProperty());
}
private void unbindDriverSelectedOnRoster() {
if (selectedDriverOnDriverRoster != null) {
driverInfoNameTextField.textProperty().unbindBidirectional(selectedDriverOnDriverRoster.driverNameProperty());
driverInfoGuidTextField.textProperty().unbindBidirectional(selectedDriverOnDriverRoster.guidProperty());
}
}
/**
* Called App settings to set the output dir
*
* @param actionEvent
*/
public void selectOutputDir(ActionEvent actionEvent) {
appSettingsDirChooser("Select Output Folder", appSettings.exportDirectoryProperty());
}
/**
* Called from app settings to set the assetto corsa dir
*
* @param actionEvent
*/
public void selectAcLocation(ActionEvent actionEvent) {
appSettingsDirChooser("Select Assetto Corsa Folder", appSettings.assettoCorsaDirectoryProperty());
}
/**
* Opern a dir chooser and update the supplied property if a selection is made.
*
* @param chooserTitle
* @param propertyToUpdate
*/
private void appSettingsDirChooser(String chooserTitle, StringProperty propertyToUpdate) {
Window window = rootPane.getScene().getWindow();
DirectoryChooser directoryChooser = new DirectoryChooser();
directoryChooser.setTitle(chooserTitle);
File inputDir = new File(propertyToUpdate.getValue());
if (inputDir.exists())
directoryChooser.setInitialDirectory(inputDir);
File selectedFile = directoryChooser.showDialog(window);
if (selectedFile != null) {
// selection made
propertyToUpdate.setValue(selectedFile.getAbsolutePath());
}
}
public void newRaceAction(ActionEvent actionEvent) {
raceUIModel.store(); // Store any of the current settings
RaceSettings rs = raceUIModel.createNewRaceSettings();
raceUIModel.selectRaceSettings(rs);
}
public void cloneRaceAction(ActionEvent actionEvent) {
raceUIModel.cloneRaceSettings(getSelectedRaceSettings());
raceUIModel.store();
}
public void deleteRaceAction(ActionEvent actionEvent) {
raceUIModel.deleteRaceSettings(getSelectedRaceSettings());
raceUIModel.store();
}
public void selectRaceAction(@SuppressWarnings("UnusedParameters") Event event) {
raceUIModel.store(); // save changes on switch.
raceUIModel.selectRaceSettings(getSelectedRaceSettings());
}
private RaceSettings getSelectedRaceSettings() {
return raceListView.getSelectionModel().getSelectedItems().get(0);
}
public void raceListEditCommit(ListView.EditEvent<RaceSettings> raceListEditEvent) {
RaceSettings partialRaceSettings = raceListEditEvent.getNewValue();
raceUIModel.selectedRaceSettingsProperty().setRaceName(partialRaceSettings.getRaceName());
raceUIModel.store(); // Store and trigger change in observable list, which updates ui.
}
}
|
package ch.unizh.ini.jaer.chip.retina;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.jaer.Description;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.eventprocessing.filter.EventRateEstimator;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.EngineeringFormat;
import com.jogamp.opengl.util.gl2.GLUT;
import net.sf.jaer.DevelopmentStatus;
/**
* Controls the rate of events from the retina by controlling retina biases. The
* event threshold is increased if rate exceeds rateHigh until rate drops below
* rateHigh. The threshold is decreased if rate is lower than rateLow.
* Hysterisis limits crossing noise. A lowpass filter smooths the rate
* measurements.
*
* @author tobi
*/
@Description("Adaptively controls biases on DVS sensors (that implement DVSTweaks on their bias generator) to control event rate")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class DVSBiasController extends EventFilter2D implements FrameAnnotater {
protected int rateHigh = getInt("rateHigh", 400);
// private int rateMid=getInt("rateMid",300);
private int rateLow = getInt("rateLow", 100);
private int rateHysteresis = getInt("rateHysteresis", 50);
private float hysteresisFactor = getFloat("hysteresisFactor", 1.3f);
private int minCommandIntervalMs = getInt("minCommandIntervalMs", 300);
private long lastCommandTime = 0; // limits use of status messages that control biases
private float tweakStepAmount = getFloat("tweakStepAmount", .01f);
private EventRateEstimator rateEstimator;
enum State {
INITIAL, LOW_RATE, MEDIUM_RATE, HIGH_RATE;
private long timeChanged = 0;
long getTimeChanged() {
return timeChanged;
}
void setTimeChanged(long t) {
timeChanged = t;
}
public String toString() {
switch (this) {
case HIGH_RATE:
return "Event rate too high, increasing threshold";
case MEDIUM_RATE:
return "Event rate within bounds";
case LOW_RATE:
return "Event rate too low: decreasing threshold";
default:
return "Initial state";
}
}
};
State state = State.INITIAL, lastState = State.INITIAL;
Writer logWriter;
private boolean writeLogEnabled = false;
long timeNowMs = 0;
/**
* Creates a new instance of DVS128BiasController
*/
public DVSBiasController(AEChip chip) {
super(chip);
rateEstimator = new EventRateEstimator(chip);
FilterChain chain = new FilterChain(chip);
chain.add(rateEstimator);
setEnclosedFilterChain(chain);
setPropertyTooltip("rateLow", "event rate in keps for LOW state");
setPropertyTooltip("rateHigh", "event rate in keps for HIGH state");
setPropertyTooltip("rateHysteresis", "hysteresis for state change; after state entry, state exited only when avg rate changes by this factor from threshold");
setPropertyTooltip("hysteresisFactor", "hysteresis for state change; after state entry, state exited only when avg rate changes by this factor from threshold");
setPropertyTooltip("tweakStepAmount", "amount to tweak bias by each step");
setPropertyTooltip("minCommandIntervalMs", "min time in ms between changing biases");
}
public Object getFilterState() {
return null;
}
@Override
synchronized public void resetFilter() {
if (chip.getHardwareInterface() == null) {
return; // avoid sending hardware commands unless the hardware is there and we are active
}
if (chip.getBiasgen() == null) {
setFilterEnabled(false);
log.warning("null biasgen object to operate on, disabled filter");
return;
}
if (!(chip.getBiasgen() instanceof DVSTweaks)) {
setFilterEnabled(false);
log.warning("Wrong type of biasgen object; should be DVS128.Biasgen but object is " + chip.getBiasgen() + "; disabled filter");
return;
}
DVSTweaks biasgen = (DVSTweaks) getChip().getBiasgen();
if (biasgen == null) {
// log.warning("null biasgen, not doing anything");
return;
}
// biasgen.loadPreferences();
state = State.INITIAL;
}
public int getRateHigh() {
return rateHigh;
}
synchronized public void setRateHigh(int upperThreshKEPS) {
rateHigh = upperThreshKEPS;
putInt("rateHigh", upperThreshKEPS);
}
public int getRateLow() {
return rateLow;
}
synchronized public void setRateLow(int lowerThreshKEPS) {
rateLow = lowerThreshKEPS;
putInt("rateLow", lowerThreshKEPS);
}
@Override
synchronized public EventPacket filterPacket(EventPacket in) {
// TODO reenable check for LIVE mode here
// if (chip.getAeViewer().getPlayMode() != AEViewer.PlayMode.LIVE) {
// return in; // don't servo on recorded data!
getEnclosedFilterChain().filterPacket(in);
float r = rateEstimator.getFilteredEventRate() * 1e-3f;
setState(r);
setBiases();
if (writeLogEnabled) {
if (logWriter == null) {
logWriter = openLoggingOutputFile();
}
try {
logWriter.write(in.getLastTimestamp() + " " + r + " " + state.ordinal() + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
return in;
}
void setState(float r) {
lastState = state;
switch (state) {
case LOW_RATE:
if (r > (rateLow * hysteresisFactor)) {
state = State.MEDIUM_RATE;
}
break;
case MEDIUM_RATE:
if (r < (rateLow / hysteresisFactor)) {
state = State.LOW_RATE;
} else if (r > (rateHigh * hysteresisFactor)) {
state = State.HIGH_RATE;
}
break;
case HIGH_RATE:
if (r < (rateHigh / hysteresisFactor)) {
state = State.MEDIUM_RATE;
}
break;
default:
state = State.MEDIUM_RATE;
}
}
void setBiases() {
timeNowMs = System.currentTimeMillis();
long dt = timeNowMs - lastCommandTime;
if ((dt > 0) && (dt < getMinCommandIntervalMs())) {
return; // don't saturate setup packet bandwidth and stall on blocking USB writes
}
lastCommandTime = timeNowMs;
DVSTweaks biasgen = (DVSTweaks) getChip().getBiasgen();
if (biasgen == null) {
log.warning("null biasgen, not doing anything");
return;
}
float bw = biasgen.getThresholdTweak();
switch (state) {
case LOW_RATE:
biasgen.setThresholdTweak(bw - getTweakStepAmount());
// biasgen.decreaseThreshold();
break;
case HIGH_RATE:
biasgen.setThresholdTweak(bw + getTweakStepAmount());
// biasgen.increaseThreshold();
break;
default:
}
System.out.println("bw=" + bw);
}
@Override
public void initFilter() {
}
public float getHysteresisFactor() {
return hysteresisFactor;
}
synchronized public void setHysteresisFactor(float h) {
if (h < 1) {
h = 1;
} else if (h > 5) {
h = 5;
}
hysteresisFactor = h;
putFloat("hysteresisFactor", hysteresisFactor);
}
/**
* @return the tweakStepAmount
*/
public float getTweakStepAmount() {
return tweakStepAmount;
}
/**
* @param tweakStepAmount the tweakStepAmount to set
*/
public void setTweakStepAmount(float tweakStepAmount) {
this.tweakStepAmount = tweakStepAmount;
putFloat("tweakStepAmount", tweakStepAmount);
}
Writer openLoggingOutputFile() {
DateFormat loggingFilenameDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ssZ");
String dateString = loggingFilenameDateFormat.format(new Date());
String className = "DVS128BiasController";
int suffixNumber = 0;
boolean suceeded = false;
String filename;
Writer writer = null;
File loggingFile;
do {
filename = className + "-" + dateString + "-" + suffixNumber + ".txt";
loggingFile = new File(filename);
if (!loggingFile.isFile()) {
suceeded = true;
}
} while ((suceeded == false) && (suffixNumber++ <= 5));
if (suceeded == false) {
log.warning("could not open a unigue new file for logging after trying up to " + filename);
return null;
}
try {
writer = new FileWriter(loggingFile);
log.info("starting logging bias control at " + dateString);
writer.write("# time rate lpRate state\n");
writer.write(String.format("# rateLow=%f rateHigh=%f hysteresisFactor=%f\n", rateLow, rateHigh, hysteresisFactor));
} catch (Exception e) {
e.printStackTrace();
}
return writer;
}
EngineeringFormat fmt = new EngineeringFormat();
@Override
public void annotate(GLAutoDrawable drawable) {
if (!isFilterEnabled()) {
return;
}
GL2 gl = drawable.getGL().getGL2();
gl.glPushMatrix();
final GLUT glut = new GLUT();
gl.glColor3f(1, 1, 1); // must set color before raster position (raster position is like glVertex)
gl.glRasterPos3f(0, 0, 0);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_12, String.format("Low passed event rate=%s Hz, state=%s", fmt.format(rateEstimator.getFilteredEventRate()), state.toString()));
gl.glPopMatrix();
}
public boolean isWriteLogEnabled() {
return writeLogEnabled;
}
public void setWriteLogEnabled(boolean writeLogEnabled) {
this.writeLogEnabled = writeLogEnabled;
}
/**
* @return the minCommandIntervalMs
*/
public int getMinCommandIntervalMs() {
return minCommandIntervalMs;
}
/**
* @param minCommandIntervalMs the minCommandIntervalMs to set
*/
public void setMinCommandIntervalMs(int minCommandIntervalMs) {
this.minCommandIntervalMs = minCommandIntervalMs;
putInt("minCommandIntervalMs", minCommandIntervalMs);
}
}
|
package com.chariotsolutions.nfc.plugin;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.util.Log;
import com.phonegap.DroidGap;
/**
* Base class handles the NFC intents for your application. Extend
*/
public class DroidGapWithNfc extends DroidGap {
//when the 'register' call finishes NdefReaderPlugin gets initialized by the plug-in
public NdefReaderPlugin ndefReaderPlugin = null;
@Override
public void onResume() {
super.onResume();
// App is open and scanning. Start NFC so we receive onNewIntent events.
if (ndefReaderPlugin != null) {
ndefReaderPlugin.startNfc();
}
// App has been opened via the intent filter
Intent resumedIntent = getIntent();
if(NfcAdapter.ACTION_NDEF_DISCOVERED.equalsIgnoreCase(resumedIntent.getAction())) {
if (ndefReaderPlugin == null) {
NdefReaderPlugin.saveIntent(resumedIntent);
return;
}
ndefReaderPlugin.parseMessage(resumedIntent);
setIntent(new Intent());
}
}
@Override
public void onPause() {
super.onPause();
if (ndefReaderPlugin != null) ndefReaderPlugin.pauseNfc();
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (ndefReaderPlugin != null) ndefReaderPlugin.parseMessage(intent);
}
}
|
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
public class ITree extends FlowPanel implements Paintable {
public static final String CLASSNAME = "i-tree";
private Set selectedIds = new HashSet();
private ApplicationConnection client;
private String paintableId;
private boolean selectable;
private boolean isMultiselect;
private HashMap keyToNode = new HashMap();
private HashMap actionMap = new HashMap();
private boolean immediate;
private boolean isNullSelectionAllowed = true;
private boolean disabled = false;
private boolean readonly;
public ITree() {
super();
setStyleName(CLASSNAME);
}
private void updateActionMap(UIDL c) {
Iterator it = c.getChildIterator();
while (it.hasNext()) {
UIDL action = (UIDL) it.next();
String key = action.getStringAttribute("key");
String caption = action.getStringAttribute("caption");
actionMap.put(key + "_c", caption);
if (action.hasAttribute("icon")) {
// TODO need some uri handling ??
actionMap.put(key + "_i", client.translateToolkitUri(action
.getStringAttribute("icon")));
}
}
}
public String getActionCaption(String actionKey) {
return (String) actionMap.get(actionKey + "_c");
}
public String getActionIcon(String actionKey) {
return (String) actionMap.get(actionKey + "_i");
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Ensure correct implementation and let container manage caption
if (client.updateComponent(this, uidl, true)) {
return;
}
this.client = client;
if (uidl.hasAttribute("partialUpdate")) {
handleUpdate(uidl);
return;
}
paintableId = uidl.getId();
immediate = uidl.hasAttribute("immediate");
disabled = uidl.getBooleanAttribute("disabled");
readonly = uidl.getBooleanAttribute("readonly");
isNullSelectionAllowed = uidl.getBooleanAttribute("nullselect");
clear();
for (Iterator i = uidl.getChildIterator(); i.hasNext();) {
UIDL childUidl = (UIDL) i.next();
if ("actions".equals(childUidl.getTag())) {
updateActionMap(childUidl);
continue;
}
TreeNode childTree = new TreeNode();
this.add(childTree);
childTree.updateFromUIDL(childUidl, client);
}
String selectMode = uidl.getStringAttribute("selectmode");
selectable = selectMode != null;
isMultiselect = "multi".equals(selectMode);
selectedIds = uidl.getStringArrayVariableAsSet("selected");
}
private void handleUpdate(UIDL uidl) {
TreeNode rootNode = (TreeNode) keyToNode.get(uidl
.getStringAttribute("rootKey"));
if (rootNode != null) {
if (!rootNode.getState()) {
// expanding node happened server side
rootNode.setState(true, false);
}
rootNode.renderChildNodes(uidl.getChildIterator());
}
}
public void setSelected(TreeNode treeNode, boolean selected) {
if (selected) {
if (!isMultiselect) {
while (selectedIds.size() > 0) {
String id = (String) selectedIds.iterator().next();
TreeNode oldSelection = (TreeNode) keyToNode.get(id);
oldSelection.setSelected(false);
selectedIds.remove(id);
}
}
treeNode.setSelected(true);
selectedIds.add(treeNode.key);
} else {
if (!isNullSelectionAllowed) {
if (!isMultiselect || selectedIds.size() == 1) {
return;
}
}
selectedIds.remove(treeNode.key);
treeNode.setSelected(false);
}
client.updateVariable(paintableId, "selected", selectedIds.toArray(),
immediate);
}
public boolean isSelected(TreeNode treeNode) {
return selectedIds.contains(treeNode.key);
}
protected class TreeNode extends SimplePanel implements ActionOwner {
public static final String CLASSNAME = "i-tree-node";
String key;
private String[] actionKeys = null;
private boolean childrenLoaded;
private Element nodeCaptionDiv;
protected Element nodeCaptionSpan;
private FlowPanel childNodeContainer;
private boolean open;
public TreeNode() {
constructDom();
sinkEvents(Event.ONCLICK);
setStyleName(CLASSNAME);
}
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
if (disabled) {
return;
}
Element target = DOM.eventGetTarget(event);
if (DOM.compare(getElement(), target)) {
// state change
toggleState();
} else if (!readonly && DOM.compare(target, nodeCaptionSpan)) {
// caption click = selection change
toggleSelection();
}
}
private void toggleSelection() {
if (selectable) {
ITree.this.setSelected(this, !isSelected());
}
}
private void toggleState() {
setState(!getState(), true);
}
protected void constructDom() {
Element root = DOM.createDiv();
nodeCaptionDiv = DOM.createDiv();
DOM.setElementProperty(nodeCaptionDiv, "className", CLASSNAME
+ "-caption");
nodeCaptionSpan = DOM.createSpan();
DOM.appendChild(root, nodeCaptionDiv);
DOM.appendChild(nodeCaptionDiv, nodeCaptionSpan);
setElement(root);
childNodeContainer = new FlowPanel();
childNodeContainer.setStylePrimaryName(CLASSNAME + "-children");
setWidget(childNodeContainer);
}
public void onDetach() {
Util.removeContextMenuEvent(nodeCaptionSpan);
super.onDetach();
}
public void onAttach() {
attachContextMenuEvent(nodeCaptionSpan);
super.onAttach();
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
setText(uidl.getStringAttribute("caption"));
key = uidl.getStringAttribute("key");
keyToNode.put(key, this);
if (uidl.hasAttribute("al")) {
actionKeys = uidl.getStringArrayAttribute("al");
}
if (uidl.getTag().equals("node")) {
if (uidl.getChidlCount() == 0) {
childNodeContainer.setVisible(false);
} else {
renderChildNodes(uidl.getChildIterator());
childrenLoaded = true;
}
} else {
addStyleName(CLASSNAME + "-leaf");
}
if (uidl.getBooleanAttribute("expanded") && !getState()) {
setState(true, false);
}
if (uidl.getBooleanAttribute("selected")) {
setSelected(true);
}
}
private void setState(boolean state, boolean notifyServer) {
if (open == state) {
return;
}
if (state) {
if (!childrenLoaded && notifyServer) {
client.updateVariable(paintableId, "requestChildTree",
true, false);
}
if (notifyServer) {
client.updateVariable(paintableId, "expand",
new String[] { key }, true);
}
addStyleName(CLASSNAME + "-expanded");
childNodeContainer.setVisible(true);
} else {
removeStyleName(CLASSNAME + "-expanded");
childNodeContainer.setVisible(false);
if (notifyServer) {
client.updateVariable(paintableId, "collapse",
new String[] { key }, true);
}
}
open = state;
}
private boolean getState() {
return open;
}
private void setText(String text) {
DOM.setInnerText(nodeCaptionSpan, text);
}
private void renderChildNodes(Iterator i) {
childNodeContainer.clear();
childNodeContainer.setVisible(true);
while (i.hasNext()) {
UIDL childUidl = (UIDL) i.next();
// actions are in bit weird place, don't mix them with children,
// but current node's actions
if ("actions".equals(childUidl.getTag())) {
updateActionMap(childUidl);
continue;
}
TreeNode childTree = new TreeNode();
childNodeContainer.add(childTree);
childTree.updateFromUIDL(childUidl, client);
}
childrenLoaded = true;
}
public boolean isChildrenLoaded() {
return childrenLoaded;
}
public Action[] getActions() {
if (actionKeys == null) {
return new Action[] {};
}
Action[] actions = new Action[actionKeys.length];
for (int i = 0; i < actions.length; i++) {
String actionKey = actionKeys[i];
TreeAction a = new TreeAction(this, String.valueOf(key),
actionKey);
a.setCaption(getActionCaption(actionKey));
a.setIconUrl(getActionIcon(actionKey));
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Adds/removes IT Mill Toolkit spesific style name. This method ought
* to be called only from Tree.
*
* @param selected
*/
public void setSelected(boolean selected) {
// add style name to caption dom structure only, not to subtree
setStyleName(nodeCaptionDiv, "i-tree-node-selected", selected);
}
public boolean isSelected() {
return ITree.this.isSelected(this);
}
public void showContextMenu(Event event) {
if (!readonly && !disabled) {
if (actionKeys != null) {
int left = DOM.eventGetClientX(event);
int top = DOM.eventGetClientY(event);
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
}
DOM.eventCancelBubble(event, true);
}
}
private native void attachContextMenuEvent(Element el)
/*-{
var node = this;
el.oncontextmenu = function(e) {
if(!e)
e = $wnd.event;
node.@com.itmill.toolkit.terminal.gwt.client.ui.ITree.TreeNode::showContextMenu(Lcom/google/gwt/user/client/Event;)(e);
return false;
};
}-*/;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.