answer
stringlengths 17
10.2M
|
|---|
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.configuration.plugins.CmsTemplatePlugin;
import org.opencms.ade.configuration.plugins.CmsTemplatePluginFinder;
import org.opencms.ade.containerpage.CmsContainerpageService;
import org.opencms.ade.containerpage.CmsDetailOnlyContainerUtil;
import org.opencms.ade.containerpage.CmsModelGroupHelper;
import org.opencms.ade.containerpage.shared.CmsFormatterConfig;
import org.opencms.ade.containerpage.shared.CmsInheritanceInfo;
import org.opencms.ade.detailpage.CmsDetailPageInfo;
import org.opencms.ade.detailpage.CmsDetailPageResourceHandler;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsRequestContext;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.history.CmsHistoryResourceHandler;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.flex.CmsFlexController;
import org.opencms.flex.CmsFlexRequest;
import org.opencms.gwt.shared.CmsGwtConstants;
import org.opencms.i18n.CmsLocaleGroupService;
import org.opencms.jsp.CmsJspBean;
import org.opencms.jsp.CmsJspResourceWrapper;
import org.opencms.jsp.CmsJspTagContainer;
import org.opencms.jsp.CmsJspTagEditable;
import org.opencms.jsp.Messages;
import org.opencms.jsp.jsonpart.CmsJsonPartFilter;
import org.opencms.loader.CmsTemplateContextManager;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.CmsRuntimeException;
import org.opencms.main.CmsSystemInfo;
import org.opencms.main.OpenCms;
import org.opencms.relations.CmsCategory;
import org.opencms.relations.CmsCategoryService;
import org.opencms.search.galleries.CmsGalleryNameMacroResolver;
import org.opencms.site.CmsSite;
import org.opencms.ui.apps.lists.CmsListManager;
import org.opencms.util.CmsCollectionsGenericWrapper;
import org.opencms.util.CmsFileUtil;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.galleries.CmsAjaxDownloadGallery;
import org.opencms.xml.containerpage.CmsADESessionCache;
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.CmsFormatterConfiguration;
import org.opencms.xml.containerpage.CmsMetaMapping;
import org.opencms.xml.containerpage.CmsXmlContainerPage;
import org.opencms.xml.containerpage.CmsXmlContainerPageFactory;
import org.opencms.xml.containerpage.I_CmsFormatterBean;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.content.CmsXmlContentProperty;
import org.opencms.xml.templatemapper.CmsTemplateMapper;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.Transformer;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.logging.Log;
import com.google.common.collect.Multimap;
/**
* 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 {
/**
* Container element wrapper to add some API methods.<p>
*/
public class CmsContainerElementWrapper extends CmsContainerElementBean {
/** Cache for the wrapped element parent. */
private CmsContainerElementWrapper m_parent;
/** Cache for the wrapped element type name. */
private String m_resourceTypeName;
/** The wrapped element instance. */
private CmsContainerElementBean m_wrappedElement;
/** Cache for the wrapped element settings. */
private Map<String, CmsJspElementSettingValueWrapper> m_wrappedSettings;
/**
* Constructor.<p>
*
* @param element the element to wrap
*/
protected CmsContainerElementWrapper(CmsContainerElementBean element) {
m_wrappedElement = element;
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#clone()
*/
@Override
public CmsContainerElementBean clone() {
return m_wrappedElement.clone();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#editorHash()
*/
@Override
public String editorHash() {
return m_wrappedElement.editorHash();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return m_wrappedElement.equals(obj);
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#getFormatterId()
*/
@Override
public CmsUUID getFormatterId() {
return m_wrappedElement.getFormatterId();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#getId()
*/
@Override
public CmsUUID getId() {
return m_wrappedElement.getId();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#getIndividualSettings()
*/
@Override
public Map<String, String> getIndividualSettings() {
return m_wrappedElement.getIndividualSettings();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#getInheritanceInfo()
*/
@Override
public CmsInheritanceInfo getInheritanceInfo() {
return m_wrappedElement.getInheritanceInfo();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#getInstanceId()
*/
@Override
public String getInstanceId() {
return m_wrappedElement.getInstanceId();
}
/**
* Returns the parent element if present.<p>
*
* @return the parent element or <code>null</code> if not available
*/
public CmsContainerElementWrapper getParent() {
if (m_parent == null) {
CmsContainerElementBean parent = getParentElement(m_wrappedElement);
m_parent = (parent != null) ? new CmsContainerElementWrapper(getParentElement(m_wrappedElement)) : null;
}
return m_parent;
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#getResource()
*/
@Override
public CmsResource getResource() {
return m_wrappedElement.getResource();
}
/**
* Returns the resource type name of the element resource.<p>
*
* @return the resource type name
*/
public String getResourceTypeName() {
if (m_resourceTypeName == null) {
m_resourceTypeName = "";
try {
m_resourceTypeName = OpenCms.getResourceManager().getResourceType(
m_wrappedElement.getResource()).getTypeName();
} catch (Exception e) {
CmsJspStandardContextBean.LOG.error(e.getLocalizedMessage(), e);
}
}
return m_resourceTypeName;
}
/**
* Returns a lazy initialized setting map.<p>
*
* The values returned in the map are instances of {@link A_CmsJspValueWrapper}.
*
* @return the wrapped settings
*/
public Map<String, CmsJspElementSettingValueWrapper> getSetting() {
if (m_wrappedSettings == null) {
m_wrappedSettings = CmsCollectionsGenericWrapper.createLazyMap(
new SettingsTransformer(m_wrappedElement));
}
return m_wrappedSettings;
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#getSettings()
*/
@Override
public Map<String, String> getSettings() {
return m_wrappedElement.getSettings();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#getSitePath()
*/
@Override
public String getSitePath() {
return m_wrappedElement.getSitePath();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#hashCode()
*/
@Override
public int hashCode() {
return m_wrappedElement.hashCode();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#initResource(org.opencms.file.CmsObject)
*/
@Override
public void initResource(CmsObject cms) throws CmsException {
m_wrappedElement.initResource(cms);
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#initSettings(org.opencms.file.CmsObject, org.opencms.ade.configuration.CmsADEConfigData, org.opencms.xml.containerpage.I_CmsFormatterBean, java.util.Locale, javax.servlet.ServletRequest, java.util.Map)
*/
@Override
public void initSettings(
CmsObject cms,
CmsADEConfigData config,
I_CmsFormatterBean formatterBean,
Locale locale,
ServletRequest request,
Map<String, String> settingPresets) {
m_wrappedElement.initSettings(cms, config, formatterBean, locale, request, settingPresets);
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#isCreateNew()
*/
@Override
public boolean isCreateNew() {
return m_wrappedElement.isCreateNew();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#isGroupContainer(org.opencms.file.CmsObject)
*/
@Override
public boolean isGroupContainer(CmsObject cms) throws CmsException {
return m_wrappedElement.isGroupContainer(cms);
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#isHistoryContent()
*/
@Override
public boolean isHistoryContent() {
return m_wrappedElement.isHistoryContent();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#isInheritedContainer(org.opencms.file.CmsObject)
*/
@Override
public boolean isInheritedContainer(CmsObject cms) throws CmsException {
return m_wrappedElement.isInheritedContainer(cms);
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#isInMemoryOnly()
*/
@Override
public boolean isInMemoryOnly() {
return m_wrappedElement.isInMemoryOnly();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#isReleasedAndNotExpired()
*/
@Override
public boolean isReleasedAndNotExpired() {
return m_wrappedElement.isReleasedAndNotExpired();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#isTemporaryContent()
*/
@Override
public boolean isTemporaryContent() {
return m_wrappedElement.isTemporaryContent();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#removeInstanceId()
*/
@Override
public void removeInstanceId() {
m_wrappedElement.removeInstanceId();
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#setFormatterId(org.opencms.util.CmsUUID)
*/
@Override
public void setFormatterId(CmsUUID formatterId) {
m_wrappedElement.setFormatterId(formatterId);
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#setHistoryFile(org.opencms.file.CmsFile)
*/
@Override
public void setHistoryFile(CmsFile file) {
m_wrappedElement.setHistoryFile(file);
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#setInheritanceInfo(org.opencms.ade.containerpage.shared.CmsInheritanceInfo)
*/
@Override
public void setInheritanceInfo(CmsInheritanceInfo inheritanceInfo) {
m_wrappedElement.setInheritanceInfo(inheritanceInfo);
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#setTemporaryFile(org.opencms.file.CmsFile)
*/
@Override
public void setTemporaryFile(CmsFile elementFile) {
m_wrappedElement.setTemporaryFile(elementFile);
}
/**
* @see org.opencms.xml.containerpage.CmsContainerElementBean#toString()
*/
@Override
public String toString() {
return m_wrappedElement.toString();
}
}
/**
* Provides a lazy initialized Map that provides the detail page link as a value when given the name of a
* (named) dynamic function or resource type as a key.<p>
*/
public class CmsDetailLookupTransformer implements Transformer {
/** The selected prefix. */
private String m_prefix;
/**
* Constructor with a prefix.<p>
*
* The prefix is used to distinguish between type detail pages and function detail pages.<p>
*
* @param prefix the prefix to use
*/
public CmsDetailLookupTransformer(String prefix) {
m_prefix = prefix;
}
/**
* @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
*/
@Override
public Object transform(Object input) {
String prefix = m_prefix;
CmsObject cms = m_cms;
String inputStr = String.valueOf(input);
return getFunctionDetailLink(cms, prefix, inputStr, false);
}
}
/**
* The element setting transformer.<p>
*/
public class SettingsTransformer implements Transformer {
/** The element formatter config. */
private I_CmsFormatterBean m_formatter;
/** The configured formatter settings. */
private Map<String, CmsXmlContentProperty> m_formatterSettingsConfig;
/** The element. */
private CmsContainerElementBean m_transformElement;
/**
* Constructor.<p>
*
* @param element the element
*/
SettingsTransformer(CmsContainerElementBean element) {
m_transformElement = element;
m_formatter = getElementFormatter(element);
}
/**
* @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
*/
@Override
public Object transform(Object settingName) {
boolean exists;
if (m_formatter != null) {
if (m_formatterSettingsConfig == null) {
m_formatterSettingsConfig = OpenCms.getADEManager().getFormatterSettings(
m_cms,
m_config,
m_formatter,
m_transformElement.getResource(),
getLocale(),
m_request);
}
exists = m_formatterSettingsConfig.get(settingName) != null;
} else {
exists = m_transformElement.getSettings().get(settingName) != null;
}
return new CmsJspElementSettingValueWrapper(
CmsJspStandardContextBean.this,
m_transformElement.getSettings().get(settingName),
exists);
}
}
/**
* Bean containing a template name and URI.<p>
*/
public static class TemplateBean {
/** True if the template context was manually selected. */
private boolean m_forced;
/** The template name. */
private String m_name;
/** The template resource. */
private CmsResource m_resource;
/** The template uri, if no resource is set. */
private String m_uri;
/**
* Creates a new instance.<p>
*
* @param name the template name
* @param resource the template resource
*/
public TemplateBean(String name, CmsResource resource) {
m_resource = resource;
m_name = name;
}
/**
* Creates a new instance with an URI instead of a resoure.<p>
*
* @param name the template name
* @param uri the template uri
*/
public TemplateBean(String name, String uri) {
m_name = name;
m_uri = uri;
}
/**
* Gets the template name.<p>
*
* @return the template name
*/
public String getName() {
return m_name;
}
/**
* Gets the template resource.<p>
*
* @return the template resource
*/
public CmsResource getResource() {
return m_resource;
}
/**
* Gets the template uri.<p>
*
* @return the template URI.
*/
public String getUri() {
if (m_resource != null) {
return m_resource.getRootPath();
} else {
return m_uri;
}
}
/**
* Returns true if the template context was manually selected.<p>
*
* @return true if the template context was manually selected
*/
public boolean isForced() {
return m_forced;
}
/**
* Sets the 'forced' flag to a new value.<p>
*
* @param forced the new value
*/
public void setForced(boolean forced) {
m_forced = forced;
}
}
/**
* The meta mappings transformer.<p>
*/
class MetaLookupTranformer implements Transformer {
/**
* @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
*/
public Object transform(Object arg0) {
String result = null;
if ((m_metaMappings != null) && m_metaMappings.containsKey(arg0)) {
MetaMapping mapping = m_metaMappings.get(arg0);
CmsGalleryNameMacroResolver resolver = null;
try {
CmsResourceFilter filter = getIsEditMode()
? CmsResourceFilter.IGNORE_EXPIRATION
: CmsResourceFilter.DEFAULT;
CmsResource res = m_cms.readResource(mapping.m_contentId, filter);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, res, m_request);
resolver = new CmsGalleryNameMacroResolver(m_cms, content, getLocale());
if (content.hasLocale(getLocale())) {
I_CmsXmlContentValue val = content.getValue(mapping.m_elementXPath, getLocale());
if (val != null) {
result = val.getStringValue(m_cms);
}
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
if (result == null) {
result = mapping.m_defaultValue;
}
if ((resolver != null) && (result != null)) {
result = resolver.resolveMacros(result);
}
}
return result;
}
}
/** The meta mapping data. */
class MetaMapping {
/** The mapping content structure id. */
CmsUUID m_contentId;
/** The default value. */
String m_defaultValue;
/** The mapping value xpath. */
String m_elementXPath;
/** The mapping key. */
String m_key;
/** The mapping order. */
int m_order;
}
/** 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 sitemap configuration. */
protected CmsADEConfigData m_config;
/** The meta mapping configuration. */
Map<String, MetaMapping> m_metaMappings;
/** The current request. */
ServletRequest m_request;
/** Lazily initialized map from a category path to all sub-categories of that category. */
private Map<String, CmsJspCategoryAccessBean> m_allSubCategories;
/** Lazily initialized map from a category path to the path's category object. */
private Map<String, CmsCategory> m_categories;
/** The container the currently rendered element is part of. */
private CmsContainerBean m_container;
/** The current detail content resource if available. */
private CmsResource m_detailContentResource;
/** The detail function page. */
private CmsResource m_detailFunctionPage;
/** The detail only page references containers that are only displayed in detail view. */
private CmsContainerPageBean m_detailOnlyPage;
/** Flag to indicate if element was just edited. */
private boolean m_edited;
/** The currently rendered element. */
private CmsContainerElementBean m_element;
/** The elements of the current page. */
private Map<String, CmsContainerElementBean> m_elementInstances;
/** The lazy initialized map which allows access to the dynamic function beans. */
private Map<String, CmsDynamicFunctionBeanWrapper> m_function;
/** The lazy initialized map for the function detail pages. */
private Map<String, String> m_functionDetailPage;
/** Indicates if in drag mode. */
private boolean m_isDragMode;
/** Stores the edit mode info. */
private Boolean m_isEditMode;
/** Lazily initialized map from the locale to the localized title property. */
private Map<String, String> m_localeTitles;
/** The currently displayed container page. */
private CmsContainerPageBean m_page;
/** The current container page resource, lazy initialized. */
private CmsJspResourceWrapper m_pageResource;
/** The parent containers to the given element instance ids. */
private Map<String, CmsContainerBean> m_parentContainers;
/** Lazily initialized map from a category path to all categories on that path. */
private Map<String, List<CmsCategory>> m_pathCategories;
/** Lazily initialized map from the root path of a resource to all categories assigned to the resource. */
private Map<String, CmsJspCategoryAccessBean> m_resourceCategories;
/** Map from root paths to site relative paths. */
private Map<String, String> m_sitePaths;
/** The template plugins. */
private Map<String, List<CmsTemplatePluginWrapper>> m_templatePlugins;
/** The lazy initialized map for the detail pages. */
private Map<String, String> m_typeDetailPage;
/** 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);
m_request = 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);
m_detailFunctionPage = CmsDetailPageResourceHandler.getDetailFunctionPage(req);
}
/**
* Gets the link to a function detail page.
*
* @param cms the CMS context
* @param prefix the function detail prefix
* @param functionName the function name
* @param fullLink true if links should be generated with server prefix
*
* @return the link
*/
public static String getFunctionDetailLink(CmsObject cms, String prefix, String functionName, boolean fullLink) {
String type = prefix + functionName;
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.addSiteRoot(cms.getRequestContext().getUri()));
List<CmsDetailPageInfo> detailPages = config.getDetailPagesForType(type);
CmsDetailPageInfo detailPage = null;
boolean usingDefault = false;
if ((detailPages == null) || (detailPages.size() == 0)) {
detailPage = config.getDefaultDetailPage();
usingDefault = true;
} else {
detailPage = detailPages.get(0);
}
if (detailPage == null) {
return "[No detail page configured for type =" + type + "=]";
}
CmsUUID id = detailPage.getId();
try {
CmsResource r = cms.readResource(id);
boolean originalForceAbsoluteLinks = cms.getRequestContext().isForceAbsoluteLinks();
try {
cms.getRequestContext().setForceAbsoluteLinks(fullLink || originalForceAbsoluteLinks);
String link = OpenCms.getLinkManager().substituteLink(cms, r);
if (usingDefault) {
link = CmsStringUtil.joinPaths(link, functionName);
}
return link;
} finally {
cms.getRequestContext().setForceAbsoluteLinks(originalForceAbsoluteLinks);
}
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
return "[Error reading detail page for type =" + type + "=]";
}
}
/**
* 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 = m_container;
if (m_detailContentResource != null) {
result.m_detailContentResource = m_detailContentResource.getCopy();
}
result.m_element = m_element;
result.setPage(m_page);
return result;
}
/**
* Uses the default text encryption method to decrypt an encrypted string.
*
* @param text the encrypted stirng
* @return the decrypted string
*/
public String decrypt(String text) {
try {
return OpenCms.getTextEncryptions().get("default").decrypt(text);
} catch (Exception e) {
return null;
}
}
/**
* Returns a caching hash specific to the element, it's properties and the current container width.<p>
*
* @return the caching hash
*/
public String elementCachingHash() {
String result = "";
if (m_element != null) {
result = m_element.editorHash();
if (m_container != null) {
result += "w:"
+ m_container.getWidth()
+ "cName:"
+ m_container.getName()
+ "cType:"
+ m_container.getType();
}
}
return result;
}
/**
* Uses the default text encryption to encrypt an input text.
*
* @param text the input text
* @return the encrypted text
*/
public String encrypt(String text) {
try {
return OpenCms.getTextEncryptions().get("default").encrypt(text);
} catch (Exception e) {
return null;
}
}
/**
* Returns the locales available for the currently requested URI.
*
* @return the locales available for the currently requested URI.
*/
public List<Locale> getAvailableLocales() {
return OpenCms.getLocaleManager().getAvailableLocales(m_cms, getRequestContext().getUri());
}
/**
* Helper for easy instantiation and initialization of custom context beans that returns
* an instance of the class specified via <code>className</code>, with the current context already set.
*
* @param className name of the class to instantiate. Must be a subclass of {@link A_CmsJspCustomContextBean}.
* @return an instance of the provided class with the current context already set.
*/
public Object getBean(String className) {
try {
Class<?> clazz = Class.forName(className);
if (A_CmsJspCustomContextBean.class.isAssignableFrom(clazz)) {
Constructor<?> constructor = clazz.getConstructor();
Object instance = constructor.newInstance();
Method setContextMethod = clazz.getMethod("setContext", CmsJspStandardContextBean.class);
setContextMethod.invoke(instance, this);
return instance;
} else {
throw new Exception();
}
} catch (Exception e) {
LOG.error(Messages.get().container(Messages.ERR_NO_CUSTOM_BEAN_1, className));
}
return null;
}
/**
* Finds the folder to use for binary uploads, based on the list configuration given as an argument or
* the current sitemap configuration.
*
* @param content the list configuration content
*
* @return the binary upload folder
*/
public String getBinaryUploadFolder(CmsJspContentAccessBean content) {
String keyToFind = CmsADEConfigData.ATTR_BINARY_UPLOAD_TARGET;
String baseValue = null;
if (content != null) {
for (CmsJspContentAccessValueWrapper wrapper : content.getValueList().get(CmsListManager.N_PARAMETER)) {
String key1 = wrapper.getValue().get(CmsListManager.N_KEY).getToString();
String value1 = wrapper.getValue().get(CmsListManager.N_VALUE).getToString();
if (key1.equals(keyToFind)) {
LOG.debug("Found upload folder in configuration: " + value1);
baseValue = value1;
break;
}
}
if (baseValue == null) {
List<CmsJspContentAccessValueWrapper> folderEntries = content.getValueList().get(
CmsListManager.N_SEARCH_FOLDER);
if (folderEntries.size() == 1) {
CmsResource resource = folderEntries.get(0).getToResource();
if (resource != null) {
if (OpenCms.getResourceManager().matchResourceType(
CmsAjaxDownloadGallery.GALLERYTYPE_NAME,
resource.getTypeId())) {
baseValue = m_cms.getSitePath(resource);
LOG.debug(
"Using single download gallery from search folder configuration as upload folder: "
+ baseValue);
}
}
}
}
}
if (baseValue == null) {
baseValue = m_config.getAttribute(keyToFind, null);
if (baseValue != null) {
LOG.debug("Found upload folder in sitemap configuration: " + baseValue);
}
}
CmsMacroResolver resolver = new CmsMacroResolver();
resolver.setCmsObject(getCmsObject());
resolver.addMacro("subsitepath", CmsFileUtil.removeTrailingSeparator(getSubSitePath()));
resolver.addMacro("sitepath", "/");
// if baseValue is still null, then resolveMacros will just return null
String result = resolver.resolveMacros(baseValue);
LOG.debug("Final value for upload folder : " + result);
return result;
}
/**
* 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;
}
/**
* Gets the CmsObject from the current Flex controller.
*
* @return the CmsObject from the current Flex controller
*/
public CmsObject getControllerCms() {
return CmsFlexController.getController(m_request).getCmsObject();
}
/**
* 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 CmsJspResourceWrapper getDetailContent() {
return CmsJspResourceWrapper.wrap(m_cms, 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, or <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 detail function page.<p>
*
* @return the detail function page
*/
public CmsJspResourceWrapper getDetailFunctionPage() {
return CmsJspResourceWrapper.wrap(m_cms, m_detailFunctionPage);
}
/**
* Returns the detail only page.<p>
*
* @return the detail only page
*/
public CmsContainerPageBean getDetailOnlyPage() {
if ((null == m_detailOnlyPage) && (null != m_detailContentResource)) {
String pageRootPath = m_cms.getRequestContext().addSiteRoot(m_cms.getRequestContext().getUri());
m_detailOnlyPage = CmsDetailOnlyContainerUtil.getDetailOnlyPage(m_cms, m_request, pageRootPath, false);
}
return m_detailOnlyPage;
}
/**
* Returns the currently rendered element.<p>
*
* @return the currently rendered element
*/
public CmsContainerElementWrapper getElement() {
return m_element != null ? new CmsContainerElementWrapper(m_element) : null;
}
/**
* Returns a lazy initialized map of wrapped container elements beans by container name suffix.<p>
*
* So in case there is more than one container where the name end with the given suffix,
* a joined list of container elements beans is returned.<p>
*
* @return a lazy initialized map of wrapped container elements beans by container name suffix
*
* @see #getElementsInContainer()
*/
public Map<String, List<CmsContainerElementWrapper>> getElementBeansInContainers() {
return CmsCollectionsGenericWrapper.createLazyMap(obj -> {
if (obj instanceof String) {
List<CmsContainerElementBean> containerElements = new ArrayList<>();
for (CmsContainerBean container : getPage().getContainers().values()) {
if (container.getName().endsWith("-" + obj)) {
for (CmsContainerElementBean element : container.getElements()) {
try {
element.initResource(m_cms);
containerElements.add(new CmsContainerElementWrapper(element));
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
}
return containerElements;
} else {
return null;
}
});
}
/**
* Returns a lazy initialized map of wrapped element resources by container name.<p>
*
* @return the lazy map of element resource wrappers
*/
public Map<String, List<CmsJspResourceWrapper>> getElementsInContainer() {
return CmsCollectionsGenericWrapper.createLazyMap(obj -> {
if (obj instanceof String) {
List<CmsJspResourceWrapper> elements = new ArrayList<>();
CmsContainerBean container = getPage().getContainers().get(obj);
if (container != null) {
for (CmsContainerElementBean element : container.getElements()) {
try {
element.initResource(m_cms);
elements.add(CmsJspResourceWrapper.wrap(m_cms, element.getResource()));
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
return elements;
} else {
return null;
}
});
}
/**
* Returns a lazy initialized map of wrapped element resources by container name suffix.<p>
*
* So in case there is more than one container where the name end with the given suffix,
* a joined list of elements is returned.<p>
*
* @return the lazy map of element resource wrappers
*
* @see #getElementBeansInContainers()
*/
public Map<String, List<CmsJspResourceWrapper>> getElementsInContainers() {
return CmsCollectionsGenericWrapper.createLazyMap(obj -> {
if (obj instanceof String) {
List<CmsJspResourceWrapper> elements = new ArrayList<>();
for (CmsContainerBean container : getPage().getContainers().values()) {
if (container.getName().endsWith("-" + obj)) {
for (CmsContainerElementBean element : container.getElements()) {
try {
element.initResource(m_cms);
elements.add(CmsJspResourceWrapper.wrap(m_cms, element.getResource()));
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
}
return elements;
} else {
return null;
}
});
}
/**
* Alternative method name for getReloadMarker().
*
* @see org.opencms.jsp.util.CmsJspStandardContextBean#getReloadMarker()
*
* @return the reload marker
*/
public String getEnableReload() {
return getReloadMarker();
}
/**
* Returns a lazy initialized Map which allows access to the dynamic function beans using the JSP EL.<p>
*
* When given a key, the returned map will look up the corresponding dynamic function bean in the module configuration.<p>
*
* @return a lazy initialized Map which allows access to the dynamic function beans using the JSP EL
*/
public Map<String, CmsDynamicFunctionBeanWrapper> getFunction() {
if (m_function == null) {
Transformer transformer = new Transformer() {
@Override
public Object transform(Object input) {
try {
CmsDynamicFunctionBean dynamicFunction = readDynamicFunctionBean((String)input);
CmsDynamicFunctionBeanWrapper wrapper = new CmsDynamicFunctionBeanWrapper(
m_cms,
dynamicFunction);
return wrapper;
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), e);
return new CmsDynamicFunctionBeanWrapper(m_cms, null);
}
}
};
m_function = CmsCollectionsGenericWrapper.createLazyMap(transformer);
}
return m_function;
}
/**
* Deprecated method to access function detail pages using the EL.<p>
*
* @return a lazy initialized Map that provides the detail page link as a value when given the name of a
* (named) dynamic function as a key
*
* @deprecated use {@link #getFunctionDetailPage()} instead
*/
@Deprecated
public Map<String, String> getFunctionDetail() {
return getFunctionDetailPage();
}
/**
* Returns a lazy initialized Map that provides the detail page link as a value when given the name of a
* (named) dynamic function as a key.<p>
*
* The provided Map key is assumed to be a String that represents a named dynamic function.<p>
*
* Usage example on a JSP with the JSTL:<pre>
* <a href=${cms.functionDetailPage['search']} />
* </pre>
*
* @return a lazy initialized Map that provides the detail page link as a value when given the name of a
* (named) dynamic function as a key
*
* @see #getTypeDetailPage()
*/
public Map<String, String> getFunctionDetailPage() {
if (m_functionDetailPage == null) {
m_functionDetailPage = CmsCollectionsGenericWrapper.createLazyMap(
new CmsDetailLookupTransformer(CmsDetailPageInfo.FUNCTION_PREFIX));
}
return m_functionDetailPage;
}
/**
* 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() {
Transformer transformer = new Transformer() {
@Override
public Object transform(Object contentAccess) {
CmsXmlContent content = (CmsXmlContent)(((CmsJspContentAccessBean)contentAccess).getRawContent());
CmsDynamicFunctionParser parser = new CmsDynamicFunctionParser();
CmsDynamicFunctionBean functionBean = null;
try {
functionBean = parser.parseFunctionBean(m_cms, content);
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), 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) {
LOG.debug(e.getLocalizedMessage(), e);
}
CmsDynamicFunctionBean.Format format = functionBean.getFormatForContainer(m_cms, type, widthNum);
CmsDynamicFunctionFormatWrapper wrapper = new CmsDynamicFunctionFormatWrapper(m_cms, format);
return wrapper;
}
};
return CmsCollectionsGenericWrapper.createLazyMap(transformer);
}
/**
* Checks if the current page is a detail page.
*
* @return true if the current page is a detail page
*/
public boolean getIsDetailPage() {
CmsJspResourceWrapper page = getPageResource();
return OpenCms.getADEManager().isDetailPage(m_cms, page);
}
/**
* Checks if the current request should be direct edit enabled.
* Online-, history-requests, previews and temporary files will not be editable.<p>
*
* @return <code>true</code> if the current request should be direct edit enabled
*/
public boolean getIsEditMode() {
if (m_isEditMode == null) {
m_isEditMode = Boolean.valueOf(CmsJspTagEditable.isEditableRequest(m_request));
}
return m_isEditMode.booleanValue();
}
/**
* Returns true if the current request is a JSON request.<p>
*
* @return true if we are in a JSON request
*/
public boolean getIsJSONRequest() {
return CmsJsonPartFilter.isJsonRequest(m_request);
}
/**
* Returns if the current project is the online project.<p>
*
* @return <code>true</code> if the current project is the online project
*/
public boolean getIsOnlineProject() {
return m_cms.getRequestContext().getCurrentProject().isOnlineProject();
}
/**
* Returns the current locale.<p>
*
* @return the current locale
*/
public Locale getLocale() {
return getRequestContext().getLocale();
}
/**
* Gets a map providing access to the locale variants of the current page.<p>
*
* Note that all available locales for the site / subsite are used as keys, not just the ones for which a locale
* variant actually exists.
*
* Usage in JSPs: ${cms.localeResource['de']]
*
* @return the map from locale strings to locale variant resources
*/
public Map<String, CmsJspResourceWrapper> getLocaleResource() {
Map<String, CmsJspResourceWrapper> result = getPageResource().getLocaleResource();
List<Locale> locales = CmsLocaleGroupService.getPossibleLocales(m_cms, getPageResource());
for (Locale locale : locales) {
if (!result.containsKey(locale.toString())) {
result.put(locale.toString(), null);
}
}
return result;
}
/**
* Gets the main locale for the current page's locale group.<p>
*
* @return the main locale for the current page's locale group
*/
public Locale getMainLocale() {
return getPageResource().getMainLocale();
}
/**
* Returns the meta mappings map.<p>
*
* @return the meta mappings
*/
public Map<String, String> getMeta() {
initMetaMappings();
return CmsCollectionsGenericWrapper.createLazyMap(new MetaLookupTranformer());
}
/**
* Returns the currently displayed container page.<p>
*
* @return the currently displayed container page
*/
public CmsContainerPageBean getPage() {
if (null == m_page) {
try {
initPage();
} catch (CmsException e) {
if (LOG.isWarnEnabled()) {
LOG.warn(e, e);
}
}
}
return m_page;
}
/**
* Returns the container page bean for the give page and locale.<p>
*
* @param page the container page resource as id, path or already as resource
* @param locale the content locale as locale or string
*
* @return the container page bean
*/
public CmsContainerPageBean getPage(Object page, Object locale) {
CmsResource pageResource = null;
CmsContainerPageBean result = null;
if (m_cms != null) {
try {
pageResource = CmsJspElFunctions.convertRawResource(m_cms, page);
Locale l = CmsJspElFunctions.convertLocale(locale);
result = getPage(pageResource);
if (result != null) {
CmsADEConfigData adeConfig = OpenCms.getADEManager().lookupConfiguration(
m_cms,
pageResource.getRootPath());
for (CmsContainerBean container : result.getContainers().values()) {
for (CmsContainerElementBean element : container.getElements()) {
boolean isGroupContainer = element.isGroupContainer(m_cms);
boolean isInheritedContainer = element.isInheritedContainer(m_cms);
I_CmsFormatterBean formatterConfig = null;
if (!isGroupContainer && !isInheritedContainer) {
element.initResource(m_cms);
// ensure that the formatter configuration id is added to the element settings, so it will be persisted on save
formatterConfig = CmsJspTagContainer.getFormatterConfigurationForElement(
m_cms,
element,
adeConfig,
container.getName(),
"",
0);
if (formatterConfig != null) {
element.initSettings(m_cms, adeConfig, formatterConfig, l, m_request, null);
}
}
}
}
}
} catch (Exception e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
return result;
}
/**
* Returns the current container page resource.<p>
*
* @return the current container page resource
*/
public CmsJspResourceWrapper getPageResource() {
try {
if (m_pageResource == null) {
// get the container page itself, checking the history first
m_pageResource = CmsJspResourceWrapper.wrap(
m_cms,
(CmsResource)CmsHistoryResourceHandler.getHistoryResource(m_request));
if (m_pageResource == null) {
m_pageResource = CmsJspResourceWrapper.wrap(
m_cms,
m_cms.readResource(
m_cms.getRequestContext().getUri(),
CmsResourceFilter.ignoreExpirationOffline(m_cms)));
}
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
return m_pageResource;
}
/**
* Returns the parent container to the current container if available.<p>
*
* @return the parent container
*/
public CmsContainerBean getParentContainer() {
CmsContainerBean result = null;
if ((getContainer() != null) && (getContainer().getParentInstanceId() != null)) {
result = m_parentContainers.get(getContainer().getParentInstanceId());
}
return result;
}
/**
* Returns the instance id parent container mapping.<p>
*
* @return the instance id parent container mapping
*/
public Map<String, CmsContainerBean> getParentContainers() {
if (m_parentContainers == null) {
initPageData();
}
return Collections.unmodifiableMap(m_parentContainers);
}
/**
* Returns the parent element to the current element if available.<p>
*
* @return the parent element or null
*/
public CmsContainerElementBean getParentElement() {
return getParentElement(getElement());
}
/**
* Gets the set of plugin group names.
*
* @return the set of plugin group names
*/
public Set<String> getPluginGroups() {
return getPlugins().keySet();
}
/**
* Gets the map of plugins by group.
*
* @return the map of active plugins by group
*/
public Map<String, List<CmsTemplatePluginWrapper>> getPlugins() {
if (m_templatePlugins == null) {
final Multimap<String, CmsTemplatePlugin> templatePluginsMultimap = new CmsTemplatePluginFinder(
this).getTemplatePlugins();
Map<String, List<CmsTemplatePluginWrapper>> templatePlugins = new HashMap<>();
for (String key : templatePluginsMultimap.keySet()) {
List<CmsTemplatePluginWrapper> wrappers = new ArrayList<>();
for (CmsTemplatePlugin plugin : templatePluginsMultimap.get(key)) {
wrappers.add(new CmsTemplatePluginWrapper(m_cms, plugin));
}
templatePlugins.put(key, Collections.unmodifiableList(wrappers));
}
m_templatePlugins = templatePlugins;
}
return m_templatePlugins;
}
/**
* JSP EL accessor method for retrieving the preview formatters.<p>
*
* @return a lazy map for accessing preview formatters
*/
public Map<String, String> getPreviewFormatter() {
Transformer transformer = new Transformer() {
@Override
public Object transform(Object uri) {
try {
String rootPath = m_cms.getRequestContext().addSiteRoot((String)uri);
CmsResource resource = m_cms.readResource((String)uri);
CmsADEManager adeManager = OpenCms.getADEManager();
CmsADEConfigData configData = adeManager.lookupConfiguration(m_cms, rootPath);
CmsFormatterConfiguration formatterConfig = configData.getFormatters(m_cms, resource);
if (formatterConfig == null) {
return "";
}
I_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 "";
}
}
};
return CmsCollectionsGenericWrapper.createLazyMap(transformer);
}
/**
* Reads all sub-categories below the provided category.
* @return The map from the provided category to it's sub-categories in a {@link CmsJspCategoryAccessBean}.
*/
public Map<String, CmsJspCategoryAccessBean> getReadAllSubCategories() {
if (null == m_allSubCategories) {
m_allSubCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
@Override
public Object transform(Object categoryPath) {
try {
List<CmsCategory> categories = CmsCategoryService.getInstance().readCategories(
m_cms,
(String)categoryPath,
true,
m_cms.getRequestContext().getUri());
CmsJspCategoryAccessBean result = new CmsJspCategoryAccessBean(
m_cms,
categories,
(String)categoryPath);
return result;
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
return null;
}
}
});
}
return m_allSubCategories;
}
/**
* Reads the categories assigned to the currently requested URI.
* @return the categories assigned to the currently requested URI.
*/
public CmsJspCategoryAccessBean getReadCategories() {
return getReadResourceCategories().get(getRequestContext().getRootUri());
}
/**
* Transforms the category path of a category to the category.
* @return a map from root or site path to category.
*/
public Map<String, CmsCategory> getReadCategory() {
if (null == m_categories) {
m_categories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
public Object transform(Object categoryPath) {
try {
CmsCategoryService catService = CmsCategoryService.getInstance();
return catService.localizeCategory(
m_cms,
catService.readCategory(m_cms, (String)categoryPath, getRequestContext().getUri()),
m_cms.getRequestContext().getLocale());
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
return null;
}
}
});
}
return m_categories;
}
/**
* Transforms the category path to the list of all categories on that path.<p>
*
* Example: For path <code>"location/europe/"</code>
* the list <code>[getReadCategory.get("location/"),getReadCategory.get("location/europe/")]</code>
* is returned.
* @return a map from a category path to list of categories on that path.
*/
public Map<String, List<CmsCategory>> getReadPathCategories() {
if (null == m_pathCategories) {
m_pathCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
public Object transform(Object categoryPath) {
List<CmsCategory> result = new ArrayList<CmsCategory>();
String path = (String)categoryPath;
if ((null == path) || (path.length() <= 1)) {
return result;
}
//cut last slash
path = path.substring(0, path.length() - 1);
List<String> pathParts = Arrays.asList(path.split("/"));
String currentPath = "";
for (String part : pathParts) {
currentPath += part + "/";
CmsCategory category = getReadCategory().get(currentPath);
if (null != category) {
result.add(category);
}
}
return CmsCategoryService.getInstance().localizeCategories(
m_cms,
result,
m_cms.getRequestContext().getLocale());
}
});
}
return m_pathCategories;
}
/**
* Reads the categories assigned to a resource.
*
* @return map from the resource path (root path) to the assigned categories
*/
public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {
if (null == m_resourceCategories) {
m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
public Object transform(Object resourceName) {
try {
CmsResource resource = m_cms.readResource(
getRequestContext().removeSiteRoot((String)resourceName));
return new CmsJspCategoryAccessBean(m_cms, resource);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
return null;
}
}
});
}
return m_resourceCategories;
}
/**
* Returns a HTML comment string that will cause the container page editor to reload the page if the element or its settings
* were edited.<p>
*
* @return the reload marker
*/
public String getReloadMarker() {
if (m_cms.getRequestContext().getCurrentProject().isOnlineProject()) {
return ""; // reload marker is not needed in Online mode
} else {
return CmsGwtConstants.FORMATTER_RELOAD_MARKER;
}
}
/**
* Gets the stored request.
*
* @return the stored request
*/
public ServletRequest getRequest() {
return m_request;
}
/**
* Returns the request context.<p>
*
* @return the request context
*/
public CmsRequestContext getRequestContext() {
return m_cms.getRequestContext();
}
/**
* Returns the current site.<p>
*
* @return the current site
*/
public CmsSite getSite() {
return OpenCms.getSiteManager().getSiteForSiteRoot(m_cms.getRequestContext().getSiteRoot());
}
/**
* Gets the wrapper for the sitemap configuration.
*
* @return the wrapper object for the sitemap configuration
*/
public CmsJspSitemapConfigWrapper getSitemapConfig() {
return new CmsJspSitemapConfigWrapper(this);
}
/**
* Transforms root paths to site paths.
*
* @return lazy map from root paths to site paths.
*
* @see CmsRequestContext#removeSiteRoot(String)
*/
public Map<String, String> getSitePath() {
if (m_sitePaths == null) {
m_sitePaths = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
public Object transform(Object rootPath) {
if (rootPath instanceof String) {
return getRequestContext().removeSiteRoot((String)rootPath);
}
return null;
}
});
}
return m_sitePaths;
}
/**
* 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 the system information.<p>
*
* @return the system information
*/
public CmsSystemInfo getSystemInfo() {
return OpenCms.getSystemInfo();
}
/**
* Gets a bean containing information about the current template.<p>
*
* @return the template information bean
*/
public TemplateBean getTemplate() {
TemplateBean templateBean = getRequestAttribute(CmsTemplateContextManager.ATTR_TEMPLATE_BEAN);
if (templateBean == null) {
templateBean = new TemplateBean("", "");
}
return templateBean;
}
/**
* Returns the title of a page delivered from OpenCms, usually used for the <code><title></code> tag of
* a HTML page.<p>
*
* If no title information has been found, the empty String "" is returned.<p>
*
* @return the title of the current page
*/
public String getTitle() {
return getLocaleSpecificTitle(null);
}
/**
* Get the title and read the Title property according the provided locale.
* @return The map from locales to the locale specific titles.
*/
public Map<String, String> getTitleLocale() {
if (m_localeTitles == null) {
m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
public Object transform(Object inputLocale) {
Locale locale = null;
if (null != inputLocale) {
if (inputLocale instanceof Locale) {
locale = (Locale)inputLocale;
} else if (inputLocale instanceof String) {
try {
locale = LocaleUtils.toLocale((String)inputLocale);
} catch (IllegalArgumentException | NullPointerException e) {
// do nothing, just go on without locale
}
}
}
return getLocaleSpecificTitle(locale);
}
});
}
return m_localeTitles;
}
/**
* Returns a lazy initialized Map that provides the detail page link as a value when given the name of a
* resource type as a key.<p>
*
* The provided Map key is assumed to be the name of a resource type that has a detail page configured.<p>
*
* Usage example on a JSP with the JSTL:<pre>
* <a href=${cms.typeDetailPage['bs-blog']} />
* </pre>
*
* @return a lazy initialized Map that provides the detail page link as a value when given the name of a
* resource type as a key
*
* @see #getFunctionDetailPage()
*/
public Map<String, String> getTypeDetailPage() {
if (m_typeDetailPage == null) {
m_typeDetailPage = CmsCollectionsGenericWrapper.createLazyMap(new CmsDetailLookupTransformer(""));
}
return m_typeDetailPage;
}
/**
* 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);
}
/**
* Returns an EL access wrapper map for the given object.<p>
*
* If the object is a {@link CmsResource}, then a {@link CmsJspResourceWrapper} is returned.
* Otherwise the object is wrapped in a {@link CmsJspObjectValueWrapper}.<p>
*
* If the object is already is a wrapper, it is returned unchanged.<p>
*
* @return an EL access wrapper map for the given object
*/
public Map<Object, Object> getWrap() {
return CmsCollectionsGenericWrapper.createLazyMap(obj -> {
if ((obj instanceof A_CmsJspValueWrapper) || (obj instanceof CmsJspResourceWrapper)) {
return obj;
} else if (obj instanceof CmsResource) {
return CmsJspResourceWrapper.wrap(m_cms, (CmsResource)obj);
} else {
return CmsJspObjectValueWrapper.createWrapper(m_cms, obj);
}
});
}
/**
* Initializes the requested container page.<p>
*
* @throws CmsException in case reading the requested resource fails
*/
public void initPage() throws CmsException {
if ((m_page == null) && (m_cms != null)) {
String requestUri = m_cms.getRequestContext().getUri();
// get the container page itself, checking the history first
CmsResource pageResource = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(m_request);
if (pageResource == null) {
pageResource = m_cms.readResource(requestUri, CmsResourceFilter.ignoreExpirationOffline(m_cms));
}
m_config = OpenCms.getADEManager().lookupConfigurationWithCache(m_cms, pageResource.getRootPath());
m_page = getPage(pageResource);
m_page = CmsTemplateMapper.get(m_request).transformContainerpageBean(
m_cms,
m_page,
pageResource.getRootPath());
}
}
/**
* Returns <code>true</code in case a detail page is available for the current element.<p>
*
* @return <code>true</code in case a detail page is available for the current element
*/
public boolean isDetailPageAvailable() {
boolean result = false;
if ((m_cms != null)
&& (m_element != null)
&& !m_element.isInMemoryOnly()
&& (m_element.getResource() != null)) {
try {
String detailPage = OpenCms.getADEManager().getDetailPageHandler().getDetailPage(
m_cms,
m_element.getResource().getRootPath(),
m_cms.getRequestContext().getUri(),
null);
result = detailPage != null;
} catch (Exception e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
return result;
}
/**
* 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 if the page is in drag mode.<p>
*
* @return if the page is in drag mode
*/
public boolean isDragMode() {
return m_isDragMode;
}
/**
* 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;
}
/**
* Returns if the current element is a model group.<p>
*
* @return <code>true</code> if the current element is a model group
*/
public boolean isModelGroupElement() {
return (m_element != null) && !m_element.isInMemoryOnly() && isModelGroupPage() && m_element.isModelGroup();
}
/**
* Returns if the current page is used to manage model groups.<p>
*
* @return <code>true</code> if the current page is used to manage model groups
*/
public boolean isModelGroupPage() {
CmsResource page = getPageResource();
return (page != null) && CmsContainerpageService.isEditingModelGroups(m_cms, page);
}
/**
* 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 detail only page.<p>
*
* @param detailOnlyPage the detail only page to set
*/
public void setDetailOnlyPage(CmsContainerPageBean detailOnlyPage) {
m_detailOnlyPage = detailOnlyPage;
clearPageData();
}
/**
* Sets if the page is in drag mode.<p>
*
* @param isDragMode if the page is in drag mode
*/
public void setDragMode(boolean isDragMode) {
m_isDragMode = isDragMode;
}
/**
* 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;
clearPageData();
}
/**
* 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) {
LOG.error(e.getLocalizedMessage(), e);
m_cms = cms;
}
try {
m_config = OpenCms.getADEManager().lookupConfigurationWithCache(cms, cms.getRequestContext().getRootUri());
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
/**
* 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;
m_request = cmsFlexRequest;
}
/**
* Accessor for the CmsObject.
*
* @return the CmsObject
*/
protected CmsObject getCmsObject() {
return m_cms;
}
/**
* Returns the formatter configuration to the given element.<p>
*
* @param element the element
*
* @return the formatter configuration
*/
protected I_CmsFormatterBean getElementFormatter(CmsContainerElementBean element) {
if (m_elementInstances == null) {
initPageData();
}
I_CmsFormatterBean formatter = null;
CmsContainerBean container = m_parentContainers.get(element.getInstanceId());
if (container == null) {
// use the current container
container = getContainer();
}
if (container != null) {
String containerName = container.getName();
Map<String, String> settings = element.getSettings();
if (settings != null) {
String formatterConfigId = settings.get(CmsFormatterConfig.getSettingsKeyForContainer(containerName));
I_CmsFormatterBean dynamicFmt = m_config.findFormatter(formatterConfigId);
if (dynamicFmt != null) {
formatter = dynamicFmt;
}
}
if (formatter == null) {
try {
CmsResource resource = m_cms.readResource(m_cms.getRequestContext().getUri());
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(
m_cms,
resource.getRootPath());
CmsFormatterConfiguration formatters = config.getFormatters(m_cms, resource);
int width = -2;
try {
width = Integer.parseInt(container.getWidth());
} catch (Exception e) {
LOG.debug(e.getLocalizedMessage(), e);
}
formatter = formatters.getDefaultSchemaFormatter(container.getType(), width);
} catch (CmsException e1) {
if (LOG.isWarnEnabled()) {
LOG.warn(e1.getLocalizedMessage(), e1);
}
}
}
}
return formatter;
}
/**
* Returns the title according to the given locale.
* @param locale the locale for which the title should be read.
* @return the title according to the given locale
*/
protected String getLocaleSpecificTitle(Locale locale) {
String result = null;
try {
if (isDetailRequest()) {
// this is a request to a detail page
CmsResource res = getDetailContent();
CmsFile file = m_cms.readFile(res);
CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file);
result = content.getHandler().getTitleMapping(m_cms, content, m_cms.getRequestContext().getLocale());
if (result == null) {
// title not found, maybe no mapping OR not available in the current locale
// read the title of the detail resource as fall back (may contain mapping from another locale)
result = m_cms.readPropertyObject(
res,
CmsPropertyDefinition.PROPERTY_TITLE,
false,
locale).getValue();
}
}
if (result == null) {
// read the title of the requested resource as fall back
result = m_cms.readPropertyObject(
m_cms.getRequestContext().getUri(),
CmsPropertyDefinition.PROPERTY_TITLE,
true,
locale).getValue();
}
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), e);
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {
result = "";
}
return result;
}
/**
* Returns the parent element if available.<p>
*
* @param element the element
*
* @return the parent element or null
*/
protected CmsContainerElementBean getParentElement(CmsContainerElementBean element) {
if (m_elementInstances == null) {
initPageData();
}
CmsContainerElementBean parent = null;
CmsContainerBean cont = m_parentContainers.get(element.getInstanceId());
if ((cont != null) && cont.isNestedContainer()) {
parent = m_elementInstances.get(cont.getParentInstanceId());
}
return parent;
}
/**
* Accessor for the sitemap configuration.
*
* @return the sitemap configuration
*/
protected CmsADEConfigData getSitemapConfigInternal() {
return m_config;
}
/**
* 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;
}
/**
* Adds the mappings of the given formatter configuration.<p>
*
* @param formatterBean the formatter bean
* @param elementId the element content structure id
* @param resolver The macro resolver used on key and default value of the mappings
* @param isDetailContent in case of a detail content
*/
private void addMappingsForFormatter(
I_CmsFormatterBean formatterBean,
CmsUUID elementId,
CmsMacroResolver resolver,
boolean isDetailContent) {
if ((formatterBean != null) && (formatterBean.getMetaMappings() != null)) {
for (CmsMetaMapping map : formatterBean.getMetaMappings()) {
String key = map.getKey();
key = resolver.resolveMacros(key);
// the detail content mapping overrides other mappings
if (isDetailContent
|| !m_metaMappings.containsKey(key)
|| (m_metaMappings.get(key).m_order <= map.getOrder())) {
MetaMapping mapping = new MetaMapping();
mapping.m_key = key;
mapping.m_elementXPath = map.getElement();
mapping.m_defaultValue = resolver.resolveMacros(map.getDefaultValue());
mapping.m_order = map.getOrder();
mapping.m_contentId = elementId;
m_metaMappings.put(key, mapping);
}
}
}
}
/**
* Clears the page element data.<p>
*/
private void clearPageData() {
m_elementInstances = null;
m_parentContainers = null;
}
/**
* Returns the container page bean for the give resource.<p>
*
* @param pageResource the resource
*
* @return the container page bean
*
* @throws CmsException in case reading the page bean fails
*/
private CmsContainerPageBean getPage(CmsResource pageResource) throws CmsException {
CmsContainerPageBean result = null;
if ((pageResource != null) && CmsResourceTypeXmlContainerPage.isContainerPage(pageResource)) {
CmsXmlContainerPage xmlContainerPage = CmsXmlContainerPageFactory.unmarshal(m_cms, pageResource, m_request);
result = xmlContainerPage.getContainerPage(m_cms);
CmsModelGroupHelper modelHelper = new CmsModelGroupHelper(
m_cms,
OpenCms.getADEManager().lookupConfiguration(m_cms, pageResource.getRootPath()),
CmsJspTagEditable.isEditableRequest(m_request) && (m_request instanceof HttpServletRequest)
? CmsADESessionCache.getCache((HttpServletRequest)m_request, m_cms)
: null,
CmsContainerpageService.isEditingModelGroups(m_cms, pageResource));
result = modelHelper.readModelGroups(xmlContainerPage.getContainerPage(m_cms));
}
return result;
}
/**
* Convenience method for getting a request attribute without an explicit cast.<p>
*
* @param name the attribute name
* @return the request attribute
*/
@SuppressWarnings("unchecked")
private <A> A getRequestAttribute(String name) {
Object attribute = m_request.getAttribute(name);
return attribute != null ? (A)attribute : null;
}
/**
* Initializes the mapping configuration.<p>
*/
private void initMetaMappings() {
if (m_metaMappings == null) {
m_metaMappings = new HashMap<String, MetaMapping>();
try {
initPage();
CmsMacroResolver resolver = new CmsMacroResolver();
resolver.setKeepEmptyMacros(true);
resolver.setCmsObject(m_cms);
resolver.setMessages(OpenCms.getWorkplaceManager().getMessages(getLocale()));
CmsResourceFilter filter = getIsEditMode()
? CmsResourceFilter.IGNORE_EXPIRATION
: CmsResourceFilter.DEFAULT;
for (CmsContainerBean container : m_page.getContainers().values()) {
for (CmsContainerElementBean element : container.getElements()) {
String settingsKey = CmsFormatterConfig.getSettingsKeyForContainer(container.getName());
String formatterConfigId = element.getSettings() != null
? element.getSettings().get(settingsKey)
: null;
I_CmsFormatterBean formatterBean = null;
formatterBean = m_config.findFormatter(formatterConfigId);
if ((formatterBean != null)
&& formatterBean.useMetaMappingsForNormalElements()
&& m_cms.existsResource(element.getId(), filter)) {
addMappingsForFormatter(formatterBean, element.getId(), resolver, false);
}
}
}
if (getDetailContentId() != null) {
try {
CmsResource detailContent = m_cms.readResource(
getDetailContentId(),
CmsResourceFilter.ignoreExpirationOffline(m_cms));
CmsFormatterConfiguration config = OpenCms.getADEManager().lookupConfiguration(
m_cms,
m_cms.getRequestContext().getRootUri()).getFormatters(m_cms, detailContent);
for (I_CmsFormatterBean formatter : config.getDetailFormatters()) {
addMappingsForFormatter(formatter, getDetailContentId(), resolver, true);
}
} catch (CmsException e) {
LOG.error(
Messages.get().getBundle().key(
Messages.ERR_READING_REQUIRED_RESOURCE_1,
getDetailContentId()),
e);
}
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
/**
* Initializes the page element data.<p>
*/
private void initPageData() {
m_elementInstances = new HashMap<String, CmsContainerElementBean>();
m_parentContainers = new HashMap<String, CmsContainerBean>();
if (m_page != null) {
for (CmsContainerBean container : m_page.getContainers().values()) {
for (CmsContainerElementBean element : container.getElements()) {
m_elementInstances.put(element.getInstanceId(), element);
m_parentContainers.put(element.getInstanceId(), container);
try {
if (element.isGroupContainer(m_cms) || element.isInheritedContainer(m_cms)) {
List<CmsContainerElementBean> children;
if (element.isGroupContainer(m_cms)) {
children = CmsJspTagContainer.getGroupContainerElements(
m_cms,
element,
m_request,
container.getType());
} else {
children = CmsJspTagContainer.getInheritedContainerElements(m_cms, element);
}
for (CmsContainerElementBean childElement : children) {
m_elementInstances.put(childElement.getInstanceId(), childElement);
m_parentContainers.put(childElement.getInstanceId(), container);
}
}
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
}
// also add detail only data
if (m_detailOnlyPage != null) {
for (CmsContainerBean container : m_detailOnlyPage.getContainers().values()) {
for (CmsContainerElementBean element : container.getElements()) {
m_elementInstances.put(element.getInstanceId(), element);
m_parentContainers.put(element.getInstanceId(), container);
}
}
}
}
}
}
|
package org.pentaho.di.trans.steps.mapping;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Messages;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.resource.ResourceDefinition;
import org.pentaho.di.resource.ResourceEntry;
import org.pentaho.di.resource.ResourceNamingInterface;
import org.pentaho.di.resource.ResourceReference;
import org.pentaho.di.resource.ResourceEntry.ResourceType;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.mappinginput.MappingInputMeta;
import org.pentaho.di.trans.steps.mappingoutput.MappingOutputMeta;
import org.w3c.dom.Node;
/**
* Meta-data for the Mapping step: contains name of the (sub-)transformation to execute
*
* @since 22-nov-2005
* @author Matt
*
*/
public class MappingMeta extends BaseStepMeta implements StepMetaInterface
{
private String transName;
private String fileName;
private String directoryPath;
private List<MappingIODefinition> inputMappings;
private List<MappingIODefinition> outputMappings;
private MappingParameters mappingParameters;
/*
* This repository object is injected from the outside at runtime or at design time.
* It comes from either Spoon or Trans
*/
private Repository repository;
public MappingMeta()
{
super(); // allocate BaseStepMeta
inputMappings = new ArrayList<MappingIODefinition>();
outputMappings = new ArrayList<MappingIODefinition>();
mappingParameters = new MappingParameters();
}
public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException
{
setDefault();
try
{
readData(stepnode);
}
catch(KettleException e)
{
throw new KettleXMLException(Messages.getString("MappingMeta.Exception.ErrorLoadingTransformationStepFromXML"), e); //$NON-NLS-1$
}
}
public Object clone()
{
Object retval = super.clone();
return retval;
}
private void readData(Node stepnode) throws KettleException
{
transName = XMLHandler.getTagValue(stepnode, "trans_name"); //$NON-NLS-1$
fileName = XMLHandler.getTagValue(stepnode, "filename"); //$NON-NLS-1$
directoryPath = XMLHandler.getTagValue(stepnode, "directory_path"); //$NON-NLS-1$
Node mappingsNode = XMLHandler.getSubNode(stepnode, "mappings"); //$NON-NLS-1$
if (mappingsNode!=null)
{
// Read all the input mapping definitions...
Node inputNode = XMLHandler.getSubNode(mappingsNode, "input"); //$NON-NLS-1$
int nrInputMappings = XMLHandler.countNodes(inputNode, MappingIODefinition.XML_TAG); //$NON-NLS-1$
for (int i=0;i<nrInputMappings;i++) {
Node mappingNode = XMLHandler.getSubNodeByNr(inputNode, MappingIODefinition.XML_TAG, i);
MappingIODefinition inputMappingDefinition = new MappingIODefinition(mappingNode);
inputMappings.add(inputMappingDefinition);
}
Node outputNode = XMLHandler.getSubNode(mappingsNode, "output"); //$NON-NLS-1$
int nrOutputMappings = XMLHandler.countNodes(outputNode, MappingIODefinition.XML_TAG); //$NON-NLS-1$
for (int i=0;i<nrOutputMappings;i++) {
Node mappingNode = XMLHandler.getSubNodeByNr(outputNode, MappingIODefinition.XML_TAG, i);
MappingIODefinition outputMappingDefinition = new MappingIODefinition(mappingNode);
outputMappings.add(outputMappingDefinition);
}
// Load the mapping parameters too..
Node mappingParametersNode = XMLHandler.getSubNode(mappingsNode, MappingParameters.XML_TAG);
mappingParameters = new MappingParameters(mappingParametersNode);
}
else
{
// backward compatibility...
Node inputNode = XMLHandler.getSubNode(stepnode, "input"); //$NON-NLS-1$
Node outputNode = XMLHandler.getSubNode(stepnode, "output"); //$NON-NLS-1$
int nrInput = XMLHandler.countNodes(inputNode, "connector"); //$NON-NLS-1$
int nrOutput = XMLHandler.countNodes(outputNode, "connector"); //$NON-NLS-1$
MappingIODefinition inputMappingDefinition = new MappingIODefinition(); // null means: auto-detect
inputMappingDefinition.setMainDataPath(true);
for (int i = 0; i < nrInput; i++) {
Node inputConnector = XMLHandler.getSubNodeByNr(inputNode, "connector", i); //$NON-NLS-1$
String inputField = XMLHandler.getTagValue(inputConnector, "field"); //$NON-NLS-1$
String inputMapping = XMLHandler.getTagValue(inputConnector, "mapping"); //$NON-NLS-1$
inputMappingDefinition.getValueRenames().add( new MappingValueRename(inputField, inputMapping) );
}
MappingIODefinition outputMappingDefinition = new MappingIODefinition(); // null means: auto-detect
outputMappingDefinition.setMainDataPath(true);
for (int i = 0; i < nrOutput; i++) {
Node outputConnector = XMLHandler.getSubNodeByNr(outputNode, "connector", i); //$NON-NLS-1$
String outputField = XMLHandler.getTagValue(outputConnector, "field"); //$NON-NLS-1$
String outputMapping = XMLHandler.getTagValue(outputConnector, "mapping"); //$NON-NLS-1$
outputMappingDefinition.getValueRenames().add( new MappingValueRename(outputMapping, outputField) );
}
// Don't forget to add these to the input and output mapping definitions...
inputMappings.add(inputMappingDefinition);
outputMappings.add(outputMappingDefinition);
// The default is to have no mapping parameters: the concept didn't exist before.
mappingParameters = new MappingParameters();
}
}
public void allocate()
{
}
public String getXML()
{
StringBuffer retval = new StringBuffer(300);
retval.append(" ").append(XMLHandler.addTagValue("trans_name", transName) ); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("filename", fileName )); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.addTagValue("directory_path", directoryPath )); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.openTag("mappings")).append(Const.CR); //$NON-NLS-1$ $NON-NLS-2$
retval.append(" ").append(XMLHandler.openTag("input")).append(Const.CR); //$NON-NLS-1$ $NON-NLS-2$
for (int i=0;i<inputMappings.size();i++)
{
retval.append(inputMappings.get(i).getXML());
}
retval.append(" ").append(XMLHandler.closeTag("input")).append(Const.CR); //$NON-NLS-1$ $NON-NLS-2$
retval.append(" ").append(XMLHandler.openTag("output")).append(Const.CR); //$NON-NLS-1$ $NON-NLS-2$
for (int i=0;i<outputMappings.size();i++)
{
retval.append(outputMappings.get(i).getXML());
}
retval.append(" ").append(XMLHandler.closeTag("output")).append(Const.CR); //$NON-NLS-1$ $NON-NLS-2$
// Add the mapping parameters too
retval.append(" ").append(mappingParameters.getXML()).append(Const.CR); //$NON-NLS-1$
retval.append(" ").append(XMLHandler.closeTag("mappings")).append(Const.CR); //$NON-NLS-1$ $NON-NLS-2$
return retval.toString();
}
public void setDefault()
{
allocate();
}
public void getFields(RowMetaInterface row, String origin, RowMetaInterface info[], StepMeta nextStep, VariableSpace space) throws KettleStepException {
// First load some interesting data...
// Then see which fields get added to the row.
TransMeta mappingTransMeta = null;
try
{
mappingTransMeta = loadMappingMeta(fileName, transName, directoryPath, repository, space);
}
catch(KettleException e)
{
throw new KettleStepException(Messages.getString("MappingMeta.Exception.UnableToLoadMappingTransformation"), e);
}
// Keep track of all the fields that need renaming...
List<MappingValueRename> inputRenameList = new ArrayList<MappingValueRename>();
/*
* Before we ask the mapping outputs anything, we should teach the mapping input steps in the sub-transformation
* about the data coming in...
*/
for (MappingIODefinition definition : inputMappings) {
RowMetaInterface inputRowMeta;
if (definition.isMainDataPath() || Const.isEmpty(definition.getInputStepname()) ) {
// The row metadata, what we pass to the mapping input step definition.getOutputStep(), is "row"
// However, we do need to re-map some fields...
inputRowMeta = row.clone();
for (MappingValueRename valueRename : definition.getValueRenames()) {
ValueMetaInterface valueMeta = inputRowMeta.searchValueMeta(valueRename.getSourceValueName());
if (valueMeta==null) {
throw new KettleStepException(Messages.getString("MappingMeta.Exception.UnableToFindField", valueRename.getSourceValueName()));
}
valueMeta.setName(valueRename.getTargetValueName());
}
}
else {
// The row metadata that goes to the info mapping input comes from the specified step
// In fact, it's one of the info steps that is going to contain this information...
String[] infoSteps = getInfoSteps();
int infoStepIndex = Const.indexOfString(definition.getInputStepname(), infoSteps);
if (infoStepIndex<0) {
throw new KettleStepException(Messages.getString("MappingMeta.Exception.UnableToFindMetadataInfo", definition.getInputStepname()));
}
inputRowMeta = info[infoStepIndex].clone();
}
// What is this mapping input step?
StepMeta mappingInputStep = mappingTransMeta.findMappingInputStep(definition.getOutputStepname());
// We're certain it's a MappingInput step...
MappingInputMeta mappingInputMeta = (MappingInputMeta) mappingInputStep.getStepMetaInterface();
// Inform the mapping input step about what it's going to receive...
mappingInputMeta.setInputRowMeta(inputRowMeta);
// What values are we changing names for?
mappingInputMeta.setValueRenames(definition.getValueRenames());
// Keep a list of the input rename values that need to be changed back at the output
if (definition.isRenamingOnOutput()) Mapping.addInputRenames(inputRenameList, definition.getValueRenames());
}
// All the mapping steps now know what they will be receiving.
// That also means that the sub-transformation / mapping has everything it needs.
// So that means that the MappingOutput steps know exactly what the output is going to be.
// That could basically be anything.
// It also could have absolutely no resemblance to what came in on the input.
// The relative old approach is therefore no longer suited.
// OK, but what we *can* do is have the MappingOutput step rename the appropriate fields.
// The mapping step will tell this step how it's done.
// Let's look for the mapping output step that is relevant for this actual call...
MappingIODefinition mappingOutputDefinition = null;
if (nextStep==null) {
// This is the main step we read from...
// Look up the main step to write to.
// This is the output mapping definition with "main path" enabled.
for (MappingIODefinition definition : outputMappings) {
if (definition.isMainDataPath() || Const.isEmpty(definition.getOutputStepname())) {
// This is the definition to use...
mappingOutputDefinition = definition;
}
}
}
else {
// Is there an output mapping definition for this step?
// If so, we can look up the Mapping output step to see what has changed.
for (MappingIODefinition definition : outputMappings) {
if (nextStep.getName().equals(definition.getOutputStepname()) ||
definition.isMainDataPath() ||
Const.isEmpty(definition.getOutputStepname())
) {
mappingOutputDefinition = definition;
}
}
}
if (mappingOutputDefinition==null) {
throw new KettleStepException(Messages.getString("MappingMeta.Exception.UnableToFindMappingDefinition"));
}
// OK, now find the mapping output step in the mapping...
// This method in TransMeta takes into account a number of things, such as the step not specified, etc.
// The method never returns null but throws an exception.
StepMeta mappingOutputStep = mappingTransMeta.findMappingOutputStep(mappingOutputDefinition.getInputStepname());
// We know it's a mapping output step...
MappingOutputMeta mappingOutputMeta = (MappingOutputMeta) mappingOutputStep.getStepMetaInterface();
// Change a few columns.
mappingOutputMeta.setOutputValueRenames(mappingOutputDefinition.getValueRenames());
// Perhaps we need to change a few input columns back to the original?
mappingOutputMeta.setInputValueRenames(inputRenameList);
// Now we know wat's going to come out of there...
// This is going to be the full row, including all the remapping, etc.
RowMetaInterface mappingOutputRowMeta = mappingTransMeta.getStepFields(mappingOutputStep);
row.clear();
row.addRowMeta(mappingOutputRowMeta);
}
@Override
public String[] getInfoSteps() {
List<String> infoSteps = new ArrayList<String>();
// The infosteps are those steps that are specified in the input mappings
for (MappingIODefinition definition : inputMappings) {
if (!definition.isMainDataPath() && !Const.isEmpty(definition.getInputStepname())) {
infoSteps.add(definition.getInputStepname());
}
}
if (infoSteps.isEmpty()) return null;
return infoSteps.toArray(new String[infoSteps.size()]);
}
@Override
public String[] getTargetSteps() {
List<String> targetSteps = new ArrayList<String>();
// The infosteps are those steps that are specified in the input mappings
for (MappingIODefinition definition : outputMappings) {
if (!definition.isMainDataPath() && !Const.isEmpty(definition.getOutputStepname())) {
targetSteps.add(definition.getOutputStepname());
}
}
if (targetSteps.isEmpty()) return null;
return targetSteps.toArray(new String[targetSteps.size()]);
}
public void readRep(Repository rep, long id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException
{
/*
* TODO re-enable repository support
*
transName = rep.getStepAttributeString(id_step, "trans_name"); //$NON-NLS-1$
fileName = rep.getStepAttributeString(id_step, "filename"); //$NON-NLS-1$
directoryPath = rep.getStepAttributeString(id_step, "directory_path"); //$NON-NLS-1$
int nrInput = rep.countNrStepAttributes(id_step, "input_field"); //$NON-NLS-1$
int nrOutput = rep.countNrStepAttributes(id_step, "output_field"); //$NON-NLS-1$
allocate(nrInput, nrOutput);
for (int i=0;i<nrInput;i++)
{
inputField[i] = rep.getStepAttributeString(id_step, i, "input_field"); //$NON-NLS-1$
inputMapping[i] = rep.getStepAttributeString(id_step, i, "input_mapping"); //$NON-NLS-1$
}
for (int i=0;i<nrOutput;i++)
{
outputField[i] = rep.getStepAttributeString(id_step, i, "output_field"); //$NON-NLS-1$
outputMapping[i] = rep.getStepAttributeString(id_step, i, "output_mapping"); //$NON-NLS-1$
}
*/
}
public void saveRep(Repository rep, long id_transformation, long id_step) throws KettleException
{
/*
* TODO re-enable repository support
*
rep.saveStepAttribute(id_transformation, id_step, "filename", fileName); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "trans_name", transName); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, "directory_path", directoryPath); //$NON-NLS-1$
if (inputField!=null)
for (int i=0;i<inputField.length;i++)
{
rep.saveStepAttribute(id_transformation, id_step, i, "input_field", inputField[i]); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, i, "input_mapping", inputMapping[i]); //$NON-NLS-1$
}
if (outputField!=null)
for (int i=0;i<outputField.length;i++)
{
rep.saveStepAttribute(id_transformation, id_step, i, "output_field", outputField[i]); //$NON-NLS-1$
rep.saveStepAttribute(id_transformation, id_step, i, "output_mapping", outputMapping[i]); //$NON-NLS-1$
}
*/
}
public synchronized static final TransMeta loadMappingMeta(String fileName, String transName, String directoryPath, Repository rep, VariableSpace space) throws KettleException
{
TransMeta mappingTransMeta = null;
String realFilename = space.environmentSubstitute(fileName);
String realTransname = space.environmentSubstitute(transName);
if ( !Const.isEmpty(realFilename))
{
try
{
// OK, load the meta-data from file...
mappingTransMeta = new TransMeta( realFilename, false ); // don't set internal variables: they belong to the parent thread!
LogWriter.getInstance().logDetailed("Loading Mapping from repository", "Mapping transformation was loaded from XML file ["+realFilename+"]");
// mappingTransMeta.setFilename(fileName);
}
catch(Exception e)
{
LogWriter.getInstance().logError("Loading Mapping from XML", "Unable to load transformation ["+realFilename+"] : "+e.toString());
LogWriter.getInstance().logError("Loading Mapping from XML", Const.getStackTracker(e));
throw new KettleException(e);
}
}
else
{
// OK, load the meta-data from the repository...
if (!Const.isEmpty(realTransname) && directoryPath!=null && rep!=null)
{
RepositoryDirectory repdir = rep.getDirectoryTree().findDirectory(directoryPath);
if (repdir!=null)
{
try
{
mappingTransMeta = new TransMeta(rep, realTransname, repdir);
LogWriter.getInstance().logDetailed("Loading Mapping from repository", "Mapping transformation ["+realTransname+"] was loaded from the repository");
}
catch(Exception e)
{
LogWriter.getInstance().logError("Loading Mapping from repository", "Unable to load transformation ["+realTransname+"] : "+e.toString());
LogWriter.getInstance().logError("Loading Mapping from repository", Const.getStackTracker(e));
}
}
else
{
throw new KettleException(Messages.getString("MappingMeta.Exception.UnableToLoadTransformation",realTransname)+directoryPath); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
return mappingTransMeta;
}
public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepinfo, RowMetaInterface prev, String input[], String output[], RowMetaInterface info)
{
CheckResult cr;
if (prev==null || prev.size()==0)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_WARNING, Messages.getString("MappingMeta.CheckResult.NotReceivingAnyFields"), stepinfo); //$NON-NLS-1$
remarks.add(cr);
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("MappingMeta.CheckResult.StepReceivingFields",prev.size()+""), stepinfo); //$NON-NLS-1$ //$NON-NLS-2$
remarks.add(cr);
}
// See if we have input streams leading to this step!
if (input.length>0)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("MappingMeta.CheckResult.StepReceivingFieldsFromOtherSteps"), stepinfo); //$NON-NLS-1$
remarks.add(cr);
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("MappingMeta.CheckResult.NoInputReceived"), stepinfo); //$NON-NLS-1$
remarks.add(cr);
}
/*
* TODO re-enable validation code for mappings...
*
// Change the names of the fields if this is required by the mapping.
for (int i=0;i<inputField.length;i++)
{
if (inputField[i]!=null && inputField[i].length()>0)
{
if (inputMapping[i]!=null && inputMapping[i].length()>0)
{
if (!inputField[i].equals(inputMapping[i])) // rename these!
{
int idx = prev.indexOfValue(inputField[i]);
if (idx<0)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("MappingMeta.CheckResult.MappingTargetFieldNotPresent",inputField[i]), stepinfo); //$NON-NLS-1$ //$NON-NLS-2$
remarks.add(cr);
}
}
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("MappingMeta.CheckResult.MappingTargetFieldNotSepecified",i+"",inputField[i]), stepinfo); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
remarks.add(cr);
}
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("MappingMeta.CheckResult.InputFieldNotSpecified",i+""), stepinfo); //$NON-NLS-1$ //$NON-NLS-2$
remarks.add(cr);
}
}
// Then check the fields that get added to the row.
//
Repository repository = Repository.getCurrentRepository();
TransMeta mappingTransMeta = null;
try
{
mappingTransMeta = loadMappingMeta(fileName, transName, directoryPath, repository);
}
catch(KettleException e)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("MappingMeta.CheckResult.UnableToLoadMappingTransformation")+":"+Const.getStackTracker(e), stepinfo); //$NON-NLS-1$
remarks.add(cr);
}
if (mappingTransMeta!=null)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("MappingMeta.CheckResult.MappingTransformationSpecified"), stepinfo); //$NON-NLS-1$
remarks.add(cr);
StepMeta stepMeta = mappingTransMeta.getMappingOutputStep();
if (stepMeta!=null)
{
// See which fields are coming out of the mapping output step of the sub-transformation
// For these fields we check the existance
//
RowMetaInterface fields = null;
try
{
fields = mappingTransMeta.getStepFields(stepMeta);
boolean allOK = true;
// Check the fields...
for (int i=0;i<outputMapping.length;i++)
{
ValueMetaInterface v = fields.searchValueMeta(outputMapping[i]);
if (v==null) // Not found!
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("MappingMeta.CheckResult.MappingOutFieldSpecifiedCouldNotFound")+outputMapping[i], stepinfo); //$NON-NLS-1$
remarks.add(cr);
allOK=false;
}
}
if (allOK)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("MappingMeta.CheckResult.AllOutputMappingFieldCouldBeFound"), stepinfo); //$NON-NLS-1$
remarks.add(cr);
}
}
catch(KettleStepException e)
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("MappingMeta.CheckResult.UnableToGetStepOutputFields")+stepMeta.getName()+"]", stepinfo); //$NON-NLS-1$ //$NON-NLS-2$
remarks.add(cr);
}
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("MappingMeta.CheckResult.NoMappingOutputStepSpecified"), stepinfo); //$NON-NLS-1$
remarks.add(cr);
}
}
else
{
cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("MappingMeta.CheckResult.NoMappingSpecified"), stepinfo); //$NON-NLS-1$
remarks.add(cr);
}
*/
}
public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta tr, Trans trans)
{
return new Mapping(stepMeta, stepDataInterface, cnr, tr, trans);
}
public StepDataInterface getStepData()
{
return new MappingData();
}
/**
* @return the directoryPath
*/
public String getDirectoryPath()
{
return directoryPath;
}
/**
* @param directoryPath the directoryPath to set
*/
public void setDirectoryPath(String directoryPath)
{
this.directoryPath = directoryPath;
}
/**
* @return the fileName
*/
public String getFileName()
{
return fileName;
}
/**
* @param fileName the fileName to set
*/
public void setFileName(String fileName)
{
this.fileName = fileName;
}
/**
* @return the transName
*/
public String getTransName()
{
return transName;
}
/**
* @param transName the transName to set
*/
public void setTransName(String transName)
{
this.transName = transName;
}
/**
* @return the inputMappings
*/
public List<MappingIODefinition> getInputMappings() {
return inputMappings;
}
/**
* @param inputMappings the inputMappings to set
*/
public void setInputMappings(List<MappingIODefinition> inputMappings) {
this.inputMappings = inputMappings;
}
/**
* @return the outputMappings
*/
public List<MappingIODefinition> getOutputMappings() {
return outputMappings;
}
/**
* @param outputMappings the outputMappings to set
*/
public void setOutputMappings(List<MappingIODefinition> outputMappings) {
this.outputMappings = outputMappings;
}
/**
* @return the mappingParameters
*/
public MappingParameters getMappingParameters() {
return mappingParameters;
}
/**
* @param mappingParameters the mappingParameters to set
*/
public void setMappingParameters(MappingParameters mappingParameters) {
this.mappingParameters = mappingParameters;
}
@Override
public List<ResourceReference> getResourceDependencies(TransMeta transMeta, StepMeta stepInfo) {
List<ResourceReference> references = new ArrayList<ResourceReference>(5);
String realFilename = transMeta.environmentSubstitute(fileName);
String realTransname = transMeta.environmentSubstitute(transName);
ResourceReference reference = new ResourceReference(stepInfo);
references.add(reference);
if (!Const.isEmpty(realFilename)) {
// Add the filename to the references, including a reference to this step meta data.
reference.getEntries().add( new ResourceEntry(realFilename, ResourceType.ACTIONFILE));
} else if (!Const.isEmpty(realTransname)) {
// Add the filename to the references, including a reference to this step meta data.
reference.getEntries().add( new ResourceEntry(realTransname, ResourceType.ACTIONFILE));
references.add(reference);
}
return references;
}
@Override
public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface resourceNamingInterface) throws KettleException {
try {
// Try to load the transformation from repository or file.
// Modify this recursively too...
if (!Const.isEmpty(fileName)) {
FileObject fileObject = KettleVFS.getFileObject(space.environmentSubstitute(fileName));
// NOTE: there is no need to clone this step because the caller is responsible for this.
// First load the mapping metadata...
TransMeta mappingTransMeta = loadMappingMeta(fileName, null, null, null, space);
String newFilename = resourceNamingInterface.nameResource(fileObject.getName().getBaseName(), fileObject.getParent().getName().getPath(), "ktr");
mappingTransMeta.setFilename(newFilename);
fileName = newFilename; // replace it BEFORE XML generation occurs!
String xml = mappingTransMeta.getXML();
definitions.put(fileObject.getName().getPath(), new ResourceDefinition(newFilename, xml));
return newFilename;
}
else {
return null;
}
} catch (Exception e) {
throw new KettleException(Messages.getString("MappingMeta.Exception.UnableToLoadTransformation",fileName)); //$NON-NLS-1$
}
}
/**
* @return the repository
*/
public Repository getRepository() {
return repository;
}
/**
* @param repository the repository to set
*/
public void setRepository(Repository repository) {
this.repository = repository;
}
}
|
package org.usfirst.frc.team2586.robot.subsystems;
import org.usfirst.frc.team2586.robot.RobotMap;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Subsystem;
public class Claw extends Subsystem {
private final Relay openClaw, closeClaw;
/**
* Create a claw using the default relay channels defined in RobotMap
*/
public Claw() {
this(RobotMap.OPEN_CLAW_RELAY, RobotMap.CLOSE_CLAW_RELAY);
}
/**
* Create a claw using the specified relay channels
*
* @param openChannel Relay channel used to open the claw
* @param closeChannel Relay channel used to close the claw
*/
public Claw(int openChannel, int closeChannel) {
this(new Relay(openChannel), new Relay(closeChannel));
}
/**
* Creates a claw using the specified relays
*
* @param open Relay to use to open the claw
* @param close Relay to use to close the claw
*/
public Claw(Relay open, Relay close) {
super("Claw");
this.openClaw = open;
this.closeClaw = close;
}
/**
* Opens the claw
*/
public void openClaw() {
closeClaw.set(Relay.Value.kOff);
openClaw.set(Relay.Value.kForward);
}
/**
* Closes the claw
*/
public void closeClaw() {
openClaw.set(Relay.Value.kOff);
closeClaw.set(Relay.Value.kForward);
}
@Override
public void initDefaultCommand() {}
}
|
package org.encog;
/**
* A report object that does nothing.
*/
public class NullStatusReportable implements StatusReportable {
/**
* Simply ignore any status reports.
*
* @param total
* Not used.
* @param current
* Not used.
* @param message
* Not used.
*/
public void report(final int total, final int current,
final String message) {
}
}
|
package controller;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import service.MachineService;
import utils.ResponseCode;
import utils.ResultData;
@RestController
@RequestMapping("/machine")
public class MachineController {
private Logger logger = LoggerFactory.getLogger(MachineController.class);
@Autowired
private MachineService machineService;
@RequestMapping(method = RequestMethod.POST, value = "/device/delete/{deviceId}")
public ResultData delete(@PathVariable String deviceId) {
ResultData resultData = machineService.deleteDevice(deviceId);
resultData.setDescription("" + deviceId);
logger.info("delete device using deviceId: " + deviceId);
return resultData;
}
@RequestMapping(method = RequestMethod.GET, value = "/idle")
public ResultData idle() {
ResultData result = new ResultData();
Map<String, Object> condition = new HashMap<>();
condition.put("blockFlag", false);
ResultData response = machineService.fetchIdleMachine(condition);
if (response.getResponseCode() == ResponseCode.RESPONSE_ERROR) {
result.setResponseCode(ResponseCode.RESPONSE_ERROR);
result.setDescription("");
return result;
}
if (response.getResponseCode() == ResponseCode.RESPONSE_OK) {
result.setResponseCode(ResponseCode.RESPONSE_OK);
result.setData(response.getData());
return result;
}
return result;
}
}
|
package org.myrobotlab.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.myrobotlab.arduino.PApplet;
import org.myrobotlab.arduino.compiler.AvrdudeUploader;
import org.myrobotlab.arduino.compiler.Compiler;
import org.myrobotlab.arduino.compiler.MessageConsumer;
import org.myrobotlab.arduino.compiler.Preferences;
import org.myrobotlab.arduino.compiler.RunnerException;
import org.myrobotlab.arduino.compiler.Target;
import org.myrobotlab.fileLib.FileIO;
import org.myrobotlab.framework.MRLError;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ToolTip;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.serial.SerialDevice;
import org.myrobotlab.serial.SerialDeviceEvent;
import org.myrobotlab.serial.SerialDeviceEventListener;
import org.myrobotlab.serial.SerialDeviceException;
import org.myrobotlab.serial.SerialDeviceFactory;
import org.myrobotlab.serial.SerialDeviceService;
import org.myrobotlab.service.data.Pin;
import org.myrobotlab.service.interfaces.ArduinoShield;
import org.myrobotlab.service.interfaces.MotorControl;
import org.myrobotlab.service.interfaces.MotorController;
import org.myrobotlab.service.interfaces.SensorDataPublisher;
import org.myrobotlab.service.interfaces.ServiceInterface;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.myrobotlab.service.interfaces.StepperControl;
import org.myrobotlab.service.interfaces.StepperController;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.slf4j.Logger;
/**
* Implementation of a Arduino Service connected to MRL through a serial port.
* The protocol is basically a pass through of system calls to the Arduino
* board. Data can be passed back from the digital or analog ports by request to
* start polling. The serial port can be wireless (bluetooth), rf, or wired. The
* communication protocol supported is in MRLComm.ino
*
* Should support nearly all Arduino board types
*
* digitalRead() works on all pins. It will just round the analog value received
* and present it to you. If analogRead(A0) is greater than or equal to 512,
* digitalRead(A0) will be 1, else 0. digitalWrite() works on all pins, with
* allowed parameter 0 or 1. digitalWrite(A0,0) is the same as
* analogWrite(A0,0), and digitalWrite(A0,1) is the same as analogWrite(A0,255)
* analogRead() works only on analog pins. It can take any value between 0 and
* 1023. analogWrite() works on all analog pins and all digital PWM pins. You
* can supply it any value between 0 and 255
*
*/
@Root
public class Arduino extends Service implements SerialDeviceEventListener, SensorDataPublisher, ServoController, MotorController, StepperController, SerialDeviceService,
MessageConsumer {
private static final long serialVersionUID = 1L;
public transient final static Logger log = LoggerFactory.getLogger(Arduino.class);
public static final int MRLCOMM_VERSION = 18;
// serial protocol functions
public static final int MAGIC_NUMBER = 170; // 10101010
public static final int DIGITAL_WRITE = 0;
public static final int DIGITAL_VALUE = 1; // normalized with PinData
public static final int ANALOG_WRITE = 2;
public static final int ANALOG_VALUE = 3; // normalized with PinData
public static final int PINMODE = 4;
public static final int PULSE_IN = 5;
public static final int SERVO_ATTACH = 6;
public static final int SERVO_WRITE = 7;
public static final int SERVO_SET_MAX_PULSE = 8;
public static final int SERVO_DETACH = 9;
public static final int SET_PWM_FREQUENCY = 11;
public static final int SET_SERVO_SPEED = 12;
public static final int ANALOG_READ_POLLING_START = 13;
public static final int ANALOG_READ_POLLING_STOP = 14;
public static final int DIGITAL_READ_POLLING_START = 15;
public static final int DIGITAL_READ_POLLING_STOP = 16;
public static final int SET_ANALOG_TRIGGER = 17;
public static final int REMOVE_ANALOG_TRIGGER = 18;
public static final int SET_DIGITAL_TRIGGER = 19;
public static final int REMOVE_DIGITAL_TRIGGER = 20;
public static final int DIGITAL_DEBOUNCE_ON = 21;
public static final int DIGITAL_DEBOUNCE_OFF = 22;
public static final int DIGITAL_TRIGGER_ONLY_ON = 23;
public static final int DIGITAL_TRIGGER_ONLY_OFF = 24;
public static final int SET_SERIAL_RATE = 25;
public static final int GET_MRLCOMM_VERSION = 26;
public static final int SET_SAMPLE_RATE = 27;
public static final int SERVO_WRITE_MICROSECONDS = 28;
public static final int MRLCOMM_ERROR = 29;
public static final int PINGDAR_ATTACH = 30;
public static final int PINGDAR_START = 31;
public static final int PINGDAR_STOP = 32;
public static final int PINGDAR_DATA = 33;
public static final int SENSOR_ATTACH = 34;
public static final int SENSOR_POLLING_START = 35;
public static final int SENSOR_POLLING_STOP = 36;
public static final int SENSOR_DATA = 37;
public static final int SERVO_SWEEP_START = 38;
public static final int SERVO_SWEEP_STOP = 39;
// callback event - e.g. position arrived
// MSG MAGIC | SZ | SERVO-INDEX | POSITION
public static final int SERVO_EVENTS_ENABLE = 40;
public static final int SERVO_EVENT = 41;
public static final int LOAD_TIMING_ENABLE = 42;
public static final int LOAD_TIMING_EVENT = 43;
public static final int STEPPER_ATTACH = 44;
public static final int STEPPER_MOVE = 45;
public static final int STEPPER_STOP = 46;
public static final int STEPPER_RESET = 47;
public static final int STEPPER_EVENT = 48;
public static final int STEPPER_EVENT_STOP = 1;
public static final int STEPPER_TYPE_POLOLU = 1;
public static final int CUSTOM_MSG = 50;
public static final int ARDUINO_TYPE_INT = 16;
// servo event types
public static final int SERVO_EVENT_STOPPED = 1;
public static final int SERVO_EVENT_POSITION_UPDATE = 2;
// error types
public static final int ERROR_SERIAL = 1;
public static final int ERROR_UNKOWN_CMD = 2;
// sensor types
public static final int SENSOR_ULTRASONIC = 1;
// need a method to identify type of board
public static final int COMMUNICATION_RESET = 252;
public static final int SOFT_RESET = 253;
public static final int NOP = 255;
public static final int TRUE = 1;
public static final int FALSE = 0;
public Integer mrlcommVersion = null;
public transient static final int REVISION = 100;
public transient static final String BOARD_TYPE_UNO = "uno";
public transient static final String BOARD_TYPE_ATMEGA168 = "atmega168";
public transient static final String BOARD_TYPE_ATMEGA328P = "atmega328p";
public transient static final String BOARD_TYPE_ATMEGA2560 = "atmega2560";
public transient static final String BOARD_TYPE_ATMEGA1280 = "atmega1280";
public transient static final String BOARD_TYPE_ATMEGA32U4 = "atmega32u4";
// vendor specific pins start at 50
public static final String VENDOR_DEFINES_BEGIN = "// --VENDOR DEFINE SECTION BEGIN--";
public static final String VENDOR_SETUP_BEGIN = "// --VENDOR SETUP BEGIN--";
public static final String VENDOR_CODE_BEGIN = "// --VENDOR CODE BEGIN--";
/**
* pin description of board
*/
ArrayList<Pin> pinList = null;
HashMap<String, StepperControl> steppers = new HashMap<String, StepperControl>();
HashMap<Integer, StepperControl> stepperIndex = new HashMap<Integer, StepperControl>();
HashMap<String, SensorData> sensors = new HashMap<String, SensorData>();
HashMap<Integer, SensorData> sensorsIndex = new HashMap<Integer, SensorData>();
// needed to dynamically adjust PWM rate (D. only?)
public static final int TCCR0B = 0x25; // register for pins 6,7
public static final int TCCR1B = 0x2E; // register for pins 9,10
public static final int TCCR2B = 0xA1; // register for pins 3,11
// FIXME - more depending on board (mega)
// Servos[NBR_SERVOS] ; // max servos is 48 for mega, 12 for other boards
// int pos
// public static final int MAX_SERVOS = 12;
public static final int MAX_SERVOS = 48;
// serial device info
private transient SerialDevice serialDevice;
// from Arduino IDE (yuk)
static HashSet<File> libraries;
static boolean commandLine;
public HashMap<String, Target> targetsTable = new HashMap<String, Target>();
static File buildFolder;
static public HashMap<String, File> importToLibraryTable;
// imported Arduino constants
public static final int HIGH = 0x1;
public static final int LOW = 0x0;
public static final int INPUT = 0x0;
public static final int OUTPUT = 0x1;
public static final int MOTOR_FORWARD = 1;
public static final int MOTOR_BACKWARD = 0;
private boolean connected = false;
private String boardType;
BlockingQueue<Object> blockingData = new LinkedBlockingQueue<Object>();
StringBuilder debugTX = new StringBuilder();
StringBuilder debugRX = new StringBuilder();
/**
* MotorData is the combination of a Motor and any controller data needed to
* implement all of MotorController API
*
*/
class MotorData implements Serializable {
private static final long serialVersionUID = 1L;
transient MotorControl motor = null;
String type = null;
int PWMPin = -1;
int dirPin0 = -1;
int dirPin1 = -1;
}
HashMap<String, MotorData> motors = new HashMap<String, MotorData>();
transient Service customEventListener = null;
class SensorData implements Serializable {
private static final long serialVersionUID = 1L;
// -- FIXME - make Sensor(controller?) interface - when we get a new
// sensor
public transient UltrasonicSensor sensor = null;
public int sensorIndex = -1;
public long duration; // for ultrasonic
}
// servos
/**
* ServoController data needed to run a servo
*
*/
class ServoData implements Serializable {
private static final long serialVersionUID = 1L;
transient ServoControl servo = null;
Integer pin = null;
int servoIndex = -1;
}
/**
* the local name to servo info
*/
HashMap<String, ServoData> servos = new HashMap<String, ServoData>();
HashMap<Integer, ServoData> servoIndex = new HashMap<Integer, ServoData>();
// from the Arduino IDE :P
public Preferences preferences;
transient Compiler compiler;
transient AvrdudeUploader uploader;
// compile / upload
private String buildPath = "";
private String sketchName = "MRLComm";
private String sketch = "";
/**
* list of serial port names from the system which the Arduino service is
* running - this list is refreshed on querySerialDevices
*/
public ArrayList<String> portNames = new ArrayList<String>();
public Arduino(String n) {
super(n);
load();
// target arduino
// board atmenga328
preferences = new Preferences(String.format("%s.preferences.txt", getName()), null);
preferences.set("sketchbook.path", ".myrobotlab");
preferences.setInteger("serial.debug_rate", 57600);
preferences.set("serial.parity", "N"); // f'ing stupid,
preferences.setInteger("serial.databits", 8);
preferences.setInteger("serial.stopbits", 1); // f'ing weird 1,1.5,2
preferences.setBoolean("upload.verbose", true);
File librariesFolder = getContentFile("libraries");
// FIXME - all below should be done inside Compiler2
try {
targetsTable = new HashMap<String, Target>();
loadHardware(getHardwareFolder());
loadHardware(getSketchbookHardwareFolder());
addLibraries(librariesFolder);
File sketchbookLibraries = getSketchbookLibrariesFolder();
addLibraries(sketchbookLibraries);
} catch (IOException e) {
Logging.logException(e);
}
compiler = new Compiler(this);
uploader = new AvrdudeUploader(this);
getPortNames();
// FIXME - hilacious long wait - need to incorporate
// .waitTillServiceReady
// especially if there are multiple initialization threads
// SWEEEET ! - Service already provides an isReady - just need to
// overload it with a Thread.sleep check -> broadcast setState
createPinList();
String filename = "MRLComm.ino";
String resourcePath = String.format("Arduino/%s/%s", filename.substring(0, filename.indexOf(".")), filename);
log.info(String.format("loadResourceFile %s", resourcePath));
String defaultSketch = FileIO.resourceToString(resourcePath);
this.sketch = defaultSketch;
}
public void setBoard(String board) {
preferences.set("board", board);
createPinList();
preferences.save();
broadcastState();
}
protected void loadHardware(File folder) {
if (!folder.isDirectory())
return;
String list[] = folder.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
// skip .DS_Store files, .svn folders, etc
if (name.charAt(0) == '.')
return false;
if (name.equals("CVS"))
return false;
return (new File(dir, name).isDirectory());
}
});
// if a bad folder or something like that, this might come back null
if (list == null)
return;
// alphabetize list, since it's not always alpha order
// replaced hella slow bubble sort with this feller for 0093
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
// after that lovely searching of dirs - will come back with
// [arduino, tools]
for (String target : list) {
File subfolder = new File(folder, target);
targetsTable.put(target, new Target(target, subfolder, this));
}
}
public void setPreference(String name, String value) {
preferences.set(name, value);
if ("board".equals(name)) {
broadcastState();
}
}
public String getSerialDeviceName() {
if (serialDevice != null) {
return serialDevice.getName();
}
return null;
}
// FIXME - this should be in SerialService interface - get rid of query!!!
/*
* public ArrayList<String> getPortNames() { return
* SerialDeviceFactory.getSerialDeviceNames(); }
*/
// FIXME - this should be in SerialService interface !!!
/*
* public ArrayList<String> querySerialDeviceNames() {
*
* log.info("queryPortNames");
*
* serialDeviceNames = SerialDeviceFactory.getSerialDeviceNames();
*
* // adding connected serial port if connected if (serialDevice != null) {
* if (serialDevice.getName() != null)
* serialDeviceNames.add(serialDevice.getName()); }
*
* return serialDeviceNames; }
*/
/**
* MRL protocol method
*
* @param function
* @param param1
* @param param2
*
* TODO - take the cheese out of this method .. it shold be
* sendMsg(byte[]...data)
*/
public synchronized void sendMsg(int function, int... params) {
// log.debug("sendMsg magic | fn " + function + " p1 " + param1 + " p2 "
// + param2);
try {
// FIXME - determin bus speed e.g. 50Khz - and limit the messages
// (buffer them?) until they
// are under that max message send value :P
// not CRC16 - but cheesy error correction of bytestream
// #include <util/crc16.h>
// _crc16_update (test, testdata);
serialDevice.write(MAGIC_NUMBER);
// msg size = function byte + x param bytes
// msg size does not include MAGIC_NUMBER & size
// MAGIC_NUMBER|3|FUNCTION|PARAM0|PARAM2 would be valid
serialDevice.write(1 + params.length);
serialDevice.write(function);
for (int i = 0; i < params.length; ++i) {
serialDevice.write(params[i]);
}
if (log.isDebugEnabled()) {
debugTX.append("sendMsg -> MAGIC_NUMBER|");
debugTX.append("SZ ").append(1 + params.length);
debugTX.append(String.format("|FN %d", function));
for (int i = 0; i < params.length; ++i) {
if (log.isDebugEnabled()) {
debugTX.append(String.format("|P%d %d", i, params[i]));
}
}
log.debug(debugTX.toString());
debugTX.setLength(0);
}
} catch (Exception e) {
error("sendMsg " + e.getMessage());
}
}
@ToolTip("sends an array of data to the serial port which an Arduino is attached to")
@Override
public void write(String data) throws IOException {
write(data.getBytes());
}
public synchronized void write(byte[] data) throws IOException {
for (int i = 0; i < data.length; ++i) {
serialDevice.write(data[i]);
}
}
@Override
public void write(char data) throws IOException {
serialDevice.write(data);
}
@Override
public void write(int data) throws IOException {
serialDevice.write(data);
}
public void setPWMFrequency(Integer address, Integer freq) {
int prescalarValue = 0;
switch (freq) {
case 31:
case 62:
prescalarValue = 0x05;
break;
case 125:
case 250:
prescalarValue = 0x04;
break;
case 500:
case 1000:
prescalarValue = 0x03;
break;
case 4000:
case 8000:
prescalarValue = 0x02;
break;
case 32000:
case 64000:
prescalarValue = 0x01;
break;
default:
prescalarValue = 0x03;
}
sendMsg(SET_PWM_FREQUENCY, address, prescalarValue);
}
// FIXME - is this re-entrant ???
public boolean servoAttach(String servoName) {
Servo servo = (Servo) Runtime.getService(servoName);
if (servo == null) {
error("servoAttach can not attach %s no service exists", servoName);
return false;
}
return servoAttach(servoName, servo.getPin()) != -1;
}
// FIXME - put in interface
public int servoAttach(Servo servo) {
if (servo == null) {
error("servoAttach servo is null");
return -1;
}
if (servo.getPin() == null) {
error("%s servo pin not set", servo.getName());
return -1;
}
return servoAttach(servo.getName(), servo.getPin());
}
@Override
public synchronized int servoAttach(String servoName, Integer pin) {
log.info(String.format("servoAttach %s pin %d", servoName, pin));
if (serialDevice == null) {
error("could not attach servo to pin " + pin + " serial port is null - not initialized?");
return -1;
}
if (servos.containsKey(servoName)) {
log.warn("servo already attach - detach first");
return -1;
}
// simple re-map - to guarantee the same MRL Servo gets the same
// MRLComm.ino servo
if (pin < 2 || pin > MAX_SERVOS + 2) {
error("pin out of range 2 < %d < %d", pin, MAX_SERVOS + 2);
return -1;
}
// complex formula to calculate servo index
// this "could" be complicated - even so compicated
// as asking MRLComm.ino to find the "next available index
// and send it back - but I've tried that scheme and
// because the Servo's don't fully "detach" using the standard library
// it proved very "bad"
// simplistic mapping where Java is in control seems best
int index = pin - 2;
// attach index pin
sendMsg(SERVO_ATTACH, index, pin);
ServoData sd = new ServoData();
sd.pin = pin;
sd.servoIndex = index;
ServoControl sc = (ServoControl)Runtime.getService(servoName);
sd.servo = sc;
servos.put(servoName, sd);
servoIndex.put(index, sd);
log.info("servo index {} pin {} attached ", index, pin);
return index;
}
@Override
public synchronized boolean servoDetach(String servoName) {
log.info(String.format("servoDetach(%s)", servoName));
if (servos.containsKey(servoName)) {
ServoData sd = servos.get(servoName);
sendMsg(SERVO_DETACH, sd.servoIndex, 0);
// FIXME - simplify remove
// sd.servo.setController((ServoController)null);
// FIXME !!! - DON'T REMOVE !!!
servos.remove(servoName);
servoIndex.remove(sd.servoIndex);
return true;
}
error("servo %s detach failed - not found", servoName);
return false;
}
@Override
public void servoWrite(String servoName, Integer newPos) {
if (serialDevice == null) {
error("serialDevice is NULL !");
return;
}
if (!servos.containsKey(servoName)) {
warn("Servo %s not attached to %s", servoName, getName());
return;
}
int index = servos.get(servoName).servoIndex;
log.info(String.format("servoWrite %s %d index %d", servoName, newPos, index));
sendMsg(SERVO_WRITE, index, newPos);
}
@Override
public void servoSweep(String servoName, int min, int max, int step) { // delay
// speed
// speed
// same
// delay
if (serialDevice == null) {
error("serialDevice is NULL !");
return;
}
if (!servos.containsKey(servoName)) {
warn("Servo %s not attached to %s", servoName, getName());
return;
}
int index = servos.get(servoName).servoIndex;
log.info(String.format("servoSweep %s index %d min %d max %d step %d", servoName, index, min, max, step));
sendMsg(SERVO_SWEEP_START, index, min, max, step);
}
/*
* @Override public Integer getServoPin(String servoName) { if
* (servos.containsKey(servoName)) { return servos.get(servoName).pin; }
* return null; }
*/
public void digitalReadPollStart(Integer address) {
log.info("digitalRead (" + address + ") to " + serialDevice.getName());
sendMsg(DIGITAL_READ_POLLING_START, address, 0);
}
public void digitalReadPollStop(Integer address) {
log.info("digitalRead (" + address + ") to " + serialDevice.getName());
sendMsg(DIGITAL_READ_POLLING_STOP, address, 0);
}
public void digitalWrite(Integer address, Integer value) {
log.info("digitalWrite (" + address + "," + value + ") to " + serialDevice.getName() + " function number " + DIGITAL_WRITE);
sendMsg(DIGITAL_WRITE, address, value);
pinList.get(address).value = value;
}
public Integer getVersion() {
try {
if (serialDevice != null) {
blockingData.clear();
sendMsg(GET_MRLCOMM_VERSION, 0, 0);
mrlcommVersion = (Integer) blockingData.poll(1000, TimeUnit.MILLISECONDS);
// int version = Integer.parseInt();
return mrlcommVersion;
} else {
return null;
}
} catch (Exception e) {
Logging.logException(e);
return null;
}
}
public Integer publishVersion(Integer version) {
return version;
}
public void pinMode(Integer address, Integer value) {
log.info("pinMode (" + address + "," + value + ") to " + serialDevice.getName() + " function number " + PINMODE);
sendMsg(PINMODE, address, value);
}
public void analogWrite(Integer address, Integer value) {
log.info("analogWrite (" + address + "," + value + ") to " + serialDevice.getName() + " function number " + ANALOG_WRITE);
sendMsg(ANALOG_WRITE, address, value);
}
/**
* This method is called with Pin data whene a pin value is changed on the
* Arduino board the Arduino must be told to poll the desired pin(s). This
* is done with a analogReadPollingStart(pin) or digitalReadPollingStart()
*/
public Pin publishPin(Pin p) {
// log.debug(p);
pinList.get(p.pin).value = p.value;
return p;
}
public String readSerialMessage(String s) {
return s;
}
// force an digital read - data will be published in a call-back
// TODO - make a serialSendBlocking
public void digitalReadPollingStart(Integer pin) {
sendMsg(PINMODE, pin, INPUT);
sendMsg(DIGITAL_READ_POLLING_START, pin, 0); // last param is not
// used in read
}
public void digitalReadPollingStop(Integer pin) {
sendMsg(DIGITAL_READ_POLLING_STOP, pin, 0); // last param is not used
// in read
}
// force an analog read - data will be published in a call-back
// TODO - make a serialSendBlocking
public void analogReadPollingStart(Integer pin) {
sendMsg(PINMODE, pin, INPUT);
sendMsg(ANALOG_READ_POLLING_START, pin, 0); // last param is not used
}
public void analogReadPollingStop(Integer pin) {
sendMsg(ANALOG_READ_POLLING_STOP, pin, 0); // last param is not used
// in read
}
@Override
public String getDescription() {
return "<html>Arduino is a service which interfaces with an Arduino micro-controller.<br>" + "This interface can operate over radio, IR, or other communications,<br>"
+ "but and appropriate .PDE file must be loaded into the micro-controller.<br>" + "See http://myrobotlab.org/communication for details";
}
public void stopService() {
super.stopService();
if (serialDevice != null) {
serialDevice.close();
}
}
static final public int MAX_MSG_LEN = 64;
//StringBuilder rxDebug = new StringBuilder ();
// TODO - define as int[] because Java bytes suck !
byte[] msg = new byte[64]; // TODO define outside
int newByte;
int byteCount = 0;
int msgSize = 0;
//StringBuffer dump = new StringBuffer();
@Element
private String portName = "";
@Element
private int rate = 57600;
@Element
private int databits = 8;
@Element
private int stopbits = 1;
@Element
private int parity = 0;
private int error_arduino_to_mrl_rx_cnt;
private int error_mrl_to_arduino_rx_cnt;
@Override
public void serialEvent(SerialDeviceEvent event) {
switch (event.getEventType()) {
case SerialDeviceEvent.BI:
case SerialDeviceEvent.OE:
case SerialDeviceEvent.FE:
case SerialDeviceEvent.PE:
case SerialDeviceEvent.CD:
case SerialDeviceEvent.CTS:
case SerialDeviceEvent.DSR:
case SerialDeviceEvent.RI:
case SerialDeviceEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialDeviceEvent.DATA_AVAILABLE:
// at this point we should have a complete message
// the msg contains only daat // METHOD | P0 | P1 ... | PN
// msg buffer
// msg[0] METHOD
// msg[1] P0
// msg[2] P1
// msg[N] PN+1
try {
/*
* DON'T EVER MAKE THIS NON-MONOLITHIC ! - the overhead of going
* into another method is high and will end up loss of data in
* serial communications !
*
* Optimize this as much as possible !
*/
while (serialDevice.isOpen() && (newByte = serialDevice.read()) > -1) {
++byteCount;
if (byteCount == 1) {
if (newByte != MAGIC_NUMBER) {
byteCount = 0;
msgSize = 0;
warn(String.format("Arduino->MRL error - bad magic number %d - %d rx errors", newByte, ++error_arduino_to_mrl_rx_cnt));
//dump.setLength(0);
}
continue;
} else if (byteCount == 2) {
// get the size of message
if (newByte > 64) {
byteCount = 0;
msgSize = 0;
error(String.format("Arduino->MRL error %d rx sz errors", ++error_arduino_to_mrl_rx_cnt));
continue;
}
msgSize = (byte) newByte;
// dump.append(String.format("MSG|SZ %d", msgSize));
} else if (byteCount > 2) {
// remove header - fill msg data - (2) headbytes -1
// (offset)
// dump.append(String.format("|P%d %d", byteCount,
// newByte));
msg[byteCount - 3] = (byte) newByte;
}
// process valid message
if (byteCount == 2 + msgSize) {
// log.error("A {}", dump.toString());
// dump.setLength(0);
// MSG CONTENTS = FN | D0 | D1 | ...
byte function = msg[0];
//log.info(String.format("%d", msg[1]));
switch (function) {
case MRLCOMM_ERROR: {
++error_mrl_to_arduino_rx_cnt;
error("MRL->Arduino rx %d type %d", error_mrl_to_arduino_rx_cnt, msg[1]);
break;
}
case GET_MRLCOMM_VERSION: {
// TODO - get vendor version
// String version = String.format("%d", msg[1]);
blockingData.add((int) msg[1] & 0xff);
invoke("publishVersion", (int) msg[1] & 0xff);
break;
}
case PULSE_IN: {
// extract signed Java long from byte array offset 1
// - length 4 :P
// FIXME dangerous - your re-using Version's
// blockingData :P
long pulse = Serial.byteToLong(msg, 1, 4);
blockingData.add(pulse);
break;
}
case ANALOG_VALUE: {
// Pin p = new Pin(msg[1], msg[0], (((msg[2] & 0xFF)
// << 8) + (msg[3] & 0xFF)), getName());
// FIXME
Pin pin = pinList.get(msg[1]);
pin.value = ((msg[2] & 0xFF) << 8) + (msg[3] & 0xFF);
invoke("publishPin", pin);
break;
}
case DIGITAL_VALUE: {
Pin pin = pinList.get(msg[1]);
pin.value = msg[2];
invoke("publishPin", pin);
break;
}
case LOAD_TIMING_EVENT: {
long microsPerLoop = Serial.byteToLong(msg, 1, 4);
info("load %d us", microsPerLoop);
// log.info(String.format(" index %d type %d cur %d target %d", servoIndex, eventType, currentPos & 0xff, targetPos & 0xff));
// invoke("publishPin", pin);
break;
}
case SERVO_EVENT: {
int index = msg[1];
int eventType = msg[2];
int currentPos = msg[3];
int targetPos = msg[4];
log.info(String.format(" index %d type %d cur %d target %d", index, eventType, currentPos & 0xff, targetPos & 0xff));
// uber good -
// TODO - deprecate ServoControl interface - not needed Servo is abstraction enough
Servo servo = (Servo) servoIndex.get(index).servo;
servo.invoke("publishServoEvent", currentPos & 0xff);
break;
}
case SENSOR_DATA: {
int index = (int) msg[1];
SensorData sd = sensorsIndex.get(index);
sd.duration = Serial.byteToLong(msg, 2, 4);
// HMM WAY TO GO - is NOT to invoke its own but
// invoke publishSensorData on Sensor
// since its its own service
// invoke("publishSensorData", sd);
// NICE !! - force sensor to have publishSensorData
// or publishRange in interface !!!
// sd.sensor.invoke("publishRange", sd);
sd.sensor.invoke("publishRange", sd.duration);
break;
}
case STEPPER_EVENT: {
int eventType = msg[1];
int index = msg[2];
int currentPos = (msg[3] << 8) + (msg[4] & 0xff);
log.info(String.format(" index %d type %d cur %d", index, eventType, currentPos));
// uber good -
// TODO - stepper ServoControl interface - not needed Servo is abstraction enough
Stepper stepper = (Stepper) stepperIndex.get(index);
stepper.invoke("publishStepperEvent", currentPos);
break;
}
case CUSTOM_MSG: {
// msg or data is of size byteCount
int paramCnt = msg[1];
int paramIndex = 2; // current index in buffer
// decode parameters
Object[] params = new Object[paramCnt];
int paramType = 0;
for (int i = 0; i < paramCnt; ++i){
// get parameter type
//paramType = msg[];
paramType = msg[paramIndex];
// convert
if (paramType == ARDUINO_TYPE_INT){
//params[i] =
int x = ((msg[++paramIndex] & 0xFF) << 8) + (msg[++paramIndex] & 0xFF);
if (x > 32767){ x = x - 65536; }
params[i] = x;
log.info(String.format("parameter %d is type ARDUINO_TYPE_INT value %d", i, x));
++paramIndex;
} else {
error("CUSTOM_MSG - unhandled type %d", paramType);
}
// load it on boxing array
}
// how to reflectively invoke multi-param method (Python?)
if (customEventListener != null){
send(customEventListener.getName(), "onCustomMsg", params);
}
break;
}
default: {
error(formatMRLCommMsg("unknown serial event <- ", msg, msgSize));
break;
}
} // end switch
if (log.isDebugEnabled()) {
log.debug(formatMRLCommMsg("serialEvent <- ", msg, msgSize));
}
// processed msg
// reset msg buffer
msgSize = 0;
byteCount = 0;
}
} // while (serialDevice.isOpen() && (newByte =
// serialDevice.read()) > -1
} catch (Exception e) {
++error_mrl_to_arduino_rx_cnt;
error("msg structure violation %d", error_mrl_to_arduino_rx_cnt);
// try again ?
msgSize = 0;
byteCount = 0;
Logging.logException(e);
}
}
}
public String formatMRLCommMsg(String prefix, byte[] message, int size){
debugRX.setLength(0);
if (prefix != null){
debugRX.append(prefix);
}
debugRX.append(String.format("MAGIC_NUMBER|SZ %d|FN %d", size, message[0]));
for (int i = 1; i < size; ++i) {
debugRX.append(String.format("|P%d %d", i, message[i]));
}
return debugRX.toString();
}
// FIXME !!! - REMOVE ALL BELOW - except compile(File) compile(String)
// upload(File) upload(String)
// supporting methods for Compiler & UPloader may be necessary
static public String getAvrBasePath() {
Platform platform = Platform.getLocalInstance();
if (platform.isLinux()) {
return ""; // avr tools are installed system-wide and in the path
} else {
return getHardwarePath() + File.separator + "tools" + File.separator + "avr" + File.separator + "bin" + File.separator;
}
}
static public String getHardwarePath() {
return getHardwareFolder().getAbsolutePath();
}
static public File getHardwareFolder() {
// calculate on the fly because it's needed by Preferences.init() to
// find
// the boards.txt and programmers.txt preferences files (which happens
// before the other folders / paths get cached).
return getContentFile("hardware");
}
static public File getContentFile(String name) {
String path = System.getProperty("user.dir");
// Get a path to somewhere inside the .app folder
Platform platform = Platform.getLocalInstance();
if (platform.isMac()) {
String javaroot = System.getProperty("javaroot");
if (javaroot != null) {
path = javaroot;
}
}
path += File.separator + "arduino";
File working = new File(path);
return new File(working, name);
}
public Map<String, String> getBoardPreferences() {
Target target = getTarget();
if (target == null)
return new LinkedHashMap();
Map map = target.getBoards();
if (map == null)
return new LinkedHashMap();
map = (Map) map.get(preferences.get("board"));
if (map == null)
return new LinkedHashMap();
return map;
}
public Target getTarget() {
return targetsTable.get(preferences.get("target"));
}
public HashMap<String, Target> getTargetsTable() {
return targetsTable;
}
public String getSketchbookLibrariesPath() {
return getSketchbookLibrariesFolder().getAbsolutePath();
}
public File getSketchbookHardwareFolder() {
return new File(getSketchbookFolder(), "hardware");
}
protected File getDefaultSketchbookFolder() {
File sketchbookFolder = null;
try {
sketchbookFolder = new File("./.myrobotlab");// platform.getDefaultSketchbookFolder();
} catch (Exception e) {
}
// create the folder if it doesn't exist already
boolean result = true;
if (!sketchbookFolder.exists()) {
result = sketchbookFolder.mkdirs();
}
if (!result) {
showError("You forgot your sketchbook", "Arduino cannot run because it could not\n" + "create a folder to store your sketchbook.", null);
}
return sketchbookFolder;
}
public File getSketchbookLibrariesFolder() {
return new File(getSketchbookFolder(), "libraries");
}
public File getSketchbookFolder() {
return new File(preferences.get("sketchbook.path"));
}
public File getBuildFolder() {
if (buildFolder == null) {
String buildPath = preferences.get("build.path");
if (buildPath != null) {
buildFolder = new File(buildPath);
} else {
// File folder = new File(getTempFolder(), "build");
// if (!folder.exists()) folder.mkdirs();
buildFolder = createTempFolder("build");
buildFolder.deleteOnExit();
}
}
return buildFolder;
}
static public File createTempFolder(String name) {
try {
File folder = File.createTempFile(name, null);
// String tempPath = ignored.getParent();
// return new File(tempPath);
folder.delete();
folder.mkdirs();
return folder;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void removeDescendants(File dir) {
if (!dir.exists())
return;
String files[] = dir.list();
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || files[i].equals(".."))
continue;
File dead = new File(dir, files[i]);
if (!dead.isDirectory()) {
if (!preferences.getBoolean("compiler.save_build_files")) {
if (!dead.delete()) {
// temporarily disabled
System.err.println("Could not delete " + dead);
}
}
} else {
removeDir(dead);
// dead.delete();
}
}
}
/**
* Remove all files in a directory and the directory itself.
*/
public void removeDir(File dir) {
if (dir.exists()) {
removeDescendants(dir);
if (!dir.delete()) {
System.err.println("Could not delete " + dir);
}
}
}
/**
* Return an InputStream for a file inside the Processing lib folder.
*/
static public InputStream getLibStream(String filename) throws IOException {
return new FileInputStream(new File(getContentFile("lib"), filename));
}
static public void saveFile(String str, File file) throws IOException {
File temp = File.createTempFile(file.getName(), null, file.getParentFile());
PApplet.saveStrings(temp, new String[] { str });
if (file.exists()) {
boolean result = file.delete();
if (!result) {
throw new IOException("Could not remove old version of " + file.getAbsolutePath());
}
}
boolean result = temp.renameTo(file);
if (!result) {
throw new IOException("Could not replace " + file.getAbsolutePath());
}
}
public static boolean isCommandLine() {
return commandLine;
}
protected boolean addLibraries(File folder) throws IOException {
if (!folder.isDirectory())
return false;
String list[] = folder.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
// skip .DS_Store files, .svn folders, etc
if (name.charAt(0) == '.')
return false;
if (name.equals("CVS"))
return false;
return (new File(dir, name).isDirectory());
}
});
// if a bad folder or something like that, this might come back null
if (list == null)
return false;
// alphabetize list, since it's not always alpha order
// replaced hella slow bubble sort with this feller for 0093
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
boolean ifound = false;
// reset the set of libraries
libraries = new HashSet<File>();
// reset the table mapping imports to libraries
importToLibraryTable = new HashMap<String, File>();
for (String libraryName : list) {
File subfolder = new File(folder, libraryName);
libraries.add(subfolder);
String packages[] = Compiler.headerListFromIncludePath(subfolder.getAbsolutePath());
for (String pkg : packages) {
importToLibraryTable.put(pkg, subfolder);
}
ifound = true;
}
return ifound;
}
public String showMessage(String msg, String desc) {
log.info("showMessage " + msg);
return msg;
}
public SerialDevice getSerialDevice() {
return serialDevice;
}
@Override
public ArrayList<String> getPortNames() {
// FIXME - is this inclusive or ones which are left ?????
portNames = SerialDeviceFactory.getSerialDeviceNames();
return portNames;
}
@Override
public boolean connect(String name, int rate, int databits, int stopbits, int parity) {
if (name == null || name.length() == 0) {
log.info("got emtpy connect name - disconnecting");
return disconnect();
}
if (isConnected()) {
if (portName != null && portName.equals(name)) {
log.info(String.format("%s already connected", portName));
return true;
} else if (portName != null && !portName.equals(name)) {
warn("requesting port change from %s to %s - disconnecting", portName, name);
disconnect();
}
}
try {
info("attempting to connect %s %d %d %d %d", name, rate, databits, stopbits, parity);
// LAME - this should be done in the constructor or don't get with
// details ! - this data makes no diff
serialDevice = SerialDeviceFactory.getSerialDevice(name, rate, databits, stopbits, parity);
if (serialDevice != null) {
this.portName = name; // serialDevice.getName();
this.rate = rate;
this.databits = databits;
this.stopbits = stopbits;
this.parity = parity;
// connect();
// MOVE ALL VALUES TO @ELEMENTS
message(String.format("\nconnecting to serial device %s\n", serialDevice.getName()));
if (!serialDevice.isOpen()) {
serialDevice.open();
serialDevice.addEventListener(this);
serialDevice.notifyOnDataAvailable(true);
serialDevice.setParams(rate, databits, stopbits, parity);
sleep(2000);
// TODO boolean config - supress getting version
Integer version = getVersion();
// String version = null;
if (version == null) {
error("did not get response from arduino....");
} else if (!version.equals(MRLCOMM_VERSION)) {
error(String.format("MRLComm.ino responded with version %s expected version is %s", version, MRLCOMM_VERSION));
} else {
info(String.format("connected %s responded version %s ... goodtimes...", serialDevice.getName(), version));
}
} else {
warn(String.format("\n%s is already open, close first before opening again\n", serialDevice.getName()));
}
connected = true;
save(); // successfully bound to port - saving
preferences.set("serial.port", portName);
// FIXME - normalize
preferences.save();
broadcastState(); // state has changed let everyone know
return true;
}
} catch (Exception e) {
logException(e);
}
error("could not connect %s to port %s", getName(), name);
return false;
}
public void setCompilingProgress(Integer progress) {
log.info(String.format("progress %d ", progress));
invoke("publishCompilingProgress", progress);
}
public Integer publishCompilingProgress(Integer progress) {
return progress;
}
public String createBuildPath(String sketchName) {
// make a work/tmp directory if one doesn't exist - TODO - new time
// stamp?
Date d = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
formatter.setCalendar(cal);
String tmpdir = String.format("obj%s%s.%s", File.separator, sketchName, formatter.format(d));
new File(tmpdir).mkdirs();
return tmpdir;
}
public void compile(String sketchName, String sketch) {
// FYI - not thread safe
this.sketchName = sketchName;
this.sketch = sketch;
this.buildPath = createBuildPath(sketchName);
try {
compiler.compile(sketchName, sketch, buildPath, true);
} catch (RunnerException e) {
logException(e);
invoke("compilerError", e.getMessage());
}
log.debug(sketch);
}
public void upload(String sketch) throws Throwable {
compile("MRLComm", sketch); // FIXME throw push error();
uploader.uploadUsingPreferences(buildPath, sketchName, false);
}
public void uploadFile(String filename) throws Throwable {
upload(FileIO.fileToString(filename));
}
/**
* Get the number of lines in a file by counting the number of newline
* characters inside a String (and adding 1).
*/
static public int countLines(String what) {
int count = 1;
for (char c : what.toCharArray()) {
if (c == '\n')
count++;
}
return count;
}
/**
* Grab the contents of a file as a string.
*/
static public String loadFile(File file) throws IOException {
String[] contents = PApplet.loadStrings(file);
if (contents == null)
return null;
return PApplet.join(contents, "\n");
}
@Override
public ArrayList<Pin> getPinList() {
return pinList;
}
public ArrayList<Pin> createPinList() {
pinList = new ArrayList<Pin>();
boardType = preferences.get("board");
int pinType = Pin.DIGITAL_VALUE;
if (boardType != null && boardType.contains("mega")) {
for (int i = 0; i < 70; ++i) {
if (i < 1 || (i > 13 && i < 54)) {
pinType = Pin.DIGITAL_VALUE;
} else if (i > 53) {
pinType = Pin.ANALOG_VALUE;
} else {
pinType = Pin.PWM_VALUE;
}
pinList.add(new Pin(i, pinType, 0, getName()));
}
} else {
for (int i = 0; i < 20; ++i) {
if (i < 14) {
pinType = Pin.DIGITAL_VALUE;
} else {
pinType = Pin.ANALOG_VALUE;
}
if (i == 3 || i == 5 || i == 6 || i == 9 || i == 10 || i == 11) {
pinType = Pin.PWM_VALUE;
}
pinList.add(new Pin(i, pinType, 0, getName()));
}
}
return pinList;
}
@Override
public void message(String msg) {
log.info(msg);
invoke("publishMessage", msg);
}
static public String showError(String error, String desc, Exception e) {
return error;
}
public String compilerError(String error) {
return error;
}
public String publishMessage(String msg) {
return msg;
}
public boolean connect() {
return connect(portName, rate, databits, stopbits, parity);
}
/**
* valid means - connected and MRLComm was found at the correct version
*
* @return
*/
public boolean isValid() {
return MRLCOMM_VERSION == getVersion();
}
public boolean isConnected() {
// I know not normalized
// but we have to do this - since
// the SerialDevice is transient
return connected;
}
@Override
public boolean disconnect() {
connected = false;
if (serialDevice == null) {
return false;
}
serialDevice.close();
portName = "";
info("disconnected");
broadcastState();
return true;
}
public String getPortName() {
return portName;
}
@Override
public boolean motorAttach(String motorName, Object... motorData) {
ServiceInterface sw = Runtime.getService(motorName);
if (!sw.isLocal()) {
error("motor is not in the same MRL instance as the motor controller");
return false;
}
ServiceInterface service = sw;
MotorControl motor = (MotorControl) service; // BE-AWARE - local
// optimization ! Will
// not work on remote
return motorAttach(motor, motorData);
}
public boolean motorAttach(String motorName, Integer PWMPin, Integer directionPin) {
return motorAttach(motorName, new Object[] { PWMPin, directionPin });
}
/**
* an implementation which supports service names is important there is no
* benefit in the object array parameter here all methods should have their
* own signature
*/
/**
* implementation of motorAttach(String motorName, Object... motorData) is
* private so that interfacing consistently uses service names to attach,
* even though service is local
*
* @param motor
* @param motorData
* @return
*/
private boolean motorAttach(MotorControl motor, Object... motorData) {
if (motor == null || motorData == null) {
error("null data or motor - can't attach motor");
return false;
}
if (motorData.length != 2 || motorData[0] == null || motorData[1] == null) {
error("motor data must be of the folowing format - motorAttach(Integer PWMPin, Integer directionPin)");
return false;
}
MotorData md = new MotorData();
md.motor = motor;
md.PWMPin = (Integer) motorData[0];
md.dirPin0 = (Integer) motorData[1];
motors.put(motor.getName(), md);
motor.setController(this);
sendMsg(PINMODE, md.PWMPin, OUTPUT);
sendMsg(PINMODE, md.dirPin0, OUTPUT);
return true;
}
@Override
public boolean motorDetach(String motorName) {
boolean ret = motors.containsKey(motorName);
if (ret) {
motors.remove(motorName);
}
return ret;
}
public void motorMove(String name) {
MotorData md = motors.get(name);
MotorControl m = md.motor;
float power = m.getPowerLevel();
if (power < 0) {
sendMsg(DIGITAL_WRITE, md.dirPin0, m.isDirectionInverted() ? MOTOR_FORWARD : MOTOR_BACKWARD);
sendMsg(ANALOG_WRITE, md.PWMPin, Math.abs((int) (255 * m.getPowerLevel())));
} else if (power > 0) {
sendMsg(DIGITAL_WRITE, md.dirPin0, m.isDirectionInverted() ? MOTOR_BACKWARD : MOTOR_FORWARD);
sendMsg(ANALOG_WRITE, md.PWMPin, (int) (255 * m.getPowerLevel()));
} else {
sendMsg(ANALOG_WRITE, md.PWMPin, 0);
}
}
public void motorMoveTo(String name, Integer position) {
// TODO Auto-generated method stub
}
public void digitalDebounceOn() {
digitalDebounceOn(50);
}
public void digitalDebounceOn(int delay) {
if (delay < 0 || delay > 32767) {
error(String.format("%d debounce delay must be 0 < delay < 32767", delay));
}
int lsb = delay & 0xff;
int msb = (delay >> 8) & 0xff;
sendMsg(DIGITAL_DEBOUNCE_ON, msb, lsb);
}
public void digitalDebounceOff() {
sendMsg(DIGITAL_DEBOUNCE_OFF, 0, 0);
}
// FIXME - too complicated.. too much code bloat .. its nice you use names
// BUT
// IT MAKES NO SENSE TO HAVE SERVOS "connecte" ON A DIFFERENT INSTANCE
// SO USING ACTUAL TYPES SIMPLIFIES LIFE !
public Boolean attach(String serviceName, Object... data) {
log.info(String.format("attaching %s", serviceName));
ServiceInterface sw = Runtime.getService(serviceName);
if (sw == null) {
error("could not attach %s - not found in registry", serviceName);
return false;
}
if (sw instanceof Servo) // Servo or ServoControl ???
{
if (data.length != 1) {
error("can not attach a Servo without a pin number");
return false;
}
if (!sw.isLocal()) {
error("servo controller and servo must be local");
return false;
}
return servoAttach(serviceName, (Integer) (data[0])) != -1;
}
if (sw instanceof Motor) // Servo or ServoControl ???
{
if (data.length != 2) {
error("can not attach a Motor without a PWMPin & directionPin ");
return false;
}
if (!sw.isLocal()) {
error("motor controller and motor must be local");
return false;
}
return motorAttach(serviceName, data);
}
if (sw instanceof ArduinoShield) // Servo or ServoControl ???
{
if (!sw.isLocal()) {
error("motor controller and motor must be local");
return false;
}
return ((ArduinoShield) sw).attach(this);
}
error("don't know how to attach");
return false;
}
public String getSketch() {
return this.sketch;
}
public String setSketch(String newSketch) {
sketch = newSketch;
return sketch;
}
public String loadSketchFromFile(String filename) throws FileNotFoundException {
sketch = FileIO.fileToString(filename);
return sketch;
}
@Override
public Object[] getMotorData(String motorName) {
MotorData md = motors.get(motorName);
Object[] data = new Object[] { md.PWMPin, md.dirPin0 };
return data;
}
public void softReset() {
sendMsg(SOFT_RESET, 0, 0);
}
@Override
public void setServoSpeed(String servoName, Float speed) {
if (speed == null || speed < 0.0f || speed > 1.0f) {
error("speed %f out of bounds", speed);
return;
}
sendMsg(SET_SERVO_SPEED, servos.get(servoName).servoIndex, (int) (speed * 100));
}
@Override
public void releaseService() {
super.releaseService();
// soft reset - detaches servos & resets polling & pinmodes
softReset();
sleep(300);
disconnect();
}
public void setDigitalTriggerOnly(Boolean b) {
if (b)
sendMsg(DIGITAL_TRIGGER_ONLY_ON, 0, 0);
else
sendMsg(DIGITAL_TRIGGER_ONLY_OFF, 0, 0);
}
public void setSerialRate(int rate) {
try {
log.info(String.format("setSerialRate %d", rate));
sendMsg(SET_SERIAL_RATE, rate, 0);
serialDevice.setParams(rate, 8, 1, 0);
} catch (SerialDeviceException e) {
logException(e);
}
}
@Override
public void stepperStep(String name, Integer steps) {
// TODO Auto-generated method stub
}
@Override
public void stepperStep(String name, Integer steps, Integer style) {
// TODO Auto-generated method stub
}
@Override
public void setSpeed(Integer speed) {
// TODO Auto-generated method stub
}
@Override
public boolean stepperDetach(String name) {
// TODO Auto-generated method stub
return false;
}
@Override
public Object[] getStepperData(String stepperName) {
// TODO Auto-generated method stub
return null;
}
/**
* connect to serial port with default parameters 57600 rate, 8 data bits, 1
* stop bit, 0 parity
*/
@Override
public boolean connect(String port) {
return connect(port, 57600, 8, 1, 0);
}
/**
* this sets the sample rate of polling reads both digital and analog it is
* a loop count modulus - default is 1 which seems to be a bit high of a
* rate to be broadcasting across the internet to several webclients :)
* valid ranges are 1 to 32,767 (for Arduino's 2 byte signed integer)
*
* @param rate
*/
public int setSampleRate(int rate) {
if (rate < 1 || rate > 32767) {
error(String.format("%d sample rate can not be < 1", rate));
}
int lsb = rate & 0xff;
int msb = (rate >> 8) & 0xff;
sendMsg(SET_SAMPLE_RATE, msb, lsb);
return rate;
}
@Override
public void servoStop(String servoName) {
// FIXME DEPRECATE OR IMPLEMENT
//sendMsg(SERVO_STOP_AND_REPORT, servos.get(servoName).servoIndex);
}
// often used as a ping echo pulse - timing is critical
// so it has to be done on the uC .. therefore
// a trigger pin has to be sent as well to the pulseIn
// as well as the pulse/echo pin
public long pulseIn(int trigPin, int echoPin) {
return pulseIn(trigPin, echoPin, HIGH, 1000);
}
public long pulseIn(int trigPin, int echoPin, Integer timeout) {
if (timeout != null) {
timeout = 1000;
}
return pulseIn(trigPin, echoPin, 1000, null);
}
public long pulseIn(int trigPin, int echoPin, int timeout, String highLow) {
int value = HIGH;
if (highLow != null && highLow.equalsIgnoreCase("LOW")) {
value = LOW;
}
return pulseIn(trigPin, echoPin, value, timeout);
}
// FIXME - rather application specific - possible to add variable delays on
// trigger
// and echo
public long pulseIn(int trigPin, int echoPin, int value, int timeout) {
try {
if (serialDevice != null) {
blockingData.clear();
sendMsg(PULSE_IN, trigPin, echoPin, value, timeout);
// downstream longer timeout than upstream
Long pulse = (Long) blockingData.poll(250 + timeout, TimeUnit.MILLISECONDS);
if (pulse == null) {
return 0;
}
return pulse;
} else {
return 0;
}
} catch (Exception e) {
Logging.logException(e);
return 0;
}
}
@Override
public int read() throws IOException {
return serialDevice.read();
}
@Override
public int read(byte[] data) throws IOException {
return serialDevice.read(data);
}
public void pinMode(int address, String mode) {
if (mode != null && mode.equalsIgnoreCase("INPUT")) {
pinMode(address, INPUT);
} else {
pinMode(address, OUTPUT);
}
}
public synchronized int sensorAttach(String sensorName) {
UltrasonicSensor sensor = (UltrasonicSensor) Runtime.getService(sensorName);
if (sensor == null) {
log.error("Sensor {} not valid", sensorName);
return -1;
}
return sensorAttach(sensor);
}
public synchronized int sensorAttach(UltrasonicSensor sensor) {
String sensorName = sensor.getName();
log.info(String.format("sensorAttach %s", sensorName));
int sensorIndex = -1;
if (serialDevice == null) {
error("could not attach sensor - no serial device!");
return -1;
}
if (sensors.containsKey(sensorName)) {
log.warn("sensor already attach - detach first");
return -1;
}
int type = -1;
if (sensor instanceof UltrasonicSensor) {
type = SENSOR_ULTRASONIC;
}
if (type == SENSOR_ULTRASONIC) {
// simple count = index mapping
sensorIndex = sensors.size();
// attach index pin
sendMsg(SENSOR_ATTACH, sensorIndex, SENSOR_ULTRASONIC, sensor.getTriggerPin(), sensor.getEchoPin());
SensorData sd = new SensorData();
sd.sensor = sensor;
sd.sensorIndex = sensorIndex;
sensors.put(sensorName, sd);
sensorsIndex.put(sensorIndex, sd);
log.info(String.format("sensor SR04 index %d pin trig %d echo %d attached ", sensorIndex, sensor.getTriggerPin(), sensor.getEchoPin()));
}
return sensorIndex;
}
public String captureServoScript() {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, ServoData> o : servos.entrySet()) {
String name = o.getKey();
sb.append(String.format("%s.moveTo(%d)\n", name, ((Servo) Runtime.getService(name)).getPos()));
}
return sb.toString();
}
public boolean sensorPollingStart(String name, int timeoutMS) {
info("sensorPollingStart %s", name);
if (!sensors.containsKey(name)) {
error("can not poll sensor %s - not defined", name);
return false;
}
int index = sensors.get(name).sensorIndex;
sendMsg(SENSOR_POLLING_START, index, timeoutMS);
return true;
}
public boolean sensorPollingStop(String name) {
info("sensorPollingStop %s", name);
if (!sensors.containsKey(name)) {
error("can not poll sensor %s - not defined", name);
return false;
}
int index = sensors.get(name).sensorIndex;
sendMsg(SENSOR_POLLING_STOP, index);
return true;
}
// FIXME - relatively clean interface BUT - ALL THIS LOGIC SHOULD BE IN STEPPER NOT ARDUINO !!!
// SO STEPPER MUST NEED TO KNOW ABOUT CONTROLLER TYPE
public boolean stepperAttach(String stepperName) {
Stepper stepper = (Stepper) Runtime.getService(stepperName);
if (stepper == null) {
log.error("Stepper {} not valid", stepperName);
return false;
}
return stepperAttach(stepper);
}
public boolean stepperAttach(StepperControl stepper) {
String stepperName = stepper.getName();
log.info(String.format("stepperAttach %s", stepperName));
Integer index = 0;
if (serialDevice == null) {
error("could not attach stepper - no serial device!");
return false;
}
if (steppers.containsKey(stepperName)) {
log.warn("stepper already attach - detach first");
return false;
}
stepper.setController(this);
if (Stepper.STEPPER_TYPE_POLOLU.equals(stepper.getStepperType())) {
// int type = Stepper.STEPPER_TYPE_POLOLU.hashCode(); heh, cool idea - but byte collision don't want to risk ;)
int type = 1;
// simple count = index mapping
index = steppers.size();
Integer [] pins = stepper.getPins();
if (pins.length != 2){
error("Pololu stepper needs 2 pins defined - direction pin & step pin");
return false;
}
// attach index pin
sendMsg(STEPPER_ATTACH, index, type, pins[0], pins[1]);
stepper.setIndex(index);
steppers.put(stepperName, stepper);
stepperIndex.put(index, stepper);
log.info(String.format("stepper STEPPER_TYPE_POLOLU index %d pin direction %d step %d attached ", index, pins[0], pins[1]));
} else {
error("unkown type of stepper");
return false;
}
return true;
}
public void stepperMove(String name, Integer newPos) {
if (!steppers.containsKey(name)){
error("%s stepper not found", name);
return;
}
StepperControl stepper = steppers.get(name);
if (Stepper.STEPPER_TYPE_POLOLU.equals(stepper.getStepperType())){
} else {
error("unknown stepper type");
return;
}
int lsb = newPos & 0xff;
int msb = (newPos >> 8) & 0xff;
sendMsg(STEPPER_MOVE, stepper.getIndex(), msb, lsb);
// TODO - call back event - to say arrived ?
// TODO - blocking method
}
public void test(String port) throws Exception {
// get running reference to self
Arduino arduino = (Arduino)Runtime.start(getName(),"Arduino");
boolean useGUI = true;
if (useGUI){
Runtime.createAndStart("gui", "GUIService");
}
if (!arduino.connect(port)) {
throw new MRLError("could not connect to port %s", port);
}
for (int i = 0; i < 1000; ++i) {
long duration = arduino.pulseIn(7, 8);
log.info("duration {} uS", duration);
// sleep(100);
}
UltrasonicSensor sr04 = (UltrasonicSensor) Runtime.start("sr04", "UltrasonicSensor");
Runtime.start("gui", "GUIService");
sr04.attach(arduino, port, 7, 8);
sr04.startRanging();
log.info("here");
sr04.stopRanging();
// TODO - test all functions
// TODO - test digital pin
// getDigitalPins
// getAnalogPins
}
public boolean setServoEventsEnabled(String servoName, boolean enable){
log.info(String.format("setServoEventsEnabled %s %b", servoName, enable));
if (servos.containsKey(servoName)) {
ServoData sd = servos.get(servoName);
if (enable){
sendMsg(SERVO_EVENTS_ENABLE, sd.servoIndex, TRUE);
} else {
sendMsg(SERVO_EVENTS_ENABLE, sd.servoIndex, FALSE);
}
return true;
}
return false;
}
public boolean setLoadTimingEnabled(boolean enable){
log.info(String.format("setLoadTimingEnabled %b", enable));
if (enable){
sendMsg(LOAD_TIMING_ENABLE, TRUE);
} else {
sendMsg(LOAD_TIMING_ENABLE, FALSE);
}
return enable;
}
// String functions to interface are important
// Interfaces should support both - "real" references and "String" references
// the String reference just "gets" the real reference - but this is important
// to support all protocols
@Override
public void stepperReset(String stepperName) {
StepperControl stepper = steppers.get(stepperName);
sendMsg(STEPPER_RESET, stepper.getIndex());
}
public void stepperStop(String name) {
StepperControl stepper = steppers.get(name);
sendMsg(STEPPER_STOP, stepper.getIndex());
}
public void onCustomMsg(Integer ax, Integer ay, Integer az){
log.info("here");
}
public static void main(String[] args) {
try {
LoggingFactory.getInstance().configure();
LoggingFactory.getInstance().setLevel(Level.INFO);
Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino");
Python python = (Python) Runtime.start("python", "Python");
Runtime.start("gui", "GUIService");
//arduino.addCustomMsgListener(python);
//arduino.customEventListener = python;
//arduino.connect("COM15");
//arduino.test("COM15");
// blocking examples
/*
* long duration = sr04.ping(); log.info("duration {}", duration);
* long range = sr04.range(); log.info("range {}", range);
*/
// non blocking - event example
// sr04.publishRange(long duration);
// arduino.pinMode(trigPin, "OUTPUT");
// arduino.pinMode(echoPin, "INPUT");
// arduino.digitalWrite(7, 0);
// arduino.digitalWrite(7, 1);
// arduino.digitalWrite(7, 0);
// Runtime.createAndStart("python", "Python");
// Runtime.createAndStart("gui01", "GUIService");
// arduino.connect("COM15");
// log.info("{}", arduino.pulseIn(5));
// FIXME - null pointer error
log.info("here");
} catch (Exception e) {
Logging.logException(e);
}
}
public void addCustomMsgListener(Service service) {
customEventListener = service;
}
}
|
package org.nees.central;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.UnmarshallerHandler;
import javax.xml.namespace.QName;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import org.nees.data.Central;
import org.nees.data.DataFile;
import org.nees.data.Experiment;
import org.nees.data.Project;
import org.nees.data.Repetition;
import org.nees.data.Trial;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
/**
* A client for the NEEScentral web services.
*
* @author Jason P. Hanley
*/
public class CentralClient {
/** the XML namespace for the NEEScentral schema */
private static final String namespace = "http://central.nees.org/api";
/** the package where the domain classes are */
private static final String domainObjectsPackage = "org.nees.data";
/** the base URL for the web services */
private String baseURL = "https://central.nees.org";
/** the GridAuth session */
private final String gaSession;
/** the XML unmarshaller */
private Unmarshaller unmarshaller;
/** the XML reader */
private XMLReader xmlReader;
/**
* Creates a client for NEEScentral.
*/
public CentralClient() throws CentralException {
this(null);
}
/**
* Creates a client for NEEScentral with the GridAuth session.
*
* @param gaSession the GridAuth session
* @throws CentralException if there is an error creating the client
*/
public CentralClient(String gaSession) throws CentralException {
super();
this.gaSession = gaSession;
try {
// setup JAXB unmarshaller
JAXBContext jaxbContext = JAXBContext.newInstance(domainObjectsPackage);
unmarshaller = jaxbContext.createUnmarshaller();
UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
// setup SAX parser
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
XMLReader rawXmlReader = parser.getXMLReader();
// setup namespace filter
xmlReader = new RemoveNamespaceFilter(rawXmlReader, namespace);
xmlReader.setContentHandler(unmarshallerHandler);
} catch (Exception e) {
throw new CentralException(e);
}
}
/**
* Sets the hostname to use when calling the web services.
*
* @param hostname the hostname for the NEEScentral instance
*/
public void setHostname(String hostname) {
baseURL = "https://" + hostname;
}
/**
* Calls a REST web service and return the response as a Central domain
* object.
*
* @param path the path for the web service
* @return the response
* @throws CentralException if there is an error calling the web service
*/
private synchronized Central callREST(String path) throws CentralException {
Central central = null;
// construct web service URL
String urlString = baseURL + "/REST/" + path;
if (gaSession != null) {
urlString += "?GAsession=" + gaSession;
}
URL url = null;
try { url = new URL(urlString); } catch (MalformedURLException e) {}
// call web service
SAXSource source;
try {
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
if (connection.getResponseCode() == 401) {
throw new CentralException("You are not authorized to view this resource");
}
source = new SAXSource(xmlReader, new InputSource(connection.getInputStream()));
} catch (IOException e) {
throw new CentralException("Error connecting to NEEScentral", e);
}
// unmarshall web service response
JAXBElement<Central> centralElement;
try {
centralElement = (JAXBElement<Central>)unmarshaller.unmarshal(source);
} catch (JAXBException e) {
throw new CentralException("NEEScentral returned an invalid response", e);
}
central = centralElement.getValue();
return central;
}
/**
* Gets all the projects the user has access to in NEEScentral.
*
* @return the projects in NEEScentral
* @throws CentralException if there is an error getting the list of projects
*/
public List<Project> getProjects() throws CentralException {
Central central = callREST("Project");
List<Project> projects = central.getProject();
for (Project project : projects) {
project.setName("NEES-" + project.getId());
}
return projects;
}
/**
* Gets the project from NEEScentral.
*
* @param projectId the id of the project
* @return the project, or null if it was not found
* @throws CentralException if there is an error getting the project
*/
public Project getProject(int projectId) throws CentralException {
Central central = callREST("Project/" + projectId);
List<Project> projects = central.getProject();
Project project;
if (projects.size() == 1) {
project = projects.get(0);
project.setId(projectId);
List<Experiment> experiments = project.getExperiment();
for (int i=0; i<experiments.size(); i++) {
experiments.get(i).setName("Experiment-" + (i+1));
}
fixDataFiles(project.getDataFile(), "NEES-");
} else {
project = null;
}
return project;
}
/**
* Gets the list of experiments for the project.
*
* @param projectId the project id
* @return a list of experiments for the project
* @throws CentralException if there is an error getting the list of
* experiments
*/
public List<Experiment> getExperiments(int projectId) throws CentralException {
Central central = callREST("Project/" + projectId +
"/Experiment");
return central.getExperiment();
}
/**
* Gets the experiment from NEEScentral.
*
* @param projectId the project id for the experiment
* @param experimentId the experiment id
* @return the experiment, or null if it is not found
* @throws CentralException if there is an error getting the experiment
*/
public Experiment getExperiment(int projectId, int experimentId) throws CentralException {
Central central = callREST("Project/" + projectId +
"/Experiment/" + experimentId);
List<Experiment> experiments = central.getExperiment();
Experiment experiment;
if (experiments.size() == 1) {
experiment = experiments.get(0);
experiment.setId(experimentId);
List<Trial> trials = experiment.getTrial();
for (int i=0; i<trials.size(); i++) {
trials.get(i).setName(new JAXBElement(new QName("uri","local"), String.class, "Trial-" + (i+1)));
}
fixDataFiles(experiment.getDataFile(), "Experiment-");
} else {
experiment = null;
}
return experiment;
}
/**
* Gets the list of trials for the experiment.
*
* @param projectId the project id for the trials
* @param experimentId the experiment id for the trials
* @return a list of trials for the experiment
* @throws CentralException if there is an error getting the list of trials
*/
public List<Trial> getTrials(int projectId, int experimentId) throws CentralException {
Central central = callREST("Project/" + projectId +
"/Experiment/" + experimentId +
"/Trial");
return central.getTrial();
}
/**
* Gets the trial from NEEScentral.
*
* @param projectId the project id for the trial
* @param experimentId the experiment id for the trial
* @param trialId the trial id
* @return the trial, or null if it is not found
* @throws CentralException if there is an error getting the trial
*/
public Trial getTrial(int projectId, int experimentId, int trialId) throws CentralException {
Central central = callREST("Project/" + projectId +
"/Experiment/" + experimentId +
"/Trial/" + trialId);
List<Trial> trials = central.getTrial();
Trial trial;
if (trials.size() == 1) {
trial = trials.get(0);
trial.setId(trialId);
List<Repetition> repetitions = trial.getRepetition();
for (int i=0; i<repetitions.size(); i++) {
repetitions.get(i).setName(new JAXBElement(new QName("uri","local"), String.class, "Rep-" + (i+1)));
}
fixDataFiles(trial.getDataFile(), "Trial-");
} else {
trial = null;
}
return trial;
}
/**
* Gets a list of repetitions for the trial.
*
* @param projectId the project id for the repetitions
* @param experimentId the experiment id for the repetitions
* @param trialId the trial id for the repetitions
* @return a list of repetitions for the trial
* @throws CentralException if there is an error getting the list of
* repetitions
*/
public List<Repetition> getRepetitions(int projectId, int experimentId, int trialId) throws CentralException {
Central central = callREST("Project/" + projectId +
"/Experiment/" + experimentId +
"/Trial/" + trialId +
"/Repetition");
return central.getRepetition();
}
/**
* Gets the repetition from NEEScentral.
*
* @param projectId the project id for the repetition
* @param experimentId the experiment id for the repetition
* @param trialId the trial id for the repetition
* @param repetitionId the repetition id
* @return the repetition, or null if it is not found
* @throws CentralException if there is an error getting the repetition
*/
public Repetition getRepetition(int projectId, int experimentId, int trialId, int repetitionId) throws CentralException {
Central central = callREST("Project/" + projectId +
"/Experiment/" + experimentId +
"/Trial/" + trialId +
"/Repetition/" + repetitionId);
List<Repetition> repetitions = central.getRepetition();
Repetition repetition;
if (repetitions.size() == 1) {
repetition = repetitions.get(0);
repetition.setId(repetitionId);
fixDataFiles(repetition.getDataFile());
} else {
repetition = null;
}
return repetition;
}
/**
* Gets the data file for the path.
*
* @param path the path of the data file
* @return the data file, or null if it is not found
* @throws CentralException if there is an error getting the data file
*/
public DataFile getDataFile(String path) throws CentralException {
// make sure the given path is a relative one
path = stripDataFilePath(path);
Central central = callREST("File/" + path);
List<DataFile> dataFiles = central.getDataFile();
DataFile dataFile;
if (dataFiles.size() == 1) {
dataFile = dataFiles.get(0);
// fix for broken isDirectory support
if (dataFile.getDataFile().size() > 0 || !dataFile.getName().contains(".")) {
dataFile.setIsDirectory(true);
}
// fix for broken content link
if (dataFile.getContentLink().startsWith("/File")) {
dataFile.setContentLink("/REST" + dataFile.getContentLink());
}
fixDataFiles(dataFile.getDataFile());
} else {
dataFile = null;
}
return dataFile;
}
/**
* Get the URL for a data file.
*
* @param dataFile the data file
* @return the URL for the data file
*/
public URL getDataFileURL(DataFile dataFile) {
String urlString = baseURL + dataFile.getContentLink();
if (gaSession != null) {
urlString += "?GAsession=" + gaSession;
}
URL url = null;
try { url = new URL(urlString); } catch (MalformedURLException e) {}
return url;
}
/**
* Returns a relative path based on the given path. This removes various
* roots from the path that may make it an absolute path.
*
* @param path the path for the data file
* @return the relative path for the data file
*/
private static String stripDataFilePath(String path) {
if (path.startsWith("/REST/File/")) {
path = path.substring(11);
} else if (path.startsWith("/File/")) {
path = path.substring(6);
} else if (path.startsWith("/")) {
path = path.substring(1);
}
return path;
}
/**
* "Fixes" the data files by populating various fields based on educated
* guesses. This is also removes any duplicate data file from the list.
*
* @param dataFiles the data file to fix
*/
private static void fixDataFiles(List<DataFile> dataFiles) {
fixDataFiles(dataFiles, null);
}
/**
* "Fixes" the data files by populating various fields based on educated
* guesses. This is also removes any duplicate data file from the list.
*
* Any data file who's name begins with the start filter will be removed from
* the list.
*
* @param dataFiles the data file to fix
* @param startFilter a filter for the data files
*/
private static void fixDataFiles(List<DataFile> dataFiles, String startFilter) {
for (DataFile dataFile : dataFiles) {
// fix for broken links
String link = dataFile.getLink();
if (!link.startsWith("/REST")) {
link = "/REST" + link;
dataFile.setLink(link);
}
// set the content link
dataFile.setContentLink(link + "/content");
String fullPath = link.substring(11);
int lastSlashIndex = fullPath.lastIndexOf('/');
// set the name and path
String name, path;
if (lastSlashIndex != -1) {
name = fullPath.substring(lastSlashIndex+1);
path = fullPath.substring(0, lastSlashIndex);
} else {
name = fullPath;
path = ".";
}
dataFile.setName(name);
dataFile.setPath(path);
// guess if this is a directory
if (!name.contains(".")) {
dataFile.setIsDirectory(true);
}
}
// remove duplicate and filtered item
for (int i=dataFiles.size()-1; i>=0; i
DataFile dataFile = dataFiles.get(i);
if (hasDuplicate(dataFiles, dataFile)) {
dataFiles.remove(i);
} else if (startFilter != null && dataFile.getName().startsWith(startFilter)) {
dataFiles.remove(i);
}
}
}
/**
* Sees if the given data file has more than one occurance in the list of data
* files.
*
* @param dataFiles a list of data files
* @param dataFile the data file to check for duplicates
* @return true if the given data file occurs more than once in the
* list of data files, otherwise false
*/
private static boolean hasDuplicate(List<DataFile> dataFiles, DataFile dataFile) {
int count = 0;
for (DataFile df : dataFiles) {
if (dataFile.getPath().equals(df.getPath()) &&
dataFile.getName().equals(df.getName())) {
count++;
if (count > 1) {
return true;
}
}
}
return false;
}
/**
* A filter to remove a namespace from XML elements.
*/
class RemoveNamespaceFilter extends XMLFilterImpl {
/** the namespace to filter */
private final String namespace;
/**
* Creates the namespace filter.
*
* @param xmlReader the XML reader
* @param namespace the namespace to filter
*/
public RemoveNamespaceFilter(XMLReader xmlReader, String namespace) {
super(xmlReader);
this.namespace = namespace;
}
/**
* This will set the namespace of the element to an empty string if it is
* null or equals the filtered namespace.
*/
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (uri == null || uri.equals(namespace)) {
uri = "";
}
super.startElement(uri, localName, qName, attributes);
}
}
}
|
package org.sugarj.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.CopyOption;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import org.apache.commons.io.IOUtils;
import org.sugarj.common.path.AbsolutePath;
import org.sugarj.common.path.Path;
import org.sugarj.common.path.RelativePath;
/**
* Provides methods for doing stuff with files.
*
* @author Sebastian Erdweg <seba at informatik uni-marburg de>
*/
public class FileCommands {
public final static boolean DO_DELETE = true;
public final static String TMP_DIR;
static {
try {
TMP_DIR = File.createTempFile("tmp", "").getParent();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
*
* @param suffix
* without dot "."
* @return
* @throws IOException
*/
public static Path newTempFile(String suffix) throws IOException {
File f = File.createTempFile("sugarj", suffix == null || suffix.isEmpty() ? suffix : "." + suffix);
final Path p = new AbsolutePath(f.getAbsolutePath());
return p;
}
public static void deleteTempFiles(Path file) throws IOException {
if (file == null)
return;
String parent = file.getFile().getParent();
if (parent == null)
return;
else if (parent.equals(TMP_DIR))
delete(file);
else
deleteTempFiles(new AbsolutePath(parent));
}
public static void delete(Path file) throws IOException {
if (file == null)
return;
if (file.getFile().listFiles() != null)
for (File f : file.getFile().listFiles())
FileCommands.delete(new AbsolutePath(f.getPath()));
file.getFile().delete();
}
public static void delete(File file) throws IOException {
delete(file.toPath());
}
public static void delete(java.nio.file.Path file) throws IOException {
if (file == null)
return;
Files.walkFileTree(file, new FileVisitor<java.nio.file.Path>() {
@Override
public FileVisitResult preVisitDirectory(java.nio.file.Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(java.nio.file.Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
public static void copyFile(Path from, Path to, CopyOption... options) throws IOException {
Set<CopyOption> optSet = new HashSet<>();
for (CopyOption o : options)
optSet.add(o);
optSet.add(StandardCopyOption.REPLACE_EXISTING);
Files.copy(from.getFile().toPath(), to.getFile().toPath(), optSet.toArray(new CopyOption[optSet.size()]));
}
public static void copyFile(File from, File to, CopyOption... options) throws IOException {
Set<CopyOption> optSet = new HashSet<>();
for (CopyOption o : options)
optSet.add(o);
optSet.add(StandardCopyOption.REPLACE_EXISTING);
Files.copy(from.toPath(), to.toPath(), optSet.toArray(new CopyOption[optSet.size()]));
}
public static void copyFile(InputStream in, OutputStream out) throws IOException {
int len;
byte[] b = new byte[1024];
while ((len = in.read(b)) > 0)
out.write(b, 0, len);
}
public static boolean acceptableAsAbsolute(String path) {
return new File(path).isAbsolute() || path.startsWith("./") || path.startsWith("." + File.separator) || path.equals(".");
}
/**
* Beware: one must not rename SDF files since the filename and the module
* name needs to coincide. Instead generate a new file which imports the other
* SDF file.
*
* @param file
* @param content
* @throws IOException
*/
public static void writeToFile(Path file, String content) throws IOException {
FileCommands.createFile(file);
FileOutputStream fos = new FileOutputStream(file.getFile());
fos.write(content.getBytes());
fos.close();
}
public static void writeToFile(java.nio.file.Path file, String content) throws IOException {
Files.write(file, Collections.singleton(content));
}
public static void writeToFile(File file, String content) throws IOException {
writeToFile(file.toPath(), content);
}
public static void writeLinesFile(Path file, List<String> lines) throws IOException {
FileCommands.createFile(file);
BufferedWriter writer = new BufferedWriter(new FileWriter(file.getFile()));
Iterator<String> iter = lines.iterator();
while (iter.hasNext()) {
writer.write(iter.next());
if (iter.hasNext()) {
writer.write("\n");
}
}
writer.flush();
writer.close();
}
public static void appendToFile(Path file, String content) throws IOException {
createFile(file);
FileOutputStream fos = new FileOutputStream(file.getFile(), true);
fos.write(content.getBytes());
fos.close();
}
public static byte[] readFileAsByteArray(Path file) throws IOException {
return readFileAsByteArray(file.getFile());
}
public static byte[] readFileAsByteArray(File file) throws IOException {
return Files.readAllBytes(file.toPath());
}
public static String readFileAsString(File file) throws IOException {
return readFileAsString(new AbsolutePath(file.getAbsolutePath()));
}
public static String readFileAsString(Path filePath) throws IOException {
StringBuilder fileData = new StringBuilder(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath.getFile()));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1)
fileData.append(buf, 0, numRead);
reader.close();
return fileData.toString();
}
public static List<String> readFileLines(Path filePath) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filePath.getFile()));
List<String> lines = new ArrayList<>();
String temp;
while ((temp = reader.readLine()) != null) {
lines.add(temp);
}
reader.close();
return lines;
}
public static String readStreamAsString(InputStream in) throws IOException {
StringBuilder fileData = new StringBuilder(1000);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1)
fileData.append(buf, 0, numRead);
reader.close();
return fileData.toString();
}
public static String fileName(URL url) {
return fileName(new AbsolutePath(url.getPath()));
}
public static String fileName(File url) {
return fileName(toCygwinPath(url.getPath()));
}
public static String fileName(URI uri) {
return fileName(new AbsolutePath(uri.getPath()));
}
public static String fileName(Path file_doof) {
return fileName(toCygwinPath(file_doof.getAbsolutePath()));
}
public static String fileName(String file) {
int index = file.lastIndexOf(File.separator);
if (index >= 0)
file = file.substring(index + 1);
index = file.lastIndexOf(".");
if (index > 0)
file = file.substring(0, index);
return file;
}
public static RelativePath[] listFiles(Path p) {
return listFiles(p, null);
}
public static RelativePath[] listFiles(Path p, FileFilter filter) {
File[] files = p.getFile().listFiles(filter);
RelativePath[] paths = new RelativePath[files.length];
for (int i = 0; i < files.length; i++)
paths[i] = new RelativePath(p, files[i].getName());
return paths;
}
public static Stream<File> streamFiles(File dir, FileFilter filter) {
return streamFiles(dir).filter((File f) -> filter.accept(f));
}
@SuppressWarnings("resource")
public static Stream<File> streamFiles(File dir) {
Stream<java.nio.file.Path> files;
try {
files = Files.walk(dir.toPath());
} catch (IOException e) {
files = Stream.empty();
}
return files.map(java.nio.file.Path::toFile);
}
public static List<java.nio.file.Path> listFilesRecursive(java.nio.file.Path p) {
return listFilesRecursive(p, null);
}
public static List<java.nio.file.Path> listFilesRecursive(java.nio.file.Path p, final FileFilter filter) {
// Guarentees that list is mutable
try {
Predicate<java.nio.file.Path> isDir = Files::isDirectory;
final Stream<java.nio.file.Path> allFiles = Files.walk(p).filter(isDir.negate());
final Stream<java.nio.file.Path> filteredFiles;
if (filter == null) {
filteredFiles = allFiles;
} else {
filteredFiles = allFiles.filter((java.nio.file.Path x) -> filter.accept(x.toFile()));
}
List<java.nio.file.Path> paths = filteredFiles.collect(Collectors.toCollection(ArrayList::new));
return paths;
} catch (IOException e) {
return Collections.emptyList();
}
}
/**
* Finds the given file in the given list of paths.
*
* @param filename
* relative filename.
* @param paths
* list of possible paths to filename
* @return full file path to filename or null
*/
@Deprecated
public static String findFile(String filename, List<String> paths) {
return findFile(filename, paths.toArray(new String[] {}));
}
/**
* Finds the given file in the given list of paths.
*
* @param filename
* relative filename.
* @param paths
* list of possible paths to filename
* @return full file path to filename or null
*/
@Deprecated
public static String findFile(String filename, String... paths) {
for (String path : paths) {
File f = new File(path + File.separator + filename);
if (f.exists())
return f.getAbsolutePath();
}
return null;
}
public static File newTempDir() throws IOException {
final File f = File.createTempFile("SugarJ", "");
// need to delete the file, but want to reuse the filename
f.delete();
f.mkdir();
return f;
}
public static File tryNewTempDir() {
try {
return newTempDir();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void prependToFile(Path file, String head) throws IOException {
Path tmp = newTempFile("");
file.getFile().renameTo(tmp.getFile());
FileInputStream in = new FileInputStream(tmp.getFile());
FileOutputStream out = new FileOutputStream(file.getFile());
out.write(head.getBytes());
int len;
byte[] b = new byte[1024];
while ((len = in.read(b)) > 0)
out.write(b, 0, len);
in.close();
out.close();
delete(tmp);
}
public static void createFile(Path file) throws IOException {
File f = file.getFile();
if (f.getParentFile().mkdirs())
f.createNewFile();
}
public static void createFile(java.nio.file.Path file) throws IOException {
try {
Files.createDirectories(file.getParent());
Files.createFile(file);
} catch (FileAlreadyExistsException e) {
// Is ok, then the file is there
}
}
public static void createFile(File file) throws IOException {
createFile(file.toPath());
}
/**
* Create file with name deduced from hash in dir.
*
* @param dir
* @param hash
* @return
* @throws IOException
*/
public static Path createFile(Path dir, int hash) throws IOException {
Path p = new RelativePath(dir, hashFileName("sugarj", hash));
createFile(p);
return p;
}
public static void createDir(Path dir) throws IOException {
boolean isMade = dir.getFile().mkdirs();
boolean exists = dir.getFile().exists();
if (!isMade && !exists)
throw new IOException("Failed to create the directories\n" + dir);
}
public static void createDir(java.nio.file.Path dir) throws IOException {
Files.createDirectories(dir);
boolean exists = Files.exists(dir);
if (!exists)
throw new IOException("Failed to create the directories\n" + dir);
}
/**
* Create directory with name deduced from hash in dir.
*
* @param dir
* @param hash
* @return
* @throws IOException
*/
public static Path createDir(Path dir, int hash) throws IOException {
Path p = new RelativePath(dir, hashFileName("SugarJ", hash));
createDir(p);
return p;
}
/**
* Ensures that a path is suitable for a cygwin command line.
*/
public static String toCygwinPath(String filepath) {
// XXX hacky
if (System.getProperty("os.name").toLowerCase().contains("win")) {
filepath = filepath.replace("\\", "/");
filepath = filepath.replace("/C:/", "/cygdrive/C/");
filepath = filepath.replace("C:/", "/cygdrive/C/");
}
return filepath;
}
/**
* Ensure that a path is suitable for a windows command line
*/
public static String toWindowsPath(String filepath) {
// XXX hacky
if (System.getProperty("os.name").toLowerCase().contains("win")) {
filepath = filepath.replace("/cygdrive/C", "C:");
filepath = filepath.replace("/C:", "C:");
filepath = filepath.replace("/", "\\");
}
return filepath;
}
/**
* checks whether f1 was modified after f2.
*
* @return true iff f1 was modified after f2.
*/
public static boolean isModifiedLater(Path f1, Path f2) {
return f1.getFile().lastModified() > f2.getFile().lastModified();
}
public static boolean fileExists(Path file) {
return file != null && file.getFile().exists() && file.getFile().isFile();
}
public static boolean fileExists(File file) {
return file != null && file.exists() && file.isFile();
}
public static boolean exists(Path file) {
return file != null && file.getFile().exists();
}
public static boolean exists(File file) {
return file != null && file.exists();
}
public static boolean exists(java.nio.file.Path file) {
return file != null && Files.exists(file);
}
public static boolean exists(URI file) {
return new File(file).exists();
}
public static String hashFileName(String prefix, int hash) {
return prefix + (hash < 0 ? "1" + Math.abs(hash) : "0" + hash);
}
public static String hashFileName(String prefix, Object o) {
return hashFileName(prefix, o.hashCode());
}
public static String getExtension(Path infile) {
return getExtension(infile.getFile());
}
public static String getExtension(File infile) {
return getExtension(infile.getName());
}
public static String getExtension(String infile) {
int i = infile.lastIndexOf('.');
if (i > 0)
return infile.substring(i + 1, infile.length());
return null;
}
public static String dropExtension(String file) {
int i = file.lastIndexOf('.');
if (i > 0)
return file.substring(0, i);
return file;
}
public static java.nio.file.Path dropExtension(java.nio.file.Path p) {
java.nio.file.Path file = p.getFileName();
java.nio.file.Path parent = p.getParent();
String fileName = file.toString();
int i = fileName.lastIndexOf('.');
if (i > 0) {
String newName = fileName.substring(0, i);
return parent.resolve(newName);
}
return p;
}
public static String dropDirectory(Path p) {
String ext = getExtension(p);
if (ext == null)
return fileName(p);
else
return fileName(p) + "." + getExtension(p);
}
public static AbsolutePath replaceExtension(AbsolutePath p, String newExtension) {
return p.replaceExtension(newExtension);
}
public static RelativePath replaceExtension(RelativePath p, String newExtension) {
return p.replaceExtension(newExtension);
}
public static java.nio.file.Path replaceExtension(java.nio.file.Path p, String newExtension) {
java.nio.file.Path withoutExt = dropExtension(p);
return addExtension(withoutExt, newExtension);
}
public static File replaceExtension(File p, String newExtension) {
return replaceExtension(p.toPath(), newExtension).toFile();
}
public static Path addExtension(Path p, String newExtension) {
if (p instanceof RelativePath)
return new RelativePath(((RelativePath) p).getBasePath(), ((RelativePath) p).getRelativePath() + "." + newExtension);
return new AbsolutePath(p.getAbsolutePath() + "." + newExtension);
}
public static AbsolutePath addExtension(AbsolutePath p, String newExtension) {
return new AbsolutePath(p.getAbsolutePath() + "." + newExtension);
}
public static java.nio.file.Path addExtension(java.nio.file.Path p, String newExtension) {
return p.getParent().resolve(p.getFileName() + "." + newExtension);
}
public static File addExtension(File p, String newExtension) {
return addExtension(p.toPath(), newExtension).toFile();
}
public static RelativePath dropFilename(RelativePath file) {
return new RelativePath(file.getBasePath(), dropFilename(file.getRelativePath()));
}
public static AbsolutePath dropFilename(Path file) {
return new AbsolutePath(dropFilename(file.getAbsolutePath()));
}
public static String dropFilename(String file) {
int i = file.lastIndexOf(File.separator);
if (i > 0)
return file.substring(0, i);
return "";
}
public static byte[] fileHash(Path file) throws IOException {
try (FileInputStream inputStream = new FileInputStream(file.getFile())) {
return streamHash(inputStream);
}
}
public static byte[] fileHash(java.nio.file.Path file) throws IOException {
try (InputStream inputStream = Files.newInputStream(file)) {
return streamHash(inputStream);
}
}
public static byte[] streamHash(InputStream inputStream) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] bytesBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytesBuffer)) != -1) {
digest.update(bytesBuffer, 0, bytesRead);
}
byte[] hashedBytes = digest.digest();
return hashedBytes;
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static byte[] tryFileHash(Path file) {
try {
return FileCommands.fileHash(file);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static boolean isEmptyFile(Path prog) throws IOException {
FileInputStream in = null;
try {
in = new FileInputStream(prog.getFile());
if (in.read() == -1)
return true;
return false;
} finally {
if (in != null)
in.close();
}
}
// cai 27.09.12
// convert path-separator to that of the OS
// so that strategoXT doesn't prepend ./ to C:/foo/bar/baz.
public static String nativePath(String path) {
return path.replace('/', File.separatorChar);
}
public static RelativePath getRelativePath(Path base, Path fullPath) {
if (fullPath instanceof RelativePath && ((RelativePath) fullPath).getBasePath().equals(base))
return (RelativePath) fullPath;
String baseS = base.getAbsolutePath();
String fullS = fullPath.getAbsolutePath();
if (fullS.startsWith(baseS))
return new RelativePath(base, fullS.substring(baseS.length()));
return null;
}
public static java.nio.file.Path getRelativePath(java.nio.file.Path base, java.nio.file.Path fullPath) {
try {
return base.relativize(fullPath);
} catch (IllegalArgumentException e) {
// Cannot be relativized
return null;
}
}
public static java.nio.file.Path getRelativePath(File base, File fullPath) {
return getRelativePath(base.toPath(), fullPath.toPath());
}
public static Path copyFile(Path from, Path to, Path file, CopyOption... options) {
RelativePath p = getRelativePath(from, file);
if (p == null)
return null;
RelativePath target = new RelativePath(to, p.getRelativePath());
if (!FileCommands.exists(p))
return target;
try {
copyFile(p, target, options);
return target;
} catch (IOException e) {
e.printStackTrace();
return target;
}
}
public static File copyFile(File from, File to, File file, CopyOption... options) {
java.nio.file.Path p = getRelativePath(from, file);
if (p == null)
return null;
File target = new File(to, p.toString());
try {
if (!FileCommands.exists(target))
target.getParentFile().mkdirs();
copyFile(file, target, options);
return target;
} catch (IOException e) {
e.printStackTrace();
return target;
}
}
public static String tryGetRelativePath(Path p) {
if (p instanceof RelativePath)
return ((RelativePath) p).getRelativePath();
return p.getAbsolutePath();
}
public static java.nio.file.Path getRessourcePath(Class<?> clazz) {
String className = clazz.getName();
URL url = clazz.getResource(className.substring(className.lastIndexOf(".") + 1) + ".class");
return getRessourcePath(url);
}
public static java.nio.file.Path getRessourcePath(URL url) {
String path = url == null ? null : url.getPath();
if (path == null)
return null;
// remove URL leftovers
if (path.startsWith("file:")) {
path = path.substring("file:".length());
}
// is the class file inside a jar?
if (path.contains(".jar!")) {
path = path.substring(0, path.indexOf(".jar!") + ".jar".length());
}
// have we found the class file?
try {
return Paths.get(path);
} catch (InvalidPathException e) {
return null;
}
}
public static boolean acceptable(String path) {
return new File(path).isAbsolute() || path.startsWith("./") || path.startsWith("." + File.separator) || path.equals(".");
}
public static File unpackJarfile(File jar) throws IOException {
File dir = newTempDir();
unpackJarfile(dir, jar);
return dir;
}
public static void unpackJarfile(File outdir, File jar) throws IOException {
try (JarFile jarFile = new JarFile(jar)) {
Enumeration<? extends ZipEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File entryDestination = new File(outdir.getAbsolutePath(), entry.getName());
entryDestination.getParentFile().mkdirs();
if (entry.isDirectory())
entryDestination.mkdirs();
else {
InputStream in = jarFile.getInputStream(entry);
OutputStream out = new FileOutputStream(entryDestination);
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
}
}
|
package com.anuragkapur.ctci.recursionanddp;
public class Prob9_2_RobotInGrid {
static int countCalls = 0;
/**
* Simple recursive solution. Has overlapping sub-problems and hence can be optimised by DP. The presence of
* overlapping sub-problems is evident by inspecting the sysout in the else block below.
*
* Run time complexity: O(2^n)
* T(x, y) = T(x-1, y) + T(x, y-1) + 1
* Abusing the notation, let x = y
* T(x, x) = 2 * T(x-1, x) = 2 * 2 * T(x-2, x) = ... = 2 * ... * 2 * T(0, x)
* = O(2^n)
*
* With memoization, there is constant amount of work happening in x * y calls. Thus,
* Run time complexity: O(xy)
*
* @param x
* @param y
* @return
*/
public int countPaths(int x, int y) {
if(x == 0 && y == 0) {
return 0;
} else if(x == 0) {
return 1;
} else if(y == 0) {
return 1;
} else {
countCalls ++;
System.out.println(countCalls + " :: " + x + " :: " + y);
int count = countPaths(x-1, y);
count += countPaths(x, y-1);
return count;
}
}
}
|
package com.chaoticdawgsoftware.algorithms;
import com.chaoticdawgsoftware.algorithms.retrievers.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ListIterator;
public class CreateAlgorithmEnums {
private static Retriever[] retrievers = {
new AlgorithmParameterGeneratorRetriever(),
new AlgorithmParametersRetriever(),
new CertificateFactoryRetriever(),
new CertPathBuilderRetriever(),
new CertPathRetriever(),
new CertPathValidatorRetriever(),
new CertStoreRetriever(),
new CipherRetriever(),
new KeyAgreementRetriever(),
new KeyFactoryRetriever(),
new KeyGeneratorRetriever(),
new KeyManagerFactoryRetriever(),
new KeyPairGeneratorRetriever(),
new KeyStoreRetriever(),
new MacRetriever(),
new MessageDigestRetriever(),
new SecretKeyFactoryRetriever(),
new SecureRandomRetriever(),
new SignatureRetriever(),
new SSLContextRetriever(),
new TrustManagerFactoryRetriever()
};
public static void create() {
createEnumsDirectory();
createEnums();
}
private static void createEnums() {
String fullClassName;
String[] splitFullClassName;
String packageName;
String className;
for (Retriever retriever: retrievers) {
fullClassName = retriever.getClass().getName();
splitFullClassName = fullClassName.split("\\.");
packageName = getPackageNameFromFullClassName(splitFullClassName);
className = splitFullClassName[splitFullClassName.length - 1];
className = className.substring(0, className.length() - "Retriever".length());
FileWriter out = null;
String filePath = buildPathFromClassName(splitFullClassName);
String fileName = filePath + className + "Algorithms.java";
if (!(new File(fileName).exists())) {
try {
out = new FileWriter(fileName);
out.write("package " + packageName + ".enums;\n\n");
out.write("@SuppressWarnings({\"unused\", \"SpellCheckingInspection\"})\n");
out.write("public enum " + className + "Algorithms {\n");
ListIterator<String> iterator = retriever.getAlgorithms().listIterator();
while (iterator.hasNext()) {
String toString = iterator.next();
String temp = toString;
boolean needsAnonymous = false;
if (Character.isDigit(temp.charAt(0))) {
temp = "_" + temp;
}
if (temp.contains(".") || temp.contains("/") || temp.contains("-")) {
needsAnonymous = true;
temp = temp.replace(".","_");
temp = temp.replace("/", "_");
temp = temp.replace("-", "_");
}
out.write("\t" + temp);
if (needsAnonymous) {
out.write(" {\n\t\tpublic String toString() {\n\t\t\treturn \""
+ toString + "\";\n\t\t}\n\t}");
}
if (iterator.hasNext()) {
out.write(",");
}
out.write("\n");
}
out.write("}");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
private static void createEnumsDirectory() {
String fullClassName= CreateAlgorithmEnums.class.getName();
String[] splitFullClassName = fullClassName.split("\\.");
String path = buildPathFromClassName(splitFullClassName);
File directory = new File(path);
if(!(directory.exists()))
if(!directory.mkdir())
// Change to throw an error
System.out.println("Error: unable to create directory");
}
private static String getPackageNameFromFullClassName(String[] splitFullClassName) {
String packageName = "";
if (splitFullClassName.length > 0) {
for (int i = 0; i < 3; ++i) {
packageName += splitFullClassName[i];
if (i < 2) {
packageName += ".";
}
}
} else {
// PackageNameUnderflowException
throw new ArrayIndexOutOfBoundsException("Index must be greater than zero.");
}
return packageName;
}
// "src/" + splitFullClassName[0] + "/" + splitFullClassName[1] + "/" + splitFullClassName[2] + "/";
private static String buildPathFromClassName(String[] splitFullClassName) {
String filePath = "src/";
if (splitFullClassName.length > 0) {
for (int i = 0; i < 3; ++i) {
filePath += splitFullClassName[i] + "/";
}
} else {
// FilePathUnderflowException
throw new ArrayIndexOutOfBoundsException("Index must be greater than zero.");
}
return filePath + "enums/";
}
}
|
package com.codepath.wwcmentorme.activities;
import android.app.Fragment;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.codepath.wwcmentorme.R;
import com.codepath.wwcmentorme.fragments.EditProfileExperiencesFragment;
import com.codepath.wwcmentorme.fragments.EditProfileLocationFragment;
import com.codepath.wwcmentorme.fragments.EditProfileSkillsFragment;
import com.codepath.wwcmentorme.models.User;
import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
public class EditProfileActivity extends AppActivity {
public static final String PROFILE_REF = "profile";
public interface OnKeyboardVisibilityListener {
void onVisibilityChanged(boolean visible);
}
private ImageView ivUserProfile;
private TextView tvFirstName;
private TextView tvLastName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
setupViews();
setupKeyboardVisibilityListener();
getFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment f = getFragmentManager().findFragmentById(R.id.flContainer);
if (f != null) {
updateTitle(f);
}
}
});
}
@Override
public void onResume() {
super.onResume();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
// If the user is not logged in, go to the
// activity showing the login view.
startLoginActivity();
} else if (currentUser.get(PROFILE_REF) != null) {
// Check if the user is currently logged
// and show any cached content
User mentorMeUser = (User)currentUser.get(PROFILE_REF);
mentorMeUser.fetchIfNeededInBackground(new GetCallback<User>() {
@Override
public void done(User user, ParseException pe) {
if (pe == null) {
populateViewsWithUserInfo(user);
}
}
});
} else {
// user is logged in but profile hasn't been sync'd
// Fetch Facebook user info if the session is active
Session session = ParseFacebookUtils.getSession();
if (session != null && session.isOpened()) {
makeMeRequest();
} else {
startLoginActivity();
}
}
}
private void startLoginActivity() {
Intent intent = new Intent(this, FbLoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void makeMeRequest() {
// Populate mentor me user with facebook profile info
Request request = Request.newMeRequest(ParseFacebookUtils.getSession(),
new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser fbGraphUser, Response response) {
if (fbGraphUser != null) {
User mentorMeUser = new User();
mentorMeUser.setFacebookId(Long.valueOf(fbGraphUser.getId()));
mentorMeUser.setFirstName(fbGraphUser.getFirstName());
mentorMeUser.setLastName(fbGraphUser.getLastName());
if (fbGraphUser.getProperty("email") != null) {
mentorMeUser.setEmail((String)fbGraphUser.getProperty("email"));
}
if (fbGraphUser.getLocation() != null && fbGraphUser.getLocation().getProperty("name") != null) {
String locationName = (String) fbGraphUser.getLocation().getProperty("name");
String city = TextUtils.substring(locationName, 0, locationName.indexOf(","));
mentorMeUser.setCity(city);
}
if (fbGraphUser.getProperty("gender") != null) {
mentorMeUser.setGender((String) fbGraphUser.getProperty("gender"));
mentorMeUser.setIsMentee("female".equalsIgnoreCase(mentorMeUser.getGender()));
}
if (fbGraphUser.getProperty("about") != null) {
mentorMeUser.setAboutMe((String) fbGraphUser.getProperty("about"));
}
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.put(PROFILE_REF, mentorMeUser);
currentUser.saveInBackground();
// Show the user info
populateViewsWithUserInfo(mentorMeUser);
} else if (response.getError() != null) {
if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
|| (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {
Log.d("MentorMe", "The facebook session was invalidated.");
onLogoutButtonClicked();
} else {
Log.d("MentorMe", "Some other error: " + response.getError().getErrorMessage());
}
}
}
});
request.executeAsync();
}
private void onLogoutButtonClicked() {
// Log the user out
ParseUser.logOut();
// Go to the login view
startLoginActivity();
}
private void populateViewsWithUserInfo(User mentorMeUser) {
User.setMe(mentorMeUser.getFacebookId());
ImageLoader.getInstance().displayImage(mentorMeUser.getProfileImageUrl(200), ivUserProfile);
tvFirstName.setText(mentorMeUser.getFirstName());
tvLastName.setText(mentorMeUser.getLastName());
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.flContainer, new EditProfileLocationFragment(), "1");
ft.commit();
}
private void setupViews() {
ivUserProfile = (ImageView) findViewById(R.id.ivUserProfile);
tvFirstName = (TextView) findViewById(R.id.tvFirstName);
tvLastName = (TextView) findViewById(R.id.tvLastName);
}
private void setupKeyboardVisibilityListener() {
final View activityRootView = findViewById(R.id.rlEditProfileRootContainer);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
private final Rect r = new Rect();
private boolean wasOpened;
@Override
public void onGlobalLayout() {
//r will be populated with the coordinates of your view that area still visible.
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView().getHeight() - r.height();
boolean isOpen = heightDiff > 100;
if (isOpen != wasOpened) { // if more than 100 pixels, it's probably an open keyboard
wasOpened = isOpen;
Fragment currentFragment = getFragmentManager().findFragmentById(R.id.flContainer);
if (currentFragment != null) {
((OnKeyboardVisibilityListener) currentFragment).onVisibilityChanged(isOpen);
}
}
}
});
}
private void updateTitle(Fragment f) {
setTitle(String.format("%s %s/3", getString(R.string.title_activity_edit_profile), f.getTag()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_profile, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void goToStep2(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.flContainer, new EditProfileExperiencesFragment(), "2").addToBackStack(null);
ft.commit();
}
public void goToAddSkills(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.flContainer, new EditProfileSkillsFragment(), "3").addToBackStack(null);
ft.commit();
}
public void addMentorSkills(View v) {
}
public void addMenteeSkills(View v) {
}
}
|
package com.five35.minecraft.fractalcrates.client;
import com.five35.minecraft.fractalcrates.CrateTileEntity;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.client.IItemRenderer;
import net.minecraftforge.common.ForgeDirection;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
public class CrateRenderer extends TileEntitySpecialRenderer implements IItemRenderer, ISimpleBlockRenderingHandler {
private final EntityItem itemEntity = new EntityItem(null);
private final RenderItem itemRenderer = new RenderItem() {
@Override
public boolean shouldBob() {
return false;
}
};
protected final int renderId;
private static boolean renderBlock(final BlockRenderHelper helper) {
return CrateRenderer.renderBlock(helper, null);
}
private static boolean renderBlock(final BlockRenderHelper helper, final Icon override) {
boolean rendered = false;
final Icon icon = override != null ? override : helper.getIcon(ForgeDirection.DOWN);
// full faces
rendered |= helper.renderFace(ForgeDirection.DOWN, icon);
rendered |= helper.renderFace(ForgeDirection.NORTH, icon);
rendered |= helper.renderFace(ForgeDirection.SOUTH, icon);
rendered |= helper.renderFace(ForgeDirection.WEST, icon);
rendered |= helper.renderFace(ForgeDirection.EAST, icon);
// rim
rendered |= helper.renderQuad(ForgeDirection.UP, icon, 0, 0, 0, 15, 1);
rendered |= helper.renderQuad(ForgeDirection.UP, icon, 0, 0, 1, 1, 16);
rendered |= helper.renderQuad(ForgeDirection.UP, icon, 0, 1, 15, 16, 16);
rendered |= helper.renderQuad(ForgeDirection.UP, icon, 0, 15, 0, 16, 15);
// "bowl"
rendered |= helper.renderQuad(ForgeDirection.UP, icon, 15, 1, 1, 15, 15);
rendered |= helper.renderQuad(ForgeDirection.NORTH, icon, 15, 1, 0, 15, 15);
rendered |= helper.renderQuad(ForgeDirection.SOUTH, icon, 15, 1, 0, 15, 15);
rendered |= helper.renderQuad(ForgeDirection.WEST, icon, 15, 1, 0, 15, 15);
rendered |= helper.renderQuad(ForgeDirection.EAST, icon, 15, 1, 0, 15, 15);
return rendered;
}
public CrateRenderer(final int renderId) {
this.renderId = renderId;
this.itemEntity.hoverStart = 0;
this.itemRenderer.setRenderManager(RenderManager.instance);
}
@Override
public int getRenderId() {
return this.renderId;
}
@Override
public boolean handleRenderType(final ItemStack item, final ItemRenderType type) {
return true;
}
@Override
public void renderInventoryBlock(final Block block, final int metadata, final int modelId, final RenderBlocks renderer) {
CrateRenderer.renderBlock(new InventoryBlockRenderHelper(block, metadata));
}
@Override
public void renderItem(final ItemRenderType type, final ItemStack stack, final Object... data) {
if (type == ItemRenderType.ENTITY) {
GL11.glPushMatrix();
GL11.glTranslated(-0.5, -0.5, -0.5);
}
CrateRenderer.renderBlock(new InventoryBlockRenderHelper(Block.blocksList[stack.itemID], stack.getItemDamage()));
if (stack.stackTagCompound != null && stack.stackTagCompound.hasKey("Contents")) {
final ItemStack contents = ItemStack.loadItemStackFromNBT(stack.stackTagCompound.getCompoundTag("Contents"));
contents.stackSize = 1;
GL11.glPushMatrix();
GL11.glTranslated(0.5, 0.5, 0.5);
GL11.glScaled(3.3, 3.3, 3.3);
this.renderStack(contents);
GL11.glPopMatrix();
}
if (type == ItemRenderType.ENTITY) {
GL11.glPopMatrix();
} else if (type == ItemRenderType.INVENTORY) {
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
}
}
private void renderStack(final ItemStack stack) {
try {
this.itemEntity.setEntityItemStack(stack);
this.itemRenderer.doRenderItem(this.itemEntity, 0, 0, 0, 0, 0);
} catch (final NullPointerException ex) {
// the render manager's render engine is null when rendering held items before the world is drawn
}
}
@Override
public void renderTileEntityAt(final TileEntity entity, final double x, final double y, final double z, final float time) {
if (!(entity instanceof CrateTileEntity)) {
return;
}
final CrateTileEntity crateEntity = (CrateTileEntity) entity;
final ItemStack contents = crateEntity.getStackInSlot(0);
if (contents == null || contents.stackSize == 0) {
return;
}
final ItemStack copy = contents.copy();
copy.stackSize = 1;
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
final Block block = contents.itemID < Block.blocksList.length ? Block.blocksList[contents.itemID] : null;
if (contents.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d(block.getRenderType())) {
// blocks render three "pixels" wide, with 2/5 of a pixel spacing between them
// 2.9 = 1 pixel of crate wall + .4 pixel gap + 1.5 pixels to offset entity origin (half their width)
double offset = 2.9 / 16;
GL11.glTranslated(offset, offset, offset);
// blocks normally render at 1/4 size; we need 3/16
GL11.glScaled(0.75, 0.75, 0.75);
// 3.4 = 3 pixels per block + .4 pixel gap
offset = 3.4 / 12;
for (int i = 0; i < contents.stackSize; i++) {
GL11.glPushMatrix();
final int itemX = i & 3;
final int itemY = i >> 4;
final int itemZ = i >> 2 & 3;
GL11.glTranslated(itemX * offset, itemY * offset, itemZ * offset);
this.renderStack(copy);
GL11.glPopMatrix();
}
} else {
GL11.glTranslated(0.5, 0.5, 0.5);
GL11.glScaled(5 / 6d, 5 / 6d, 5 / 6d);
GL11.glTranslated(-0.5, -0.5, -0.5);
// scale to half size (four quadrants)
GL11.glScaled(0.5, 0.5, 0.5);
for (int i = 0; i < contents.stackSize; i++) {
GL11.glPushMatrix();
// add four items to each quadrant before moving on to the next
// fill all quadrants before moving to the next layer
final int itemX = i >> 2 & 1;
final int itemY = (i >> 4) * 4 + (i & 3);
final int itemZ = i >> 3 & 1;
// 4/31 arranges the vertical stack so that the top of the
// topmost items coincides with the top of the block and the
// bottom of the bottommost items coincides with the bottom of
// the block
GL11.glTranslated(itemX, itemY * 4 / 31d, itemZ);
// so that it will lay face-up
GL11.glTranslated(0.5, 0.5, 0.5);
GL11.glScaled(0.9, 0.9, 0.9);
GL11.glRotated(180, 0, 0, 1);
GL11.glTranslated(-0.5, 0.5, -0.5);
// lay the item flat
GL11.glRotated(-90, 1, 0, 0);
// reverse the transforms applied by the item renderer
GL11.glTranslated(0.5, -0.75, 0.35 / 16);
GL11.glScaled(2, 2, 2);
this.renderStack(copy);
GL11.glPopMatrix();
}
}
GL11.glPopMatrix();
}
@Override
public boolean renderWorldBlock(final IBlockAccess world, final int x, final int y, final int z, final Block block, final int modelId, final RenderBlocks renderer) {
return CrateRenderer.renderBlock(new WorldBlockRenderHelper(world, x, y, z), renderer.overrideBlockTexture);
}
@Override
public boolean shouldRender3DInInventory() {
return true;
}
@Override
public boolean shouldUseRenderHelper(final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper) {
return true;
}
}
|
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.HashMap;
import java.util.Iterator;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.ComplexPanel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Caption;
import com.itmill.toolkit.terminal.gwt.client.CaptionWrapper;
import com.itmill.toolkit.terminal.gwt.client.Container;
import com.itmill.toolkit.terminal.gwt.client.ContainerResizedListener;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
/**
* Custom Layout implements complex layout defined with HTML template.
*
* @author IT Mill
*
*/
public class ICustomLayout extends ComplexPanel implements Paintable,
Container, ContainerResizedListener {
public static final String CLASSNAME = "i-customlayout";
/** Location-name to containing element in DOM map */
private HashMap locationToElement = new HashMap();
/** Location-name to contained widget map */
private HashMap locationToWidget = new HashMap();
/** Widget to captionwrapper map */
private HashMap widgetToCaptionWrapper = new HashMap();
/** Currently rendered style */
String currentTemplate;
/** Unexecuted scripts loaded from the template */
private String scripts = "";
/** Paintable ID of this paintable */
private String pid;
private ApplicationConnection client;
public ICustomLayout() {
setElement(DOM.createDiv());
// Clear any unwanted styling
DOM.setStyleAttribute(getElement(), "border", "none");
DOM.setStyleAttribute(getElement(), "margin", "0");
DOM.setStyleAttribute(getElement(), "padding", "0");
DOM.setStyleAttribute(getElement(), "overflow", "hidden");
setStyleName(CLASSNAME);
}
public void setWidget(Widget widget, String location) {
if (widget == null) {
return;
}
// If no given location is found in the layout, and exception is throws
Element elem = (Element) locationToElement.get(location);
if (elem == null && hasTemplate()) {
throw new IllegalArgumentException("No location " + location
+ " found");
}
// Get previous widget
Widget previous = (Widget) locationToWidget.get(location);
// NOP if given widget already exists in this location
if (previous == widget) {
return;
}
remove(previous);
// if template is missing add element in order
if (!hasTemplate()) {
elem = getElement();
}
// Add widget to location
super.add(widget, elem);
locationToWidget.put(location, widget);
}
/** Update the layout from UIDL */
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
this.client = client;
// Client manages general cases
if (client.updateComponent(this, uidl, false)) {
return;
}
// Update PID
pid = uidl.getId();
if (!hasTemplate()) {
// Update HTML template only once
initializeHTML(uidl, client);
}
// Set size
if (uidl.hasAttribute("width")) {
setWidth(uidl.getStringAttribute("width"));
} else {
setWidth("100%");
}
if (uidl.hasAttribute("height")) {
setHeight(uidl.getStringAttribute("height"));
} else {
setHeight("100%");
}
// Evaluate scripts
eval(scripts);
scripts = null;
// For all contained widgets
for (Iterator i = uidl.getChildIterator(); i.hasNext();) {
UIDL uidlForChild = (UIDL) i.next();
if (uidlForChild.getTag().equals("location")) {
String location = uidlForChild.getStringAttribute("name");
Widget child = client.getWidget(uidlForChild.getChildUIDL(0));
try {
setWidget(child, location);
((Paintable) child).updateFromUIDL(uidlForChild
.getChildUIDL(0), client);
} catch (IllegalArgumentException e) {
// If no location is found, this component is not visible
}
}
}
iLayout();
}
/** Initialize HTML-layout. */
private void initializeHTML(UIDL uidl, ApplicationConnection client) {
String newTemplate = uidl.getStringAttribute("template");
// Get the HTML-template from client
String template = client
.getResource("layouts/" + newTemplate + ".html");
if (template == null) {
template = "<em>Layout file layouts/"
+ newTemplate
+ ".html is missing. Components will be drawn for debug purposes.</em>";
} else {
currentTemplate = newTemplate;
}
// Connect body of the template to DOM
template = extractBodyAndScriptsFromTemplate(template);
DOM.setInnerHTML(getElement(), template);
// Remap locations to elements
locationToElement.clear();
scanForLocations(getElement());
// Remap image srcs in layout
Widget parent = getParent();
while (parent != null && !(parent instanceof IView)) {
parent = parent.getParent();
}
if (parent != null && ((IView) parent).getTheme() != null) {
String prefix;
if (uriEndsWithSlash()) {
prefix = "../ITMILL/themes/";
} else {
prefix = "ITMILL/themes/";
}
prefixImgSrcs(getElement(), prefix + ((IView) parent).getTheme()
+ "/layouts/");
} else {
throw (new IllegalStateException(
"Could not find IView; maybe updateFromUIDL() was called before attaching the widget?"));
}
publishResizedFunction(DOM.getFirstChild(getElement()));
}
private native boolean uriEndsWithSlash()
/*-{
var path = $wnd.location.pathname;
if(path.charAt(path.length - 1) == "/")
return true;
return false;
}-*/;
private boolean hasTemplate() {
if (currentTemplate == null) {
return false;
} else {
return true;
}
}
/** Collect locations from template */
private void scanForLocations(Element elem) {
String location = getLocation(elem);
if (location != null) {
locationToElement.put(location, elem);
DOM.setInnerHTML(elem, "");
} else {
int len = DOM.getChildCount(elem);
for (int i = 0; i < len; i++) {
scanForLocations(DOM.getChild(elem, i));
}
}
}
/** Get the location attribute for given element */
private static native String getLocation(Element elem)
/*-{
return elem.getAttribute("location");
}-*/;
/** Evaluate given script in browser document */
private static native void eval(String script)
/*-{
try {
if (script != null)
eval("{ var document = $doc; var window = $wnd; "+ script + "}");
} catch (e) {
}
}-*/;
/** Prefix all img tag srcs with given prefix. */
private static native void prefixImgSrcs(Element e, String srcPrefix)
/*-{
try {
var divs = e.getElementsByTagName("img");
var base = "" + $doc.location;
var l = base.length-1;
while (l >= 0 && base.charAt(l) != "/") l--;
base = base.substring(0,l+1);
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
var src = div.getAttribute("src");
if (src.indexOf(base) == 0) div.setAttribute("src",base + srcPrefix + src.substring(base.length));
else if (src.indexOf("http") != 0) div.setAttribute("src",srcPrefix + src);
}
} catch (e) { alert(e + " " + srcPrefix);}
}-*/;
/**
* Extract body part and script tags from raw html-template.
*
* Saves contents of all script-tags to private property: scripts. Returns
* contents of the body part for the html without script-tags. Also replaces
* all _UID_ tags with an unique id-string.
*
* @param html
* Original HTML-template received from server
* @return html that is used to create the HTMLPanel.
*/
private String extractBodyAndScriptsFromTemplate(String html) {
// Replace UID:s
html = html.replaceAll("_UID_", pid + "__");
// Exctract script-tags
scripts = "";
int endOfPrevScript = 0;
int nextPosToCheck = 0;
String lc = html.toLowerCase();
String res = "";
int scriptStart = lc.indexOf("<script", nextPosToCheck);
while (scriptStart > 0) {
res += html.substring(endOfPrevScript, scriptStart);
scriptStart = lc.indexOf(">", scriptStart);
int j = lc.indexOf("</script>", scriptStart);
scripts += html.substring(scriptStart + 1, j) + ";";
nextPosToCheck = endOfPrevScript = j + "</script>".length();
scriptStart = lc.indexOf("<script", nextPosToCheck);
}
res += html.substring(endOfPrevScript);
// Extract body
html = res;
lc = html.toLowerCase();
int startOfBody = lc.indexOf("<body");
if (startOfBody < 0) {
res = html;
} else {
res = "";
startOfBody = lc.indexOf(">", startOfBody) + 1;
int endOfBody = lc.indexOf("</body>", startOfBody);
if (endOfBody > startOfBody) {
res = html.substring(startOfBody, endOfBody);
} else {
res = html.substring(startOfBody);
}
}
return res;
}
/** Replace child components */
public void replaceChildComponent(Widget from, Widget to) {
String location = getLocation(from);
if (location == null) {
throw new IllegalArgumentException();
}
setWidget(to, location);
}
/** Does this layout contain given child */
public boolean hasChildComponent(Widget component) {
return locationToWidget.containsValue(component);
}
/** Update caption for given widget */
public void updateCaption(Paintable component, UIDL uidl) {
CaptionWrapper wrapper = (CaptionWrapper) widgetToCaptionWrapper
.get(component);
if (Caption.isNeeded(uidl)) {
if (wrapper == null) {
String loc = getLocation((Widget) component);
super.remove((Widget) component);
wrapper = new CaptionWrapper(component, client);
super.add(wrapper, (Element) locationToElement.get(loc));
widgetToCaptionWrapper.put(component, wrapper);
}
wrapper.updateCaption(uidl);
} else {
if (wrapper != null) {
String loc = getLocation((Widget) component);
super.remove(wrapper);
super.add((Widget) wrapper.getPaintable(),
(Element) locationToElement.get(loc));
widgetToCaptionWrapper.remove(component);
}
}
}
/** Get the location of an widget */
public String getLocation(Widget w) {
for (Iterator i = locationToWidget.keySet().iterator(); i.hasNext();) {
String location = (String) i.next();
if (locationToWidget.get(location) == w) {
return location;
}
}
return null;
}
/** Removes given widget from the layout */
public boolean remove(Widget w) {
client.unregisterPaintable((Paintable) w);
String location = getLocation(w);
if (location != null) {
locationToWidget.remove(location);
}
CaptionWrapper cw = (CaptionWrapper) widgetToCaptionWrapper.get(w);
if (cw != null) {
widgetToCaptionWrapper.remove(w);
return super.remove(cw);
} else if (w != null) {
return super.remove(w);
}
return false;
}
/** Adding widget without specifying location is not supported */
public void add(Widget w) {
throw new UnsupportedOperationException();
}
/** Clear all widgets from the layout */
public void clear() {
super.clear();
locationToWidget.clear();
widgetToCaptionWrapper.clear();
}
public void iLayout() {
if (!iLayoutJS(DOM.getFirstChild(getElement()))) {
Util.runDescendentsLayout(this);
}
}
/**
* This method is published to JS side with the same name into first DOM
* node of custom layout. This way if one implements some resizeable
* containers in custom layout he/she can notify children after resize.
*/
public void notifyChildrenOfSizeChange() {
Util.runDescendentsLayout(this);
}
public void onDetach() {
detachResizedFunction(DOM.getFirstChild(getElement()));
}
private native void detachResizedFunction(Element element)
/*-{
element.notifyChildrenOfSizeChange = null;
}-*/;
private native void publishResizedFunction(Element element)
/*-{
var self = this;
element.notifyChildrenOfSizeChange = function() {
self.@com.itmill.toolkit.terminal.gwt.client.ui.ICustomLayout::notifyChildrenOfSizeChange()();
};
}-*/;
/**
* In custom layout one may want to run layout functions made with
* JavaScript. This function tests if one exists (with name "iLayoutJS" in
* layouts first DOM node) and runs if it. Return value is used to determine
* is children needs to be notified of size changes.
*
* @param el
* @return true if layout function was run and it returned true.
*/
private native boolean iLayoutJS(Element el)
/*-{
if(el && el.iLayoutJS) {
try {
el.iLayoutJS();
return true;
} catch (e) {
return false;
}
} else {
return false;
}
}-*/;
}
|
package com.mebigfatguy.fbcontrib.detect;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.Type;
import com.mebigfatguy.fbcontrib.collect.MethodInfo;
import com.mebigfatguy.fbcontrib.collect.Statistics;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.OpcodeUtils;
import com.mebigfatguy.fbcontrib.utils.RegisterUtils;
import com.mebigfatguy.fbcontrib.utils.TernaryPatcher;
import com.mebigfatguy.fbcontrib.utils.ToString;
import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.XField;
/**
* looks for variable assignments at a scope larger than its use. In this case, the assignment can be pushed down into the smaller scope to reduce the
* performance impact of that assignment.
*/
@CustomUserValue
public class BloatedAssignmentScope extends BytecodeScanningDetector {
private static final Set<String> dangerousAssignmentClassSources = UnmodifiableSet.create(
//@formatter:off
"java/io/BufferedInputStream",
"java/io/DataInput",
"java/io/DataInputStream",
"java/io/InputStream",
"java/io/ObjectInputStream",
"java/io/BufferedReader",
"java/io/FileReader",
"java/io/Reader",
"javax/nio/channels/Channel",
"io/netty/channel/Channel"
//@formatter:on
);
private static final Set<String> dangerousAssignmentMethodSources = UnmodifiableSet.create(
//@formatter:off
"java/lang/System.currentTimeMillis()J",
"java/lang/System.nanoTime()J",
"java/util/Calendar.get(I)I",
"java/util/GregorianCalendar.get(I)I",
"java/util/Iterator.next()Ljava/lang/Object;",
"java/util/regex/Matcher.start()I",
"java/util/concurrent/TimeUnit.toMillis(J)J"
//@formatter:on
);
private static final Set<Pattern> dangerousAssignmentMethodPatterns = UnmodifiableSet.create(
//@formatter:off
Pattern.compile(".*serial.*", Pattern.CASE_INSENSITIVE),
Pattern.compile(".*\\.read[^.]*", Pattern.CASE_INSENSITIVE),
Pattern.compile(".*\\.create[^.]*", Pattern.CASE_INSENSITIVE)
//@formatter:on
);
private static final Set<String> dangerousStoreClassSigs = UnmodifiableSet.create("Ljava/util/concurrent/Future;");
BugReporter bugReporter;
private OpcodeStack stack;
private BitSet ignoreRegs;
private ScopeBlock rootScopeBlock;
private BitSet tryBlocks;
private BitSet catchHandlers;
private BitSet switchTargets;
private List<Integer> monitorSyncPCs;
private boolean dontReport;
private boolean sawDup;
private boolean sawNull;
/**
* constructs a BAS detector given the reporter to report bugs on
*
* @param bugReporter
* the sync of bug reports
*/
public BloatedAssignmentScope(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
/**
* implements the visitor to create and the clear the register to location map
*
* @param classContext
* the context object of the currently parsed class
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
ignoreRegs = new BitSet();
tryBlocks = new BitSet();
catchHandlers = new BitSet();
switchTargets = new BitSet();
monitorSyncPCs = new ArrayList<>(5);
stack = new OpcodeStack();
super.visitClassContext(classContext);
} finally {
ignoreRegs = null;
tryBlocks = null;
catchHandlers = null;
switchTargets = null;
monitorSyncPCs = null;
stack = null;
}
}
/**
* implements the visitor to reset the register to location map
*
* @param obj
* the context object of the currently parsed code block
*/
@Override
public void visitCode(Code obj) {
try {
ignoreRegs.clear();
Method method = getMethod();
if (!method.isStatic()) {
ignoreRegs.set(0);
}
int[] parmRegs = RegisterUtils.getParameterRegisters(method);
for (int parm : parmRegs) {
ignoreRegs.set(parm);
}
rootScopeBlock = new ScopeBlock(0, obj.getLength());
tryBlocks.clear();
catchHandlers.clear();
CodeException[] exceptions = obj.getExceptionTable();
if (exceptions != null) {
for (CodeException ex : exceptions) {
tryBlocks.set(ex.getStartPC());
catchHandlers.set(ex.getHandlerPC());
}
}
switchTargets.clear();
stack.resetForMethodEntry(this);
dontReport = false;
sawDup = false;
sawNull = false;
super.visitCode(obj);
if (!dontReport) {
rootScopeBlock.findBugs(new HashSet<Integer>());
}
} finally {
rootScopeBlock = null;
}
}
/**
* implements the visitor to look for variables assigned below the scope in which they are used.
*
* @param seen
* the opcode of the currently parsed instruction
*/
@Override
public void sawOpcode(int seen) {
UserObject uo = null;
try {
stack.precomputation(this);
int pc = getPC();
if (tryBlocks.get(pc)) {
ScopeBlock sb = new ScopeBlock(pc, findCatchHandlerFor(pc));
sb.setTry();
rootScopeBlock.addChild(sb);
}
if (OpcodeUtils.isStore(seen)) {
sawStore(seen, pc);
} else if (OpcodeUtils.isLoad(seen)) {
sawLoad(seen, pc);
} else if ((seen == INVOKEVIRTUAL) || (seen == INVOKEINTERFACE)) {
uo = sawInstanceCall(pc);
} else if ((seen == INVOKESTATIC) || (seen == INVOKESPECIAL)) {
uo = sawStaticCall();
} else if (((seen >= IFEQ) && (seen <= GOTO)) || (seen == IFNULL) || (seen == IFNONNULL) || (seen == GOTO_W)) {
sawBranch(seen, pc);
} else if (seen == GETFIELD) {
uo = sawGetField();
} else if (seen == IINC) {
sawIINC(pc);
} else if ((seen == TABLESWITCH) || (seen == LOOKUPSWITCH)) {
sawSwitch(pc);
} else if (seen == MONITORENTER) {
sawMonitorEnter(pc);
} else if (seen == MONITOREXIT) {
sawMonitorExit(pc);
}
sawDup = seen == DUP;
sawNull = seen == ACONST_NULL;
} finally {
TernaryPatcher.pre(stack, seen);
stack.sawOpcode(this, seen);
TernaryPatcher.post(stack, seen);
if ((uo != null) && (stack.getStackDepth() > 0)) {
OpcodeStack.Item item = stack.getStackItem(0);
item.setUserValue(uo);
}
}
}
/**
* processes a register store by updating the appropriate scope block to mark this register as being stored in the block
*
* @param seen
* the currently parsed opcode
* @param pc
* the current program counter
*/
private void sawStore(int seen, int pc) {
int reg = RegisterUtils.getStoreReg(this, seen);
if (catchHandlers.get(pc)) {
ignoreRegs.set(reg);
ScopeBlock catchSB = findScopeBlock(rootScopeBlock, pc + 1);
if ((catchSB != null) && (catchSB.getStart() < pc)) {
ScopeBlock sb = new ScopeBlock(pc, catchSB.getFinish());
catchSB.setFinish(getPC() - 1);
rootScopeBlock.addChild(sb);
}
} else if (monitorSyncPCs.size() > 0) {
ignoreRegs.set(reg);
} else if (sawNull) {
ignoreRegs.set(reg);
} else if (isRiskyStoreClass(reg)) {
ignoreRegs.set(reg);
}
if (!ignoreRegs.get(reg)) {
ScopeBlock sb = findScopeBlock(rootScopeBlock, pc);
if (sb != null) {
UserObject assoc = null;
if (stack.getStackDepth() > 0) {
assoc = (UserObject) stack.getStackItem(0).getUserValue();
}
if ((assoc != null) && assoc.isRisky) {
ignoreRegs.set(reg);
} else {
sb.addStore(reg, pc, assoc);
if (sawDup) {
sb.addLoad(reg, pc);
}
}
} else {
ignoreRegs.set(reg);
}
}
ScopeBlock sb = findScopeBlock(rootScopeBlock, pc);
if (sb != null) {
sb.markFieldAssociatedWrites(reg);
}
}
/**
* processes a register IINC by updating the appropriate scope block to mark this register as being stored in the block
*
* @param pc
* the current program counter
*/
private void sawIINC(int pc) {
int reg = getRegisterOperand();
if (!ignoreRegs.get(reg)) {
ScopeBlock sb = findScopeBlock(rootScopeBlock, pc);
if (sb != null) {
sb.addLoad(reg, pc);
} else {
ignoreRegs.set(reg);
}
}
if (catchHandlers.get(pc)) {
ignoreRegs.set(reg);
} else if (monitorSyncPCs.size() > 0) {
ignoreRegs.set(reg);
} else if (sawNull) {
ignoreRegs.set(reg);
}
if (!ignoreRegs.get(reg)) {
ScopeBlock sb = findScopeBlock(rootScopeBlock, pc);
if (sb != null) {
sb.addStore(reg, pc, null);
if (sawDup) {
sb.addLoad(reg, pc);
}
} else {
ignoreRegs.set(reg);
}
}
}
/**
* processes a register store by updating the appropriate scope block to mark this register as being read in the block
*
* @param seen
* the currently parsed opcode
* @param pc
* the current program counter
*/
private void sawLoad(int seen, int pc) {
int reg = RegisterUtils.getLoadReg(this, seen);
if (!ignoreRegs.get(reg)) {
ScopeBlock sb = findScopeBlock(rootScopeBlock, pc);
if (sb != null) {
sb.addLoad(reg, pc);
} else {
ignoreRegs.set(reg);
}
}
}
/**
* creates a scope block to describe this branch location.
*
* @param seen
* the currently parsed opcode
* @param pc
* the current program counter
*/
private void sawBranch(int seen, int pc) {
int target = getBranchTarget();
if (target > pc) {
if ((seen == GOTO) || (seen == GOTO_W)) {
int nextPC = getNextPC();
if (!switchTargets.get(nextPC)) {
ScopeBlock sb = findScopeBlockWithTarget(rootScopeBlock, pc, nextPC);
if (sb == null) {
sb = new ScopeBlock(pc, target);
sb.setLoop();
sb.setGoto();
rootScopeBlock.addChild(sb);
} else {
sb = new ScopeBlock(nextPC, target);
sb.setGoto();
rootScopeBlock.addChild(sb);
}
}
} else {
ScopeBlock sb = findScopeBlockWithTarget(rootScopeBlock, pc, target);
if ((sb != null) && !sb.isLoop() && !sb.isCase() && !sb.hasChildren()) {
if (sb.isGoto()) {
ScopeBlock parent = sb.getParent();
sb.pushUpLoadStores();
if (parent != null) {
parent.removeChild(sb);
}
sb = new ScopeBlock(pc, target);
rootScopeBlock.addChild(sb);
} else {
sb.pushUpLoadStores();
sb.setStart(pc);
}
} else {
sb = new ScopeBlock(pc, target);
rootScopeBlock.addChild(sb);
}
}
} else {
ScopeBlock sb = findScopeBlock(rootScopeBlock, pc);
if (sb != null) {
ScopeBlock parentSB = sb.getParent();
while (parentSB != null) {
if (parentSB.getStart() >= target) {
sb = parentSB;
parentSB = parentSB.getParent();
} else {
break;
}
}
if (sb.getStart() > target) {
ScopeBlock previous = findPreviousSiblingScopeBlock(sb);
if ((previous != null) && (previous.getStart() >= target)) {
sb = previous;
}
}
sb.setLoop();
}
}
}
/**
* creates a new scope block for each case statement
*
* @param pc
* the current program counter
*/
private void sawSwitch(int pc) {
int[] offsets = getSwitchOffsets();
List<Integer> targets = new ArrayList<>(offsets.length);
for (int offset : offsets) {
targets.add(Integer.valueOf(offset + pc));
}
Integer defOffset = Integer.valueOf(getDefaultSwitchOffset() + pc);
if (!targets.contains(defOffset)) {
targets.add(defOffset);
}
Collections.sort(targets);
Integer lastTarget = targets.get(0);
for (int i = 1; i < targets.size(); i++) {
Integer nextTarget = targets.get(i);
ScopeBlock sb = new ScopeBlock(lastTarget.intValue(), nextTarget.intValue());
sb.setCase();
rootScopeBlock.addChild(sb);
lastTarget = nextTarget;
}
for (Integer target : targets) {
switchTargets.set(target.intValue());
}
}
/**
* processes a instance method call to see if that call is modifies state or is otherwise'risky', if so mark the variable(s) associated with the caller as
* not reportable
*
* @param pc
* the current program counter
*
* @return a user object to place on the return value's OpcodeStack item
*/
private UserObject sawInstanceCall(int pc) {
String signature = getSigConstantOperand();
String name = getNameConstantOperand();
// this is kind of a wart. there should be a more seemless way to check this
if ("wasNull".equals(getNameConstantOperand()) && "()Z".equals(signature)) {
dontReport = true;
}
if (signature.endsWith("V")) {
return null;
}
UserObject uo = new UserObject();
MethodInfo mi = Statistics.getStatistics().getMethodStatistics(getClassConstantOperand(), name, signature);
uo.isRisky = mi.getModifiesState() || isRiskyMethodCall();
uo.caller = getCallingObject();
if (uo.caller != null) {
ScopeBlock sb = findScopeBlock(rootScopeBlock, pc);
if (sb != null) {
sb.removeByAssoc(uo.caller);
}
}
return uo;
}
/**
* processes a static call or initializer by checking to see if the call is risky, and returning a OpcodeStack item user value saying so.
*
* @return the user object to place on the OpcodeStack
*/
private UserObject sawStaticCall() {
if (getSigConstantOperand().endsWith("V")) {
return null;
}
UserObject uo = new UserObject();
uo.isRisky = isRiskyMethodCall();
return uo;
}
private UserObject sawGetField() {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item itm = stack.getStackItem(0);
int reg = itm.getRegisterNumber();
if (reg >= 0) {
UserObject uo = new UserObject();
uo.fieldFromReg = reg;
return uo;
}
}
return null;
}
/**
* processes a monitor enter call to create a scope block
*
* @param pc
* the current program counter
*/
private void sawMonitorEnter(int pc) {
monitorSyncPCs.add(Integer.valueOf(pc));
ScopeBlock sb = new ScopeBlock(pc, Integer.MAX_VALUE);
sb.setSync();
rootScopeBlock.addChild(sb);
}
/**
* processes a monitor exit to set the end of the already created scope block
*
* @param pc
* the current program counter
*/
private void sawMonitorExit(int pc) {
if (monitorSyncPCs.size() > 0) {
ScopeBlock sb = findSynchronizedScopeBlock(rootScopeBlock, monitorSyncPCs.get(0).intValue());
if (sb != null) {
sb.setFinish(pc);
}
monitorSyncPCs.remove(monitorSyncPCs.size() - 1);
}
}
/**
* returns either a register number of a field reference of the object that a method is being called on, or null, if it can't be determined.
*
* @return either an Integer for a register, or a String for the field name, or null
*/
private Comparable<?> getCallingObject() {
String sig = getSigConstantOperand();
if ("V".equals(Type.getReturnType(sig).getSignature())) {
return null;
}
Type[] types = Type.getArgumentTypes(sig);
if (stack.getStackDepth() <= types.length) {
return null;
}
OpcodeStack.Item caller = stack.getStackItem(types.length);
UserObject uo = (UserObject) caller.getUserValue();
if ((uo != null) && (uo.caller != null)) {
return uo.caller;
}
int reg = caller.getRegisterNumber();
if (reg >= 0) {
return Integer.valueOf(reg);
}
/*
* We ignore the possibility of two fields with the same name in different classes
*/
XField f = caller.getXField();
if (f != null) {
return f.getName();
}
return null;
}
/**
* returns the scope block in which this register was assigned, by traversing the scope block tree
*
* @param sb
* the scope block to start searching in
* @param pc
* the current program counter
* @return the scope block or null if not found
*/
private ScopeBlock findScopeBlock(ScopeBlock sb, int pc) {
if ((pc <= sb.getStart()) || (pc >= sb.getFinish())) {
return null;
}
if (sb.children != null) {
for (ScopeBlock child : sb.children) {
ScopeBlock foundSb = findScopeBlock(child, pc);
if (foundSb != null) {
return foundSb;
}
}
}
return sb;
}
/**
* returns an existing scope block that has the same target as the one looked for
*
* @param sb
* the scope block to start with
* @param target
* the target to look for
*
* @return the scope block found or null
*/
private ScopeBlock findScopeBlockWithTarget(ScopeBlock sb, int start, int target) {
ScopeBlock parentBlock = null;
if ((sb.startLocation < start) && (sb.finishLocation >= start) && ((sb.finishLocation <= target) || (sb.isGoto() && !sb.isLoop()))) {
parentBlock = sb;
}
if (sb.children != null) {
for (ScopeBlock child : sb.children) {
ScopeBlock targetBlock = findScopeBlockWithTarget(child, start, target);
if (targetBlock != null) {
return targetBlock;
}
}
}
return parentBlock;
}
/**
* looks for the ScopeBlock has the same parent as this given one, but precedes it in the list.
*
* @param sb
* the scope block to look for the previous scope block
* @return the previous sibling scope block, or null if doesn't exist
*/
private ScopeBlock findPreviousSiblingScopeBlock(ScopeBlock sb) {
ScopeBlock parent = sb.getParent();
if (parent == null) {
return null;
}
List<ScopeBlock> children = parent.getChildren();
if (children == null) {
return null;
}
ScopeBlock lastSibling = null;
for (ScopeBlock sibling : children) {
if (sibling.equals(sb)) {
return lastSibling;
}
lastSibling = sibling;
}
return null;
}
/**
* finds the scope block that is the active synchronized block
*
* @return the scope block
*/
private ScopeBlock findSynchronizedScopeBlock(ScopeBlock sb, int monitorEnterPC) {
ScopeBlock monitorBlock = sb;
if (sb.hasChildren()) {
for (ScopeBlock child : sb.getChildren()) {
if (child.isSync() && (child.getStart() > monitorBlock.getStart())) {
monitorBlock = child;
monitorBlock = findSynchronizedScopeBlock(monitorBlock, monitorEnterPC);
}
}
}
return monitorBlock;
}
/**
* returns the catch handler for a given try block
*
* @param pc
* the current instruction
* @return the pc of the handler for this pc if it's the start of a try block, or -1
*
*/
private int findCatchHandlerFor(int pc) {
CodeException[] exceptions = getMethod().getCode().getExceptionTable();
if (exceptions != null) {
for (CodeException ex : exceptions) {
if (ex.getStartPC() == pc) {
return ex.getHandlerPC();
}
}
}
return -1;
}
/**
* holds the description of a scope { } block, be it a for, if, while block
*/
private class ScopeBlock {
private ScopeBlock parent;
private int startLocation;
private int finishLocation;
private boolean isLoop;
private boolean isGoto;
private boolean isSync;
private boolean isTry;
private boolean isCase;
private Map<Integer, Integer> loads;
private Map<Integer, Integer> stores;
private Map<UserObject, Integer> assocs;
private List<ScopeBlock> children;
/**
* constructs a new scope block
*
* @param start
* the beginning of the block
* @param finish
* the end of the block
*/
public ScopeBlock(int start, int finish) {
parent = null;
startLocation = start;
finishLocation = finish;
isLoop = false;
isGoto = false;
isSync = false;
isTry = false;
isCase = false;
loads = null;
stores = null;
assocs = null;
children = null;
}
/**
* returns a string representation of the scope block
*
* @return a string representation
*/
@Override
public String toString() {
return ToString.build(this, "parent");
}
/**
* returns the scope blocks parent
*
* @return the parent of this scope block
*/
public ScopeBlock getParent() {
return parent;
}
/**
* returns the children of this scope block
*
* @return the scope blocks children
*/
public List<ScopeBlock> getChildren() {
return children;
}
/**
* returns the start of the block
*
* @return the start of the block
*/
public int getStart() {
return startLocation;
}
/**
* returns the end of the block
*
* @return the end of the block
*/
public int getFinish() {
return finishLocation;
}
/**
* sets the start pc of the block
*
* @param start
* the start pc
*/
public void setStart(int start) {
startLocation = start;
}
/**
* sets the finish pc of the block
*
* @param finish
* the finish pc
*/
public void setFinish(int finish) {
finishLocation = finish;
}
public boolean hasChildren() {
return children != null;
}
/**
* sets that this block is a loop
*/
public void setLoop() {
isLoop = true;
}
/**
* returns whether this scope block is a loop
*
* @return whether this block is a loop
*/
public boolean isLoop() {
return isLoop;
}
/**
* sets that this block was caused from a goto, (an if block exit)
*/
public void setGoto() {
isGoto = true;
}
/**
* returns whether this block was caused from a goto
*
* @return whether this block was caused by a goto
*/
public boolean isGoto() {
return isGoto;
}
/**
* sets that this block was caused from a synchronized block
*/
public void setSync() {
isSync = true;
}
/**
* returns whether this block was caused from a synchronized block
*
* @return whether this block was caused by a synchronized block
*/
public boolean isSync() {
return isSync;
}
/**
* sets that this block was caused from a try block
*/
public void setTry() {
isTry = true;
}
/**
* returns whether this block was caused from a try block
*
* @return whether this block was caused by a try block
*/
public boolean isTry() {
return isTry;
}
/**
* sets that this block was caused from a case block
*/
public void setCase() {
isCase = true;
}
/**
* returns whether this block was caused from a case block
*
* @return whether this block was caused by a case block
*/
public boolean isCase() {
return isCase;
}
/**
* adds the register as a store in this scope block
*
* @param reg
* the register that was stored
* @param pc
* the instruction that did the store
*/
public void addStore(int reg, int pc, UserObject assocObject) {
if (stores == null) {
stores = new HashMap<>(6);
}
stores.put(Integer.valueOf(reg), Integer.valueOf(pc));
if (assocs == null) {
assocs = new HashMap<>(6);
}
assocs.put(assocObject, Integer.valueOf(reg));
}
/**
* removes stores to registers that where retrieved from method calls on assocObject
*
* @param assocObject
* the object that a method call was just performed on
*/
public void removeByAssoc(Object assocObject) {
if (assocs != null) {
Integer reg = assocs.remove(assocObject);
if (reg != null) {
if (loads != null) {
loads.remove(reg);
}
if (stores != null) {
stores.remove(reg);
}
}
}
}
/**
* adds the register as a load in this scope block
*
* @param reg
* the register that was loaded
* @param pc
* the instruction that did the load
*/
public void addLoad(int reg, int pc) {
if (loads == null) {
loads = new HashMap<>(10);
}
loads.put(Integer.valueOf(reg), Integer.valueOf(pc));
}
/**
* adds a scope block to this subtree by finding the correct place in the hierarchy to store it
*
* @param newChild
* the scope block to add to the tree
*/
public void addChild(ScopeBlock newChild) {
newChild.parent = this;
if (children != null) {
for (ScopeBlock child : children) {
if ((newChild.startLocation > child.startLocation) && (newChild.startLocation < child.finishLocation)) {
if (newChild.finishLocation > child.finishLocation) {
newChild.finishLocation = child.finishLocation;
}
child.addChild(newChild);
return;
}
}
int pos = 0;
for (ScopeBlock child : children) {
if (newChild.startLocation < child.startLocation) {
children.add(pos, newChild);
return;
}
pos++;
}
children.add(newChild);
return;
}
children = new ArrayList<>();
children.add(newChild);
}
/**
* removes a child from this node
*
* @param child
* the child to remove
*/
public void removeChild(ScopeBlock child) {
if (children != null) {
children.remove(child);
}
}
public void markFieldAssociatedWrites(int fieldFromReg) {
if (assocs != null) {
UserObject uo = new UserObject();
uo.fieldFromReg = fieldFromReg;
Integer preWrittenFromField = assocs.get(uo);
if (preWrittenFromField != null) {
if (stores != null) {
stores.remove(preWrittenFromField);
}
}
}
}
/**
* report stores that occur at scopes higher than associated loads that are not involved with loops
*/
public void findBugs(Set<Integer> parentUsedRegs) {
if (isLoop) {
return;
}
Set<Integer> usedRegs = new HashSet<>(parentUsedRegs);
if (stores != null) {
usedRegs.addAll(stores.keySet());
}
if (loads != null) {
usedRegs.addAll(loads.keySet());
}
if (stores != null) {
if (loads != null) {
stores.keySet().removeAll(loads.keySet());
}
stores.keySet().removeAll(parentUsedRegs);
for (int r = ignoreRegs.nextSetBit(0); r >= 0; r = ignoreRegs.nextSetBit(r + 1)) {
stores.remove(Integer.valueOf(r));
}
if ((children != null) && (stores.size() > 0)) {
for (Map.Entry<Integer, Integer> entry : stores.entrySet()) {
int childUseCount = 0;
boolean inIgnoreSB = false;
Integer reg = entry.getKey();
for (ScopeBlock child : children) {
if (child.usesReg(reg)) {
if (child.isLoop || child.isSync() || child.isTry()) {
inIgnoreSB = true;
break;
}
childUseCount++;
}
}
if (!inIgnoreSB && (childUseCount == 1)) {
bugReporter.reportBug(new BugInstance(BloatedAssignmentScope.this, BugType.BAS_BLOATED_ASSIGNMENT_SCOPE.name(), NORMAL_PRIORITY)
.addClass(BloatedAssignmentScope.this).addMethod(BloatedAssignmentScope.this)
.addSourceLine(BloatedAssignmentScope.this, entry.getValue().intValue()));
}
}
}
}
if (children != null) {
for (ScopeBlock child : children) {
child.findBugs(usedRegs);
}
}
}
/**
* returns whether this block either loads or stores into the register in question
*
* @param reg
* the register to look for loads or stores
*
* @return whether the block uses the register
*/
public boolean usesReg(Integer reg) {
if ((loads != null) && loads.containsKey(reg)) {
return true;
}
if ((stores != null) && stores.containsKey(reg)) {
return true;
}
if (children != null) {
for (ScopeBlock child : children) {
if (child.usesReg(reg)) {
return true;
}
}
}
return false;
}
/**
* push all loads and stores to this block up to the parent
*/
public void pushUpLoadStores() {
if (parent != null) {
if (loads != null) {
if (parent.loads != null) {
parent.loads.putAll(loads);
} else {
parent.loads = loads;
}
}
if (stores != null) {
if (parent.stores != null) {
parent.stores.putAll(stores);
} else {
parent.stores = stores;
}
}
loads = null;
stores = null;
}
}
}
public boolean isRiskyMethodCall() {
String clsName = getClassConstantOperand();
if (dangerousAssignmentClassSources.contains(clsName)) {
return true;
}
String key = clsName + '.' + getNameConstantOperand() + getSigConstantOperand();
if (dangerousAssignmentMethodSources.contains(key)) {
return true;
}
for (Pattern p : dangerousAssignmentMethodPatterns) {
Matcher m = p.matcher(key);
if (m.matches()) {
return true;
}
}
return false;
}
public boolean isRiskyStoreClass(int reg) {
LocalVariableTable lvt = getMethod().getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = lvt.getLocalVariable(reg, getNextPC());
if ((lv != null) && dangerousStoreClassSigs.contains(lv.getSignature())) {
return true;
}
}
return false;
}
static class UserObject {
Comparable<?> caller;
boolean isRisky;
int fieldFromReg = -1;
@Override
public int hashCode() {
return ((caller == null) ? 0 : caller.hashCode()) | (isRisky ? 1 : 0) | fieldFromReg;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof UserObject)) {
return false;
}
UserObject that = (UserObject) o;
if (caller == null) {
if (that.caller != null) {
return false;
}
} else {
boolean eq = caller.equals(that.caller);
if (!eq) {
return false;
}
}
return (isRisky == that.isRisky) && (fieldFromReg == that.fieldFromReg);
}
@Override
public String toString() {
return ToString.build(this);
}
}
}
|
package com.mebigfatguy.fbcontrib.detect;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.Unknown;
import org.apache.bcel.generic.Type;
import com.mebigfatguy.fbcontrib.utils.TernaryPatcher;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
/** looks for odd uses of the Assert class of the JUnit framework */
public class JUnitAssertionOddities extends BytecodeScanningDetector
{
private enum State {SAW_NOTHING, SAW_IF_ICMPNE, SAW_ICONST_1, SAW_GOTO, SAW_ICONST_0, SAW_EQUALS};
private static final String RUNTIME_VISIBLE_ANNOTATIONS = "RuntimeVisibleAnnotations";
private static final String TESTCASE_CLASS = "junit.framework.TestCase";
private static final String TEST_CLASS = "org.junit.Test";
private static final String TEST_ANNOTATION_SIGNATURE = "Lorg/junit/Test;";
private static final String OLD_ASSERT_CLASS = "junit/framework/Assert";
private static final String NEW_ASSERT_CLASS = "org/junit/Assert";
private BugReporter bugReporter;
private JavaClass testCaseClass;
private JavaClass testAnnotationClass;
private OpcodeStack stack;
private boolean isTestCaseDerived;
private boolean isAnnotationCapable;
private State state;
/**
* constructs a JOA detector given the reporter to report bugs on
* @param bugReporter the sync of bug reports
*/
public JUnitAssertionOddities(BugReporter bugReporter) {
this.bugReporter = bugReporter;
try {
testCaseClass = Repository.lookupClass(TESTCASE_CLASS);
} catch (ClassNotFoundException cnfe) {
testCaseClass = null;
bugReporter.reportMissingClass(DescriptorFactory.createClassDescriptor(TESTCASE_CLASS));
}
try {
testAnnotationClass = Repository.lookupClass(TEST_CLASS);
} catch (ClassNotFoundException cnfe) {
testAnnotationClass = null;
bugReporter.reportMissingClass(DescriptorFactory.createClassDescriptor(TEST_CLASS));
}
}
/**
* override the visitor to see if this class could be a test class
*
* @param classContext the context object of the currently parsed class
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
JavaClass cls = classContext.getJavaClass();
isTestCaseDerived = ((testCaseClass != null) && cls.instanceOf(testCaseClass));
isAnnotationCapable = (cls.getMajor() >= 5) && (testAnnotationClass != null);
if (isTestCaseDerived || isAnnotationCapable) {
stack = new OpcodeStack();
super.visitClassContext(classContext);
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
} finally {
stack = null;
}
}
@Override
public void visitCode(Code obj) {
Method m = getMethod();
boolean isTestMethod = isTestCaseDerived && m.getName().startsWith("test");
if (!isTestMethod && isAnnotationCapable) {
Attribute[] atts = m.getAttributes();
for (Attribute att : atts) {
ConstantPool cp = att.getConstantPool();
Constant c = cp.getConstant(att.getNameIndex());
if (c instanceof ConstantUtf8) {
String name = ((ConstantUtf8) c).getBytes();
if (RUNTIME_VISIBLE_ANNOTATIONS.equals(name)) {
if (att instanceof Unknown) {
Unknown unAtt = (Unknown)att;
byte[] bytes = unAtt.getBytes();
int constantPoolIndex = bytes[3] & 0x000000FF;
c = cp.getConstant(constantPoolIndex);
if (c instanceof ConstantUtf8) {
name = ((ConstantUtf8) c).getBytes();
if (TEST_ANNOTATION_SIGNATURE.equals(name)) {
isTestMethod = true;
break;
}
}
}
}
}
}
}
if (isTestMethod) {
stack.resetForMethodEntry(this);
state = State.SAW_NOTHING;
super.visitCode(obj);
}
}
@Override
public void sawOpcode(int seen) {
String userValue = null;
try {
stack.mergeJumps(this);
if (seen == INVOKESTATIC) {
String clsName = getClassConstantOperand();
if (OLD_ASSERT_CLASS.equals(clsName) || NEW_ASSERT_CLASS.equals(clsName)) {
String methodName = getNameConstantOperand();
if ("assertEquals".equals(methodName)) {
String signature = getSigConstantOperand();
Type[] argTypes = Type.getArgumentTypes(signature);
if (argTypes.length == 2) {
if (argTypes[0].equals(Type.STRING) && argTypes[1].equals(Type.STRING))
return;
if (stack.getStackDepth() >= 2) {
OpcodeStack.Item item1 = stack.getStackItem(1);
Object cons1 = item1.getConstant();
if ((cons1 != null) && (argTypes[argTypes.length-1].equals(Type.BOOLEAN)) && (argTypes[argTypes.length-2].equals(Type.BOOLEAN))) {
bugReporter.reportBug(new BugInstance(this, "JAO_JUNIT_ASSERTION_ODDITIES_BOOLEAN_ASSERT", NORMAL_PRIORITY)
.addClass(this)
.addMethod(this)
.addSourceLine(this));
return;
}
OpcodeStack.Item item0 = stack.getStackItem(0);
if (item0.getConstant() != null) {
bugReporter.reportBug(new BugInstance(this, "JAO_JUNIT_ASSERTION_ODDITIES_ACTUAL_CONSTANT", NORMAL_PRIORITY)
.addClass(this)
.addMethod(this)
.addSourceLine(this));
return;
}
if (argTypes[0].equals(Type.OBJECT) && argTypes[1].equals(Type.OBJECT)) {
if ("Ljava/lang/Double;".equals(item0.getSignature()) && "Ljava/lang/Double;".equals(item1.getSignature())) {
bugReporter.reportBug(new BugInstance(this, "JAO_JUNIT_ASSERTION_ODDITIES_INEXACT_DOUBLE", NORMAL_PRIORITY)
.addClass(this)
.addMethod(this)
.addSourceLine(this));
return;
}
}
}
}
} else if ("assertNotNull".equals(methodName)) {
if (stack.getStackDepth() > 0) {
if ("valueOf".equals(stack.getStackItem(0).getUserValue())) {
bugReporter.reportBug(new BugInstance(this, "JAO_JUNIT_ASSERTION_ODDITIES_IMPOSSIBLE_NULL", NORMAL_PRIORITY)
.addClass(this)
.addMethod(this)
.addSourceLine(this));
}
}
} else if ("assertTrue".equals(methodName)) {
if ((state == State.SAW_ICONST_0) || (state == State.SAW_EQUALS)) {
bugReporter.reportBug(new BugInstance(this, "JAO_JUNIT_ASSERTION_ODDITIES_USE_ASSERT_EQUALS", NORMAL_PRIORITY)
.addClass(this)
.addMethod(this)
.addSourceLine(this));
}
}
} else {
String methodName = getNameConstantOperand();
String sig = getSigConstantOperand();
if (clsName.startsWith("java/lang/")
&& "valueOf".equals(methodName)
&& (sig.indexOf(")Ljava/lang/") >= 0)) {
userValue = "valueOf";
}
}
} else if (seen == ATHROW) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
String throwClass = item.getSignature();
if ("Ljava/lang/AssertionError;".equals(throwClass)) {
bugReporter.reportBug(new BugInstance(this, "JAO_JUNIT_ASSERTION_ODDITIES_ASSERT_USED", NORMAL_PRIORITY)
.addClass(this)
.addMethod(this)
.addSourceLine(this));
}
}
}
switch (state) {
case SAW_NOTHING:
case SAW_EQUALS:
if (seen == IF_ICMPNE)
state = State.SAW_IF_ICMPNE;
else
state = State.SAW_NOTHING;
break;
case SAW_IF_ICMPNE:
if (seen == ICONST_1)
state = State.SAW_ICONST_1;
else
state = State.SAW_NOTHING;
break;
case SAW_ICONST_1:
if (seen == GOTO)
state = State.SAW_GOTO;
else
state = State.SAW_NOTHING;
break;
case SAW_GOTO:
if (seen == ICONST_0)
state = State.SAW_ICONST_0;
else
state = State.SAW_NOTHING;
break;
default:
state = State.SAW_NOTHING;
break;
}
if (seen == INVOKEVIRTUAL) {
String methodName = getNameConstantOperand();
String sig = getSigConstantOperand();
if ("equals".equals(methodName) && "(Ljava/lang/Object;)Z".equals(sig)) {
state = State.SAW_EQUALS;
}
}
} finally {
TernaryPatcher.pre(stack, seen);
stack.sawOpcode(this, seen);
TernaryPatcher.post(stack, seen);
if ((userValue != null) && (stack.getStackDepth() > 0)) {
OpcodeStack.Item item = stack.getStackItem(0);
item.setUserValue(userValue);
}
}
}
}
|
package com.palyrobotics.frc2017.vision;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import org.json.simple.parser.ParseException;
import org.spectrum3847.RIOdroid.RIOdroid;
import com.palyrobotics.frc2017.config.Constants;
import com.palyrobotics.frc2017.util.logger.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
/**
* Supplies wrapper methods for using adb to control the Android
*
* <h1><b>Fields</b></h1>
* <ul>
* <li>Instance and State variables:
* <ul>
* <li>{@link AndroidConnectionHelper#s_instance}: Private instance of this class (Singleton)</li>
* <li>{@link AndroidConnectionHelper#m_connectionState}: Current state of connection (private)</li>
* <li>{@link AndroidConnectionHelper#m_streamState}: Current state of streaming</li>
* <li><b>See:</b>{@link ConnectionState}</li>
* </ul>
* </li>
* <li>Utility variables:
* <ul>
* <li>{@link AndroidConnectionHelper#m_secondsAlive}: Private count of seconds the program has run for</li>
* <li>{@link AndroidConnectionHelper#m_stateAliveTime}: Private count of seconds the state has run for</li>
* <li>{@link AndroidConnectionHelper#m_adbServerCreated}: Private boolean representing existence an adb server</li>
* <li>{@link AndroidConnectionHelper#m_visionRunning}: Private boolean representing whether vision program is currently running</li>
* <li>{@link AndroidConnectionHelper#m_running}: Private boolean representing whether the thread is running</li>
* <li>{@link AndroidConnectionHelper#mTesting}: Private boolean representing whether program is testing on a pc with
* adb installed and included in the path </li>
* </ul>
* </li>
* </ul>
*
* <h1><b>Accessors and Mutators</b></h1>
* <ul>
* <li>{@link AndroidConnectionHelper#getInstance()}</li>
* <li>{@link AndroidConnectionHelper#SetState(ConnectionState)}</li>
* <li>{@link AndroidConnectionHelper#SetStreamState(StreamState)}</li>
* </ul>
*
* <h1><b>External Access Functions</b>
* <br><BLOCKQUOTE>For using as a wrapper for RIOdroid</BLOCKQUOTE></h1>
* <ul>
* <li>{@link AndroidConnectionHelper#start(StreamState)}</li>
* <li>{@link AndroidConnectionHelper#StartVisionApp()}</li>
* </ul>
*
* <h1><b>Internal Functions</b>
* <br><BLOCKQUOTE>Paired with external access functions. These compute the actual function for the external access</BLOCKQUOTE></h1>
* <ul>
* <li>{@link AndroidConnectionHelper#InitializeServer()}</li>
* <li>{@link AndroidConnectionHelper#VisionInit()}</li>
* <li>{@link AndroidConnectionHelper#StreamVision()}</li>
* </ul>
*
* @see ConnectionState
* @see StreamState
* @author Alvin
*
*/
public class AndroidConnectionHelper implements Runnable{
/**
* State of connection between the roboRIO and nexus
*
* <ul>
* <li>{@link ConnectionState#PREINIT}</li>
* <li>{@link ConnectionState#STARTING_SERVER}</li>
* <li>{@link ConnectionState#IDLE}</li>
* <li>{@link ConnectionState#START_VISION_APP}</li>
* </ul>
*/
public enum ConnectionState{
PREINIT, STARTING_SERVER, IDLE, START_VISION_APP, STREAMING;
}
/**
* State of streaming data from Nexus
*
* <ul>
* <li>{@link StreamState#IDLE}</li>
* <li>{@link StreamState#JSON}</li>
* <li>{@link StreamState#BROADCAST}</li>
* </ul>
*/
public enum StreamState{
IDLE, JSON, BROADCAST
}
// Instance and state variables
private static AndroidConnectionHelper s_instance;
private ConnectionState m_connectionState = ConnectionState.PREINIT;
private StreamState m_streamState = StreamState.IDLE;
// Utility variables
private double m_secondsAlive = 0;
private double m_stateAliveTime = 0;
private byte[] m_imageData = null;
private boolean m_adbServerCreated = false;
private boolean m_visionRunning = false;
private boolean m_running = false;
private boolean mTesting = false;
private double m_x_dist = 0;
private String m_androidState = "NONE";
private Object m_android_lock = new Object();
/**
* Creates an AndroidConnectionHelper instance
* Cannot be called outside as a Singleton
*/
private AndroidConnectionHelper(){}
/**
* @return The instance of the ACH
*/
public static AndroidConnectionHelper getInstance(){
if(s_instance == null){
s_instance = new AndroidConnectionHelper();
}
return s_instance;
}
/**
* Sets the state of connection
* @param state State to switch to
*/
private void SetState(ConnectionState state){
m_connectionState = state;
}
/**
* Sets the state of streaming between the Nexus
* @param state State to switch to
*/
private void SetStreamState(StreamState state){
if(m_streamState.equals(state)){
System.out.println("Warning: in AndroidConnectionHelper.SetStreamState(), "
+ "no chane to write state");
}else{
m_streamState = state;
}
}
/**
* Starts the AndroidConnectionHelper thread
*/
public void start(StreamState state){
this.start(false, state);
}
/**
* Starts the AndroidConnectionHelper thread
* <br>(accounts for running program for testing)
* @param isTesting
*/
public void start(boolean isTesting, StreamState streamState){
if(m_connectionState != ConnectionState.PREINIT) { // This should never happen
System.out.println("Error: in AndroidConnectionHelper.start(), "
+ "connection is already initialized");
}
if(m_running){ // This should never happen
System.out.println("Error: in AndroidConnectionHelper.start(), "
+ "thread is already running");
}
// Initialize Thread Variables
this.SetState(ConnectionState.STARTING_SERVER);
m_running = true;
m_streamState = streamState;
this.mTesting = isTesting;
System.out.println("Starting Thread: AndroidConnectionHelper ");
(new Thread(this, "AndroidConnectionHelper")).start();
}
/**
* Initializes RIOdroid and RIOadb
* @return The state after execution
*/
private ConnectionState InitializeServer() {
boolean connected = false;
if(m_adbServerCreated){ // This should never happen
System.out.print("Error: in AndroidConnectionHelper.InitializeServer(), "
+ "adb server already connected (or this function was called before)");
return ConnectionState.IDLE;
}else {
try { // RIOadb.init() possible error is not being handled, sketchily fix later
// Initializes RIOdroid usb and RIOadb adb daemon
if(!this.mTesting) {
RIOdroid.init();
if(m_streamState.equals(StreamState.BROADCAST)){
// Forward the port and start the server socket for data
RIOdroid.executeCommand("adb reverse tcp:" +
Constants.kAndroidDataSocketPort + " tcp:" +
Constants.kAndroidDataSocketPort);
System.out.println("Starting DataServerThread");
DataServerThread.getInstance().start(Constants.kAndroidDataSocketPort);
}
// Forward the port and start the server socket for vision
RIOdroid.executeCommand("adb reverse tcp:" +
Constants.kAndroidVisionSocketPort + " tcp:" +
Constants.kAndroidVisionSocketPort);
System.out.println("Starting VisionServerThread");
VisionServerThread.getInstance().start(mTesting);
}else{
RuntimeExecutor.getInstance().init();
if(m_streamState.equals(StreamState.BROADCAST)){
// Forward the port and start the server socket
RuntimeExecutor.getInstance().exec("adb reverse tcp:" +
Constants.kAndroidDataSocketPort + " tcp:" +
Constants.kAndroidDataSocketPort);
System.out.println("Starting VisionServerThread");
DataServerThread.getInstance().start(Constants.kAndroidDataSocketPort);
}
// Forward the port and start the server socket for vision
RuntimeExecutor.getInstance().exec("adb reverse tcp:" +
Constants.kAndroidVisionSocketPort + " tcp:" +
Constants.kAndroidVisionSocketPort);
System.out.println("Starting VisionServerThread");
VisionServerThread.getInstance().start(mTesting);
}
connected = true;
} catch (Exception e) {
System.out.println("Error: in AndroidConnectionHelper.InitializeServer(), "
+ "could not connect.\n" + e.getStackTrace());
}
// Let it retry connection for 10 seconds, then give in
if (m_secondsAlive - m_stateAliveTime > 10 && !connected) {
System.out.println("Error: in AndroidConnectionHelper.InitializeServer(), "
+ "connection timed out");
}
if (connected) {
m_adbServerCreated = true;
// } else {
// return m_connectionState;
}
System.out.println((this.m_adbServerCreated) ? "Started vision stream":"Failed to start vision stream");
Logger.getInstance().logRobotThread((this.m_adbServerCreated) ? "Started vision stream":"Failed to start vision stream");
this.m_visionRunning = true;
return ConnectionState.STREAMING;
}
}
/**
* Starts up the vision app
*/
public void StartVisionApp(){
if(!m_adbServerCreated){ // No abd server, can't start app
System.out.println("Warning: on call AndroidConnectionHelper.StartVisionApp(), " +
"adb server not started, abandoning app startup");
// return;
}
if(m_visionRunning){ // This should never happen, but easily can due to outside calling
System.out.println("Warning: On call AndroidConnectionHelper.StartVisionApp(), "
+ "vision app already running (or function has been called before)");
}else{
if(m_connectionState.equals(ConnectionState.STARTING_SERVER)){
int limit = 40;
int count = 0;
while(!m_connectionState.equals(ConnectionState.IDLE)){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (count>= limit){
break;
}
count++;
}
}else if(!m_connectionState.equals(ConnectionState.IDLE)){
System.out.println("Error: in AndroidConnectionHelper.StartVisionApp(), "
+ "connection not in a state to start app");
}
this.SetState(ConnectionState.START_VISION_APP);
}
}
/**
* Sends command to boot up the vision app
* @return The state after execution
*/
private ConnectionState VisionInit(){
boolean connected = false;
try { // RIOadb.init() possible error is not being handled, sketchily fix later
// Starts app through adb shell, and outputs the returned console message
if(!this.mTesting) {
System.out.println(RIOdroid.executeCommand(
"adb shell am start -n " + Constants.kPackageName + "/" +
Constants.kPackageName + "." + Constants.kActivityName));
}else{
System.out.println(RuntimeExecutor.getInstance().exec(
"adb shell am start -n " + Constants.kPackageName + "/" +
Constants.kPackageName + "." + Constants.kActivityName));
}
connected = true;
}catch (Exception e) {
System.out.println("Error: in AndroidConnectionHelper.VisionInit(), "
+ "could not connect.\n" + e.getStackTrace());
}
// Let it retry connection for 10 seconds, then give in
if (m_secondsAlive - m_stateAliveTime > 10) {
System.out.println("Error: in AndroidConnectionHelper.VisionInit(), "
+ "connection timed out");
}
if(connected) {
m_visionRunning = true;
System.out.println("Starting Vision Stream");
return ConnectionState.STREAMING;
} else {
return m_connectionState;
}
}
/**
* Streams in the vision data
* @return The state after execution
*/
private ConnectionState StreamVision(){
if(!m_visionRunning){ // This should never happen
// System.out.println("Error: in AndroidConnectionHelper.StreamVision(), "
// + "vision program i not running (or has not been initialized inside this program)");
}
switch (m_streamState){
case IDLE:
System.out.println("Error: in AndroidConnectionHelper.StreamVision(), "
+ "streaming in IDLE state, nothing streaming");
break;
case JSON:
this.StreamJSON();
break;
case BROADCAST:
this.StreamBroadcast();
break;
}
return m_connectionState;
}
/**
* Streams vision data via sending a broadcast and
* receiving the output data through a socket
*/
private void StreamBroadcast(){
DataServerThread.getInstance().AwaitClient();
String out = "";
// Broadcast an Intent to the app signaling the call to get data
if(!mTesting){
out = RIOdroid.executeCommand("adb shell am broadcast -a "+Constants.kPackageName+".GET_DATA --es type data");
}else{
out = RuntimeExecutor.getInstance().exec("adb shell am broadcast -a "+Constants.kPackageName+".GET_DATA --es type data");
}
// System.out.println(out);
// Receive data from android client
String raw_data = DataServerThread.getInstance().AwaitOutput();
parseJSON(raw_data);
}
/**
* Streams vision data via pulling a JSON file with
* data written to it
*/
private void StreamJSON(){
String raw_data;
// Read the JSON file which stores the vision data
if(!this.mTesting){
raw_data = RIOdroid.executeCommand("adb shell run-as "+Constants.kPackageName+" cat /data/data/"+ Constants.kPackageName
+ "/files/data.json");
}else{
raw_data = RuntimeExecutor.getInstance().exec("adb shell run-as "+Constants.kPackageName+" cat /data/data/"+ Constants.kPackageName
+ "/files/data.json");
}
parseJSON(raw_data);
}
/**
* Computes parsing of streamed data (for now just prints to console)
* @param raw_data Raw JSON formatted data (String)
*/
private void parseJSON(String raw_data){
if(raw_data == null || raw_data.equals("") || raw_data.equals("error: no devices/emulators found")){
return;
}
// Create JSONObject from the raw String data
JSONObject json = null;
try {
JSONParser parser = new JSONParser();
json = (JSONObject) parser.parse(raw_data);
} catch (ParseException e) {
// This is spammy
// e.printStackTrace();
}
// Compute based on app state (given in the data)
if(json != null){
String state = (String) json.get("state");
if(!(state == null) && !state.equals("")){ // Handle based on state
synchronized (m_android_lock) {
if (state.equals("STREAMING")) {
// Get image data
Number data_x = ((Number) json.get("x_displacement"));
if (data_x != null) {
this.m_x_dist = data_x.doubleValue();
}
}
m_androidState = state;
}
}
}
}
public void setFlash(boolean isFlashOn){
String out;
if(!mTesting){
out = RIOdroid.executeCommand("adb shell am broadcast -a "+Constants.kPackageName+".GET_DATA --es type flash --ez isFlash "+isFlashOn);
}else{
out = RuntimeExecutor.getInstance().exec("adb shell am broadcast -a "+Constants.kPackageName+".GET_DATA --es type flash --ez isFlash "+isFlashOn);
}
}
public double getXDist(){
if(!m_androidState.equals("STREAMING")){
System.out.println("Warning in AndroidConnectionHelper.getXDist(), " +
"not streaming, android state is "+m_androidState+", returning last valid x_distance");
}
return m_x_dist;
}
public boolean isServerStarted(){
return this.m_adbServerCreated;
}
public boolean isNexusConnected(){
String[] outp = RuntimeExecutor.getInstance().exec("adb devices").split("\\n");
return outp.length > 1;
}
/**
* Updates the thread at {@link Constants#kAndroidConnectionUpdateRate} ms
*/
@Override
public void run() {
while(m_running){
ConnectionState initState = m_connectionState;
switch(m_connectionState){
case PREINIT: // Shouldn't happen, but can due to error
System.out.println("Error: in AndroidConnectionHelper.run(), "
+ "thread running on preinit state");
break;
case STARTING_SERVER: // Triggered by start(), should be called externally
this.SetState(this.InitializeServer());
break;
case START_VISION_APP: // Triggered by StartVisionApp(), should be called externally
this.SetState(this.VisionInit());
break;
case STREAMING:
this.SetState(this.StreamVision());
break;
case IDLE:
break;
}
// Reset state start time if state changed
if (!initState.equals(m_connectionState)) {
m_stateAliveTime = m_secondsAlive;
}
// Handle thread sleeping, sleep for set constant update delay
try {
Thread.sleep(Constants.kAndroidConnectionUpdateRate);
m_secondsAlive += Constants.kAndroidConnectionUpdateRate/1000.0;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package com.qmetry.qaf.automation.testng.pro;
import static com.qmetry.qaf.automation.core.ConfigurationManager.getBundle;
import static com.qmetry.qaf.automation.testng.dataprovider.DataProviderFactory.getDataProvider;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;
import org.testng.IInvokedMethod;
import org.testng.IRetryAnalyzer;
import org.testng.ISuite;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.ITestAnnotation;
import org.testng.annotations.Test;
import org.testng.internal.ConstructorOrMethod;
import com.qmetry.qaf.automation.core.CheckpointResultBean;
import com.qmetry.qaf.automation.core.LoggingBean;
import com.qmetry.qaf.automation.core.QAFTestBase;
import com.qmetry.qaf.automation.core.TestBaseProvider;
import com.qmetry.qaf.automation.integration.ResultUpdator;
import com.qmetry.qaf.automation.integration.TestCaseResultUpdator;
import com.qmetry.qaf.automation.integration.TestCaseRunResult;
import com.qmetry.qaf.automation.keys.ApplicationProperties;
import com.qmetry.qaf.automation.step.client.TestNGScenario;
import com.qmetry.qaf.automation.testng.RetryAnalyzer;
import com.qmetry.qaf.automation.testng.dataprovider.QAFDataProvider;
import com.qmetry.qaf.automation.testng.report.ReporterUtil;
import com.qmetry.qaf.automation.util.ClassUtil;
import com.qmetry.qaf.automation.util.StringUtil;
/**
* All in one Listener for ISFW. If this listener is added, you don't required
* to add any other ISFW specific listener.
*
* @author Chirag Jayswal.
*/
public class QAFTestNGListener2 extends QAFTestNGListener
// implements
// IAnnotationTransformer2,
// IMethodInterceptor,
// IResultListener,
// ISuiteListener,
// IInvokedMethodListener2,
// IMethodSelector
{
private final Log logger = LogFactoryImpl.getLog(getClass());
public QAFTestNGListener2() {
logger.debug("QAFTestNGListener registered!...");
}
@Override
public void onStart(final ISuite suite) {
if (skipReporting())
return;
super.onStart(suite);
ReporterUtil.createMetaInfo(suite);
}
@Override
public void onFinish(ISuite suite) {
if (skipReporting())
return;
super.onFinish(suite);
logger.debug("onFinish: start");
ReporterUtil.createMetaInfo(suite);
logger.debug("onFinish: done");
}
@Override
public void onFinish(ITestContext testContext) {
if (skipReporting())
return;
super.onFinish(testContext);
ReporterUtil.updateOverview(testContext, null);
}
@SuppressWarnings("rawtypes")
public void transform(ITestAnnotation testAnnotation, Class clazz, Constructor arg2,
Method method) {
try {
if ((method.getAnnotation(QAFDataProvider.class) != null)
&& (null != method.getParameterTypes()) && (null != method)
&& (method.getParameterTypes().length > 0)) {
String dp = getDataProvider(method);
if (StringUtil.isNotBlank(dp)) {
testAnnotation.setDataProvider(dp);
testAnnotation.setDataProviderClass(DataProviderUtil.class);
}
}
if (null != method) {
String tmtURL = getBundle().getString(method.getName() + ".testspec.url");
if (StringUtil.isNotBlank(tmtURL)) {
String desc = String.format("%s<br/><a href=\"%s\">[test-spec]</a>",
testAnnotation.getDescription(), tmtURL);
testAnnotation.setDescription(desc);
}
if (getBundle().getBoolean("report.javadoc.link", false)) {
String linkRelPath = String.format("%s%s.html
getBundle().getString("javadoc.folderpath",
"../../../docs/tests/"),
method.getDeclaringClass().getCanonicalName()
.replaceAll("\\.", "/"),
ClassUtil.getMethodSignture(method, false));
String desc = String.format(
"%s " + getBundle().getString("report.javadoc.link.format",
"<a href=\"%s\" target=\"_blank\">[View-doc]</a>"),
testAnnotation.getDescription(), linkRelPath);
testAnnotation.setDescription(desc);
}
testAnnotation.setDescription(getBundle().getSubstitutor()
.replace(testAnnotation.getDescription()));
testAnnotation.setRetryAnalyzer(
Class.forName(ApplicationProperties.RETRY_ANALYZER
.getStringVal(RetryAnalyzer.class.getName())));
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void afterInvocation(final IInvokedMethod method, final ITestResult tr,
final ITestContext context) {
super.afterInvocation(method, tr, context);
// pro
if (method.isTestMethod() && !shouldRetry(tr)) {
deployResult(tr, context);
}
}
private boolean shouldRetry(ITestResult tr) {
IRetryAnalyzer retryAnalyzer = tr.getMethod().getRetryAnalyzer();
boolean shouldRetry = false;
if (null != retryAnalyzer && retryAnalyzer instanceof RetryAnalyzer) {
shouldRetry = (((RetryAnalyzer) retryAnalyzer).shouldRetry(tr));
}
return shouldRetry;
}
@Override
protected void report(ITestResult tr) {
super.report(tr);
if (skipReporting())
return;
QAFTestBase stb = TestBaseProvider.instance().get();
final List<CheckpointResultBean> checkpoints =
new ArrayList<CheckpointResultBean>(stb.getCheckPointResults());
// pro
final List<LoggingBean> logs = new ArrayList<LoggingBean>(stb.getLog());
ITestContext testContext = (ITestContext) tr.getAttribute("context");
ReporterUtil.createMethodResult(testContext, tr, logs, checkpoints);
if (tr.getStatus() != ITestResult.FAILURE) {
getBundle().clearProperty(RetryAnalyzer.RETRY_INVOCATION_COUNT);
}
}
private void deployResult(ITestResult tr, ITestContext context) {
QAFTestBase stb = TestBaseProvider.instance().get();
try {
if ((tr.getMethod() instanceof TestNGScenario)
&& ((tr.getStatus() == ITestResult.FAILURE)
|| (tr.getStatus() == ITestResult.SUCCESS
|| tr.getStatus() == ITestResult.SKIP))) {
ConstructorOrMethod testCase = tr.getMethod().getConstructorOrMethod();
testCase.getMethod().getAnnotation(Test.class);
TestCaseRunResult result = tr.getStatus() == ITestResult.SUCCESS
? TestCaseRunResult.PASS : tr.getStatus() == ITestResult.FAILURE
? TestCaseRunResult.FAIL : TestCaseRunResult.SKIPPED;
// String method = testCase.getName();
String updator = getBundle().getString("result.updator");
if (StringUtil.isNotBlank(updator)) {
Class<?> updatorCls = Class.forName(updator);
TestCaseResultUpdator updatorObj =
(TestCaseResultUpdator) updatorCls.newInstance();
TestNGScenario scenario = (TestNGScenario) tr.getMethod();
Map<String, Object> params =
new HashMap<String, Object>(scenario.getMetaData());
params.put("duration", tr.getEndMillis() - tr.getStartMillis());
ResultUpdator.updateResult(result,
stb.getHTMLFormattedLog() + stb.getAssertionsLog(),
updatorObj, params);
}
}
} catch (Exception e) {
logger.warn("Unable to deploy result", e);
}
}
private boolean skipReporting() {
return getBundle().getBoolean("disable.qaf.testng.reporter", false)
|| getBundle().getBoolean("cucumber.run.mode", true);
}
}
|
package com.saintsrobotics.tshirt.subsystems;
import com.saintsrobotics.tshirt.RobotMap;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Subsystem;
public class PneumaticSubsystem extends Subsystem {
DigitalInput pressureSwitch = new DigitalInput(RobotMap.PRESSURE_SWITCH);
Relay firingValve = new Relay(RobotMap.FIRING_RELAY, RobotMap.FIRING_DIRECTION);
Relay tankValve = new Relay(RobotMap.TANK_RELAY, RobotMap.TANK_DIRECTION);
protected void initDefaultCommand() { }
/**
* Opens or closes the valve connected to the air tanks.
*
* @param val true for open, false for closed
*/
public void setTankValve(boolean val) {
tankValve.set(invert(val, RobotMap.TANK_INVERTED) ? Relay.Value.kOn : Relay.Value.kOff);
}
/**
* Opens or closes the valve connected to the firing tube.
*
* @param val true for open, false for closed
*/
public void setFiringValve(boolean val) {
firingValve.set(invert(val, RobotMap.FIRING_INVERTED) ? Relay.Value.kOn : Relay.Value.kOff);
}
/**
* Gets the current setting of the tank valve.
*
* @return true if on (or forward in bidirectional mode), false if off
* (or backwards in bidirectional mode).
*/
public boolean getTankValve() {
return firingValve.get().equals(Relay.Value.kOn)||
firingValve.get().equals(Relay.Value.kForward);
}
/**
* Gets the current setting of the firing valve.
*
* @return true if on (or forward in bidirectional mode), false if off
* (or backwards in bidirectional mode).
*/
public boolean getFiringValve() {
return firingValve.get().equals(Relay.Value.kOn) ||
firingValve.get().equals(Relay.Value.kForward);
}
/**
* Gets the value of the pressure switch.
*
* @return true if pressure is high, false if pressure is low
*/
public boolean getPressureSwitch() {
return invert(pressureSwitch.get(), RobotMap.PRESSURE_SWITCH_INVERTED);
}
/**
* Invert a value if it's supposed to be.
*
* @param val the original value
* @param inv whether or not to invert
* @return {@code val} inverted if it's supposed to be
*/
private boolean invert(boolean val, boolean inv) {
return val ^ inv;
}
}
|
package codeine.db.mysql.connectors;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import codeine.db.IStatusDatabaseConnector;
import codeine.db.mysql.DbUtils;
import codeine.jsons.global.ExperimentalConfJsonStore;
import codeine.jsons.peer_status.PeerStatusJsonV2;
import codeine.jsons.peer_status.PeerStatusString;
import codeine.jsons.peer_status.PeerType;
import codeine.utils.ExceptionUtils;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
public class StatusMysqlConnector implements IStatusDatabaseConnector{
private static final Logger log = Logger.getLogger(StatusMysqlConnector.class);
@Inject
private DbUtils dbUtils;
@Inject
private Gson gson;
@Inject private ExperimentalConfJsonStore webConfJsonStore;
private String tableName = "ProjectStatusList";
public StatusMysqlConnector() {
super();
}
public StatusMysqlConnector(DbUtils dbUtils, Gson gson, ExperimentalConfJsonStore webConfJsonStore) {
super();
this.dbUtils = dbUtils;
this.gson = gson;
this.webConfJsonStore = webConfJsonStore;
}
public void createTables() {
if (webConfJsonStore.get().readonly_web_server()) {
log.info("read only mode");
return;
}
String colsDefinition = "peer_key VARCHAR(150) NOT NULL PRIMARY KEY, data text, update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, status VARCHAR(50) DEFAULT 'On' NOT NULL";
dbUtils.executeUpdate("create table if not exists " + tableName + " (" + colsDefinition + ")");
}
@Override
public void putReplaceStatus(PeerStatusJsonV2 p) {
String json = gson.toJson(p);
log.info("will update status to " + dbUtils.server() + "\n" + json);
dbUtils.executeUpdate("DELETE FROM "+tableName+" WHERE peer_key = '" + p.peer_old_key() + "'");
dbUtils.executeUpdate("REPLACE INTO "+tableName+" (peer_key, data, update_time ) VALUES (?, ?, CURRENT_TIMESTAMP())", p.peer_key(), json);
}
@Override
public Map<String, PeerStatusJsonV2> getPeersStatus() {
log.info("getPeersStatus " + dbUtils.server());
final Map<String, PeerStatusJsonV2> $ = Maps.newHashMap();
Function<ResultSet, Void> function = new Function<ResultSet, Void>() {
@Override
public Void apply(ResultSet rs){
try {
String key = rs.getString(1);
String value = rs.getString(2);
PeerStatusJsonV2 peerStatus = gson.fromJson(value, PeerStatusJsonV2.class);
peerStatus.status(PeerStatusString.valueOf(rs.getString("status")));
updateNodesWithPeer(peerStatus);
$.put(key, peerStatus);
return null;
} catch (SQLException e) {
throw ExceptionUtils.asUnchecked(e);
}
}
};
dbUtils.executeQuery("select * from " + tableName, function);
return $;
}
private void updateNodesWithPeer(PeerStatusJsonV2 peerStatus) {
peerStatus.updateNodesWithPeer();
}
@Override
public void updatePeersStatus(final long timeToRemove, final long timeToDisc) {
final List<String> idToRemove = Lists.newArrayList();
final List<String> idToDisc = Lists.newArrayList();
Function<ResultSet, Void> function = new Function<ResultSet, Void>() {
@Override
public Void apply(ResultSet rs){
try {
String key = rs.getString("peer_key");
// PeerStatusString status = PeerStatusString.valueOf(rs.getString("status"));
String value = rs.getString("data");
String status = rs.getString("status");
PeerStatusJsonV2 peerStatus = gson.fromJson(value, PeerStatusJsonV2.class);
PeerType peerType = peerStatus.peer_type();
long timeToRemovePeer = peerType == PeerType.Reporter ? timeToRemove + TimeUnit.DAYS.toMinutes(7) : timeToRemove;
long timeToDiscPeer = peerType == PeerType.Reporter ? timeToDisc + TimeUnit.DAYS.toMinutes(7) : timeToDisc;
long timeDiff = rs.getLong("TIME_DIFF");
log.debug("time diff is " + timeDiff);
if (timeDiff > timeToRemovePeer){
log.info("time diff is " + timeDiff);
log.info("deleting " + peerStatus);
// rs.deleteRow();
idToRemove.add(key);
}
else if (timeDiff > timeToDiscPeer && !status.equals("Disc")){
log.info("time diff is " + timeDiff);
log.info("update to disc " + peerStatus);
idToDisc.add(key);
// rs.updateString("status", "Disc");
// rs.updateRow();
}
return null;
} catch (SQLException e) {
throw ExceptionUtils.asUnchecked(e);
}
}
};
dbUtils.executeUpdateableQuery("select *,TIMESTAMPDIFF(MINUTE,update_time,CURRENT_TIMESTAMP()) as TIME_DIFF from " + tableName, function);
if (webConfJsonStore.get().readonly_web_server()) {
log.info("read only mode");
return;
}
for (String key : idToRemove) {
log.info("deleting " + key);
dbUtils.executeUpdate("DELETE from " + tableName + " WHERE peer_key = ?", key);
}
for (String key : idToDisc) {
log.info("discing " + key);
dbUtils.executeUpdate("UPDATE " + tableName + " SET status = 'Disc' WHERE peer_key = ?", key);
}
}
@Override
public String server() {
return dbUtils.toString();
}
@Override
public String toString() {
return "StatusMysqlConnector [dbUtils=" + dbUtils + "]";
}
}
|
package dr.evomodel.continuous;
import dr.xml.*;
import dr.evolution.tree.BranchAttributeProvider;
/*
* @author Marc Suchard
*/
public class BranchMagnitudeAttributeProvider extends BivariateTraitBranchAttributeProvider {
public static final String MAGNITUDE_PROVIDER = "branchMagnitudes";
public static final String SCALE = "scaleByLength";
public static String DISTANCE_EXTENSION = ".distance";
public static final String RATE_EXTENSION = ".rate";
public BranchMagnitudeAttributeProvider(SampledMultivariateTraitLikelihood traitLikelihood, boolean scale) {
super(traitLikelihood);
this.scale = scale;
label = traitName + extensionName();
}
protected String extensionName() {
if (scale)
return RATE_EXTENSION;
return DISTANCE_EXTENSION;
}
protected double convert(double latValue, double longValue, double timeValue) {
double result = Math.sqrt(latValue*latValue + longValue*longValue);
if (scale)
result /= timeValue;
return result;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
SampledMultivariateTraitLikelihood traitLikelihood = (SampledMultivariateTraitLikelihood)
xo.getChild(SampledMultivariateTraitLikelihood.class);
boolean scale = xo.getAttribute(SCALE,false);
return new BranchMagnitudeAttributeProvider(traitLikelihood, scale);
}
public XMLSyntaxRule[] getSyntaxRules() {
return new XMLSyntaxRule[] {
new ElementRule(SampledMultivariateTraitLikelihood.class),
AttributeRule.newBooleanRule(SCALE,true),
};
}
public String getParserDescription() {
return null;
}
public Class getReturnType() {
return BranchAttributeProvider.class;
}
public String getParserName() {
return MAGNITUDE_PROVIDER;
}
};
private boolean scale;
}
|
package edu.psu.compbio.seqcode.projects.akshay.utils;
import java.awt.BasicStroke;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.jfree.chart.annotations.XYLineAnnotation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import edu.psu.compbio.seqcode.gse.utils.ArgParser;
import edu.psu.compbio.seqcode.gse.utils.Pair;
import edu.psu.compbio.seqcode.gse.viz.scatter.ScatterPlot;
import Jama.Matrix;
public class MAPlotter {
protected Matrix DEPval;
protected Matrix CondFold;
protected Matrix CondMean;
protected HashMap<String, Integer> unitToIndex;
protected HashMap<Integer, String> indextoUnit;
public final double LOG_FC_LIMIT = 10;
// Import edgeR results
public void loadMatices(String diffFilename) throws IOException{
File dfFile = new File(diffFilename);
BufferedReader reader = new BufferedReader(new FileReader(dfFile));
//First line should have column labels
String line= reader.readLine();
int u = 0;
unitToIndex = new HashMap<String, Integer>();
indextoUnit = new HashMap<Integer, String>();
while ((line = reader.readLine()) != null) {
line = line.trim();
String[] words = line.split("\\s+");
String pointStr = words[0].replaceAll("\"", "");
unitToIndex.put(pointStr, u);
indextoUnit.put(u, pointStr);
u++;
}reader.close();
DEPval = new Matrix(u,1);
CondFold = new Matrix(u,1);
CondMean = new Matrix(u,1);
BufferedReader reader1 = new BufferedReader(new FileReader(dfFile));
line= reader1.readLine();
u=0;
while ((line = reader1.readLine()) != null) {
line = line.trim();
String[] words = line.split("\\s+");
//Edit for Double correctness
if(words[1].equals("Inf")){words[1]="Infinite";} if(words[1].equals("-Inf")){words[1]="-Infinite";}
if(words[2].equals("Inf")){words[2]="Infinite";} if(words[2].equals("-Inf")){words[2]="-Infinite";}
if(words[5].equals("Inf")){words[5]="Infinite";} if(words[5].equals("-Inf")){words[5]="-Infinite";}
//Format:
//Point logFC logCPM LR PValue FDR
Double logFC = new Double(words[1]);
if(logFC>LOG_FC_LIMIT){ logFC=LOG_FC_LIMIT; }
if(logFC<-LOG_FC_LIMIT){ logFC=-LOG_FC_LIMIT; }
Double logCPM = new Double(words[2]);
Double FDR = new Double(words[5]);
DEPval.set(u, 0, FDR);
CondFold.set(u, 0, logFC);
CondMean.set(u,0,logCPM);
u++;
}reader1.close();
}
public void plot(String DEevents, String ConstantEvents) throws IOException{
List<Pair<Double,Double>> DEhighlight = new ArrayList<Pair<Double,Double>>();
List<Pair<Double,Double>> ConstantHighlight = new ArrayList<Pair<Double,Double>>();
List<Pair<Double,Double>> otherMA = new ArrayList<Pair<Double,Double>>();
HashMap<String, Integer> inDE = new HashMap<String, Integer>();
HashMap<String, Integer> isConst = new HashMap<String, Integer>();
BufferedReader DEreader = new BufferedReader(new FileReader(DEevents));
String line;
while ((line = DEreader.readLine()) != null) {
line = line.trim();
String[] words = line.split("\\s+");
inDE.put(words[0], 0);
}DEreader.close();
BufferedReader Constreader = new BufferedReader(new FileReader(ConstantEvents));
while ((line = Constreader.readLine()) != null) {
line = line.trim();
String[] words = line.split("\\s+");
isConst.put(words[0], 0);
}Constreader.close();
double A_min=1;
for(int d=0; d<unitToIndex.keySet().size(); d++){
double fold=CondFold.get(d, 0), avg = CondMean.get(d,0);
if(avg<A_min)
avg = A_min;
if(inDE.containsKey(indextoUnit.get(d)))
DEhighlight.add(new Pair<Double,Double>(fold,avg));
else if(isConst.containsKey(indextoUnit.get(d)))
ConstantHighlight.add(new Pair<Double,Double>(fold,avg));
else
otherMA.add(new Pair<Double,Double>(fold,avg));
}
// make matrices
Matrix maMatrixDE = new Matrix(DEhighlight.size(),2);
Matrix maMatrixConst = new Matrix(ConstantHighlight.size(),2);
Matrix maMatrixOther = new Matrix(otherMA.size(),2);
int count=0;
for(Pair<Double,Double> v : DEhighlight){
maMatrixDE.set(count, 0, v.cdr());
maMatrixDE.set(count, 1, v.car());
count++;
}
count=0;
for(Pair<Double,Double> v : ConstantHighlight){
maMatrixConst.set(count, 0, v.cdr());
maMatrixConst.set(count, 1, v.car());
count++;
}
count=0;
for(Pair<Double,Double> v : otherMA){
maMatrixOther.set(count, 0, v.cdr());
maMatrixOther.set(count, 1, v.car());
count++;
}
ThreeClassScatterPlotMaker plotter = new ThreeClassScatterPlotMaker("Main");
plotter.saveMAplot(maMatrixOther, maMatrixDE, maMatrixConst, 0.0, "ScatterPlot", true);
}
public class ThreeClassScatterPlotMaker extends ScatterPlot{
public ThreeClassScatterPlotMaker(String title) {
super(title);
}
public void saveMAplot(Matrix datapoints, Matrix datapoints_highlight, Matrix datapoints_constant, Double yLine, String outFilename, boolean rasterImage){
this.setWidth(800);
this.setHeight(800);
this.setXLogScale(false);
this.setYLogScale(false);
this.addDataset("other", datapoints, new Color(75,75,75,80), 3);
if(datapoints_highlight!=null)
this.addDataset("DE", datapoints_highlight, new Color(0,0,255,80), 3);
if(datapoints_constant !=null)
this.addDataset("Constant", datapoints_constant, new Color(255,80,0,0), 3);
this.setXAxisLabel("A");
this.setYAxisLabel("M");
this.setXRangeFromData();
this.setYRange(-10.5,10.5);
//Set the tick units according to the range
double xUpper = daxis.getRange().getUpperBound();
double xLower = daxis.getRange().getLowerBound();
//if(daxis instanceof org.jfree.chart.axis.NumberAxis)
// ((NumberAxis)daxis).setTickUnit(new NumberTickUnit(5));
double yUpper = raxis.getRange().getUpperBound();
double yLower = raxis.getRange().getLowerBound();
if(raxis instanceof org.jfree.chart.axis.NumberAxis)
((NumberAxis)raxis).setTickUnit(new NumberTickUnit(3));
//Draw a line along y = yLine
if(yLine!=null){
XYLineAnnotation lineAnnot = new XYLineAnnotation(xLower, yLine, xUpper, yLine, new BasicStroke(1), new Color(0,0,0));
this.plot.addAnnotation(lineAnnot);
}
try {
this.saveImage(new File(outFilename), width, height, rasterImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException{
ArgParser ap = new ArgParser(args);
String diffFilename = ap.getKeyValue("EdgeRmat");
String DEevents = ap.getKeyValue("DEevents");
String ConstantEvents = ap.getKeyValue("ConstantEvents");
MAPlotter ma = new MAPlotter();
ma.loadMatices(diffFilename);
ma.plot(DEevents, ConstantEvents);
}
}
|
package gov.nih.nci.caintegrator.analysis.server;
import gov.nih.nci.caintegrator.analysis.messaging.AnalysisRequest;
import gov.nih.nci.caintegrator.analysis.messaging.AnalysisResult;
import gov.nih.nci.caintegrator.analysis.messaging.ClassComparisonRequest;
import gov.nih.nci.caintegrator.analysis.messaging.HierarchicalClusteringRequest;
import gov.nih.nci.caintegrator.analysis.messaging.PrincipalComponentAnalysisRequest;
import gov.nih.nci.caintegrator.exceptions.AnalysisServerException;
import java.io.FileInputStream;
import java.util.Hashtable;
import java.util.Properties;
import javax.jms.DeliveryMode;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* This class implements the analysis server module.
*
* @author Michael A. Harris
*
*
* AnalysisServer should register handlers which are specifed from a
* configuration file.
*
* Version 5.6 - changed error check to allow any number of reporters for clustering by samples
* and allow 3000 reporters for clustering by genes.
*/
public class AnalysisServer implements MessageListener, ExceptionListener, AnalysisResultSender {
public static String version = "5.6";
private boolean debugRcommands = false;
private static String JBossMQ_locationIp = null;
private static int numComputeThreads = -1;
private static int defaultNumComputeThreads = 1;
private static String RserverIp = null;
private static String defaultRserverIp = "localhost";
private static String RdataFileName = null;
private RThreadPoolExecutor executor;
private QueueConnection queueConnection;
private Queue requestQueue;
private Queue resultQueue;
private QueueSession queueSession;
private Hashtable contextProperties = new Hashtable();
private String factoryJNDI = null;
private static long reconnectWaitTimeMS = -1L;
private static long defaultReconnectWaitTimeMS = 10000L;
private static Logger logger = Logger.getLogger(AnalysisServer.class);
private QueueReceiver requestReceiver;
//private QueueSender resultSender;
/**
* Sets up all the JMS fixtures.
*
* Use close() when finished with object.
*
* @param factoryJNDI
* name of the topic connection factory to look up.
* @param topicJNDI
* name of the topic destination to look up
*/
public AnalysisServer(String factoryJNDI, String serverPropertiesFileName) throws JMSException,
NamingException {
this.factoryJNDI = factoryJNDI;
// load properties from a properties file
Properties analysisServerConfigProps = new Properties();
try {
analysisServerConfigProps.load(new FileInputStream(
serverPropertiesFileName));
//Configure log4J
PropertyConfigurator.configure(analysisServerConfigProps);
JBossMQ_locationIp = getMandatoryStringProperty(analysisServerConfigProps, "jmsmq_location");
RserverIp = getStringProperty(analysisServerConfigProps,"rserve_location", defaultRserverIp);
numComputeThreads = getIntegerProperty(analysisServerConfigProps,"num_compute_threads", defaultNumComputeThreads);
RdataFileName = getMandatoryStringProperty(analysisServerConfigProps,"RdefinitionFile");
debugRcommands = getBooleanProperty(analysisServerConfigProps, "debugRcommands", false);
reconnectWaitTimeMS = getLongProperty(analysisServerConfigProps, "reconnectWaitTimeMS", defaultReconnectWaitTimeMS);
} catch (Exception ex) {
logger.error("Error loading server properties from file: " + analysisServerConfigProps);
logger.error(ex);
//System.out.println("Error loading server properties from file: " + analysisServerConfigProps);
//ex.printStackTrace(System.out);
}
// initialize the compute threads
executor = new RThreadPoolExecutor(numComputeThreads, RserverIp,
RdataFileName, this);
executor.setDebugRcommmands(debugRcommands);
//establish the JMS queue connections
contextProperties.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
contextProperties.put(Context.PROVIDER_URL, JBossMQ_locationIp);
contextProperties.put("java.naming.rmi.security.manager", "yes");
contextProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.naming");
establishQueueConnection();
logger.info("AnalysisServer version=" + version
+ " successfully initialized. numComputeThreads=" + numComputeThreads + " RserverIp=" + RserverIp + " RdataFileName=" + RdataFileName);
}
private boolean getBooleanProperty(Properties props, String propertyName, boolean defaultValue) {
String propValue = props.getProperty(propertyName);
if (propValue == null) {
return defaultValue;
}
return Boolean.parseBoolean(propValue);
}
private String getMandatoryStringProperty(Properties props, String propertyName) {
String propValue = props.getProperty(propertyName);
if (propValue == null) {
throw new IllegalStateException("Could not load mandatory property name=" + propertyName);
}
return propValue;
}
private String getStringProperty(Properties props, String propertyName, String defaultValue) {
String propValue = props.getProperty(propertyName);
if (propValue == null) {
return defaultValue;
}
return propValue;
}
private int getIntegerProperty(Properties props, String propertyName, int defaultValue) {
String propValue = props.getProperty(propertyName);
if (propValue == null) {
return defaultValue;
}
return Integer.parseInt(propValue);
}
private long getLongProperty(Properties props, String propertyName, long defaultValue) {
String propValue = props.getProperty(propertyName);
if (propValue == null) {
return defaultValue;
}
return Long.parseLong(propValue);
}
public AnalysisServer(String factoryJNDI) throws JMSException,
NamingException {
this(factoryJNDI, "analysisServer.properties");
}
/**
* Establish a connection to the JMS queues. If it is not possible
* to connect then this method will sleep for reconnectWaitTimeMS milliseconds and
* then try to connect again.
*
*/
private void establishQueueConnection() {
boolean connected = false;
Context context = null;
int numConnectAttempts = 0;
while (!connected) {
try {
//logger.info("Attempting to establish queue connection with provider: " + contextProperties.get(Context.PROVIDER_URL));
//Get the initial context with given properties
context = new InitialContext(contextProperties);
requestQueue = (Queue) context.lookup("queue/AnalysisRequest");
resultQueue = (Queue) context.lookup("queue/AnalysisResponse");
QueueConnectionFactory qcf = (QueueConnectionFactory) context
.lookup(factoryJNDI);
queueConnection = qcf.createQueueConnection();
queueConnection.setExceptionListener(this);
queueSession = queueConnection.createQueueSession(false,
QueueSession.AUTO_ACKNOWLEDGE);
requestReceiver = queueSession.createReceiver(requestQueue);
requestReceiver.setMessageListener(this);
//resultSender = queueSession.createSender(resultQueue);
//now creating senders when a message needs to be sent
//because of problem with closed sessions
queueConnection.start();
connected = true;
numConnectAttempts = 0;
//System.out.println(" successfully established queue connection.");
//System.out.println("Now listening for requests...");
logger.info(" successfully established queue connection with provider=" + contextProperties.get(Context.PROVIDER_URL));
logger.info("Now listening for requests...");
}
catch (Exception ex) {
numConnectAttempts++;
if (numConnectAttempts <= 10) {
logger.warn(" could not establish connection with provider=" + contextProperties.get(Context.PROVIDER_URL) + " after numAttempts=" + numConnectAttempts + " Will try again in " + Long.toString(reconnectWaitTimeMS/1000L) + " seconds...");
if (numConnectAttempts == 10) {
logger.warn(" Will only print connection attempts every 600 atttempts to reduce log size.");
}
}
else if ((numConnectAttempts % 600) == 0) {
logger.info(" could not establish connection after numAttempts=" + numConnectAttempts + " will keep trying every " + Long.toString(reconnectWaitTimeMS/1000L) + " seconds...");
}
try {
Thread.sleep(reconnectWaitTimeMS);
}
catch (Exception ex2) {
logger.error("Caugh exception while trying to sleep.." + ex2.getMessage());
logger.error(ex2);
//ex2.printStackTrace(System.out);
return;
}
}
}
}
/**
* Implementation of the MessageListener interface, messages will be
* received through this method.
*/
public void onMessage(Message m) {
// Unpack the message, be careful when casting to the correct
// message type. onMessage should not throw any application
// exceptions.
try {
// String msg = ((TextMessage)m).getText();
ObjectMessage msg = (ObjectMessage) m;
AnalysisRequest request = (AnalysisRequest) msg.getObject();
//System.out.println("AnalysisProcessor got request: " + request);
logger.info("AnalysisProcessor got request: " + request);
if (request instanceof ClassComparisonRequest) {
processClassComparisonRequest((ClassComparisonRequest) request);
} else if (request instanceof HierarchicalClusteringRequest) {
processHierarchicalClusteringRequest((HierarchicalClusteringRequest) request);
} else if (request instanceof PrincipalComponentAnalysisRequest) {
processPrincipalComponentAnalysisRequest((PrincipalComponentAnalysisRequest) request);
}
// sendResult(request);
} catch (JMSException ex) {
logger.error("AnalysisProcessor exception: " + ex);
logger.error(ex);
// System.err.println("AnalysisProcessor exception: " + ex);
// ex.printStackTrace();
} catch (Exception ex2) {
logger.error("Got exception in onMessage:");
logger.error(ex2);
}
}
/**
* Process a class comparison analysis request.
*
* @param ccRequest
*/
public void processClassComparisonRequest(ClassComparisonRequest ccRequest) {
executor.execute(new ClassComparisonTaskR(ccRequest, true));
}
/**
* Process a hierarchicalClusteringAnalysisRequest.
*
* @param hcRequest
*/
public void processHierarchicalClusteringRequest(
HierarchicalClusteringRequest hcRequest) {
executor.execute(new HierarchicalClusteringTaskR(hcRequest, true));
}
/**
* Process a PrincipalComponentAnalysisRequest.
*
* @param pcaRequest
*/
public void processPrincipalComponentAnalysisRequest(
PrincipalComponentAnalysisRequest pcaRequest) {
executor.execute(new PrincipalComponentAnalysisTaskR(pcaRequest, true));
}
public void sendException(AnalysisServerException analysisServerException) {
try {
logger.info("AnalysisServer sending AnalysisServerException sessionId="
+ analysisServerException.getFailedRequest()
.getSessionId()
+ " taskId="
+ analysisServerException.getFailedRequest()
.getTaskId() + " msg=" + analysisServerException.getMessage());
QueueSession exceptionSession = queueConnection.createQueueSession(false,
QueueSession.AUTO_ACKNOWLEDGE);
ObjectMessage msg = exceptionSession
.createObjectMessage(analysisServerException);
QueueSender exceptionSender = exceptionSession.createSender(resultQueue);
exceptionSender.send(msg, DeliveryMode.NON_PERSISTENT,
Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
exceptionSender.close();
exceptionSession.close();
} catch (JMSException ex) {
logger.error("Error while sending AnalysisException");
logger.error(ex);
//ex.printStackTrace(System.out);
}
catch (Exception ex) {
logger.error("Caught exception when trying to send exception analysisServerException:");
logger.error(ex);
}
}
public void sendResult(AnalysisResult result) {
try {
logger.debug("AnalysisServer sendResult sessionId="
+ result.getSessionId() + " taskId="
+ result.getTaskId());
QueueSession resultSession = queueConnection.createQueueSession(false,
QueueSession.AUTO_ACKNOWLEDGE);
ObjectMessage msg = resultSession
.createObjectMessage(result);
QueueSender resultSender = resultSession.createSender(resultQueue);
resultSender.send(msg, DeliveryMode.NON_PERSISTENT,
Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
resultSender.close();
resultSession.close();
} catch (JMSException ex) {
logger.error("Caught JMS exception when trying to send result.");
logger.error(ex);
} catch (Exception ex) {
logger.error("Caught exception when trying to send result.");
logger.error(ex);
}
}
public static void main(String[] args) {
try {
if (args.length > 0) {
String serverPropsFile = args[0];
AnalysisServer server = new AnalysisServer("ConnectionFactory", serverPropsFile);
}
else {
AnalysisServer server = new AnalysisServer("ConnectionFactory");
}
}
catch (Exception ex) {
logger.error("An exception occurred while testing AnalysisProcessor: "
+ ex);
logger.error(ex);
// System.err
// .println("An exception occurred while testing AnalysisProcessor: "
// ex.printStackTrace();
}
}
/**
* If there is a problem with the connection then re-establish
* the connection.
*/
public void onException(JMSException exception) {
//System.out.println("onException: caught JMSexception: " + exception.getMessage());
logger.error("onException: caught JMSexception: " + exception.getMessage());
try
{
if (queueConnection != null) {
queueConnection.setExceptionListener(null);
//close();
queueConnection.close();
}
}
catch (JMSException c)
{
logger.info("Ignoring exception thrown when closing broken connection msg=" + c.getMessage());
//System.out.println("Ignoring exception thrown when closing broken connection msg=" + c.getMessage());
//c.printStackTrace(System.out);
}
//attempt to re-establish the queue connection
establishQueueConnection();
}
}
|
/**
*
* $Id: XenograftPopulateAction.java,v 1.27 2006-09-11 16:55:23 georgeda Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.26 2006/05/23 18:16:20 georgeda
* Added other into species dropdown
*
* Revision 1.25 2006/05/19 16:40:44 pandyas
* Defect #249 - add other to species on the Xenograft screen
*
* Revision 1.24 2006/04/27 15:06:29 pandyas
* cleaned up as a result of testing
*
* Revision 1.23 2006/04/20 19:46:14 pandyas
* Modified host species/ host strain / otherHostStrain text on Xenograft screen
*
* Revision 1.22 2006/04/20 18:11:16 pandyas
* Cleaned up Species or Strain save of Other in DB
*
* Revision 1.21 2006/04/17 19:09:40 pandyas
* caMod 2.1 OM changes
*
* Revision 1.20 2005/12/12 17:33:37 georgeda
* Defect #265, store host/origin species in correct places
*
* Revision 1.19 2005/11/28 22:52:05 pandyas
* Defect #186: Added organ/tissue to Xenograft page, modified search page to display multiple Xenografts with headers, modified XenograftManagerImpl so it does not create or save an organ object if not organ is selected
*
* Revision 1.18 2005/11/28 13:51:20 georgeda
* Defect #207, handle nulls for pages w/ uncontrolled vocab
*
* Revision 1.17 2005/11/18 22:50:02 georgeda
* Defect #184. Cleanup editing of old models
*
* Revision 1.16 2005/11/14 14:22:37 georgeda
* Cleanup
*
* Revision 1.15 2005/11/11 16:28:26 pandyas
* expanded species list
*
*
*/
package gov.nih.nci.camod.webapp.action;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.AnimalModel;
import gov.nih.nci.camod.domain.Species;
import gov.nih.nci.camod.domain.Xenograft;
import gov.nih.nci.camod.service.AnimalModelManager;
import gov.nih.nci.camod.service.impl.XenograftManagerSingleton;
import gov.nih.nci.camod.webapp.form.XenograftForm;
import gov.nih.nci.camod.webapp.util.DropdownOption;
import gov.nih.nci.camod.webapp.util.NewDropdownUtil;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class XenograftPopulateAction extends BaseAction
{
/**
* Pre-populate all field values in the form <FormName> Used by <jspName>
*
*/
public ActionForward populate(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
// Create a form to edit
XenograftForm xenograftForm = (XenograftForm) form;
// Grab the current Xenograft we are working with related to this AM
String aXenograftID = request.getParameter("aXenograftID");
Xenograft xeno = XenograftManagerSingleton.instance().get(aXenograftID);
if (xeno == null)
{
request.setAttribute(Constants.Parameters.DELETED, "true");
}
else
{
request.setAttribute("aXenograftID", aXenograftID);
xenograftForm.setXenograftName(xeno.getXenograftName());
// Set the other flag or the selected administrative site from the DB
if (xeno.getAdminSiteUnctrlVocab() != null)
{
xenograftForm.setAdministrativeSite(Constants.Dropdowns.OTHER_OPTION);
xenograftForm.setOtherAdministrativeSite(xeno.getAdminSiteUnctrlVocab());
}
else
{
xenograftForm.setAdministrativeSite(xeno.getAdministrativeSite());
}
xenograftForm.setGeneticManipulation(xeno.getGeneticManipulation());
xenograftForm.setModificationDescription(xeno.getModificationDescription());
xenograftForm.setParentalCellLineName(xeno.getParentalCellLineName());
xenograftForm.setAtccNumber(xeno.getAtccNumber());
xenograftForm.setCellAmount(xeno.getCellAmount());
xenograftForm.setGrowthPeriod(xeno.getGrowthPeriod());
// Species was required in previous versions of caMod and is stored in donorSpecies column
// The species and strain are required for 2.1 and strain_id is stored for all future versions
// Therefore, we must search in both to populate correctly
if (xeno.getDonorSpecies() != null)
{
// Populate species if uncontrolled vocab - old models
if (xeno.getDonorSpecies().getScientificNameUnctrlVocab() != null)
{
xenograftForm.setDonorScientificName(Constants.Dropdowns.OTHER_OPTION);
xenograftForm.setOtherDonorScientificName(xeno.getDonorSpecies().getScientificNameUnctrlVocab());
}
else
{
xenograftForm.setDonorScientificName(xeno.getDonorSpecies().getScientificName());
}
}
else if (xeno.getStrain() != null)
{
//Populate strain for all new models - check for uncontrolled vocab
if (xeno.getStrain().getNameUnctrlVocab() != null)
{
xenograftForm.setDonorEthinicityStrain(Constants.Dropdowns.OTHER_OPTION);
xenograftForm.setOtherDonorEthinicityStrain(xeno.getStrain().getNameUnctrlVocab());
}
else
{
xenograftForm.setDonorEthinicityStrain(xeno.getStrain().getName());
}
// Populate species if strain_id is used - models submitted after 2.0
// check for uncontrolled vocab
if (xeno.getStrain().getSpecies().getScientificNameUnctrlVocab() != null)
{
xenograftForm.setDonorScientificName(Constants.Dropdowns.OTHER_OPTION);
xenograftForm.setOtherDonorScientificName(xeno.getStrain().getSpecies().getScientificNameUnctrlVocab());
}
else
{
xenograftForm.setDonorScientificName(xeno.getStrain().getSpecies().getScientificName());
}
}
// since we are always querying from concept code (save and edit),
// simply display EVSPreferredDescription
// work around when getEVSPreferredDescription() does not work
if (xeno.getOrgan() != null)
{
if (xeno.getOrgan().getEVSPreferredDescription() != null)
{
xenograftForm.setOrgan(xeno.getOrgan().getEVSPreferredDescription());
//xenograftForm.setOrgan(xeno.getOrgan().getName());
xenograftForm.setOrganTissueCode(xeno.getOrgan().getConceptCode());
}
}
else
{
xenograftForm.setOrgan(xeno.getOrgan().getName());
//xenograftForm.setOrgan(xeno.getOrgan().getName());
xenograftForm.setOrganTissueCode(xeno.getOrgan().getConceptCode());
}
// Set the other flag or the normal graft type
if (xeno.getGraftTypeUnctrlVocab() != null)
{
xenograftForm.setGraftType(Constants.Dropdowns.OTHER_OPTION);
xenograftForm.setOtherGraftType(xeno.getGraftTypeUnctrlVocab());
}
else
{
xenograftForm.setGraftType(xeno.getGraftType());
}
}
// Prepopulate all dropdown fields, set the global Constants to the
// following
this.dropdown(request, response, xenograftForm);
return mapping.findForward("submitTransplantXenograft");
}
/**
* Populate the dropdown menus for submitEnvironmentalFactors
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward dropdown(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
log.info("<XenograftPopulateAction dropdown> Entering dropdown() ");
XenograftForm theForm = (XenograftForm) form;
// setup dropdown menus
this.dropdown(request, response, theForm);
log.info("<XenograftPopulateAction dropdown> before return submitTransplantXenograft ");
return mapping.findForward("submitTransplantXenograft");
}
/**
* Populate all drowpdowns for this type of form
*
* @param request
* @param response
* @throws Exception
*/
private void dropdown(HttpServletRequest request,
HttpServletResponse response,
XenograftForm inForm) throws Exception
{
log.info("<XenograftPopulateAction dropdown> Entering void dropdown()");
// Set the Species drop drop for the Xenograft form
NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.SPECIESQUERYDROP, Constants.Dropdowns.ADD_BLANK_AND_OTHER_OPTION);
// theSpecies will be null the first time (submitXenograft screen) - default to full list of strains
// but this is needed to populate the strain on the submitXenograft screen
String theSpecies = inForm.getDonorScientificName();
if (theSpecies == null)
{
List speciesList = (List) request.getSession().getAttribute(Constants.Dropdowns.SPECIESQUERYDROP);
DropdownOption theOption = (DropdownOption) speciesList.get(0);
theSpecies = theOption.getValue();
}
NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.STRAINDROP, theSpecies);
NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.AGEUNITSDROP, "");
NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.GRAFTTYPEDROP, Constants.Dropdowns.ADD_BLANK_AND_OTHER);
NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.XENOGRAFTADMINSITESDROP, Constants.Dropdowns.ADD_BLANK_AND_OTHER);
// Retrieve the Species and Strain set for the AnimalModel (via submitNewModel.jsp)
// This is displayed on the JSP page as the HOST SPECIES / STRAIN
String modelID = (String) request.getSession().getAttribute(Constants.MODELID);
AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager");
AnimalModel animalModel = animalModelManager.get(modelID);
if (animalModel.getStrain() != null)
{
Species theAMSpecies = animalModel.getStrain().getSpecies();
request.getSession().setAttribute(Constants.Dropdowns.MODELSPECIES, theAMSpecies.getScientificName());
// If the animal model has an 'Other' strain selected, display the otherName on the Xenograft screen
if (animalModel.getStrain().getNameUnctrlVocab() != null)
{
request.getSession().setAttribute(Constants.Dropdowns.OTHERMODELSTRAIN, animalModel.getStrain().getNameUnctrlVocab());
}
else
{
request.getSession().setAttribute(Constants.Dropdowns.MODELSTRAIN, animalModel.getStrain().getName());
}
}
log.info("<XenograftPopulateAction dropdown> Exiting void dropdown()");
}
/**
* Repopulate the Strain dropdown with it's matching species
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setStrainDropdown(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
XenograftForm xenograftForm = (XenograftForm) form;
//request.setAttribute("aXenograftID", request.getParameter("aXenograftID"));
NewDropdownUtil.populateDropdown(request, Constants.Dropdowns.STRAINDROP, xenograftForm.getDonorScientificName());
// Must Reset both fields when new species is chosen or edited
xenograftForm.setDonorEthinicityStrain("");
xenograftForm.setOtherDonorEthinicityStrain("");
return mapping.findForward("submitTransplantXenograft");
}
}
|
package org.rstudio.core.client.theme;
import org.rstudio.core.client.BrowseCap;
import org.rstudio.core.client.Point;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.dom.DomUtils;
import org.rstudio.core.client.dom.DomUtils.NodePredicate;
import org.rstudio.core.client.dom.ElementEx;
import org.rstudio.core.client.events.HasTabCloseHandlers;
import org.rstudio.core.client.events.HasTabClosedHandlers;
import org.rstudio.core.client.events.HasTabClosingHandlers;
import org.rstudio.core.client.events.HasTabReorderHandlers;
import org.rstudio.core.client.events.TabCloseEvent;
import org.rstudio.core.client.events.TabCloseHandler;
import org.rstudio.core.client.events.TabClosedEvent;
import org.rstudio.core.client.events.TabClosedHandler;
import org.rstudio.core.client.events.TabClosingEvent;
import org.rstudio.core.client.events.TabClosingHandler;
import org.rstudio.core.client.events.TabReorderEvent;
import org.rstudio.core.client.events.TabReorderHandler;
import org.rstudio.core.client.js.JsObject;
import org.rstudio.core.client.theme.res.ThemeResources;
import org.rstudio.core.client.theme.res.ThemeStyles;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.satellite.Satellite;
import org.rstudio.studio.client.workbench.views.source.SourceWindowManager;
import org.rstudio.studio.client.workbench.views.source.events.DocTabDragInitiatedEvent;
import org.rstudio.studio.client.workbench.views.source.events.DocTabDragStartedEvent;
import org.rstudio.studio.client.workbench.views.source.events.DocTabDragStateChangedEvent;
import org.rstudio.studio.client.workbench.views.source.events.DocWindowChangedEvent;
import org.rstudio.studio.client.workbench.views.source.events.PopoutDocInitiatedEvent;
import org.rstudio.studio.client.workbench.views.source.model.DocTabDragParams;
import com.google.gwt.animation.client.Animation;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.BorderStyle;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Float;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.DragStartEvent;
import com.google.gwt.event.dom.client.DragStartHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* A tab panel that is styled for document tabs.
*/
public class DocTabLayoutPanel
extends TabLayoutPanel
implements HasTabClosingHandlers,
HasTabCloseHandlers,
HasTabClosedHandlers,
HasTabReorderHandlers
{
public interface TabCloseObserver
{
public void onTabClose();
}
public interface TabMoveObserver
{
public void onTabMove(Widget tab, int oldPos, int newPos);
}
public DocTabLayoutPanel(boolean closeableTabs,
int padding,
int rightMargin)
{
super(BAR_HEIGHT, Style.Unit.PX);
closeableTabs_ = closeableTabs;
padding_ = padding;
rightMargin_ = rightMargin;
styles_ = ThemeResources.INSTANCE.themeStyles();
addStyleName(styles_.docTabPanel());
addStyleName(styles_.moduleTabPanel());
dragManager_ = new DragManager();
// listen for global drag events (these are broadcasted from other windows
// to notify us of incoming drags)
events_ = RStudioGinjector.INSTANCE.getEventBus();
events_.addHandler(DocTabDragStartedEvent.TYPE, dragManager_);
// sink drag-related events on the tab bar element; unfortunately
// GWT does not provide bits for the drag-related events, and
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
Element tabBar = getTabBarElement();
DOM.sinkBitlessEvent(tabBar, "dragenter");
DOM.sinkBitlessEvent(tabBar, "dragover");
DOM.sinkBitlessEvent(tabBar, "dragend");
DOM.sinkBitlessEvent(tabBar, "dragleave");
DOM.sinkBitlessEvent(tabBar, "drop");
Event.setEventListener(tabBar, dragManager_);
}
});
}
@Override
public void add(final Widget child, String text)
{
add(child, null, null, text, null, null);
}
public void add(final Widget child, String docId, String text)
{
add(child, null, docId, text, null, null);
}
public void add(final Widget child,
ImageResource icon,
String docId,
final String text,
String tooltip,
Integer position)
{
if (closeableTabs_)
{
DocTab tab = new DocTab(icon, docId, text, tooltip,
new TabCloseObserver()
{
public void onTabClose()
{
int index = getWidgetIndex(child);
if (index >= 0)
{
tryCloseTab(index, null);
}
}
});
if (position == null || position < 0)
super.add(child, tab);
else
super.insert(child, tab, position);
}
else
{
if (position == null || position < 0)
super.add(child, text);
else
super.insert(child, text, position);
}
}
public boolean tryCloseTab(int index, Command onClosed)
{
TabClosingEvent event = new TabClosingEvent(index);
fireEvent(event);
if (event.isCancelled())
return false;
closeTab(index, onClosed);
return true;
}
public void closeTab(int index, Command onClosed)
{
if (remove(index))
{
if (onClosed != null)
onClosed.execute();
}
}
public void moveTab(int index, int delta)
{
// do no work if we haven't been asked to move anywhere
if (delta == 0)
return;
Element tabHost = getTabBarElement();
// ignore moving left if the tab is already the leftmost tab (same for
// right)
int dest = index + delta;
if (dest < 0 || dest >= tabHost.getChildCount())
return;
// rearrange the DOM
Element tab = Element.as(tabHost.getChild(index));
Element prev = Element.as(tabHost.getChild(dest));
tabHost.removeChild(tab);
if (delta > 0)
tabHost.insertAfter(tab, prev);
else
tabHost.insertBefore(tab, prev);
// fire the tab reorder event (this syncs the editor state)
TabReorderEvent event = new TabReorderEvent(index, dest);
fireEvent(event);
}
@Override
public void selectTab(int index)
{
super.selectTab(index);
ensureSelectedTabIsVisible(true);
}
public void ensureSelectedTabIsVisible(boolean animate)
{
if (currentAnimation_ != null)
{
currentAnimation_.cancel();
currentAnimation_ = null;
}
Element selectedTab = (Element) DomUtils.findNode(
getElement(),
true,
false,
new NodePredicate()
{
public boolean test(Node n)
{
if (n.getNodeType() != Node.ELEMENT_NODE)
return false;
return ((Element) n).getClassName()
.contains("gwt-TabLayoutPanelTab-selected");
}
});
if (selectedTab == null)
{
return;
}
selectedTab = selectedTab.getFirstChildElement()
.getFirstChildElement();
Element tabBar = getTabBarElement();
if (!isVisible() || !isAttached() || tabBar.getOffsetWidth() == 0)
return; // not yet loaded
final Element tabBarParent = tabBar.getParentElement();
final int start = tabBarParent.getScrollLeft();
int end = DomUtils.ensureVisibleHoriz(tabBarParent,
selectedTab,
padding_,
padding_ + rightMargin_,
true);
// When tabs are closed, the overall width shrinks, and this can lead
// to cases where there's too much empty space on the screen
Node lastTab = getLastChildElement(tabBar);
if (lastTab == null || lastTab.getNodeType() != Node.ELEMENT_NODE)
return;
int edge = DomUtils.getRelativePosition(tabBarParent, Element.as(lastTab)).x
+ Element.as(lastTab).getOffsetWidth();
end = Math.min(end,
Math.max(0,
edge - (tabBarParent.getOffsetWidth() - rightMargin_)));
if (edge <= tabBarParent.getOffsetWidth() - rightMargin_)
end = 0;
if (start != end)
{
if (!animate)
{
tabBarParent.setScrollLeft(end);
}
else
{
final int finalEnd = end;
currentAnimation_ = new Animation() {
@Override
protected void onUpdate(double progress)
{
double delta = (finalEnd - start) * progress;
tabBarParent.setScrollLeft((int) (start + delta));
}
@Override
protected void onComplete()
{
if (this == currentAnimation_)
{
tabBarParent.setScrollLeft(finalEnd);
currentAnimation_ = null;
}
}
};
currentAnimation_.run(Math.max(200,
Math.min(1500,
Math.abs(end - start)*2)));
}
}
}
@Override
public void onResize()
{
super.onResize();
ensureSelectedTabIsVisible(false);
}
@Override
public boolean remove(int index)
{
if ((index < 0) || (index >= getWidgetCount())) {
return false;
}
fireEvent(new TabCloseEvent(index));
if (getSelectedIndex() == index)
{
boolean closingLastTab = index == getWidgetCount() - 1;
int indexToSelect = closingLastTab
? index - 1
: index + 1;
if (indexToSelect >= 0)
selectTab(indexToSelect);
}
if (!super.remove(index))
return false;
fireEvent(new TabClosedEvent(index));
ensureSelectedTabIsVisible(true);
return true;
}
@Override
public void add(Widget child, String text, boolean asHtml)
{
if (asHtml)
throw new UnsupportedOperationException("HTML tab names not supported");
add(child, text);
}
@Override
public void add(Widget child, Widget tab)
{
throw new UnsupportedOperationException("Not supported");
}
public void cancelTabDrag()
{
dragManager_.endDrag(null, DragManager.ACTION_CANCEL);
}
private class DragManager implements EventListener,
DocTabDragStartedEvent.Handler
{
@Override
public void onBrowserEvent(Event event)
{
if (event.getType() == "dragenter")
{
if (dropPoint_ != null && event.getClientX() == dropPoint_.getX() &&
event.getClientY() == dropPoint_.getY())
{
// Very occasionally (~5%?), dropping a tab will generate a
// superfluous "dragenter" event immediately after the drop event
// at exactly the same coordinates. We want to ignore this since
// it will send us into dragging state; to do so, we cache the
// coordinates when a tab is dropped and suppress entering drag
// mode from those coordinates very briefly (note that this won't
// keep the user from immediately dragging the tab around since
// you need to move the cursor in some way to initiate a drag,
// invalidating the coordinates.)
dropPoint_ = null;
return;
}
if (curState_ == STATE_EXTERNAL)
{
// element that was being dragged around outside boundaries
// has come back in; clear it and treat like a new drag
dragElement_.getStyle().clearOpacity();
dragElement_ = null;
curState_ = STATE_NONE;
}
if (curState_ == STATE_NONE)
{
// if we know what we're dragging, initiate it; otherwise, let
// the event continue unimpeded (so we won't appear as a drag
// target)
if (initDragParams_ == null)
return;
else
beginDrag(event);
}
event.preventDefault();
}
else if (event.getType() == "dragover")
{
if (curState_ == STATE_DRAGGING)
drag(event);
event.preventDefault();
}
else if (event.getType() == "drop")
{
endDrag(event, ACTION_COMMIT);
event.preventDefault();
// cache the drop point for 250ms (see comments in event handler for
// dragenter)
dropPoint_ = new Point(event.getClientX(), event.getClientY());
Scheduler.get().scheduleFixedDelay(new Scheduler.RepeatingCommand()
{
@Override
public boolean execute()
{
dropPoint_ = null;
return false;
}
}, 250);
}
else if (event.getType() == "dragend")
{
if (curState_ != STATE_NONE)
{
endDrag(event, ACTION_CANCEL);
}
event.preventDefault();
}
else if (event.getType() == "dragleave")
{
if (curState_ == STATE_NONE)
return;
// when a drag leaves the window entirely, we get a dragleave event
// at 0, 0 (which we always want to treat as a cancel)
if (!(event.getClientX() == 0 && event.getClientY() == 0))
{
// look at where the cursor is now--if it's inside the tab panel,
// do nothing, but if it's outside the tab panel, treat that as
// a cancel
Element ele = DomUtils.elementFromPoint(event.getClientX(),
event.getClientY());
while (ele != null && ele != Document.get().getBody())
{
if (ele.getClassName().contains("gwt-TabLayoutPanelTabs"))
{
return;
}
ele = ele.getParentElement();
}
}
if (dragElement_ != null)
{
// dim the element being drag to hint that it'll be moved
endDrag(event, ACTION_EXTERNAL);
}
else
{
// if this wasn't our element, we can cancel the drag entirely
endDrag(event, ACTION_CANCEL);
}
}
}
@Override
public void onDocTabDragStarted(DocTabDragStartedEvent event)
{
initDragParams_ = event.getDragParams();
initDragWidth_ = initDragParams_.getTabWidth();
}
private void beginDrag(Event evt)
{
// skip if we don't know what we're dragging -- these parameters
// should get injected by the editor but might not if a failure occurs
// during its processing of the DocTabDragInitiatedEvent.
if (initDragParams_ == null)
return;
String docId = initDragParams_.getDocId();
int dragTabWidth = initDragWidth_;
// set drag element state
dragTabsHost_ = getTabBarElement();
dragScrollHost_ = dragTabsHost_.getParentElement();
outOfBounds_ = 0;
candidatePos_ = null;
startPos_ = null;
// attempt to determine which tab the cursor is over
Point hostPos = DomUtils.getRelativePosition(
Document.get().getBody(), dragTabsHost_);
int dragX = evt.getClientX() - hostPos.getX();
for (int i = 0; i < dragTabsHost_.getChildCount(); i++)
{
Node node = dragTabsHost_.getChild(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
int left = DomUtils.leftRelativeTo(dragTabsHost_,
Element.as(node)) -
dragScrollHost_.getScrollLeft();
int right = left + Element.as(node).getOffsetWidth();
if (left <= dragX && dragX <= right)
{
candidatePos_ = i;
break;
}
}
}
// let the rest of the IDE know we're dragging (this will enable us to
// disable drag targets that might otherwise be happy to accept the
// data)
curState_ = STATE_DRAGGING;
events_.fireEvent(new DocTabDragStateChangedEvent(
DocTabDragStateChangedEvent.STATE_DRAGGING));
// the relative position of the last node determines how far we
// can drag
dragMax_ = DomUtils.leftRelativeTo(dragTabsHost_,
getLastChildElement(dragTabsHost_)) +
getLastChildElement(dragTabsHost_).getClientWidth();
lastCursorX_= evt.getClientX();
// account for cursor starting out of bounds (e.g. dragging into
// empty space on the right of the panel)
if (lastCursorX_ > dragMax_ + (initDragParams_.getCursorOffset()))
outOfBounds_ = (lastCursorX_ - dragMax_) -
initDragParams_.getCursorOffset();
// attempt to ascertain whether the element being dragged is one of
// our own documents
for (int i = 0; i < getWidgetCount(); i++)
{
DocTab tab = (DocTab)getTabWidget(i);
if (tab.getDocId() == docId)
{
dragElement_ =
tab.getElement().getParentElement().getParentElement();
break;
}
}
// if we couldn't find the horizontal drag position in any tab, append
// to the end
if (candidatePos_ == null)
{
candidatePos_ = dragTabsHost_.getChildCount();
}
destPos_ = candidatePos_;
// if we're dragging one of our own documents, figure out its physical
// position
if (dragElement_ != null)
{
for (int i = 0; i < dragTabsHost_.getChildCount(); i++)
{
if (dragTabsHost_.getChild(i) == dragElement_)
{
startPos_ = i;
break;
}
}
}
// compute the start location for the drag
if (candidatePos_ >= dragTabsHost_.getChildCount())
{
Element lastTab = getLastChildElement(dragTabsHost_);
lastElementX_ = DomUtils.leftRelativeTo(dragTabsHost_, lastTab) +
lastTab.getOffsetWidth();
}
else
{
lastElementX_ = DomUtils.leftRelativeTo(
dragTabsHost_, Element.as(dragTabsHost_.getChild(candidatePos_)));
}
// if we're dragging one of our own tabs, snap it out of the
// tabset
if (dragElement_ != null)
{
dragElement_.getStyle().setPosition(Position.ABSOLUTE);
dragElement_.getStyle().setLeft(lastElementX_, Unit.PX);
dragElement_.getStyle().setZIndex(100);
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
// we may not still be dragging when the event loop comes
// back, so be sure there's an element before hiding it
if (dragElement_ != null)
dragElement_.getStyle().setDisplay(Display.NONE);
}
});
}
// create the placeholder that shows where this tab will go when the
// mouse is released
dragPlaceholder_ = Document.get().createDivElement();
dragPlaceholder_.getStyle().setWidth(
dragTabWidth - 4, Unit.PX);
dragPlaceholder_.getStyle().setHeight(
dragTabsHost_.getClientHeight() - 3, Unit.PX);
dragPlaceholder_.getStyle().setDisplay(Display.INLINE_BLOCK);
dragPlaceholder_.getStyle().setPosition(Position.RELATIVE);
dragPlaceholder_.getStyle().setFloat(Float.LEFT);
dragPlaceholder_.getStyle().setBorderStyle(BorderStyle.DOTTED);
dragPlaceholder_.getStyle().setBorderColor("#A1A2A3");
dragPlaceholder_.getStyle().setBorderWidth(1, Unit.PX);
dragPlaceholder_.getStyle().setMarginLeft(1, Unit.PX);
dragPlaceholder_.getStyle().setMarginRight(1, Unit.PX);
dragPlaceholder_.getStyle().setProperty("borderTopLeftRadius", "4px");
dragPlaceholder_.getStyle().setProperty("borderTopRightRadius", "4px");
dragPlaceholder_.getStyle().setProperty("borderBottom", "0px");
if (candidatePos_ < dragTabsHost_.getChildCount())
{
dragTabsHost_.insertBefore(dragPlaceholder_,
dragTabsHost_.getChild(candidatePos_));
}
else
{
dragTabsHost_.appendChild(dragPlaceholder_);
}
}
private void drag(Event evt)
{
int offset = evt.getClientX() - lastCursorX_;
lastCursorX_ = evt.getClientX();
// cursor is outside the tab area
if (outOfBounds_ != 0)
{
// did the cursor move back in bounds?
if (outOfBounds_ + offset > 0 != outOfBounds_ > 0)
{
outOfBounds_ = 0;
offset = outOfBounds_ + offset;
}
else
{
// cursor is still out of bounds
outOfBounds_ += offset;
return;
}
}
int targetLeft = lastElementX_ + offset;
int targetRight = targetLeft + initDragWidth_;
int scrollLeft = dragScrollHost_.getScrollLeft();
if (targetLeft < 0)
{
// dragged past the beginning - lock to beginning
targetLeft = 0;
outOfBounds_ += offset;
}
else if (targetLeft > dragMax_)
{
// dragged past the end - lock to the end
targetLeft = dragMax_;
outOfBounds_ += offset;
}
if (targetLeft - scrollLeft < SCROLL_THRESHOLD &&
scrollLeft > 0)
{
// dragged past scroll threshold, to the left--autoscroll
outOfBounds_ = (targetLeft - scrollLeft) - SCROLL_THRESHOLD;
targetLeft = scrollLeft + SCROLL_THRESHOLD;
Scheduler.get().scheduleFixedPeriod(new RepeatingCommand()
{
@Override
public boolean execute()
{
return autoScroll(-1);
}
}, 5);
}
else if (targetRight + SCROLL_THRESHOLD > scrollLeft +
dragScrollHost_.getClientWidth() &&
scrollLeft < dragScrollHost_.getScrollWidth() -
dragScrollHost_.getClientWidth())
{
// dragged past scroll threshold, to the right--autoscroll
outOfBounds_ = (targetRight + SCROLL_THRESHOLD) -
(scrollLeft + dragScrollHost_.getClientWidth());
targetLeft = scrollLeft + dragScrollHost_.getClientWidth() -
(initDragWidth_ + SCROLL_THRESHOLD);
Scheduler.get().scheduleFixedPeriod(new RepeatingCommand()
{
@Override
public boolean execute()
{
return autoScroll(1);
}
}, 5);
}
commitPosition(targetLeft);
}
private void commitPosition(int pos)
{
lastElementX_ = pos;
// check to see if we're overlapping with another tab
for (int i = 0; i < dragTabsHost_.getChildCount(); i++)
{
// skip non-element DOM nodes
Node node = dragTabsHost_.getChild(i);
if (node.getNodeType() != Node.ELEMENT_NODE)
{
continue;
}
// skip the current candidate (no point in testing it for swap)
if (i == candidatePos_)
{
continue;
}
// skip the element we're dragging and elements that are not tabs
Element ele = (Element)node;
if (ele == dragElement_ ||
ele.getClassName().indexOf("gwt-TabLayoutPanelTab") < 0)
{
continue;
}
int left = DomUtils.leftRelativeTo(dragTabsHost_, ele);
int right = left + ele.getClientWidth();
int minOverlap = Math.min(initDragWidth_ / 2,
ele.getClientWidth() / 2);
// a little complicated: compute the number of overlapping pixels
// with this element; if the overlap is more than half of our width
// (or the width of the candidate), it's swapping time
if (Math.min(lastElementX_ + initDragWidth_, right) -
Math.max(lastElementX_, left) >= minOverlap)
{
dragTabsHost_.removeChild(dragPlaceholder_);
if (candidatePos_ > i)
{
dragTabsHost_.insertBefore(dragPlaceholder_, ele);
}
else
{
dragTabsHost_.insertAfter(dragPlaceholder_, ele);
}
candidatePos_ = i;
// account for the extra element when moving to the right of the
// original location
if (dragElement_ != null && startPos_ != null)
{
destPos_ = startPos_ <= candidatePos_ ?
candidatePos_ - 1 : candidatePos_;
}
else
{
destPos_ = candidatePos_;
}
}
}
}
private boolean autoScroll(int dir)
{
// move while the mouse is still out of bounds
if (curState_ == STATE_DRAGGING && outOfBounds_ != 0)
{
// if mouse is far out of bounds, use it to accelerate movement
if (Math.abs(outOfBounds_) > 100)
{
dir *= 1 + Math.round(Math.abs(outOfBounds_) / 75);
}
// move if there's moving to be done
if (dir < 0 && lastElementX_ > 0 ||
dir > 0 && lastElementX_ < dragMax_)
{
commitPosition(lastElementX_ + dir);
// scroll if there's scrolling to be done
int left = dragScrollHost_.getScrollLeft();
if ((dir < 0 && left > 0) ||
(dir > 0 && left < dragScrollHost_.getScrollWidth() -
dragScrollHost_.getClientWidth()))
{
dragScrollHost_.setScrollLeft(left + dir);
}
}
return true;
}
return false;
}
public void endDrag(final Event evt, int action)
{
if (curState_ == STATE_NONE)
return;
// remove the properties used to position for dragging
if (dragElement_ != null)
{
dragElement_.getStyle().clearLeft();
dragElement_.getStyle().clearPosition();
dragElement_.getStyle().clearZIndex();
dragElement_.getStyle().clearDisplay();
dragElement_.getStyle().clearOpacity();
// insert this tab where the placeholder landed if we're not
// cancelling
if (action == ACTION_COMMIT)
{
dragTabsHost_.removeChild(dragElement_);
dragTabsHost_.insertAfter(dragElement_, dragPlaceholder_);
}
}
// remove the placeholder
if (dragPlaceholder_ != null)
{
dragTabsHost_.removeChild(dragPlaceholder_);
dragPlaceholder_ = null;
}
if (dragElement_ != null && action == ACTION_EXTERNAL)
{
// if we own the dragged tab, change to external drag state
dragElement_.getStyle().setOpacity(0.4);
curState_ = STATE_EXTERNAL;
}
else
{
// otherwise, we're back to pristine
curState_ = STATE_NONE;
events_.fireEvent(new DocTabDragStateChangedEvent(
DocTabDragStateChangedEvent.STATE_NONE));
}
if (dragElement_ != null && action == ACTION_COMMIT)
{
// let observer know we moved; adjust the destination position one to
// the left if we're right of the start position to account for the
// position of the tab prior to movement
if (startPos_ != null && startPos_ != destPos_)
{
TabReorderEvent event = new TabReorderEvent(startPos_, destPos_);
fireEvent(event);
}
}
// this is the case when we adopt someone else's doc
if (dragElement_ == null && evt != null && action == ACTION_COMMIT)
{
// pull the document ID and source window out
String data = evt.getDataTransfer().getData(
getDataTransferFormat());
if (StringUtil.isNullOrEmpty(data))
return;
// the data format is docID|windowID; windowID can be omitted if
// the main window is the origin
String pieces[] = data.split("\\|");
if (pieces.length < 1)
return;
events_.fireEvent(new DocWindowChangedEvent(pieces[0],
pieces.length > 1 ? pieces[1] : "",
initDragParams_, destPos_));
}
// this is the case when our own drag ends; if it ended outside our
// window and outside all satellites, treat it as a tab tear-off
if (dragElement_ != null && evt != null && action == ACTION_CANCEL)
{
// if this is the last tab in satellite, we don't want to tear
// it out
boolean isLastSatelliteTab = getWidgetCount() == 1 &&
Satellite.isCurrentWindowSatellite();
// did the user drag the tab outside this doc?
if (!isLastSatelliteTab &&
DomUtils.elementFromPoint(evt.getClientX(),
evt.getClientY()) == null)
{
// did it end in any RStudio satellite window?
String targetWindowName;
Satellite satellite = RStudioGinjector.INSTANCE.getSatellite();
if (Satellite.isCurrentWindowSatellite())
{
// this is a satellite, ask the main window
targetWindowName = satellite.getWindowAtPoint(
evt.getScreenX(), evt.getScreenY());
}
else
{
// this is the main window, query our own satellites
targetWindowName =
RStudioGinjector.INSTANCE.getSatelliteManager()
.getWindowAtPoint(evt.getScreenX(), evt.getScreenY());
}
if (targetWindowName == null)
{
// it was dragged over nothing RStudio owns--pop it out
events_.fireEvent(new PopoutDocInitiatedEvent(
initDragParams_.getDocId(), new Point(
evt.getScreenX(), evt.getScreenY())));
}
}
}
if (curState_ != STATE_EXTERNAL)
{
// if we're in an end state, clear the drag element
dragElement_ = null;
}
}
private int lastCursorX_ = 0;
private int lastElementX_ = 0;
private Integer startPos_ = null;
private Integer candidatePos_ = null;
private int destPos_ = 0;
private int dragMax_ = 0;
private int outOfBounds_ = 0;
private int initDragWidth_;
private DocTabDragParams initDragParams_;
private Element dragElement_;
private Element dragTabsHost_;
private Element dragScrollHost_;
private Element dragPlaceholder_;
private int curState_ = STATE_NONE;
private Point dropPoint_;
private final static int SCROLL_THRESHOLD = 25;
// No drag operation is taking place
private final static int STATE_NONE = 0;
// A tab is being dragged inside this tab panel
private final static int STATE_DRAGGING = 1;
// A tab from this panel is being dragged elsewhere
private final static int STATE_EXTERNAL = 2;
// the drag operation should be cancelled
private final static int ACTION_CANCEL = 0;
// the drag operation should be continued outside this window
private final static int ACTION_EXTERNAL = 1;
// the drag operation should be committed in this window
private final static int ACTION_COMMIT = 2;
}
private class DocTab extends Composite
{
private DocTab(ImageResource icon,
String docId,
String title,
String tooltip,
TabCloseObserver closeHandler)
{
docId_ = docId;
final HorizontalPanel layoutPanel = new HorizontalPanel();
layoutPanel.setStylePrimaryName(styles_.tabLayout());
layoutPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM);
layoutPanel.getElement().setDraggable("true");
layoutPanel.addDomHandler(new DragStartHandler()
{
@Override
public void onDragStart(DragStartEvent evt)
{
evt.getDataTransfer().setData(
getDataTransferFormat(), docId_ + "|" +
SourceWindowManager.getSourceWindowId());
JsObject dt = evt.getDataTransfer().cast();
dt.setString("effectAllowed", "move");
// figure out where the cursor is inside the element; because the
// drag shows an image of the tab, knowing where the cursor is
// inside that image is necessary for us to know the screen
// location of the dragged image
int evtX = evt.getNativeEvent().getClientX();
ElementEx ele = getElement().cast();
// if the drag leaves the window, the destination is going to
// need to know information we don't have here (such as the
// cursor position in the editor); this event gets handled by
// the editor, which adds the needed information and broadcasts
// it to all the windows.
events_.fireEvent(new DocTabDragInitiatedEvent(docId_,
getElement().getClientWidth(),
evtX - ele.getBoundingClientRect().getLeft()));
}
}, DragStartEvent.getType());
HTML left = new HTML();
left.setStylePrimaryName(styles_.tabLayoutLeft());
layoutPanel.add(left);
contentPanel_ = new HorizontalPanel();
contentPanel_.setTitle(tooltip);
contentPanel_.setStylePrimaryName(styles_.tabLayoutCenter());
contentPanel_.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
if (icon != null)
contentPanel_.add(imageForIcon(icon));
label_ = new Label(title, false);
label_.addStyleName(styles_.docTabLabel());
contentPanel_.add(label_);
appendDirtyMarker();
Image img = new Image(ThemeResources.INSTANCE.closeTab());
img.setStylePrimaryName(styles_.closeTabButton());
img.addStyleName(ThemeStyles.INSTANCE.handCursor());
contentPanel_.add(img);
layoutPanel.add(contentPanel_);
HTML right = new HTML();
right.setStylePrimaryName(styles_.tabLayoutRight());
layoutPanel.add(right);
initWidget(layoutPanel);
this.sinkEvents(Event.ONCLICK);
closeHandler_ = closeHandler;
closeElement_ = img.getElement();
}
private void appendDirtyMarker()
{
Label marker = new Label("*");
marker.setStyleName(styles_.dirtyTabIndicator());
contentPanel_.insert(marker, 2);
}
public void replaceTitle(String title)
{
label_.setText(title);
}
public void replaceTooltip(String tooltip)
{
contentPanel_.setTitle(tooltip);
}
public void replaceIcon(ImageResource icon)
{
if (contentPanel_.getWidget(0) instanceof Image)
contentPanel_.remove(0);
contentPanel_.insert(imageForIcon(icon), 0);
}
public String getDocId()
{
return docId_;
}
private Image imageForIcon(ImageResource icon)
{
Image image = new Image(icon);
image.setStylePrimaryName(styles_.docTabIcon());
return image;
}
@Override
public void onBrowserEvent(Event event)
{
switch(DOM.eventGetType(event))
{
case Event.ONCLICK:
{
// tabs can be closed by (a) middle mouse (anywhere), or (b)
// left click on close element
if (event.getButton() == Event.BUTTON_MIDDLE ||
(Element.as(event.getEventTarget()) == closeElement_ &&
event.getButton() == Event.BUTTON_LEFT))
{
closeHandler_.onTabClose();
event.stopPropagation();
event.preventDefault();
}
break;
}
}
super.onBrowserEvent(event);
}
private TabCloseObserver closeHandler_;
private Element closeElement_;
private final Label label_;
private final String docId_;
private final HorizontalPanel contentPanel_;
}
public void replaceDocName(int index,
ImageResource icon,
String title,
String tooltip)
{
DocTab tab = (DocTab) getTabWidget(index);
tab.replaceIcon(icon);
tab.replaceTitle(title);
tab.replaceTooltip(tooltip);
}
public HandlerRegistration addTabClosingHandler(TabClosingHandler handler)
{
return addHandler(handler, TabClosingEvent.TYPE);
}
@Override
public HandlerRegistration addTabCloseHandler(
TabCloseHandler handler)
{
return addHandler(handler, TabCloseEvent.TYPE);
}
public HandlerRegistration addTabClosedHandler(TabClosedHandler handler)
{
return addHandler(handler, TabClosedEvent.TYPE);
}
@Override
public HandlerRegistration addTabReorderHandler(TabReorderHandler handler)
{
return addHandler(handler, TabReorderEvent.TYPE);
}
public int getTabsEffectiveWidth()
{
if (getWidgetCount() == 0)
return 0;
Element parent = getTabBarElement();
if (parent == null)
{
return 0;
}
Element lastChild = getLastChildElement(parent);
if (lastChild == null)
{
return 0;
}
return lastChild.getOffsetLeft() + lastChild.getOffsetWidth();
}
@Override
public void onBrowserEvent(Event event)
{
super.onBrowserEvent(event);
}
private Element getTabBarElement()
{
return (Element) DomUtils.findNode(
getElement(),
true,
false,
new NodePredicate()
{
public boolean test(Node n)
{
if (n.getNodeType() != Node.ELEMENT_NODE)
return false;
return ((Element) n).getClassName()
.contains("gwt-TabLayoutPanelTabs");
}
});
}
private Element getLastChildElement(Element parent)
{
Node lastTab = parent.getLastChild();
while (lastTab.getNodeType() != Node.ELEMENT_NODE)
{
lastTab = lastTab.getPreviousSibling();
}
return Element.as(lastTab);
}
private String getDataTransferFormat()
{
// IE only supports textual data; for other browsers, though, use our own
// format so it doesn't activate text drag targets in other apps
if (BrowseCap.INSTANCE.isInternetExplorer())
return "text";
else
return "application/rstudio-tab";
}
public static final int BAR_HEIGHT = 24;
private final boolean closeableTabs_;
private final EventBus events_;
private int padding_;
private int rightMargin_;
private final ThemeStyles styles_;
private Animation currentAnimation_;
private DragManager dragManager_;
}
|
package io.limberest.api.validate.params;
import static io.limberest.service.http.Status.BAD_REQUEST;
import static io.limberest.service.http.Status.OK;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import org.json.JSONArray;
import org.json.JSONObject;
import io.limberest.api.validate.SwaggerRequest;
import io.limberest.api.validate.props.ArrayPropertyValidator;
import io.limberest.api.validate.props.PropertyValidator;
import io.limberest.api.validate.props.PropertyValidators;
import io.limberest.service.http.Status;
import io.limberest.validate.Result;
import io.limberest.validate.ValidationException;
import io.swagger.models.Model;
import io.swagger.models.RefModel;
import io.swagger.models.parameters.BodyParameter;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import io.swagger.util.PrimitiveType;
import io.swagger.util.ReflectionUtils;
public class BodyParameterValidator implements ParameterValidator<BodyParameter> {
private SwaggerRequest swaggerRequest;
private PropertyValidators propertyValidators;
public BodyParameterValidator(PropertyValidators propertyValidators) {
this.propertyValidators = propertyValidators;
}
@Override
public Result validate(SwaggerRequest request, BodyParameter parameter, Object value, boolean strict) throws ValidationException {
this.swaggerRequest = request;
return validate(parameter, (JSONObject)value, strict);
}
public Result validate(BodyParameter bodyParam, JSONObject body, boolean strict) throws ValidationException {
Result result = new Result();
if (body == null) {
if (bodyParam.getRequired())
result.also(Status.BAD_REQUEST, "Missing required body parameter: " + bodyParam.getName());
}
else {
Model model = bodyParam.getSchema();
if (model instanceof RefModel) {
Model bodyModel = swaggerRequest.getDefinitions().get(((RefModel)model).getSimpleRef());
if (bodyModel != null)
result.also(validate(body, bodyModel, "", strict));
}
}
return result;
}
/**
* Validate a json object against its swagger model.
* @param json object
* @param model swagger model
* @param path cumulative path for message building
* @param strict
* @return combined status
*/
private Result validate(JSONObject json, Model model, String path, boolean strict) throws ValidationException {
Result result = new Result();
for (Property prop : model.getProperties().values()) {
result.also(validate(json, prop, path, strict));
}
if (strict) {
result.also(validateExtraneous(json, model, path));
}
return result;
}
/**
* Validate a json object against a swagger property.
* @param json the containing JSONObject
* @param prop swagger property
* @param path cumulative path for message building
* @param strict
* @return status
*/
protected Result validate(JSONObject json, Property prop, String path, boolean strict) throws ValidationException {
Result result = new Result();
String name = prop.getName();
path += path == null || path.isEmpty() ? name : "." + name;
if (json.has(name)) {
if (prop.getReadOnly() != null && prop.getReadOnly()) {
result.also(BAD_REQUEST, path + " is read-only");
}
else {
Result typeMatch = matchType(json.get(name), prop, path);
if (typeMatch.getStatus().getCode() == OK.getCode()) {
if (prop instanceof RefProperty) {
JSONObject obj = json.getJSONObject(name);
String ref = ((RefProperty)prop).getSimpleRef();
Model model = swaggerRequest.getDefinitions().get(ref);
result.also(validate(obj, model, path, strict));
}
else if (prop instanceof ArrayProperty) {
Property itemsProp = ((ArrayProperty)prop).getItems();
if (itemsProp != null)
result.also(validate(json.getJSONArray(name), itemsProp, path, strict));
}
else {
for (PropertyValidator<? extends Property> validator : propertyValidators.getValidators(prop)) {
result.also(validator.doValidate(json, prop, path, strict));
}
}
}
else {
result.also(typeMatch);
}
}
}
else if (prop.getRequired()) {
String msg = path + " is required";
result.also(BAD_REQUEST, msg);
}
return result;
}
protected Result validate(JSONArray jsonArray, Property prop, String path, boolean strict) throws ValidationException {
Result result = new Result();
if (prop instanceof RefProperty) {
for (int i = 0; i < jsonArray.length(); i++) {
String itemPath = path + "[" + i + "]";
JSONObject obj = jsonArray.getJSONObject(i);
String ref = ((RefProperty)prop).getSimpleRef();
Model model = swaggerRequest.getDefinitions().get(ref);
result.also(validate(obj, model, itemPath, strict));
}
}
else if (prop instanceof ArrayProperty) {
for (int i = 0; i < jsonArray.length(); i++) {
String itemPath = path + "[" + i + "]";
Property itemsProp = ((ArrayProperty)prop).getItems();
if (itemsProp != null)
result.also(validate(jsonArray.getJSONArray(i), itemsProp, itemPath, strict));
}
}
else {
for (ArrayPropertyValidator<? extends Property> validator : propertyValidators.getArrayValidators(prop)) {
result.also(validator.doValidate(jsonArray, prop, path));
}
}
return result;
}
private Result validateExtraneous(JSONObject json, Model model, String path) throws ValidationException {
Result result = new Result();
for (String name : JSONObject.getNames(json)) {
if (!model.getProperties().containsKey(name)) {
String msg = (path == null || path.isEmpty() ? name : path + "." + name) + ": unknown property";
result.also(BAD_REQUEST, msg);
}
}
return result;
}
protected Result matchType(Object obj, Property prop, String path) throws ValidationException {
String expectedType = prop.getType();
if ("array".equals(expectedType)) {
expectedType = JSONArray.class.getName();
}
else if ("ref".equals(expectedType) || "object".equals(expectedType)) {
expectedType = JSONObject.class.getName();
}
else {
PrimitiveType type = PrimitiveType.fromName(prop.getType());
if (type != null) {
expectedType = type.getKeyClass().getName();
if (BigDecimal.class.getName().equals(expectedType))
expectedType = Double.class.getName();
}
else {
Type refType = ReflectionUtils.typeFromString(prop.getType());
if (refType != null)
expectedType = refType.getTypeName();
}
}
String foundType = obj.getClass().getName();
boolean match = foundType.equals(expectedType);
if (!match) {
// forgive rounded numeric types
if (BigDecimal.class.getName().equals(expectedType)) {
if (foundType.equals(Double.class.getName()) || foundType.equals(Integer.class.getName()))
match = true;
}
else if (Double.class.getName().equals(expectedType)) {
if (foundType.equals(Integer.class.getName()))
match = true;
}
else if (Integer.class.getName().equals(expectedType)) {
if (foundType.equals(Long.class.getName()) && "int64".equals(prop.getFormat()))
match = true;
}
}
if (match)
return new Result();
else
return new Result(BAD_REQUEST, path + ": expected " + expectedType + " but found " + foundType);
}
}
|
package org.xins.client;
import org.xins.types.TypeValueException;
import org.xins.util.service.TargetDescriptor;
/**
* Splitter that takes a client-side session ID and returns a server
* identification and a server-side session ID.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*
* @since XINS 0.74
*/
public interface SessionIDSplitter {
void splitSessionID(String sessionID, String[] result)
throws IllegalArgumentException, TypeValueException;
}
|
package org.kuali.coeus.award.finance;
import org.kuali.coeus.sys.api.model.ScaleTwoDecimal;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class AccountDto {
private Long id;
private String accountNumber;
@Digits(integer = 22, fraction=0)
private Long createdByAwardId;
@Size(min = 1, max = 15)
@Pattern(regexp = "[a-zA-Z]+")
private String status;
@Digits(integer = 10, fraction = 2)
private ScaleTwoDecimal budgeted;
@Digits(integer = 10, fraction = 2)
private ScaleTwoDecimal pending;
@Digits(integer = 10, fraction = 2)
private ScaleTwoDecimal income;
@Digits(integer = 10, fraction = 2)
private ScaleTwoDecimal expense;
@Digits(integer = 10, fraction = 2)
private ScaleTwoDecimal available;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public Long getCreatedByAwardId() {
return createdByAwardId;
}
public void setCreatedByAwardId(Long createdByAwardId) {
this.createdByAwardId = createdByAwardId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public ScaleTwoDecimal getBudgeted() {
return budgeted;
}
public void setBudgeted(ScaleTwoDecimal budgeted) {
this.budgeted = budgeted;
}
public ScaleTwoDecimal getPending() {
return pending;
}
public void setPending(ScaleTwoDecimal pending) {
this.pending = pending;
}
public ScaleTwoDecimal getIncome() {
return income;
}
public void setIncome(ScaleTwoDecimal income) {
this.income = income;
}
public ScaleTwoDecimal getExpense() {
return expense;
}
public void setExpense(ScaleTwoDecimal expense) {
this.expense = expense;
}
public ScaleTwoDecimal getAvailable() {
return available;
}
public void setAvailable(ScaleTwoDecimal available) {
this.available = available;
}
}
|
package org.xins.types;
import org.xins.util.MandatoryArgumentChecker;
/**
* Exception thrown to indicate a value is invalid for a certain type.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public class TypeValueException extends Exception {
// Class fields
// Class functions
// Constructors
public TypeValueException(Type type, String value)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("type", type, "value", value);
// Store the arguments
_type = type;
_value = value;
}
// Fields
/**
* The concerning parameter type. This field is never <code>null</code>.
*/
private final Type _type;
/**
* The value that is considered invalid. This field is never <code>null</code>.
*/
private final String _value;
// Methods
/**
* Retrieves the type.
*
* @return
* the type, never <code>null</code>.
*/
public final Type getType() {
return _type;
}
/**
* Retrieves the value that was considered invalid.
*
* @return
* the value that was considered invalid, not <code>null</code>.
*/
public final String getValue() {
return _value;
}
}
|
package com.bubelov.coins.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentProviderOperation;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import com.bubelov.coins.Constants;
import com.bubelov.coins.R;
import com.bubelov.coins.event.MerchantsSyncFinishedEvent;
import com.bubelov.coins.event.NewMerchantsLoadedEvent;
import com.bubelov.coins.manager.UserNotificationManager;
import com.bubelov.coins.model.Currency;
import com.bubelov.coins.database.Database;
import com.bubelov.coins.model.Merchant;
import com.bubelov.coins.util.Utils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class DatabaseSyncService extends CoinsIntentService {
private static final String TAG = DatabaseSyncService.class.getSimpleName();
private static final String FORCE_SYNC_EXTRA = "force_sync";
private static final String KEY_IS_SYNCING = "syncing";
private static final String KEY_INITIALIZED = "initialized";
private static final String KEY_LAST_SYNC_MILLIS = "last_sync_millis";
private static final long SYNC_INTERVAL_MILLIS = TimeUnit.HOURS.toMillis(1);
private static final int MAX_MERCHANTS_PER_REQUEST = 250;
private SharedPreferences preferences;
private AlarmManager alarmManager;
private PendingIntent syncIntent;
public static Intent makeIntent(Context context, boolean forceSync) {
Intent intent = new Intent(context, DatabaseSyncService.class);
intent.putExtra(FORCE_SYNC_EXTRA, forceSync);
return intent;
}
public static boolean isSyncing(Context context) {
SharedPreferences preferences = context.getSharedPreferences(TAG, MODE_PRIVATE);
return preferences.getBoolean(KEY_IS_SYNCING, false);
}
public DatabaseSyncService() {
super(TAG);
}
@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "Got new intent");
preferences = getSharedPreferences(TAG, MODE_PRIVATE);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
syncIntent = PendingIntent.getService(this, 0, DatabaseSyncService.makeIntent(this, true), PendingIntent.FLAG_CANCEL_CURRENT);
if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(getString(R.string.pref_sync_merchants_key), true)) {
Log.d(TAG, "Database sync turned off");
}
if (isSyncing()) {
Log.d(TAG, "Service already running");
return;
}
long lastSyncMillis = preferences.getLong(KEY_LAST_SYNC_MILLIS, 0);
alarmManager.set(AlarmManager.RTC, lastSyncMillis + SYNC_INTERVAL_MILLIS, syncIntent);
if (intent.getBooleanExtra(FORCE_SYNC_EXTRA, false) || System.currentTimeMillis() - preferences.getLong(KEY_LAST_SYNC_MILLIS, 0) > SYNC_INTERVAL_MILLIS) {
if (Utils.isOnline(this)) {
setSyncing(true);
super.onStart(intent, startId);
} else {
Log.d(TAG, "Network is unavailable. Will try later");
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5), syncIntent);
}
} else {
Log.d(TAG, "Too early for sync");
}
}
@Override
protected void onHandleIntent(Intent intent) {
try {
sync();
getSharedPreferences(TAG, MODE_PRIVATE).edit().putBoolean(KEY_INITIALIZED, true).apply();
} catch (Exception exception) {
Log.e(TAG, "Couldn't synchronize database", exception);
} finally {
setSyncing(false);
preferences.edit().putLong(KEY_LAST_SYNC_MILLIS, System.currentTimeMillis()).apply();
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + SYNC_INTERVAL_MILLIS, syncIntent);
getBus().post(new MerchantsSyncFinishedEvent());
}
}
@Override
public void onDestroy() {
setSyncing(false);
super.onDestroy();
}
private void sync() throws Exception {
checkInitialized();
syncCurrenciesIfNecessary();
Cursor currencies = getContentResolver().query(Database.Currencies.CONTENT_URI,
new String[]{Database.Currencies._ID, Database.Currencies.CODE},
null,
null,
null);
while (currencies.moveToNext()) {
Long id = currencies.getLong(currencies.getColumnIndex(Database.Currencies._ID));
String code = currencies.getString(currencies.getColumnIndex(Database.Currencies.CODE));
syncMerchants(id, code);
}
currencies.close();
}
private void checkInitialized() {
Cursor merchantsCount = getContentResolver().query(Database.Currencies.CONTENT_URI,
new String[]{"count(*) AS count"},
null,
null,
null);
if (merchantsCount.moveToNext() && merchantsCount.getInt(0) == 0) {
getSharedPreferences(TAG, MODE_PRIVATE).edit().putBoolean(KEY_INITIALIZED, false).apply();
}
}
private void syncCurrenciesIfNecessary() throws RemoteException, OperationApplicationException {
Cursor countCursor = getContentResolver().query(Database.Currencies.CONTENT_URI,
new String[]{"count(*) AS count "},
null,
null,
null);
countCursor.moveToFirst();
int count = countCursor.getInt(0);
countCursor.close();
Log.d(TAG, count + " currencies found in DB");
if (count == 0) {
Log.d(TAG, "Loading currencies from server");
List<Currency> currencies = getApi().getCurrencies();
Log.d(TAG, String.format("Downloaded %s currencies", currencies.size()));
saveCurrencies(currencies);
}
}
private void syncMerchants(long currencyId, String currencyCode) throws RemoteException, OperationApplicationException {
SQLiteDatabase db = getDatabaseHelper().getWritableDatabase();
UserNotificationManager notificationManager = new UserNotificationManager(getApplicationContext());
boolean initialized = getSharedPreferences(TAG, MODE_PRIVATE).getBoolean(KEY_INITIALIZED, false);
while (true) {
long lastUpdateMillis;
Cursor cursor = db.rawQuery("select max(m._updated_at) from merchants as m join currencies_merchants as mc on m._id = mc.merchant_id join currencies c on c._id = mc.currency_id where c.code = ?",
new String[] { currencyCode });
if (!cursor.moveToNext()) {
Log.e(TAG, "Couldn't get last update timestamp");
cursor.close();
break;
}
lastUpdateMillis = cursor.isNull(0) ? 0 : cursor.getLong(0);
cursor.close();
List<Merchant> merchants = getApi().getMerchants(currencyCode, new SimpleDateFormat(Constants.DATE_FORMAT).format(lastUpdateMillis), MAX_MERCHANTS_PER_REQUEST);
Log.d(TAG, String.format("Downloaded %s merchants accepting %s", merchants.size(), currencyCode));
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
for (Merchant merchant : merchants) {
if (initialized && notificationManager.shouldNotifyUser(merchant)) {
notificationManager.notifyUser(merchant.getId(), merchant.getName());
}
operations.add(ContentProviderOperation
.newInsert(Database.Merchants.CONTENT_URI)
.withValue(Database.Merchants._ID, merchant.getId())
.withValue(Database.Merchants._CREATED_AT, merchant.getCreatedAt().getTime())
.withValue(Database.Merchants._UPDATED_AT, merchant.getUpdatedAt().getTime())
.withValue(Database.Merchants.LATITUDE, merchant.getLatitude())
.withValue(Database.Merchants.LONGITUDE, merchant.getLongitude())
.withValue(Database.Merchants.NAME, merchant.getName())
.withValue(Database.Merchants.DESCRIPTION, merchant.getDescription())
.withValue(Database.Merchants.PHONE, merchant.getPhone())
.withValue(Database.Merchants.WEBSITE, merchant.getWebsite())
.withValue(Database.Merchants.AMENITY, merchant.getAmenity())
.withValue(Database.Merchants.OPENING_HOURS, merchant.getOpeningHours())
.withValue(Database.Merchants.ADDRESS, merchant.getAddress())
.build());
operations.add(ContentProviderOperation
.newInsert(ContentUris.withAppendedId(Database.Merchants.CONTENT_URI, merchant.getId()).buildUpon().appendPath("currencies").build())
.withValue(Database.Currencies._ID, currencyId)
.build());
}
getContentResolver().applyBatch(Database.AUTHORITY, operations);
if (merchants.size() > 0) {
getApp().getMerchantsCache().invalidate();
getBus().post(new NewMerchantsLoadedEvent());
}
if (merchants.size() < MAX_MERCHANTS_PER_REQUEST) {
break;
}
}
}
private void saveCurrencies(Collection<Currency> currencies) throws RemoteException, OperationApplicationException {
ArrayList<ContentProviderOperation> operations = new ArrayList<>();
for (Currency currency : currencies) {
operations.add(ContentProviderOperation
.newInsert(Database.Currencies.CONTENT_URI)
.withValue(Database.Currencies._ID, currency.getId())
.withValue(Database.Currencies._CREATED_AT, currency.getCreatedAt().getTime())
.withValue(Database.Currencies._UPDATED_AT, currency.getUpdatedAt().getTime())
.withValue(Database.Currencies.NAME, currency.getName())
.withValue(Database.Currencies.CODE, currency.getCode())
.build());
}
getContentResolver().applyBatch(Database.AUTHORITY, operations);
}
private boolean isSyncing() {
return isSyncing(this);
}
private void setSyncing(boolean syncing) {
preferences.edit().putBoolean(KEY_IS_SYNCING, syncing).apply();
}
}
|
package io.atomix.catalyst.util.concurrent;
import org.slf4j.Logger;
import java.util.concurrent.RejectedExecutionException;
/**
* Runnable utilities.
*/
final class Runnables {
private Runnables() {
}
/**
* Returns a wrapped runnable that logs and rethrows uncaught exceptions.
*/
static Runnable logFailure(final Runnable runnable, Logger logger) {
return () -> {
try {
runnable.run();
} catch (Throwable t) {
if (!(t instanceof RejectedExecutionException)) {
logger.error("An uncaught exception occurred", t);
}
throw t;
}
};
}
}
|
package nl.b3p.viewer.stripes;
import java.io.StringReader;
import javax.persistence.EntityManager;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.config.services.Category;
import nl.b3p.viewer.config.services.GeoService;
import nl.b3p.viewer.config.services.Layer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@UrlBinding("/action/geoserviceregistry/")
@StrictBinding
public class GeoServiceRegistryActionBean implements ActionBean {
private ActionBeanContext context;
@Validate
private String nodeId;
//<editor-fold defaultstate="collapsed" desc="getters and setters">
public ActionBeanContext getContext() {
return context;
}
public void setContext(ActionBeanContext context) {
this.context = context;
}
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
//</editor-fold>
public Resolution load() throws JSONException {
EntityManager em = Stripersist.getEntityManager();
final JSONArray children = new JSONArray();
String type = nodeId.substring(0, 1);
int id = Integer.parseInt(nodeId.substring(1));
if(type.equals("c")) {
Category c = em.find(Category.class, new Long(id));
// TODO check readers
for(Category sub: c.getChildren()) {
JSONObject j = new JSONObject();
j.put("id", "c" + sub.getId());
j.put("name", sub.getName());
j.put("type", "category");
j.put("isLeaf", sub.getChildren().isEmpty() && sub.getServices().isEmpty());
if(sub.getParent() != null) {
j.put("parentid", sub.getParent().getId());
}
children.put(j);
}
for(GeoService service: c.getServices()) {
JSONObject j = new JSONObject();
j.put("id", "s" + service.getId());
j.put("service", service.toJSONObject(false));
j.put("name", service.getName());
j.put("type", "service");
j.put("isLeaf", service.getTopLayer() == null);
j.put("status", "ok");//Math.random() > 0.5 ? "ok" : "error");
j.put("parentid", nodeId);
children.put(j);
}
} else if(type.equals("s")) {
// TODO check readers
GeoService gs = em.find(GeoService.class, new Long(id));
// GeoService may be invalid and not have a top layer
if(gs.getTopLayer() != null) {
// TODO check readers
for(Layer sublayer: gs.getTopLayer().getChildren()) {
JSONObject j = layerJSON(sublayer);
j.put("parentid", nodeId);
children.put(j);
}
}
} else if(type.equals("l")) {
Layer layer = em.find(Layer.class, new Long(id));
for(Layer sublayer: layer.getChildren()) {
// TODO check readers
JSONObject j = layerJSON(sublayer);
j.put("parentid", nodeId);
children.put(j);
}
}
return new StreamingResolution("application/json", new StringReader(children.toString()));
}
private static JSONObject layerJSON(Layer l) throws JSONException {
JSONObject j = new JSONObject();
j.put("id", "l" + l.getId());
j.put("name", l.getName());
String alias = l.getName();
if(l.getTitleAlias() != null){
alias = l.getTitleAlias();
}else if(l.getTitle() != null){
alias = l.getTitle();
}
j.put("alias", alias);
j.put("type", "layer");
j.put("isLeaf", l.getChildren().isEmpty());
j.put("isVirtual", l.isVirtual());
return j;
}
}
|
package org.neo4j.server;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.configuration.Configuration;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.graphdb.DependencyResolver;
import org.neo4j.helpers.Clock;
import org.neo4j.kernel.impl.transaction.xaframework.ForceMode;
import org.neo4j.kernel.impl.util.JobScheduler;
import org.neo4j.kernel.impl.util.StringLogger;
import org.neo4j.kernel.info.DiagnosticsManager;
import org.neo4j.kernel.logging.Logging;
import org.neo4j.server.configuration.ConfigurationProvider;
import org.neo4j.server.configuration.Configurator;
import org.neo4j.server.database.CypherExecutor;
import org.neo4j.server.database.CypherExecutorProvider;
import org.neo4j.server.database.Database;
import org.neo4j.server.database.DatabaseProvider;
import org.neo4j.server.database.GraphDatabaseServiceProvider;
import org.neo4j.server.database.InjectableProvider;
import org.neo4j.server.database.RrdDbWrapper;
import org.neo4j.server.logging.Logger;
import org.neo4j.server.modules.RESTApiModule;
import org.neo4j.server.modules.ServerModule;
import org.neo4j.server.plugins.PluginInvocatorProvider;
import org.neo4j.server.plugins.PluginManager;
import org.neo4j.server.preflight.PreFlightTasks;
import org.neo4j.server.preflight.PreflightFailedException;
import org.neo4j.server.rest.paging.LeaseManager;
import org.neo4j.server.rest.repr.InputFormatProvider;
import org.neo4j.server.rest.repr.OutputFormatProvider;
import org.neo4j.server.rest.repr.RepresentationFormatRepository;
import org.neo4j.server.rest.transactional.TransactionFacade;
import org.neo4j.server.rest.transactional.TransactionFilter;
import org.neo4j.server.rest.transactional.TransactionHandleRegistry;
import org.neo4j.server.rest.transactional.TransactionRegistry;
import org.neo4j.server.rest.transactional.TransitionalPeriodTransactionMessContainer;
import org.neo4j.server.rest.web.DatabaseActions;
import org.neo4j.server.rrd.RrdDbProvider;
import org.neo4j.server.rrd.RrdFactory;
import org.neo4j.server.security.KeyStoreFactory;
import org.neo4j.server.security.KeyStoreInformation;
import org.neo4j.server.security.SslCertificateFactory;
import org.neo4j.server.statistic.StatisticCollector;
import org.neo4j.server.web.SimpleUriBuilder;
import org.neo4j.server.web.WebServer;
import org.neo4j.server.web.WebServerProvider;
import static java.lang.Math.round;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.neo4j.helpers.Clock.SYSTEM_CLOCK;
import static org.neo4j.helpers.collection.Iterables.option;
import static org.neo4j.server.configuration.Configurator.DEFAULT_SCRIPT_SANDBOXING_ENABLED;
import static org.neo4j.server.configuration.Configurator.DEFAULT_TRANSACTION_TIMEOUT;
import static org.neo4j.server.configuration.Configurator.SCRIPT_SANDBOXING_ENABLED_KEY;
import static org.neo4j.server.configuration.Configurator.TRANSACTION_TIMEOUT;
import static org.neo4j.server.database.InjectableProvider.providerForSingleton;
public abstract class AbstractNeoServer implements NeoServer
{
@Deprecated // Please use #logging instead of this.
public static final Logger log = Logger.getLogger( AbstractNeoServer.class );
protected Database database;
protected CypherExecutor cypherExecutor;
protected Configurator configurator;
protected WebServer webServer;
protected final StatisticCollector statisticsCollector = new StatisticCollector();
private PreFlightTasks preflight;
private final List<ServerModule> serverModules = new ArrayList<>();
private final SimpleUriBuilder uriBuilder = new SimpleUriBuilder();
private InterruptThreadTimer interruptStartupTimer;
private DatabaseActions databaseActions;
private RoundRobinJobScheduler rrdDbScheduler = new RoundRobinJobScheduler();
private RrdDbWrapper rrdDbWrapper;
private TransactionFacade transactionFacade;
private TransactionHandleRegistry transactionRegistry;
private Logging logging;
protected abstract PreFlightTasks createPreflightTasks();
protected abstract Iterable<ServerModule> createServerModules();
protected abstract Database createDatabase();
protected abstract WebServer createWebServer();
@Override
public void init()
{
this.preflight = createPreflightTasks();
this.database = createDatabase();
this.webServer = createWebServer();
for ( ServerModule moduleClass : createServerModules() )
{
registerModule( moduleClass );
}
}
@Override
public void start() throws ServerStartupException
{
interruptStartupTimer = createInterruptStartupTimer();
try
{
// Pre-flight tasks run outside the boot timeout limit
runPreflightTasks();
interruptStartupTimer.startCountdown();
try
{
database.start();
DiagnosticsManager diagnosticsManager = resolveDependency(DiagnosticsManager.class);
logging = resolveDependency( Logging.class );
StringLogger diagnosticsLog = diagnosticsManager.getTargetLog();
diagnosticsLog.info( "
databaseActions = createDatabaseActions();
// TODO: RrdDb is not needed once we remove the old webadmin
rrdDbWrapper = new RrdFactory( configurator.configuration() )
.createRrdDbAndSampler( database, new RoundRobinJobScheduler() );
transactionFacade = createTransactionalActions();
cypherExecutor = new CypherExecutor( database, logging.getMessagesLog( CypherExecutor.class ) );
configureWebServer();
cypherExecutor.start();
diagnosticsManager.register( Configurator.DIAGNOSTICS, configurator );
startModules( diagnosticsLog );
startWebServer( diagnosticsLog );
diagnosticsLog.info( "
}
finally
{
interruptStartupTimer.stopCountdown();
}
}
catch ( Throwable t )
{
// Guard against poor operating systems that don't clear interrupt flags
// after having handled interrupts (looking at you, Bill).
Thread.interrupted();
if ( interruptStartupTimer.wasTriggered() )
{
// Make sure we don't leak rrd db files
stopRrdDb();
// If the database has been started, attempt to cleanly shut it down to avoid unclean shutdowns.
if(database.isRunning())
{
stopDatabase();
}
throw new ServerStartupException(
"Startup took longer than " + interruptStartupTimer.getTimeoutMillis() + "ms, " +
"and was stopped. You can disable this behavior by setting '" + Configurator
.STARTUP_TIMEOUT + "' to 0.",
1 );
}
throw new ServerStartupException( String.format( "Starting Neo4j Server failed: %s", t.getMessage() ), t );
}
}
public DependencyResolver getDependencyResolver()
{
return dependencyResolver;
}
protected DatabaseActions createDatabaseActions()
{
return new DatabaseActions(
new LeaseManager( SYSTEM_CLOCK ),
ForceMode.forced,
configurator.configuration().getBoolean(
SCRIPT_SANDBOXING_ENABLED_KEY,
DEFAULT_SCRIPT_SANDBOXING_ENABLED ), database.getGraph() );
}
private TransactionFacade createTransactionalActions()
{
final long timeoutMillis = getTransactionTimeoutMillis();
final Clock clock = SYSTEM_CLOCK;
transactionRegistry =
new TransactionHandleRegistry( clock, timeoutMillis, logging.getMessagesLog(TransactionRegistry.class) );
// ensure that this is > 0
long runEvery = round( timeoutMillis / 2.0 );
resolveDependency( JobScheduler.class ).scheduleRecurring( new Runnable()
{
@Override
public void run()
{
long maxAge = clock.currentTimeMillis() - timeoutMillis;
transactionRegistry.rollbackSuspendedTransactionsIdleSince( maxAge );
}
}, runEvery, MILLISECONDS );
return new TransactionFacade(
new TransitionalPeriodTransactionMessContainer( database.getGraph() ),
new ExecutionEngine( database.getGraph(), logging.getMessagesLog( ExecutionEngine.class ) ),
transactionRegistry,
baseUri(), logging.getMessagesLog( TransactionFacade.class )
);
}
private long getTransactionTimeoutMillis()
{
final int timeout = configurator.configuration().getInt( TRANSACTION_TIMEOUT, DEFAULT_TRANSACTION_TIMEOUT );
return Math.max( SECONDS.toMillis( timeout ), 1000L );
}
protected InterruptThreadTimer createInterruptStartupTimer()
{
long startupTimeout = SECONDS.toMillis(
getConfiguration().getInt( Configurator.STARTUP_TIMEOUT, Configurator.DEFAULT_STARTUP_TIMEOUT ) );
InterruptThreadTimer stopStartupTimer;
if ( startupTimeout > 0 )
{
log.info( "Setting startup timeout to: " + startupTimeout + "ms based on " + getConfiguration().getInt(
Configurator.STARTUP_TIMEOUT, -1 ) );
stopStartupTimer = InterruptThreadTimer.createTimer(
startupTimeout,
Thread.currentThread() );
}
else
{
stopStartupTimer = InterruptThreadTimer.createNoOpTimer();
}
return stopStartupTimer;
}
/**
* Use this method to register server modules from subclasses
*
* @param module
*/
protected final void registerModule( ServerModule module )
{
serverModules.add( module );
}
private void startModules( StringLogger logger )
{
for ( ServerModule module : serverModules )
{
module.start( logger );
}
}
private void stopModules()
{
for ( ServerModule module : serverModules )
{
try
{
module.stop();
}
catch ( Exception e )
{
log.error( "Unable to stop module.", e );
}
}
}
private void runPreflightTasks()
{
if ( !preflight.run() )
{
throw new PreflightFailedException( preflight.failedTask() );
}
}
@Override
public Configuration getConfiguration()
{
return configurator.configuration();
}
protected Logging getLogging()
{
return logging;
}
// TODO: Once WebServer is fully implementing LifeCycle,
// it should manage all but static (eg. unchangeable during runtime)
// configuration itself.
private void configureWebServer()
{
int webServerPort = getWebServerPort();
String webServerAddr = getWebServerAddress();
int maxThreads = getMaxThreads();
int sslPort = getHttpsPort();
boolean sslEnabled = getHttpsEnabled();
log.info( String.format("Starting HTTP on port :%s with %d threads available", webServerPort, maxThreads));
webServer.setPort( webServerPort );
webServer.setAddress( webServerAddr );
webServer.setMaxThreads( maxThreads );
webServer.setEnableHttps( sslEnabled );
webServer.setHttpsPort( sslPort );
webServer.setWadlEnabled(
Boolean.valueOf( String.valueOf( getConfiguration().getProperty( Configurator.WADL_ENABLED ) ) ) );
webServer.setDefaultInjectables( createDefaultInjectables() );
if ( sslEnabled )
{
log.info( String.format("Enabling HTTPS on port :%s", sslPort) );
webServer.setHttpsCertificateInformation( initHttpsKeyStore() );
}
}
private int getMaxThreads()
{
return configurator.configuration()
.containsKey( Configurator.WEBSERVER_MAX_THREADS_PROPERTY_KEY ) ? configurator.configuration()
.getInt( Configurator.WEBSERVER_MAX_THREADS_PROPERTY_KEY ) : defaultMaxWebServerThreads();
}
private int defaultMaxWebServerThreads()
{
return 10 * Runtime.getRuntime()
.availableProcessors();
}
private void startWebServer( StringLogger logger )
{
try
{
if ( httpLoggingProperlyConfigured() )
{
webServer.setHttpLoggingConfiguration(
new File( getConfiguration().getProperty( Configurator.HTTP_LOG_CONFIG_LOCATION ).toString()
) );
}
webServer.start();
Integer limit = getConfiguration().getInteger( Configurator.WEBSERVER_LIMIT_EXECUTION_TIME_PROPERTY_KEY,
null );
if ( limit != null )
{
webServer.addExecutionLimitFilter( limit, database.getGraph().getGuard() );
}
if ( logger != null )
{
logger.logMessage( "Server started on: " + baseUri() );
}
log.info( String.format( "Remote interface ready and available at [%s]", baseUri() ) );
}
catch ( RuntimeException e )
{
log.error( String.format( "Failed to start Neo Server on port [%d], reason [%s]",
getWebServerPort(), e.getMessage() ) );
throw e;
}
}
private boolean httpLoggingProperlyConfigured()
{
return loggingEnabled() && configLocated();
}
private boolean configLocated()
{
final Object property = getConfiguration().getProperty( Configurator.HTTP_LOG_CONFIG_LOCATION );
return property != null && new File( String.valueOf( property ) ).exists();
}
private boolean loggingEnabled()
{
return "true".equals( String.valueOf( getConfiguration().getProperty( Configurator.HTTP_LOGGING ) ) );
}
protected int getWebServerPort()
{
return configurator.configuration()
.getInt( Configurator.WEBSERVER_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_PORT );
}
protected boolean getHttpsEnabled()
{
return configurator.configuration()
.getBoolean( Configurator.WEBSERVER_HTTPS_ENABLED_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_HTTPS_ENABLED );
}
protected int getHttpsPort()
{
return configurator.configuration()
.getInt( Configurator.WEBSERVER_HTTPS_PORT_PROPERTY_KEY, Configurator.DEFAULT_WEBSERVER_HTTPS_PORT );
}
protected String getWebServerAddress()
{
return configurator.configuration()
.getString( Configurator.WEBSERVER_ADDRESS_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_ADDRESS );
}
// TODO: This is jetty-specific, move to Jetty9WebServer
protected KeyStoreInformation initHttpsKeyStore()
{
File keystorePath = new File( configurator.configuration().getString(
Configurator.WEBSERVER_KEYSTORE_PATH_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_KEYSTORE_PATH ) );
File privateKeyPath = new File( configurator.configuration().getString(
Configurator.WEBSERVER_HTTPS_KEY_PATH_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_HTTPS_KEY_PATH ) );
File certificatePath = new File( configurator.configuration().getString(
Configurator.WEBSERVER_HTTPS_CERT_PATH_PROPERTY_KEY,
Configurator.DEFAULT_WEBSERVER_HTTPS_CERT_PATH ) );
if ( !certificatePath.exists() )
{
log.info( "No SSL certificate found, generating a self-signed certificate.." );
SslCertificateFactory certFactory = new SslCertificateFactory();
certFactory.createSelfSignedCertificate( certificatePath, privateKeyPath, getWebServerAddress() );
}
KeyStoreFactory keyStoreFactory = new KeyStoreFactory();
return keyStoreFactory.createKeyStore( keystorePath, privateKeyPath, certificatePath );
}
@Override
public void stop()
{
try
{
stopWebServer();
stopModules();
stopRrdDb();
log.info( "Successfully shutdown Neo4j Server." );
stopDatabase();
log.info( "Successfully shutdown database." );
}
catch ( Exception e )
{
log.warn( "Failed to cleanly shutdown database." );
}
}
private void stopRrdDb()
{
try
{
if( rrdDbScheduler != null) rrdDbScheduler.stopJobs();
if( rrdDbWrapper != null ) rrdDbWrapper.close();
} catch(IOException e)
{
// If we fail on shutdown, we can't really recover from it. Log the issue and carry on.
log.error( "Unable to cleanly shut down statistics database.", e );
}
}
private void stopWebServer()
{
if ( webServer != null )
{
webServer.stop();
}
}
private void stopDatabase()
{
if ( database != null )
{
try
{
database.stop();
}
catch ( Throwable e )
{
throw new RuntimeException( e );
}
}
}
@Override
public Database getDatabase()
{
return database;
}
@Override
public TransactionRegistry getTransactionRegistry()
{
return transactionRegistry;
}
@Override
public URI baseUri()
{
return uriBuilder.buildURI( getWebServerAddress(), getWebServerPort(), false );
}
public URI httpsUri()
{
return uriBuilder.buildURI( getWebServerAddress(), getHttpsPort(), true );
}
public WebServer getWebServer()
{
return webServer;
}
@Override
public Configurator getConfigurator()
{
return configurator;
}
@Override
public PluginManager getExtensionManager()
{
if ( hasModule( RESTApiModule.class ) )
{
return getModule( RESTApiModule.class ).getPlugins();
}
else
{
return null;
}
}
protected Collection<InjectableProvider<?>> createDefaultInjectables()
{
Collection<InjectableProvider<?>> singletons = new ArrayList<InjectableProvider<?>>();
Database database = getDatabase();
singletons.add( new DatabaseProvider( database ) );
singletons.add( new DatabaseActions.Provider( databaseActions ) );
singletons.add( new GraphDatabaseServiceProvider( database ) );
singletons.add( new NeoServerProvider( this ) );
singletons.add( new ConfigurationProvider( getConfiguration() ) );
singletons.add( new RrdDbProvider( rrdDbWrapper ) );
singletons.add( new WebServerProvider( getWebServer() ) );
PluginInvocatorProvider pluginInvocatorProvider = new PluginInvocatorProvider( this );
singletons.add( pluginInvocatorProvider );
RepresentationFormatRepository repository = new RepresentationFormatRepository( this );
singletons.add( new InputFormatProvider( repository ) );
singletons.add( new OutputFormatProvider( repository ) );
singletons.add( new CypherExecutorProvider( cypherExecutor ) );
singletons.add( providerForSingleton( transactionFacade, TransactionFacade.class ) );
singletons.add( new TransactionFilter( database ) );
return singletons;
}
private boolean hasModule( Class<? extends ServerModule> clazz )
{
for ( ServerModule sm : serverModules )
{
if ( sm.getClass() == clazz )
{
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
private <T extends ServerModule> T getModule( Class<T> clazz )
{
for ( ServerModule sm : serverModules )
{
if ( sm.getClass() == clazz )
{
return (T) sm;
}
}
return null;
}
protected <T> T resolveDependency( Class<T> type )
{
return dependencyResolver.resolveDependency( type );
}
private final DependencyResolver dependencyResolver = new DependencyResolver.Adapter()
{
private <T> T resolveKnownSingleDependency( Class<T> type )
{
if ( type.equals( Database.class ) )
{
return (T) database;
}
else if ( type.equals( PreFlightTasks.class ) )
{
return (T) preflight;
}
else if ( type.equals( InterruptThreadTimer.class ) )
{
return (T) interruptStartupTimer;
}
// TODO: Note that several component dependencies are inverted here. For instance, logging
// should be provided by the server to the kernel, not the other way around. Same goes for job
// scheduling and configuration. Probably several others as well.
DependencyResolver kernelDependencyResolver = database.getGraph().getDependencyResolver();
return kernelDependencyResolver.resolveDependency( type );
}
@Override
public <T> T resolveDependency( Class<T> type, SelectionStrategy selector )
{
return selector.select( type, option( resolveKnownSingleDependency( type ) ) );
}
};
}
|
package org.apache.log4j.chainsaw.receivers;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.chainsaw.PopupListener;
import org.apache.log4j.chainsaw.SmallButton;
import org.apache.log4j.chainsaw.help.HelpManager;
import org.apache.log4j.chainsaw.helper.SwingHelper;
import org.apache.log4j.chainsaw.icons.ChainsawIcons;
import org.apache.log4j.chainsaw.icons.LevelIconFactory;
import org.apache.log4j.chainsaw.icons.LineIconFactory;
import org.apache.log4j.chainsaw.messages.MessageCenter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.net.SocketNodeEventListener;
import org.apache.log4j.net.SocketReceiver;
import org.apache.log4j.plugins.Pauseable;
import org.apache.log4j.plugins.Plugin;
import org.apache.log4j.plugins.PluginRegistry;
import org.apache.log4j.plugins.Receiver;
/**
* This panel is used to manage all the Receivers configured within Log4j
*
*
* @author Paul Smith <psmith@apache.org>
* @author Scott Debogy <sdeboy@apache.org>
*/
public class ReceiversPanel extends JPanel {
final Action newReceiverButtonAction;
final Action pauseReceiverButtonAction;
final Action playReceiverButtonAction;
final Action shutdownReceiverButtonAction;
private final Action showReceiverHelpAction;
private final Action startAllAction;
private final JPopupMenu popupMenu = new ReceiverPopupMenu();
private final JTree receiversTree = new JTree();
private final NewReceiverPopupMenu newReceiverPopup =
new NewReceiverPopupMenu();
private final ReceiverToolbar buttonPanel;
private final Runnable updateReceiverTree;
private final JSplitPane splitter = new JSplitPane();
private final PluginPropertyEditorPanel pluginEditorPanel =
new PluginPropertyEditorPanel();
public ReceiversPanel() {
super();
setLayout(new BorderLayout());
setBorder(BorderFactory.createEtchedBorder());
setPreferredSize(new Dimension(200, 400));
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
final ReceiversTreeModel model = new ReceiversTreeModel();
PluginRegistry.addPluginListener(model);
receiversTree.setModel(model);
receiversTree.setExpandsSelectedPaths(true);
model.addTreeModelListener(
new TreeModelListener() {
public void treeNodesChanged(TreeModelEvent e) {
expandRoot();
}
public void treeNodesInserted(TreeModelEvent e) {
expandRoot();
}
public void treeNodesRemoved(TreeModelEvent e) {
expandRoot();
}
public void treeStructureChanged(TreeModelEvent e) {
expandRoot();
}
private void expandRoot() {
receiversTree.expandPath(
new TreePath(model.getPathToRoot(model.RootNode)));
}
});
receiversTree.expandPath(
new TreePath(model.getPathToRoot(model.RootNode)));
receiversTree.addTreeWillExpandListener(
new TreeWillExpandListener() {
public void treeWillCollapse(TreeExpansionEvent event)
throws ExpandVetoException {
if (event.getPath().getLastPathComponent() == model.RootNode) {
throw new ExpandVetoException(event);
}
}
public void treeWillExpand(TreeExpansionEvent event)
throws ExpandVetoException {
}
});
receiversTree.addTreeSelectionListener(
new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getNewLeadSelectionPath();
if (path != null) {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode) path.getLastPathComponent();
if (
(node != null) && (node.getUserObject() != null)
&& (node.getUserObject() instanceof Plugin)) {
Plugin p = (Plugin) node.getUserObject();
LogLog.debug("plugin=" + p);
pluginEditorPanel.setPlugin(p);
} else {
pluginEditorPanel.setPlugin(null);
}
}
}
});
receiversTree.setToolTipText("Allows you to manage Log4j Receivers");
newReceiverButtonAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
newReceiverPopup.show(
buttonPanel.newReceiverButton, 0,
buttonPanel.newReceiverButton.getHeight());
}
};
newReceiverButtonAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.ICON_NEW_RECEIVER));
newReceiverButtonAction.putValue(
Action.SHORT_DESCRIPTION, "Creates and configures a new Receiver");
newReceiverButtonAction.putValue(Action.NAME, "New Receiver");
newReceiverButtonAction.putValue(
Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_N));
newReceiverButtonAction.setEnabled(true);
playReceiverButtonAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
playCurrentlySelectedReceiver();
}
};
playReceiverButtonAction.putValue(
Action.SHORT_DESCRIPTION, "Resumes the selected Node");
playReceiverButtonAction.putValue(Action.NAME, "Resume");
playReceiverButtonAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.ICON_RESUME_RECEIVER));
playReceiverButtonAction.setEnabled(false);
playReceiverButtonAction.putValue(
Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_R));
pauseReceiverButtonAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
pauseCurrentlySelectedReceiver();
}
};
pauseReceiverButtonAction.putValue(
Action.SHORT_DESCRIPTION,
"Pause the selected Receiver. All events received will be discarded.");
pauseReceiverButtonAction.putValue(Action.NAME, "Pause");
pauseReceiverButtonAction.putValue(
Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_P));
pauseReceiverButtonAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.PAUSE));
pauseReceiverButtonAction.setEnabled(false);
shutdownReceiverButtonAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
shutdownCurrentlySelectedReceiver();
}
};
shutdownReceiverButtonAction.putValue(
Action.SHORT_DESCRIPTION,
"Shuts down the selected Receiver, and removes it from the Plugin registry");
shutdownReceiverButtonAction.putValue(Action.NAME, "Shutdown");
shutdownReceiverButtonAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.ICON_STOP_RECEIVER));
shutdownReceiverButtonAction.putValue(
Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_S));
shutdownReceiverButtonAction.setEnabled(false);
showReceiverHelpAction =
new AbstractAction("Help") {
public void actionPerformed(ActionEvent e) {
Receiver receiver = getCurrentlySelectedReceiver();
if (receiver != null) {
HelpManager.getInstance().showHelpForClass(receiver.getClass());
}
}
};
showReceiverHelpAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.HELP));
showReceiverHelpAction.putValue(
Action.SHORT_DESCRIPTION, "Displays the JavaDoc page for this Plugin");
startAllAction =
new AbstractAction(
"(Re)start All Receivers", new ImageIcon(ChainsawIcons.ICON_RESTART)) {
public void actionPerformed(ActionEvent e) {
if (
JOptionPane.showConfirmDialog(
null,
"This will cause any active Receiver to stop, and disconnect. Is this ok?",
"Confirm", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
new Thread(
new Runnable() {
public void run() {
Collection allReceivers =
PluginRegistry.getPlugins(
LogManager.getLoggerRepository(), Receiver.class);
for (Iterator iter = allReceivers.iterator();
iter.hasNext();) {
Receiver item = (Receiver) iter.next();
PluginRegistry.stopPlugin(item);
PluginRegistry.startPlugin(item);
}
updateReceiverTreeInDispatchThread();
MessageCenter.getInstance().getLogger().info(
"All Receivers have been (re)started");
}
}).start();
}
}
};
startAllAction.putValue(
Action.SHORT_DESCRIPTION,
"Ensures that any Receiver that isn't active, is started.");
/**
* We need to setup a runnable that updates the tree
* any time a Socket event happens (opening/closing of a socket).
*
* We do this by installing a SocketNodeEventListener in ALL the
* registered SocketReceivers
*/
updateReceiverTree =
new Runnable() {
public void run() {
ReceiversTreeModel model =
(ReceiversTreeModel) receiversTree.getModel();
model.refresh();
}
};
receiversTree.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
receiversTree.setCellRenderer(new ReceiverTreeCellRenderer());
buttonPanel = new ReceiverToolbar();
receiversTree.addTreeSelectionListener(buttonPanel);
PopupListener popupListener = new PopupListener(popupMenu);
receiversTree.addMouseListener(popupListener);
this.addMouseListener(popupListener);
JComponent component = receiversTree;
JScrollPane pane = new JScrollPane(component);
splitter.setOrientation(JSplitPane.VERTICAL_SPLIT);
splitter.setTopComponent(pane);
splitter.setBottomComponent(pluginEditorPanel);
splitter.setResizeWeight(0.7);
add(buttonPanel, BorderLayout.NORTH);
add(splitter, BorderLayout.CENTER);
/**
* This Tree likes to be notified when Socket's are accepted so
* we listen for them and update the Tree.
*/
SocketNodeEventListener listener =
new SocketNodeEventListener() {
public void socketOpened(String remoteInfo) {
updateReceiverTreeInDispatchThread();
}
public void socketClosedEvent(Exception e) {
updateReceiverTreeInDispatchThread();
}
};
/**
* add this listener to all SocketReceivers
*/
List socketReceivers =
PluginRegistry.getPlugins(
LogManager.getLoggerRepository(), SocketReceiver.class);
for (Iterator iter = socketReceivers.iterator(); iter.hasNext();) {
SocketReceiver element = (SocketReceiver) iter.next();
element.addSocketNodeEventListener(listener);
}
}
protected ReceiversTreeModel getReceiverTreeModel() {
return ((ReceiversTreeModel) receiversTree.getModel());
}
protected void updateCurrentlySelectedNodeInDispatchThread() {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode) receiversTree
.getLastSelectedPathComponent();
if (node == null) {
return;
}
getReceiverTreeModel().nodeChanged(node);
updateActions();
}
});
}
/**
* Returns the currently selected Receiver, or null if there is no
* selected Receiver (this could be because a) nothing at all is selected
* or b) a non Receiver type node is selected
*
* @return Receiver or null
*/
private Receiver getCurrentlySelectedReceiver() {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode) receiversTree.getLastSelectedPathComponent();
if (node == null) {
return null;
}
Object userObject = node.getUserObject();
if (userObject instanceof Receiver) {
return (Receiver) userObject;
}
return null;
}
private Receiver[] getSelectedReceivers() {
TreePath[] paths = receiversTree.getSelectionPaths();
Collection receivers = new ArrayList();
for (int i = 0; i < paths.length; i++) {
TreePath path = paths[i];
DefaultMutableTreeNode node =
(DefaultMutableTreeNode) path.getLastPathComponent();
if ((node != null) && node.getUserObject() instanceof Receiver) {
receivers.add(node.getUserObject());
}
}
return (Receiver[]) receivers.toArray(new Receiver[0]);
}
/**
* Returns the currently seleted node's User Object, or null
* if there is no selected node, or if the currently selected node has
* not user Object
* @return Object representing currently seleted Node's User Object
*/
private Object getCurrentlySelectedUserObject() {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode) receiversTree.getLastSelectedPathComponent();
if (node == null) {
return null;
}
return node.getUserObject();
}
/**
* Takes the currently selected Receiver and pauess it, effectively
* discarding any received event BEFORE it is even posted to the logger
* repository.
*
* The user is NOT asked to confirm this operation
*
*/
private void pauseCurrentlySelectedReceiver() {
new Thread(
new Runnable() {
public void run() {
Object obj = getCurrentlySelectedUserObject();
if ((obj != null) && obj instanceof Pauseable) {
((Pauseable) obj).setPaused(true);
updateCurrentlySelectedNodeInDispatchThread();
}
}
}).start();
}
/**
* Ensures that the currently selected receiver active property is set to
* true
*
*/
private void playCurrentlySelectedReceiver() {
new Thread(
new Runnable() {
public void run() {
Object obj = getCurrentlySelectedUserObject();
if ((obj != null) && obj instanceof Pauseable) {
((Pauseable) obj).setPaused(false);
updateCurrentlySelectedNodeInDispatchThread();
}
}
}).start();
}
/**
* Takes the currently selected Receiver and stops it, which effectively
* removes it from the PluginRegistry.
*
* The user is asked to confirm this operation
*
*/
private void shutdownCurrentlySelectedReceiver() {
if (
JOptionPane.showConfirmDialog(
null,
"Are you sure you wish to shutdown this receiver?\n\nThis will disconnect any network resources, and remove it from the PluginRegistry.",
"Confirm stop of Receiver", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
new Thread(
new Runnable() {
public void run() {
Receiver[] receivers = getSelectedReceivers();
if (receivers != null) {
for (int i = 0; i < receivers.length; i++) {
PluginRegistry.stopPlugin(receivers[i]);
}
}
}
}).start();
}
}
/**
* Sets the state of actions depending on certain conditions (i.e what is
* currently selected etc.)
*/
private void updateActions() {
Object object = getCurrentlySelectedUserObject();
if ((object != null) && object instanceof Pauseable) {
Pauseable pauseable = (Pauseable) object;
if (!pauseable.isPaused()) {
pauseReceiverButtonAction.setEnabled(true);
playReceiverButtonAction.setEnabled(false);
} else {
pauseReceiverButtonAction.setEnabled(false);
playReceiverButtonAction.setEnabled(true);
}
} else {
pauseReceiverButtonAction.setEnabled(false);
playReceiverButtonAction.setEnabled(false);
}
if (object instanceof Receiver) {
newReceiverButtonAction.setEnabled(true);
shutdownReceiverButtonAction.setEnabled(true);
} else {
shutdownReceiverButtonAction.setEnabled(false);
newReceiverButtonAction.setEnabled(true);
}
}
/**
* Ensures that the Receiver tree is updated with the latest information
* and that this operation occurs in the Swing Event Dispatch thread.
*
*/
public void updateReceiverTreeInDispatchThread() {
LogLog.debug(
"updateReceiverTreeInDispatchThread, should not be needed now");
// if (SwingUtilities.isEventDispatchThread()) {
// updateReceiverTree.run();
// } else {
// SwingUtilities.invokeLater(updateReceiverTree);
}
/* (non-Javadoc)
* @see java.awt.Component#setVisible(boolean)
*/
public void setVisible(boolean aFlag) {
boolean oldValue = isVisible();
super.setVisible(aFlag);
firePropertyChange("visible", oldValue, isVisible());
}
/**
* A popup menu that allows the user to choose which
* style of Receiver to create, which spawns a relevant Dialog
* to enter the information and create the Receiver
*
* @author Paul Smith <psmith@apache.org>
*
*/
class NewReceiverPopupMenu extends JPopupMenu {
NewReceiverPopupMenu() {
try {
final List receiverList =
ReceiversHelper.getInstance().getKnownReceiverClasses();
String separatorCheck = null;
for (Iterator iter = receiverList.iterator(); iter.hasNext();) {
final Class toCreate = (Class) iter.next();
Package thePackage = toCreate.getPackage();
final String name =
toCreate.getName().substring(thePackage.getName().length() + 1);
if (separatorCheck == null) {
separatorCheck = name.substring(0, 1);
} else {
String current = name.substring(0, 1);
if (!current.equals(separatorCheck)) {
addSeparator();
separatorCheck = current;
}
}
add(
new AbstractAction("New " + name + "...") {
public void actionPerformed(ActionEvent e) {
Container container = SwingUtilities.getAncestorOfClass(JFrame.class, ReceiversPanel.this);
final JDialog dialog = new JDialog((JFrame) container,"New " + toCreate.getName() + "..." ,true);
try {
final NewReceiverDialogPanel panel =
NewReceiverDialogPanel.create(toCreate);
dialog.getContentPane().add(panel);
dialog.pack();
SwingHelper.centerOnScreen(dialog);
/**
* Make the default button the ok button
*/
dialog.getRootPane().setDefaultButton(panel.getOkPanel().getOkButton());
/**
* Use the standard Cancel metaphor
*/
SwingHelper.configureCancelForDialog(dialog, panel.getOkPanel().getCancelButton());
panel.getOkPanel().getOkButton().addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
Plugin plugin = panel.getPlugin();
PluginRegistry.startPlugin(plugin);
MessageCenter.getInstance().addMessage("Plugin '" + plugin.getName() + "' started");
}
});
dialog.show();
} catch (Exception e1) {
e1.printStackTrace();
MessageCenter.getInstance().getLogger().error(
"Failed to create the new Receiver dialog", e1);
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
}
/**
* A popup menu class for when the user uses the popup trigger action
* on a node in the Receiver tree.
*
* @author Paul Smith <psmith@apache.org>
*
*/
class ReceiverPopupMenu extends JPopupMenu {
ReceiverPopupMenu() {
}
/* (non-Javadoc)
* @see javax.swing.JPopupMenu#show(java.awt.Component, int, int)
*/
public void show(Component invoker, int x, int y) {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode) receiversTree.getLastSelectedPathComponent();
if (node == null) {
return;
}
Object userObject = node.getUserObject();
removeAll();
if (userObject == getRootOfTree().getUserObject()) {
buildForReceiversRoot();
} else if (getCurrentlySelectedReceiver() != null) {
buildForReceiverNode();
} else {
return;
}
this.invalidate();
this.validate();
super.show(invoker, x, y);
}
private DefaultMutableTreeNode getRootOfTree() {
return (DefaultMutableTreeNode) receiversTree.getModel().getRoot();
}
/**
* Builds the popup menu with relevant items for a selected
* Receiver node in the Tree.
*/
private void buildForReceiverNode() {
final Action pauseReceiver =
new AbstractAction(
"Pause this Receiver", new ImageIcon(ChainsawIcons.PAUSE)) {
public void actionPerformed(ActionEvent e) {
pauseCurrentlySelectedReceiver();
}
};
add(playReceiverButtonAction);
add(pauseReceiverButtonAction);
add(shutdownReceiverButtonAction);
addSeparator();
final Receiver r = getCurrentlySelectedReceiver();
add(createLevelRadioButton(r, Level.DEBUG));
add(createLevelRadioButton(r, Level.INFO));
add(createLevelRadioButton(r, Level.WARN));
add(createLevelRadioButton(r, Level.ERROR));
addSeparator();
add(createLevelRadioButton(r, Level.OFF));
add(createLevelRadioButton(r, Level.ALL));
addSeparator();
add(showReceiverHelpAction);
}
private JRadioButtonMenuItem createLevelRadioButton(
final Receiver r, final Level l) {
Map levelIconMap = LevelIconFactory.getInstance().getLevelToIconMap();
Action action =
new AbstractAction(
l.toString(), (Icon) levelIconMap.get(l.toString())) {
public void actionPerformed(ActionEvent e) {
if (r != null) {
r.setThreshold(l);
updateCurrentlySelectedNodeInDispatchThread();
}
}
};
JRadioButtonMenuItem item = new JRadioButtonMenuItem(action);
item.setSelected(r.getThreshold() == l);
return item;
}
/**
* Builds a relevant set of menus for when the Root node in the Receiver
* tree has been selected
*
*/
private void buildForReceiversRoot() {
JMenuItem startAll = new JMenuItem(startAllAction);
add(newReceiverButtonAction);
addSeparator();
add(startAll);
}
private JMenuItem createNotDoneYet() {
final JMenuItem notDoneYet = new JMenuItem("Not Implemented Yet, sorry");
notDoneYet.setEnabled(false);
return notDoneYet;
}
}
/**
* A simple Panel that has toolbar buttons for restarting,
* playing, pausing, and stoping receivers
*
* @author Paul Smith <psmith@apache.org>
*
*/
private class ReceiverToolbar extends JToolBar
implements TreeSelectionListener {
final SmallButton newReceiverButton;
private ReceiverToolbar() {
setFloatable(false);
SmallButton playReceiverButton =
new SmallButton(playReceiverButtonAction);
playReceiverButton.setText(null);
SmallButton pauseReceiverButton =
new SmallButton(pauseReceiverButtonAction);
pauseReceiverButton.setText(null);
SmallButton shutdownReceiverButton =
new SmallButton(shutdownReceiverButtonAction);
shutdownReceiverButton.setText(null);
SmallButton restartAllButton = new SmallButton(startAllAction);
restartAllButton.setText(null);
newReceiverButton = new SmallButton(newReceiverButtonAction);
newReceiverButton.setText(null);
newReceiverButton.addMouseListener(new PopupListener(newReceiverPopup));
add(newReceiverButton);
addSeparator();
add(playReceiverButton);
add(pauseReceiverButton);
add(shutdownReceiverButton);
addSeparator();
add(restartAllButton);
Action closeAction =
new AbstractAction(null, LineIconFactory.createCloseIcon()) {
public void actionPerformed(ActionEvent e) {
ReceiversPanel.this.setVisible(false);
}
};
closeAction.putValue(
Action.SHORT_DESCRIPTION, "Closes the Receiver panel");
add(Box.createHorizontalGlue());
add(new SmallButton(closeAction));
add(Box.createHorizontalStrut(5));
}
/**
* Ensures the enabled property of the actions is set properly
* according to the currently selected node in the tree
*/
public void valueChanged(TreeSelectionEvent e) {
updateActions();
}
}
}
|
package org.kane.base.io.benchmark;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.kane.base.immutability.StandardImmutableObject;
import org.kane.base.io.GZIPUtils;
import org.kane.base.io.SmallDocumentReader;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.BucketVersioningConfiguration;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.SetBucketVersioningConfigurationRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import com.amazonaws.util.StringUtils;
public class S3Benchmark
{
static private final String BUCKET_NAME = "rws-dev-jimmutable-s3-benchmark-us-west-2";
static private final String EXPERIMENT_NAME = "first";
static public void loadFilesFromS3() throws Exception
{
}
static public void uploadFilesToS3(File src) throws Exception
{
System.out.println("Uploading objects into s3");
System.out.println(String.format("Source file: %s", src.getAbsolutePath()));
System.out.println(String.format("Destination Bucket: %s, experiment name: %s", BUCKET_NAME, EXPERIMENT_NAME));
System.out.println();
AmazonS3Client client = new AmazonS3Client(AWSAPIKeys.getAWSCredentialsDev());
client.setRegion(Region.getRegion(Regions.US_WEST_2));
//upsertBucket(client,BUCKET_NAME);
InputStream in_raw = GZIPUtils.gunzipStreamIfNeeded(new FileInputStream(src));
Reader reader_raw = new BufferedReader(new InputStreamReader(in_raw,"UTF-8"));
SmallDocumentReader reader = new SmallDocumentReader(reader_raw);
long t1 = System.currentTimeMillis();
TransferManager manager = new TransferManager(AWSAPIKeys.getAWSCredentialsDev());
List<Upload> in_progress = new ArrayList();
for ( int i = 0; i < 100_000; i++ )
{
reader.readNextDocument();
TestObjectProductData data = (TestObjectProductData)StandardImmutableObject.fromXML(reader.getCurrentDocument(null));
PutObjectRequest request = createRequest(data);
Upload upload = manager.upload(request);
in_progress.add(upload);
}
System.out.println(String.format("Requests Created! Created %,d PutObjectRequest(s) objects in %,d ms", in_progress.size(), System.currentTimeMillis()-t1));
System.out.println();
while(true)
{
int complete_count = getCompleteCount(in_progress);
if ( complete_count >= in_progress.size() )
break;
System.out.println(String.format("Uploaded %,d objects in %,d ms", complete_count, System.currentTimeMillis()-t1));
Thread.currentThread().sleep(500);
}
manager.shutdownNow();
System.out.println();
System.out.println(String.format("Finished! Uploaded %,d objects in %,d ms", in_progress.size(), System.currentTimeMillis()-t1));
System.exit(0);
}
static private int getCompleteCount(List<Upload> uploads)
{
int count = 0;
for ( Upload upload : uploads )
{
if ( upload.isDone() )
count++;
}
return count;
}
static private PutObjectRequest createRequest(TestObjectProductData data)
{
byte[] contentBytes = data.toXML().getBytes(StringUtils.UTF8);
InputStream is = new ByteArrayInputStream(contentBytes);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType("text/plain");
metadata.setContentLength(contentBytes.length);
return new PutObjectRequest(BUCKET_NAME, getS3ObjectKey(data), is, metadata);
}
static private String getS3ObjectKey(TestObjectProductData data)
{
return String.format("%s/%s/%s.xml", EXPERIMENT_NAME, data.getSimpleBrandCode(), data.getSimplePN());
}
static private void upsertBucket(AmazonS3Client client, String bucket_name)
{
CreateBucketRequest request = new CreateBucketRequest(bucket_name);
request.setRegion(Regions.US_WEST_2.getName());
client.createBucket(request);
System.out.println("Created: "+bucket_name);
// Turn versioning on
{
BucketVersioningConfiguration bvc = new BucketVersioningConfiguration(BucketVersioningConfiguration.ENABLED);
client.setBucketVersioningConfiguration(new SetBucketVersioningConfigurationRequest(bucket_name, bvc));
System.out.println("turned versioning on: "+bucket_name);
}
}
}
|
package com.yahoo.vespa.model;
import com.yahoo.config.ConfigBuilder;
import com.yahoo.config.ConfigInstance;
import com.yahoo.config.ConfigurationRuntimeException;
import com.yahoo.config.codegen.CNode;
import com.yahoo.config.codegen.ConfigGenerator;
import com.yahoo.config.codegen.InnerCNode;
import com.yahoo.config.codegen.LeafCNode;
import com.yahoo.log.LogLevel;
import com.yahoo.vespa.config.ConfigDefinitionKey;
import com.yahoo.vespa.config.ConfigKey;
import com.yahoo.vespa.config.ConfigPayload;
import com.yahoo.vespa.config.ConfigPayloadBuilder;
import com.yahoo.vespa.config.ConfigTransformer;
import com.yahoo.vespa.config.GenericConfig;
import com.yahoo.vespa.config.buildergen.ConfigDefinition;
import com.yahoo.yolean.Exceptions;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* <p>
* This class is capable of resolving config from a config model for a given request. It will handle
* incompatibilities of the def version in the request and the version of the config classes the model
* is using.
* </p>
* <p>
* This class is agnostic of transport protocol and server implementation.
* </p>
* <p>
* Thread safe.
* </p>
*
* @author vegardh
* @since 5.1.5
*/
// TODO This functionality should be on VespaModel itself, but we don't have a way right now to apply a config override to a ConfigInstance.Builder
class InstanceResolver {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(InstanceResolver.class.getName());
/**
* Resolves this config key into a correctly typed ConfigInstance using the given config builder.
* FIXME: Make private once config overrides are deprecated.?
*
* @param key a ConfigKey
* @param builder a ConfigBuilder to create the instance from.
* @param targetDef the def to use
* @return the config instance or null of no producer for this found in model
*/
static ConfigInstance resolveToInstance(ConfigKey<?> key, ConfigBuilder builder, InnerCNode targetDef) {
ConfigDefinitionKey defKey = new ConfigDefinitionKey(key);
try {
if (targetDef != null) applyDef(builder, targetDef);
ConfigInstance instance = getInstance(defKey, builder.getClass().getClassLoader());
Class<? extends ConfigInstance> clazz = instance.getClass();
return clazz.getConstructor(new Class<?>[]{builder.getClass()}).newInstance(builder);
} catch (Exception e) {
throw new ConfigurationRuntimeException(e);
}
}
/**
* Resolves this config key into a correctly typed ConfigBuilder using the given config model.
* FIXME: Make private once config overrides are deprecated.?
*
* @return the config builder or null if no producer for this found in model
*/
static ConfigBuilder resolveToBuilder(ConfigKey<?> key, VespaModel model, ConfigDefinition targetDef) {
if (model == null) return null;
ConfigDefinitionKey defKey = new ConfigDefinitionKey(key);
ConfigInstance.Builder builder = model.createBuilder(defKey, targetDef);
model.getConfig(builder, key.getConfigId());
return builder;
}
/**
* If some fields on the builder are null now, set them from the def. Do recursively.
* <p>
* If the targetDef has some schema incompatibilities, they are not handled here
* (except logging in some cases), but in ConfigInstance.serialize().
*
* @param builder a {@link com.yahoo.config.ConfigBuilder}
* @param targetDef a config definition
* @throws Exception if applying values form config definitions fails
*/
static void applyDef(ConfigBuilder builder, InnerCNode targetDef) throws Exception {
for (Map.Entry<String, CNode> e: targetDef.children().entrySet()) {
CNode node = e.getValue();
if (node instanceof LeafCNode) {
setLeafValueIfUnset(targetDef, builder, (LeafCNode)node);
} else if (node instanceof InnerCNode) {
// Is there a private field on the builder that matches this inner node in the def?
if (hasField(builder.getClass(), node.getName())) {
Field innerField = builder.getClass().getDeclaredField(node.getName());
innerField.setAccessible(true);
Object innerFieldVal = innerField.get(builder);
if (innerFieldVal instanceof List) {
// inner array? Check that list elems are ConfigBuilder
List<?> innerList = (List<?>) innerFieldVal;
for (Object b : innerList) {
if (b instanceof ConfigBuilder) {
applyDef((ConfigBuilder) b, (InnerCNode) node);
}
}
} else if (innerFieldVal instanceof ConfigBuilder) {
// Struct perhaps
applyDef((ConfigBuilder) innerFieldVal, (InnerCNode) node);
} else {
// Likely a config value mismatch. That is handled in ConfigInstance.serialize() (error message, omit from response.)
}
}
}
}
}
private static boolean hasField(Class<?> aClass, String name) {
for (Field field : aClass.getDeclaredFields()) {
if (name.equals(field.getName())) {
return true;
}
}
return false;
}
private static void setLeafValueIfUnset(InnerCNode targetDef, Object builder, LeafCNode node) throws Exception {
if (hasField(builder.getClass(), node.getName())) {
Field field = builder.getClass().getDeclaredField(node.getName());
field.setAccessible(true);
Object val = field.get(builder);
if (val==null) {
// Not set on builder, if the leaf node has a default value, try the private setter that takes String
try {
if (node.getDefaultValue()!=null) {
Method setter = builder.getClass().getDeclaredMethod(node.getName(), String.class);
setter.setAccessible(true);
setter.invoke(builder, node.getDefaultValue().getValue());
}
} catch (Exception e) {
log.severe("For config '"+targetDef.getFullName()+"': Unable to apply the default value for field '"+node.getName()+
"' to config Builder (where it wasn't set): "+
Exceptions.toMessageString(e));
}
}
}
}
/**
* Returns a {@link ConfigInstance} of right type for given key using reflection
*
* @param cKey a ConfigKey
* @return a {@link ConfigInstance} or null if not available in classpath
*/
private static ConfigInstance getInstance(ConfigDefinitionKey cKey, ClassLoader instanceLoader) {
String className = ConfigGenerator.createClassName(cKey.getName());
Class<?> clazz;
String fullClassName = packageName(cKey) + "." + className;
try {
clazz = instanceLoader != null ? instanceLoader.loadClass(fullClassName) : Class.forName(fullClassName);
} catch (ClassNotFoundException e) {
return null;
}
Object i;
try {
Constructor<?> configConstructor = clazz.getDeclaredConstructor();
configConstructor.setAccessible(true);
i = configConstructor.newInstance();
} catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) {
throw new ConfigurationRuntimeException(e);
}
if (!(i instanceof ConfigInstance)) {
throw new ConfigurationRuntimeException(fullClassName + " is not a ConfigInstance, can not produce config for the name '" + cKey.getName() + "'.");
}
return (ConfigInstance) i;
}
static String packageName(ConfigDefinitionKey cKey) {
String prefix = "com.yahoo.";
return prefix + (cKey.getNamespace().isEmpty() ? CNode.DEFAULT_NAMESPACE : cKey.getNamespace());
}
}
|
package org.tuckey.web.filters.urlrewrite;
import org.tuckey.web.filters.urlrewrite.utils.Log;
import org.tuckey.web.filters.urlrewrite.utils.ModRewriteConfLoader;
import org.tuckey.web.filters.urlrewrite.utils.NumberUtils;
import org.tuckey.web.filters.urlrewrite.utils.ServerNameMatcher;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Properties;
public class UrlRewriteFilter implements Filter {
private static Log log = Log.getLog(UrlRewriteFilter.class);
public static final String VERSION = "3.2.0";
public static final String DEFAULT_WEB_CONF_PATH = "/WEB-INF/urlrewrite.xml";
/**
* The conf for this filter.
*/
private UrlRewriter urlRewriter = null;
/**
* A user defined setting that can enable conf reloading.
*/
private boolean confReloadCheckEnabled = false;
/**
* A user defined setting that says how often to check the conf has changed.
*/
private int confReloadCheckInterval = 0;
/**
* A user defined setting that will allow configuration to be swapped via an HTTP to rewrite-status.
*/
private boolean allowConfSwapViaHttp = false;
/**
* The last time that the conf file was loaded.
*/
private long confLastLoad = 0;
private Conf confLastLoaded = null;
private long confReloadLastCheck = 30;
private boolean confLoadedFromFile = true;
/**
* path to conf file.
*/
private String confPath;
/**
* Flag to make sure we don't bog the filter down during heavy load.
*/
private boolean confReloadInProgress = false;
private boolean statusEnabled = true;
private String statusPath = "/rewrite-status";
private boolean modRewriteStyleConf = false;
public static final String DEFAULT_MOD_REWRITE_STYLE_CONF_PATH = "/WEB-INF/.htaccess";
private ServerNameMatcher statusServerNameMatcher;
private static final String DEFAULT_STATUS_ENABLED_ON_HOSTS = "localhost, local, 127.0.0.1";
private ServletContext context = null;
/**
* Init is called automatically by the application server when it creates this filter.
*
* @param filterConfig The config of the filter
*/
public void init(final FilterConfig filterConfig) throws ServletException {
log.debug("filter init called");
if (filterConfig == null) {
log.error("unable to init filter as filter config is null");
return;
}
log.debug("init: calling destroy just in case we are being re-inited uncleanly");
destroyActual();
context = filterConfig.getServletContext();
if (context == null) {
log.error("unable to init as servlet context is null");
return;
}
// set the conf of the logger to make sure we get the messages in context log
Log.setConfiguration(filterConfig);
// get init paramerers from context web.xml file
String confReloadCheckIntervalStr = filterConfig.getInitParameter("confReloadCheckInterval");
String confPathStr = filterConfig.getInitParameter("confPath");
String statusPathConf = filterConfig.getInitParameter("statusPath");
String statusEnabledConf = filterConfig.getInitParameter("statusEnabled");
String statusEnabledOnHosts = filterConfig.getInitParameter("statusEnabledOnHosts");
String allowConfSwapViaHttpStr = filterConfig.getInitParameter("allowConfSwapViaHttp");
if (!StringUtils.isBlank(allowConfSwapViaHttpStr)) {
allowConfSwapViaHttp = "true".equalsIgnoreCase(allowConfSwapViaHttpStr);
}
// confReloadCheckInterval (default to null)
if (!StringUtils.isBlank(confReloadCheckIntervalStr)) {
// convert to millis
confReloadCheckInterval = 1000 * NumberUtils.stringToInt(confReloadCheckIntervalStr);
if (confReloadCheckInterval < 0) {
confReloadCheckEnabled = false;
log.info("conf reload check disabled");
} else if (confReloadCheckInterval == 0) {
confReloadCheckEnabled = true;
log.info("conf reload check performed each request");
} else {
confReloadCheckEnabled = true;
log.info("conf reload check set to " + confReloadCheckInterval / 1000 + "s");
}
} else {
confReloadCheckEnabled = false;
}
String modRewriteConf = filterConfig.getInitParameter("modRewriteConf");
if (!StringUtils.isBlank(modRewriteConf)) {
modRewriteStyleConf = "true".equals(StringUtils.trim(modRewriteConf).toLowerCase());
}
if (!StringUtils.isBlank(confPathStr)) {
confPath = StringUtils.trim(confPathStr);
} else {
confPath = modRewriteStyleConf ? DEFAULT_MOD_REWRITE_STYLE_CONF_PATH : DEFAULT_WEB_CONF_PATH;
}
log.debug("confPath set to " + confPath);
// status enabled (default true)
if (statusEnabledConf != null && !"".equals(statusEnabledConf)) {
log.debug("statusEnabledConf set to " + statusEnabledConf);
statusEnabled = "true".equals(statusEnabledConf.toLowerCase());
}
if (statusEnabled) {
// status path (default /rewrite-status)
if (statusPathConf != null && !"".equals(statusPathConf)) {
statusPath = statusPathConf.trim();
log.info("status display enabled, path set to " + statusPath);
}
} else {
log.info("status display disabled");
}
if (StringUtils.isBlank(statusEnabledOnHosts)) {
statusEnabledOnHosts = DEFAULT_STATUS_ENABLED_ON_HOSTS;
} else {
log.debug("statusEnabledOnHosts set to " + statusEnabledOnHosts);
}
statusServerNameMatcher = new ServerNameMatcher(statusEnabledOnHosts);
// now load conf from snippet in web.xml if modRewriteStyleConf is set
String modRewriteConfText = filterConfig.getInitParameter("modRewriteConfText");
if (!StringUtils.isBlank(modRewriteConfText)) {
ModRewriteConfLoader loader = new ModRewriteConfLoader();
Conf conf = new Conf();
loader.process(modRewriteConfText, conf);
conf.initialise();
checkConf(conf);
confLoadedFromFile = false;
} else {
loadUrlRewriter(filterConfig);
}
}
/**
* Separate from init so that it can be overidden.
*/
protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
try {
loadUrlRewriterLocal();
} catch(Throwable e) {
log.error(e);
throw new ServletException(e);
}
}
private void loadUrlRewriterLocal() {
InputStream inputStream = context.getResourceAsStream(confPath);
// attempt to retrieve from location other than local WEB-INF
if ( inputStream == null ) {
inputStream = ClassLoader.getSystemResourceAsStream(confPath);
}
URL confUrl = null;
try {
confUrl = context.getResource(confPath);
} catch (MalformedURLException e) {
log.debug(e);
}
String confUrlStr = null;
if (confUrl != null) {
confUrlStr = confUrl.toString();
}
if (inputStream == null) {
log.error("unable to find urlrewrite conf file at " + confPath);
// set the writer back to null
if (urlRewriter != null) {
log.error("unloading existing conf");
urlRewriter = null;
}
} else {
Conf conf = new Conf(context, inputStream, confPath, confUrlStr, modRewriteStyleConf);
checkConf(conf);
}
}
/**
* Separate from checkConfLocal so that it can be overidden.
*/
protected void checkConf(Conf conf) {
checkConfLocal(conf);
}
private void checkConfLocal(Conf conf) {
if (log.isDebugEnabled()) {
if (conf.getRules() != null) {
log.debug("inited with " + conf.getRules().size() + " rules");
}
log.debug("conf is " + (conf.isOk() ? "ok" : "NOT ok"));
}
confLastLoaded = conf;
if (conf.isOk() && conf.isEngineEnabled()) {
urlRewriter = new UrlRewriter(conf);
log.info("loaded (conf ok)");
} else {
if (!conf.isOk()) {
log.error("Conf failed to load");
}
if (!conf.isEngineEnabled()) {
log.error("Engine explicitly disabled in conf"); // not really an error but we want ot to show in logs
}
if (urlRewriter != null) {
log.error("unloading existing conf");
urlRewriter = null;
}
}
}
/**
* Destroy is called by the application server when it unloads this filter.
*/
public void destroy() {
log.info("destroy called");
destroyActual();
}
public void destroyActual() {
destroyUrlRewriter();
context = null;
confLastLoad = 0;
confPath = DEFAULT_WEB_CONF_PATH;
confReloadCheckEnabled = false;
confReloadCheckInterval = 0;
confReloadInProgress = false;
}
protected void destroyUrlRewriter() {
if (urlRewriter != null) {
urlRewriter.destroy();
urlRewriter = null;
}
}
/**
* The main method called for each request that this filter is mapped for.
*
* @param request the request to filter
* @param response the response to filter
* @param chain the chain for the filtering
* @throws IOException
* @throws ServletException
*/
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
UrlRewriter urlRewriter = getUrlRewriter(request, response, chain);
final HttpServletRequest hsRequest = (HttpServletRequest) request;
final HttpServletResponse hsResponse = (HttpServletResponse) response;
UrlRewriteWrappedResponse urlRewriteWrappedResponse = new UrlRewriteWrappedResponse(hsResponse, hsRequest,
urlRewriter);
// check for status request
if (statusEnabled && statusServerNameMatcher.isMatch(request.getServerName())) {
String uri = hsRequest.getRequestURI();
if (log.isDebugEnabled()) {
log.debug("checking for status path on " + uri);
}
String contextPath = hsRequest.getContextPath();
if (uri != null && uri.startsWith(contextPath + statusPath)) {
showStatus(hsRequest, urlRewriteWrappedResponse);
return;
}
}
boolean requestRewritten = false;
if (urlRewriter != null) {
// process the request
requestRewritten = urlRewriter.processRequest(hsRequest, urlRewriteWrappedResponse, chain);
} else {
if (log.isDebugEnabled()) {
log.debug("urlRewriter engine not loaded ignoring request (could be a conf file problem)");
}
}
// if no rewrite has taken place continue as normal
if (!requestRewritten) {
chain.doFilter(hsRequest, urlRewriteWrappedResponse);
}
}
/**
* Called for every request.
* <p/>
* Split from doFilter so that it can be overriden.
*/
protected UrlRewriter getUrlRewriter(ServletRequest request, ServletResponse response, FilterChain chain) {
// check to see if the conf needs reloading
if (isTimeToReloadConf()) {
reloadConf();
}
return urlRewriter;
}
/**
* Is it time to reload the configuration now. Depends on is conf reloading is enabled.
*/
public boolean isTimeToReloadConf() {
if (!confLoadedFromFile) return false;
long now = System.currentTimeMillis();
return confReloadCheckEnabled && !confReloadInProgress && (now - confReloadCheckInterval) > confReloadLastCheck;
}
/**
* Forcibly reload the configuration now.
*/
public void reloadConf() {
long now = System.currentTimeMillis();
confReloadInProgress = true;
confReloadLastCheck = now;
log.debug("starting conf reload check");
long confFileCurrentTime = getConfFileLastModified();
if (confLastLoad < confFileCurrentTime) {
// reload conf
confLastLoad = System.currentTimeMillis();
log.info("conf file modified since last load, reloading");
loadUrlRewriterLocal();
} else {
log.debug("conf is not modified");
}
confReloadInProgress = false;
}
/**
* Gets the last modified date of the conf file.
*
* @return time as a long
*/
private long getConfFileLastModified() {
File confFile = new File(context.getRealPath(confPath));
return confFile.lastModified();
}
/**
* Show the status of the conf and the filter to the user.
*
* @param request to get status info from
* @param response response to show the status on.
* @throws java.io.IOException if the output cannot be written
*/
private void showStatus(final HttpServletRequest request, final ServletResponse response)
throws IOException {
log.debug("showing status");
if ( allowConfSwapViaHttp ) {
String newConfPath = request.getParameter("conf");
if ( !StringUtils.isBlank(newConfPath)) {
confPath = newConfPath;
loadUrlRewriterLocal();
}
}
Status status = new Status(confLastLoaded, this);
status.displayStatusInContainer(request);
response.setContentType("text/html; charset=UTF-8");
response.setContentLength(status.getBuffer().length());
final PrintWriter out = response.getWriter();
out.write(status.getBuffer().toString());
out.close();
}
public boolean isConfReloadCheckEnabled() {
return confReloadCheckEnabled;
}
/**
* The amount of seconds between reload checks.
*
* @return int number of millis
*/
public int getConfReloadCheckInterval() {
return confReloadCheckInterval / 1000;
}
public Date getConfReloadLastCheck() {
return new Date(confReloadLastCheck);
}
public boolean isStatusEnabled() {
return statusEnabled;
}
public String getStatusPath() {
return statusPath;
}
public boolean isLoaded() {
return urlRewriter != null;
}
public static String getFullVersionString() {
Properties props = new Properties();
String buildNumberStr = "";
try {
InputStream is = UrlRewriteFilter.class.getResourceAsStream("build.number.properties");
if ( is != null ) {
props.load(is);
String buildNumber = (String) props.get("build.number");
if (!StringUtils.isBlank(buildNumber)){
buildNumberStr = " build " + props.get("build.number");
}
}
} catch (IOException e) {
log.error(e);
}
return VERSION + buildNumberStr;
}
}
|
package io.spine.validate;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.Message;
import com.google.protobuf.ProtocolStringList;
import com.google.protobuf.StringValue;
import com.google.protobuf.Timestamp;
import io.spine.base.FieldPath;
import io.spine.option.OptionsProto;
import io.spine.option.Time;
import io.spine.protobuf.AnyPacker;
import io.spine.test.validate.AggregateState;
import io.spine.test.validate.CustomMessageRequiredByteStringFieldValue;
import io.spine.test.validate.CustomMessageRequiredEnumFieldValue;
import io.spine.test.validate.CustomMessageRequiredMsgFieldValue;
import io.spine.test.validate.CustomMessageRequiredRepeatedMsgFieldValue;
import io.spine.test.validate.CustomMessageRequiredStringFieldValue;
import io.spine.test.validate.CustomMessageWithNoRequiredOption;
import io.spine.test.validate.DecimalMaxIncNumberFieldValue;
import io.spine.test.validate.DecimalMaxNotIncNumberFieldValue;
import io.spine.test.validate.DecimalMinIncNumberFieldValue;
import io.spine.test.validate.DecimalMinNotIncNumberFieldValue;
import io.spine.test.validate.DigitsCountNumberFieldValue;
import io.spine.test.validate.EnclosedMessageFieldValue;
import io.spine.test.validate.EnclosedMessageFieldValueWithCustomInvalidMessage;
import io.spine.test.validate.EnclosedMessageFieldValueWithoutAnnotationFieldValueWithCustomInvalidMessage;
import io.spine.test.validate.EnclosedMessageWithRequiredString;
import io.spine.test.validate.EnclosedMessageWithoutAnnotationFieldValue;
import io.spine.test.validate.MaxNumberFieldValue;
import io.spine.test.validate.MinNumberFieldValue;
import io.spine.test.validate.PatternStringFieldValue;
import io.spine.test.validate.ProjectionState;
import io.spine.test.validate.RepeatedRequiredMsgFieldValue;
import io.spine.test.validate.RequiredBooleanFieldValue;
import io.spine.test.validate.RequiredByteStringFieldValue;
import io.spine.test.validate.RequiredEnumFieldValue;
import io.spine.test.validate.RequiredMsgFieldValue;
import io.spine.test.validate.RequiredStringFieldValue;
import io.spine.test.validate.TimeInFutureFieldValue;
import io.spine.test.validate.TimeInPastFieldValue;
import io.spine.test.validate.TimeWithoutOptsFieldValue;
import io.spine.test.validate.anyfields.AnyContainer;
import io.spine.test.validate.anyfields.UncheckedAnyContainer;
import io.spine.test.validate.command.EntityIdByteStringFieldValue;
import io.spine.test.validate.command.EntityIdDoubleFieldValue;
import io.spine.test.validate.command.EntityIdIntFieldValue;
import io.spine.test.validate.command.EntityIdLongFieldValue;
import io.spine.test.validate.command.EntityIdMsgFieldValue;
import io.spine.test.validate.command.EntityIdRepeatedFieldValue;
import io.spine.test.validate.command.EntityIdStringFieldValue;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.List;
import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.truth.Truth.assertThat;
import static com.google.protobuf.util.Timestamps.add;
import static com.google.protobuf.util.Timestamps.subtract;
import static io.spine.base.Identifier.newUuid;
import static io.spine.base.Time.getCurrentTime;
import static io.spine.protobuf.TypeConverter.toMessage;
import static io.spine.validate.MessageValidatorTestEnv.FIFTY_NANOSECONDS;
import static io.spine.validate.MessageValidatorTestEnv.SECONDS_IN_5_MINUTES;
import static io.spine.validate.MessageValidatorTestEnv.ZERO_NANOSECONDS;
import static io.spine.validate.MessageValidatorTestEnv.currentTimeWithNanos;
import static io.spine.validate.MessageValidatorTestEnv.freezeTime;
import static io.spine.validate.MessageValidatorTestEnv.timeWithNanos;
import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SuppressWarnings({"ClassWithTooManyMethods", "OverlyCoupledClass", "OverlyComplexClass"})
@DisplayName("MessageValidator should")
class MessageValidatorTest {
private static final double EQUAL_MIN = 16.5;
private static final double GREATER_THAN_MIN = EQUAL_MIN + 5;
private static final double LESS_THAN_MIN = EQUAL_MIN - 5;
private static final double EQUAL_MAX = 64.5;
private static final double GREATER_THAN_MAX = EQUAL_MAX + 5;
private static final double LESS_THAN_MAX = EQUAL_MAX - 5;
private static final double INT_DIGIT_COUNT_GREATER_THAN_MAX = 123.5;
private static final double INT_DIGIT_COUNT_EQUAL_MAX = 12.5;
private static final double INT_DIGIT_COUNT_LESS_THAN_MAX = 1.5;
private static final double FRACTIONAL_DIGIT_COUNT_GREATER_THAN_MAX = 1.123;
private static final double FRACTIONAL_DIGIT_COUNT_EQUAL_MAX = 1.12;
private static final double FRACTIONAL_DIGIT_COUNT_LESS_THAN_MAX = 1.0;
@SuppressWarnings("DuplicateStringLiteralInspection")
private static final String VALUE = "value";
private static final String EMAIL = "email";
private static final String OUTER_MSG_FIELD = "outer_msg_field";
private static final String NO_VALUE_MSG = "Value must be set.";
private static final String LESS_THAN_MIN_MSG = "Number must be greater than or equal to 16.5.";
private static final String GREATER_MAX_MSG = "Number must be less than or equal to 64.5.";
private static final String MATCH_REGEXP_MSG = "String must match the regular expression '%s'.";
private final MessageValidator validator = MessageValidator.newInstance();
private List<ConstraintViolation> violations;
/*
* Required option tests.
*/
@Test
@DisplayName("find out that required Message field is set")
void find_out_that_required_Message_field_is_set() {
RequiredMsgFieldValue validMsg = RequiredMsgFieldValue
.newBuilder()
.setValue(newStringValue())
.build();
validate(validMsg);
assertIsValid(true);
}
@Test
@DisplayName("find out that required message field is NOT set")
void find_out_that_required_Message_field_is_NOT_set() {
RequiredMsgFieldValue invalidMsg = RequiredMsgFieldValue.getDefaultInstance();
validate(invalidMsg);
assertIsValid(false);
}
@Test
@DisplayName("find out that required String field is set")
void find_out_that_required_String_field_is_set() {
RequiredStringFieldValue validMsg = RequiredStringFieldValue.newBuilder()
.setValue(newUuid())
.build();
validate(validMsg);
assertIsValid(true);
}
@Test
@DisplayName("find out that required String field is NOT set")
void find_out_that_required_String_field_is_NOT_set() {
RequiredStringFieldValue invalidMsg = RequiredStringFieldValue.getDefaultInstance();
validate(invalidMsg);
assertIsValid(false);
}
@Test
@DisplayName("find out that required ByteString field is set")
void find_out_that_required_ByteString_field_is_set() {
RequiredByteStringFieldValue validMsg =
RequiredByteStringFieldValue.newBuilder()
.setValue(newByteString())
.build();
validate(validMsg);
assertIsValid(true);
}
@Test
@DisplayName("find out that required ByteString field is NOT set")
void find_out_that_required_ByteString_field_is_NOT_set() {
RequiredByteStringFieldValue invalidMsg = RequiredByteStringFieldValue.getDefaultInstance();
validate(invalidMsg);
assertIsValid(false);
}
@Test
@DisplayName("find out that required Enum field is set")
void find_out_that_required_Enum_field_is_NOT_set() {
RequiredEnumFieldValue invalidMsg = RequiredEnumFieldValue.getDefaultInstance();
validate(invalidMsg);
assertIsValid(false);
}
@Test
@DisplayName("find out that required Enum field is NOT set")
void find_out_that_required_Enum_field_is_set() {
RequiredEnumFieldValue invalidMsg = RequiredEnumFieldValue.newBuilder()
.setValue(Time.FUTURE)
.build();
validate(invalidMsg);
assertIsValid(true);
}
@Test
@DisplayName("find out that required NOT set Boolean field passes validation")
void find_out_that_required_NOT_set_Boolean_field_pass_validation() {
validate(RequiredBooleanFieldValue.getDefaultInstance());
assertIsValid(true);
}
@Test
@DisplayName("find out that repeated required field has valid values")
void find_out_that_repeated_required_field_has_valid_values() {
RepeatedRequiredMsgFieldValue invalidMsg =
RepeatedRequiredMsgFieldValue.newBuilder()
.addValue(newStringValue())
.addValue(newStringValue())
.build();
validate(invalidMsg);
assertIsValid(true);
}
@Test
@DisplayName("find out that repeated required field has not values")
void find_out_that_repeated_required_field_has_no_values() {
validate(RepeatedRequiredMsgFieldValue.getDefaultInstance());
assertIsValid(false);
}
@Test
@DisplayName("ignore repeated required field with an empty value")
void ignore_repeated_required_field_with_empty_value() {
RepeatedRequiredMsgFieldValue msg =
RepeatedRequiredMsgFieldValue.newBuilder()
.addValue(newStringValue()) // valid value
.addValue(
StringValue.getDefaultInstance()) // empty value
.build();
validate(msg);
assertIsValid(true);
}
@Test
@DisplayName("consider field is valid if no required option set")
void consider_field_is_valid_if_no_required_option_set() {
validate(StringValue.getDefaultInstance());
assertIsValid(true);
}
@Test
@DisplayName("provide one valid violation if required field is NOT set")
void provide_one_valid_violation_if_required_field_is_NOT_set() {
RequiredStringFieldValue invalidMsg = RequiredStringFieldValue.getDefaultInstance();
validate(invalidMsg);
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals(NO_VALUE_MSG, violation.getMsgFormat());
assertFieldPathIs(violation, VALUE);
assertTrue(violation.getViolationList()
.isEmpty());
}
@Test
@DisplayName("propagate proper error message if custom message set and required Message field is NOT set")
void propagate_proper_error_message_if_custom_message_set_and_required_Message_field_is_NOT_set() {
CustomMessageRequiredMsgFieldValue invalidMsg =
CustomMessageRequiredMsgFieldValue.getDefaultInstance();
String expectedMessage =
getCustomErrorMessage(CustomMessageRequiredMsgFieldValue.getDescriptor());
validate(invalidMsg);
assertIsValid(false);
checkErrorMessage(expectedMessage);
}
@Test
@DisplayName("propagate proper error message if custom message set and required String field is NOT set")
void propagate_proper_error_message_if_custom_message_set_and_required_String_field_is_NOT_set() {
CustomMessageRequiredStringFieldValue invalidMsg =
CustomMessageRequiredStringFieldValue.getDefaultInstance();
String expectedMessage = getCustomErrorMessage(
CustomMessageRequiredStringFieldValue.getDescriptor());
validate(invalidMsg);
assertIsValid(false);
checkErrorMessage(expectedMessage);
}
@Test
@DisplayName("propagate proper error message if custom message set and required ByteString field is NOT set")
void propagate_proper_error_message_if_custom_message_set_and_required_ByteString_field_is_NOT_set() {
CustomMessageRequiredByteStringFieldValue invalidMsg =
CustomMessageRequiredByteStringFieldValue.getDefaultInstance();
String expectedMessage =
getCustomErrorMessage(CustomMessageRequiredByteStringFieldValue.getDescriptor());
validate(invalidMsg);
assertIsValid(false);
checkErrorMessage(expectedMessage);
}
@Test
@DisplayName("propagate proper error message if custom message set and required repeated field is NOT set")
void propagate_proper_error_message_if_custom_message_set_and_required_RepeatedMsg_field_is_NOT_set() {
CustomMessageRequiredRepeatedMsgFieldValue invalidMsg =
CustomMessageRequiredRepeatedMsgFieldValue.getDefaultInstance();
String expectedMessage =
getCustomErrorMessage(CustomMessageRequiredRepeatedMsgFieldValue.getDescriptor());
validate(invalidMsg);
assertIsValid(false);
checkErrorMessage(expectedMessage);
}
@Test
@DisplayName("propagate proper error message if custom message set and required Enum field is NOT set")
void propagate_proper_error_message_if_custom_message_set_and_required_Enum_field_is_NOT_set() {
CustomMessageRequiredEnumFieldValue invalidMsg =
CustomMessageRequiredEnumFieldValue.getDefaultInstance();
String expectedMessage =
getCustomErrorMessage(CustomMessageRequiredEnumFieldValue.getDescriptor());
validate(invalidMsg);
assertIsValid(false);
checkErrorMessage(expectedMessage);
}
@Test
@DisplayName("ignore IfMissingOption if field is not marked required")
void ignore_if_missing_option_if_field_not_marked_required() {
CustomMessageWithNoRequiredOption invalidMsg =
CustomMessageWithNoRequiredOption.getDefaultInstance();
validate(invalidMsg);
assertIsValid(true);
assertTrue(violations.isEmpty());
}
private void checkErrorMessage(String expectedMessage) {
ConstraintViolation constraintViolation = firstViolation();
assertEquals(expectedMessage, constraintViolation.getMsgFormat());
}
private static String getCustomErrorMessage(Descriptors.Descriptor descriptor) {
Descriptors.FieldDescriptor firstFieldDescriptor = descriptor.getFields()
.get(0);
return firstFieldDescriptor.getOptions()
.getExtension(OptionsProto.ifMissing)
.getMsgFormat();
}
/*
* Time option tests.
*/
@Test
@DisplayName("find out that time is in future")
void find_out_that_time_is_in_future() {
TimeInFutureFieldValue validMsg = TimeInFutureFieldValue.newBuilder()
.setValue(getFuture())
.build();
validate(validMsg);
assertIsValid(true);
}
@Test
@DisplayName("find out that time is NOT in future")
void find_out_that_time_is_NOT_in_future() {
TimeInFutureFieldValue invalidMsg = TimeInFutureFieldValue.newBuilder()
.setValue(getPast())
.build();
validate(invalidMsg);
assertIsValid(false);
}
@Test
@DisplayName("find out that time is in past")
void find_out_that_time_is_in_past() {
TimeInPastFieldValue validMsg = TimeInPastFieldValue.newBuilder()
.setValue(getPast())
.build();
validate(validMsg);
assertIsValid(true);
}
@Test
@DisplayName("find out that time is NOT in past")
void find_out_that_time_is_NOT_in_past() {
TimeInPastFieldValue invalidMsg = TimeInPastFieldValue.newBuilder()
.setValue(getFuture())
.build();
validate(invalidMsg);
assertIsValid(false);
}
@Test
@DisplayName("find out that time is NOT in the past by nanoseconds")
void find_out_that_time_is_NOT_in_the_past_by_nanos() {
Timestamp currentTime = currentTimeWithNanos(ZERO_NANOSECONDS);
Timestamp timeInFuture = timeWithNanos(currentTime, FIFTY_NANOSECONDS);
freezeTime(currentTime);
TimeInPastFieldValue invalidMsg =
TimeInPastFieldValue.newBuilder()
.setValue(timeInFuture)
.build();
validate(invalidMsg);
assertIsValid(false);
}
@Test
@DisplayName("find out that time is in the past by nanoseconds")
void find_out_that_time_is_in_the_past_by_nanos() {
Timestamp currentTime = currentTimeWithNanos(FIFTY_NANOSECONDS);
Timestamp timeInPast = timeWithNanos(currentTime, ZERO_NANOSECONDS);
freezeTime(currentTime);
TimeInPastFieldValue invalidMsg =
TimeInPastFieldValue.newBuilder()
.setValue(timeInPast)
.build();
validate(invalidMsg);
assertIsValid(true);
}
@Test
@DisplayName("consider Timestamp field valid if no TimeOption set")
void consider_timestamp_field_is_valid_if_no_time_option_set() {
validate(TimeWithoutOptsFieldValue.getDefaultInstance());
assertIsValid(true);
}
@Test
@DisplayName("provide one valid violation if time is invalid")
void provide_one_valid_violation_if_time_is_invalid() {
TimeInFutureFieldValue invalidMsg = TimeInFutureFieldValue.newBuilder()
.setValue(getPast())
.build();
validate(invalidMsg);
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals(
"Timestamp value must be in the future.",
format(firstViolation().getMsgFormat(), firstViolation().getParam(0))
);
assertFieldPathIs(violation, VALUE);
assertTrue(violation.getViolationList()
.isEmpty());
}
/*
* `google.protobuf.Any` field tests.
*/
@Test
@DisplayName("consider Any valid if content is valid")
void consider_Any_valid_if_content_is_valid() {
RequiredMsgFieldValue value = RequiredMsgFieldValue
.newBuilder()
.setValue(newStringValue())
.build();
Any content = AnyPacker.pack(value);
AnyContainer container = AnyContainer
.newBuilder()
.setAny(content)
.build();
validate(container);
assertIsValid(true);
}
@Test
@DisplayName("consider Any not valid if content is not valid")
void consider_Any_not_valid_if_content_is_not_valid() {
RequiredMsgFieldValue value = RequiredMsgFieldValue.getDefaultInstance();
Any content = AnyPacker.pack(value);
AnyContainer container = AnyContainer
.newBuilder()
.setAny(content)
.build();
validate(container);
assertIsValid(false);
}
@Test
@DisplayName("consider Any valid if validation is not required")
void consider_Any_valid_if_validation_is_not_required() {
RequiredMsgFieldValue value = RequiredMsgFieldValue.getDefaultInstance();
Any content = AnyPacker.pack(value);
UncheckedAnyContainer container = UncheckedAnyContainer
.newBuilder()
.setAny(content)
.build();
validate(container);
assertIsValid(true);
}
@Test
@DisplayName("validate recursive messages")
void validate_recursive_messages() {
RequiredMsgFieldValue value = RequiredMsgFieldValue.getDefaultInstance();
Any internalAny = AnyPacker.pack(value);
AnyContainer internal = AnyContainer
.newBuilder()
.setAny(internalAny)
.build();
Any externalAny = AnyPacker.pack(internal);
AnyContainer external = AnyContainer
.newBuilder()
.setAny(externalAny)
.build();
validate(external);
assertIsValid(false);
}
/*
* Decimal min option tests.
*/
@Test
@DisplayName("Consider number field is valid if no number options set")
void consider_number_field_is_valid_if_no_number_options_set() {
Message nonZeroValue = DoubleValue.newBuilder()
.setValue(5)
.build();
validate(nonZeroValue);
assertIsValid(true);
}
@Test
@DisplayName("find out that number is greater than decimal min inclusive")
void find_out_that_number_is_greater_than_decimal_min_inclusive() {
minDecimalNumberTest(GREATER_THAN_MIN, true, true);
}
@Test
@DisplayName("find out that number is equal to decimal min inclusive")
void find_out_that_number_is_equal_to_decimal_min_inclusive() {
minDecimalNumberTest(EQUAL_MIN, true, true);
}
@Test
@DisplayName("find out that number is less than decimal min inclusive")
void find_out_that_number_is_less_than_decimal_min_inclusive() {
minDecimalNumberTest(LESS_THAN_MIN, true, false);
}
@Test
@DisplayName("find out that number is grated than decimal min NOT inclusive")
void find_out_that_number_is_greater_than_decimal_min_NOT_inclusive() {
minDecimalNumberTest(GREATER_THAN_MIN, false, true);
}
@Test
@DisplayName("find out that number is equal to decimal min NOT inclusive")
void find_out_that_number_is_equal_to_decimal_min_NOT_inclusive() {
minDecimalNumberTest(EQUAL_MIN, false, false);
}
@Test
@DisplayName("find out that number is less than decimal min NOT inclusive")
void find_out_that_number_is_less_than_decimal_min_NOT_inclusive() {
minDecimalNumberTest(LESS_THAN_MIN, false, false);
}
@Test
@DisplayName("provide one valid violation if number is less than decimal min")
void provide_one_valid_violation_if_number_is_less_than_decimal_min() {
minDecimalNumberTest(LESS_THAN_MIN, true, false);
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals(LESS_THAN_MIN_MSG, format(violation.getMsgFormat(), violation.getParam(0),
violation.getParam(1)));
assertFieldPathIs(violation, VALUE);
assertTrue(violation.getViolationList()
.isEmpty());
}
/*
* Decimal max option tests.
*/
@Test
@DisplayName("find out that number is greater than decimal max inclusive")
void find_out_that_number_is_greater_than_decimal_max_inclusive() {
maxDecimalNumberTest(GREATER_THAN_MAX, true, false);
}
@Test
@DisplayName("find out that number is equal to decimal max inclusive")
void find_out_that_number_is_equal_to_decimal_max_inclusive() {
maxDecimalNumberTest(EQUAL_MAX, true, true);
}
@Test
@DisplayName("find out that number is less than decimal max inclusive")
void find_out_that_number_is_less_than_decimal_max_inclusive() {
maxDecimalNumberTest(LESS_THAN_MAX, true, true);
}
@Test
@DisplayName("find out that number is greated than decimal max NOT inclusive")
void find_out_that_number_is_greater_than_decimal_max_NOT_inclusive() {
maxDecimalNumberTest(GREATER_THAN_MAX, false, false);
}
@Test
@DisplayName("find out that number is equal to decimal max NOT inclusive")
void find_out_that_number_is_equal_to_decimal_max_NOT_inclusive() {
maxDecimalNumberTest(EQUAL_MAX, false, false);
}
@Test
@DisplayName("find out that number is less than decimal max NOT inclusive")
void find_out_that_number_is_less_than_decimal_max_NOT_inclusive() {
maxDecimalNumberTest(LESS_THAN_MAX, false, true);
}
@Test
@DisplayName("provide one valid violation if number is greater than decimal max")
void provide_one_valid_violation_if_number_is_greater_than_decimal_max() {
maxDecimalNumberTest(GREATER_THAN_MAX, true, false);
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals(GREATER_MAX_MSG, format(violation.getMsgFormat(), violation.getParam(0),
violation.getParam(1)));
assertFieldPathIs(violation, VALUE);
assertTrue(violation.getViolationList()
.isEmpty());
}
/*
* Min option tests.
*/
@Test
@DisplayName("find out that number is greater than min")
void find_out_that_number_is_greater_than_min() {
MinNumberFieldValue msg = MinNumberFieldValue.newBuilder()
.setValue(GREATER_THAN_MIN)
.build();
validate(msg);
assertIsValid(true);
}
@Test
@DisplayName("find out that number is equal to min")
void find_out_that_number_is_equal_to_min() {
MinNumberFieldValue msg = MinNumberFieldValue.newBuilder()
.setValue(EQUAL_MIN)
.build();
validate(msg);
assertIsValid(true);
}
@Test
@DisplayName("find out that number is less than min")
void find_out_that_number_is_less_than_min() {
MinNumberFieldValue msg = MinNumberFieldValue.newBuilder()
.setValue(LESS_THAN_MIN)
.build();
validate(msg);
assertIsValid(false);
}
@Test
@DisplayName("provide one valid violation if number is less than min")
void provide_one_valid_violation_if_number_is_less_than_min() {
MinNumberFieldValue msg = MinNumberFieldValue.newBuilder()
.setValue(LESS_THAN_MIN)
.build();
validate(msg);
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals(LESS_THAN_MIN_MSG, format(violation.getMsgFormat(), violation.getParam(0)));
assertFieldPathIs(violation, VALUE);
assertTrue(violation.getViolationList()
.isEmpty());
}
/*
* Max option tests.
*/
@Test
@DisplayName("find out that number is greater than max inclusive")
void find_out_that_number_is_greater_than_max_inclusive() {
MaxNumberFieldValue msg = MaxNumberFieldValue.newBuilder()
.setValue(GREATER_THAN_MAX)
.build();
validate(msg);
assertIsValid(false);
}
@Test
@DisplayName("find out that number is equal to max inclusive")
void find_out_that_number_is_equal_to_max_inclusive() {
MaxNumberFieldValue msg = MaxNumberFieldValue.newBuilder()
.setValue(EQUAL_MAX)
.build();
validate(msg);
assertIsValid(true);
}
@Test
@DisplayName("find out that number is less than max inclusive")
void find_out_that_number_is_less_than_max_inclusive() {
MaxNumberFieldValue msg = MaxNumberFieldValue.newBuilder()
.setValue(LESS_THAN_MAX)
.build();
validate(msg);
assertIsValid(true);
}
@Test
@DisplayName("provide one valid violation if number is greater than max")
void provide_one_valid_violation_if_number_is_greater_than_max() {
MaxNumberFieldValue msg = MaxNumberFieldValue.newBuilder()
.setValue(GREATER_THAN_MAX)
.build();
validate(msg);
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals(GREATER_MAX_MSG, format(violation.getMsgFormat(), violation.getParam(0)));
assertFieldPathIs(violation, VALUE);
assertTrue(violation.getViolationList()
.isEmpty());
}
/*
* Digits option tests.
*/
@Test
@DisplayName("find out that integral digit count is greater than max")
void find_out_that_integral_digit_count_is_greater_than_max() {
digitsCountTest(INT_DIGIT_COUNT_GREATER_THAN_MAX, false);
}
@Test
@DisplayName("find out that integral digits count is equal to max")
void find_out_that_integral_digits_count_is_equal_to_max() {
digitsCountTest(INT_DIGIT_COUNT_EQUAL_MAX, true);
}
@Test
@DisplayName("find out that integral digit count is less than max")
void find_out_that_integral_digit_count_is_less_than_max() {
digitsCountTest(INT_DIGIT_COUNT_LESS_THAN_MAX, true);
}
@Test
@DisplayName("find out that fractional digit count is greater than max")
void find_out_that_fractional_digit_count_is_greater_than_max() {
digitsCountTest(FRACTIONAL_DIGIT_COUNT_GREATER_THAN_MAX, false);
}
@Test
@DisplayName("find out that fractional digit count is equal to max")
void find_out_that_fractional_digit_count_is_equal_to_max() {
digitsCountTest(FRACTIONAL_DIGIT_COUNT_EQUAL_MAX, true);
}
@Test
@DisplayName("find out that fractional digit count is less than max")
void find_out_that_fractional_digit_count_is_less_than_max() {
digitsCountTest(FRACTIONAL_DIGIT_COUNT_LESS_THAN_MAX, true);
}
@Test
@DisplayName("provide one valid violation if integral digit count is greater than max")
void provide_one_valid_violation_if_integral_digit_count_is_greater_than_max() {
digitsCountTest(INT_DIGIT_COUNT_GREATER_THAN_MAX, false);
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals(
"Number value is out of bounds, expected: <2 max digits>.<2 max digits>.",
format(violation.getMsgFormat(), violation.getParam(0), violation.getParam(1))
);
assertFieldPathIs(violation, VALUE);
assertTrue(violation.getViolationList()
.isEmpty());
}
/*
* String pattern option tests.
*/
@Test
@DisplayName("find out that string matches to regex pattern")
void find_out_that_string_matches_to_regex_pattern() {
PatternStringFieldValue msg = PatternStringFieldValue.newBuilder()
.setEmail("valid.email@mail.com")
.build();
validate(msg);
assertIsValid(true);
}
@Test
@DisplayName("find out that string does not match to regex pattern")
void find_out_that_string_does_not_match_to_regex_pattern() {
PatternStringFieldValue msg = PatternStringFieldValue.newBuilder()
.setEmail("invalid email")
.build();
validate(msg);
assertIsValid(false);
}
@Test
@DisplayName("consider field is valid if PatternOption is not set")
void consider_field_is_valid_if_no_pattern_option_set() {
validate(StringValue.getDefaultInstance());
assertIsValid(true);
}
@Test
@DisplayName("provide one valid violation if string does not match to regex pattern")
void provide_one_valid_violation_if_string_does_not_match_to_regex_pattern() {
PatternStringFieldValue msg = PatternStringFieldValue.newBuilder()
.setEmail("invalid email")
.build();
validate(msg);
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals(MATCH_REGEXP_MSG, violation.getMsgFormat());
assertEquals(
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$",
firstViolation().getParam(0));
assertFieldPathIs(violation, EMAIL);
assertTrue(violation.getViolationList()
.isEmpty());
}
/*
* Enclosed message field validation option tests.
*/
@Test
@DisplayName("find out that enclosed message field is valid")
void find_out_that_enclosed_message_field_is_valid() {
PatternStringFieldValue enclosedMsg =
PatternStringFieldValue.newBuilder()
.setEmail("valid.email@mail.com")
.build();
EnclosedMessageFieldValue msg = EnclosedMessageFieldValue.newBuilder()
.setOuterMsgField(enclosedMsg)
.build();
validate(msg);
assertIsValid(true);
}
@Test
@DisplayName("find out enclosed message field is NOT valid")
void find_out_that_enclosed_message_field_is_NOT_valid() {
PatternStringFieldValue enclosedMsg = PatternStringFieldValue.newBuilder()
.setEmail("invalid email")
.build();
EnclosedMessageFieldValue msg = EnclosedMessageFieldValue.newBuilder()
.setOuterMsgField(enclosedMsg)
.build();
validate(msg);
assertIsValid(false);
}
@Test
@DisplayName("consider field valid if no valid option is set")
void consider_field_valid_if_no_valid_option_is_set() {
PatternStringFieldValue enclosedMsg = PatternStringFieldValue.newBuilder()
.setEmail("invalid email")
.build();
EnclosedMessageWithoutAnnotationFieldValue msg =
EnclosedMessageWithoutAnnotationFieldValue.newBuilder()
.setOuterMsgField(enclosedMsg)
.build();
validate(msg);
assertIsValid(true);
}
@Test
@DisplayName("consider field valid if it is not set")
void consider_field_valid_if_it_is_not_set() {
EnclosedMessageWithRequiredString msg = EnclosedMessageWithRequiredString.newBuilder()
.build();
validate(msg);
assertIsValid(true);
}
@Test
@DisplayName("provide valid violations if enclosed message field is not valid")
void provide_valid_violations_if_enclosed_message_field_is_not_valid() {
PatternStringFieldValue enclosedMsg = PatternStringFieldValue.newBuilder()
.setEmail("invalid email")
.build();
EnclosedMessageFieldValue msg = EnclosedMessageFieldValue.newBuilder()
.setOuterMsgField(enclosedMsg)
.build();
validate(msg);
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals("Message must have valid properties.", violation.getMsgFormat());
assertFieldPathIs(violation, OUTER_MSG_FIELD);
List<ConstraintViolation> innerViolations = violation.getViolationList();
assertEquals(1, innerViolations.size());
ConstraintViolation innerViolation = innerViolations.get(0);
assertEquals(MATCH_REGEXP_MSG, innerViolation.getMsgFormat());
assertFieldPathIs(innerViolation, OUTER_MSG_FIELD, EMAIL);
assertTrue(innerViolation.getViolationList()
.isEmpty());
}
@Test
@DisplayName("provide custom invalid field message if specified")
void provide_custom_invalid_field_message_if_specified() {
PatternStringFieldValue enclosedMsg = PatternStringFieldValue.newBuilder()
.setEmail("invalid email")
.build();
EnclosedMessageFieldValueWithCustomInvalidMessage msg =
EnclosedMessageFieldValueWithCustomInvalidMessage.newBuilder()
.setOuterMsgField(enclosedMsg)
.build();
validate(msg);
assertThat(violations).hasSize(1);
ConstraintViolation violation = firstViolation();
assertEquals("Custom error", violation.getMsgFormat());
}
@Test
@DisplayName("ignore custom invalid field message if validation is disabled")
void ignore_custom_invalid_field_message_if_validation_is_disabled() {
validate(
EnclosedMessageFieldValueWithoutAnnotationFieldValueWithCustomInvalidMessage.getDefaultInstance());
assertIsValid(true);
}
@Nested
@DisplayName("validate an entity ID")
class EntityId {
@Nested
@DisplayName("in a command file and")
class InCommandFile {
@Test
@DisplayName("find out that Message is valid")
void find_out_that_Message_entity_id_in_command_is_valid() {
EntityIdMsgFieldValue msg = EntityIdMsgFieldValue.newBuilder()
.setValue(newStringValue())
.build();
assertValid(msg);
}
@Test
@DisplayName("find out that Message is NOT valid")
void find_out_that_Message_entity_id_in_command_is_NOT_valid() {
EntityIdMsgFieldValue msg = EntityIdMsgFieldValue.getDefaultInstance();
assertNotValid(msg);
}
@Test
@DisplayName("find out that String is valid")
void find_out_that_String_entity_id_in_command_is_valid() {
EntityIdStringFieldValue msg = EntityIdStringFieldValue.newBuilder()
.setValue(newUuid())
.build();
assertValid(msg);
}
@Test
@DisplayName("find out that String is NOT valid")
void find_out_that_String_entity_id_in_command_is_NOT_valid() {
EntityIdStringFieldValue msg = EntityIdStringFieldValue.getDefaultInstance();
assertNotValid(msg);
}
@Test
@DisplayName("find out that Integer is valid")
void find_out_that_Integer_entity_id_in_command_is_valid() {
EntityIdIntFieldValue msg = EntityIdIntFieldValue.newBuilder()
.setValue(5)
.build();
assertValid(msg);
}
@Test
@DisplayName("find out that Integer is NOT valid")
void find_out_that_Integer_entity_id_in_command_is_NOT_valid() {
EntityIdIntFieldValue msg = EntityIdIntFieldValue.getDefaultInstance();
assertNotValid(msg);
}
@Test
@DisplayName("find out that Long is valid")
void find_out_that_Long_entity_id_in_command_is_valid() {
EntityIdLongFieldValue msg = EntityIdLongFieldValue.newBuilder()
.setValue(5)
.build();
assertValid(msg);
}
@Test
@DisplayName("find out that Long is NOT valid")
void find_out_that_Long_entity_id_in_command_is_NOT_valid() {
EntityIdLongFieldValue msg = EntityIdLongFieldValue.getDefaultInstance();
assertNotValid(msg);
}
@Test
@DisplayName("find out that repeated is NOT valid")
void find_out_that_repeated_entity_id_in_command_is_not_valid() {
EntityIdRepeatedFieldValue msg = EntityIdRepeatedFieldValue.newBuilder()
.addValue(newUuid())
.build();
assertValid(msg);
}
@Test
@DisplayName("provide one valid violation if is not valid")
void provide_one_valid_violation_if_entity_id_in_command_is_not_valid() {
validate(EntityIdMsgFieldValue.getDefaultInstance());
assertEquals(1, violations.size());
ConstraintViolation violation = firstViolation();
assertEquals(NO_VALUE_MSG, violation.getMsgFormat());
assertFieldPathIs(violation, VALUE);
assertTrue(violation.getViolationList()
.isEmpty());
}
}
@Nested
@DisplayName("in state and")
class InState {
@Test
@DisplayName("consider it required by default")
void requiredByDefault() {
AggregateState stateWithDefaultId = AggregateState.getDefaultInstance();
assertNotValid(stateWithDefaultId);
}
@Test
@DisplayName("match only the first field named `id` or ending with `_id`")
void onlyFirstField() {
AggregateState onlyEntityIdSet = AggregateState.newBuilder()
.setEntityId(newUuid())
.build();
assertValid(onlyEntityIdSet);
}
@Test
@DisplayName("not consider it (required) if the option is set explicitly set to false")
void notRequiredIfOptionIsFalse() {
ProjectionState stateWithDefaultId = ProjectionState.getDefaultInstance();
assertValid(stateWithDefaultId);
}
}
@Nested
@DisplayName("and reject")
class Reject {
@Test
@DisplayName("ByteString")
void find_out_that_entity_id_in_command_cannot_be_ByteString() {
EntityIdByteStringFieldValue msg = EntityIdByteStringFieldValue.newBuilder()
.setValue(newByteString())
.build();
assertNotValid(msg);
}
@Test
@DisplayName("Float")
void find_out_that_entity_id_in_command_cannot_be_float_number() {
@SuppressWarnings("MagicNumber") EntityIdDoubleFieldValue msg =
EntityIdDoubleFieldValue.newBuilder()
.setValue(1.1)
.build();
assertNotValid(msg);
}
}
}
/*
* Utility methods.
*/
private void minDecimalNumberTest(double value, boolean inclusive, boolean isValid) {
Message msg = inclusive ?
DecimalMinIncNumberFieldValue.newBuilder()
.setValue(value)
.build() :
DecimalMinNotIncNumberFieldValue.newBuilder()
.setValue(value)
.build();
validate(msg);
assertIsValid(isValid);
}
private void maxDecimalNumberTest(double value, boolean inclusive, boolean isValid) {
Message msg = inclusive ?
DecimalMaxIncNumberFieldValue.newBuilder()
.setValue(value)
.build() :
DecimalMaxNotIncNumberFieldValue.newBuilder()
.setValue(value)
.build();
validate(msg);
assertIsValid(isValid);
}
private void digitsCountTest(double value, boolean isValid) {
Message msg = DigitsCountNumberFieldValue.newBuilder()
.setValue(value)
.build();
validate(msg);
assertIsValid(isValid);
}
private void validate(Message msg) {
violations = validator.validate(msg);
}
private ConstraintViolation firstViolation() {
return violations.get(0);
}
private void assertValid(Message msg) {
validate(msg);
assertIsValid(true);
}
private void assertNotValid(Message msg) {
validate(msg);
assertIsValid(false);
}
private void assertIsValid(boolean isValid) {
if (isValid) {
assertTrue(violations.isEmpty(), () -> violations.toString());
} else {
assertFalse(violations.isEmpty());
for (ConstraintViolation violation : violations) {
String format = violation.getMsgFormat();
assertTrue(!format.isEmpty());
boolean noParams = violation.getParamList()
.isEmpty();
if (format.contains("%s")) {
assertFalse(noParams);
} else {
assertTrue(noParams);
}
assertFalse(violation.getFieldPath()
.getFieldNameList()
.isEmpty());
}
}
}
private static void assertFieldPathIs(ConstraintViolation violation, String... expectedFields) {
FieldPath path = violation.getFieldPath();
ProtocolStringList actualFields = path.getFieldNameList();
assertEquals(expectedFields.length, actualFields.size());
assertEquals(copyOf(expectedFields), copyOf(actualFields));
}
private static Timestamp getFuture() {
Timestamp future = add(getCurrentTime(),
MessageValidatorTestEnv.newDuration(SECONDS_IN_5_MINUTES));
return future;
}
private static Timestamp getPast() {
Timestamp past = subtract(getCurrentTime(),
MessageValidatorTestEnv.newDuration(SECONDS_IN_5_MINUTES));
return past;
}
private static StringValue newStringValue() {
return toMessage(newUuid());
}
private static ByteString newByteString() {
ByteString bytes = ByteString.copyFromUtf8(newUuid());
return bytes;
}
}
|
package com.yahoo.vespa.model.utils;
import com.yahoo.config.FileReference;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.application.api.FileRegistry;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.config.model.producer.UserConfigRepo;
import com.yahoo.path.Path;
import com.yahoo.vespa.config.ConfigDefinition;
import com.yahoo.vespa.config.ConfigDefinition.DefaultValued;
import com.yahoo.vespa.config.ConfigDefinitionKey;
import com.yahoo.vespa.config.ConfigPayloadBuilder;
import com.yahoo.vespa.model.AbstractService;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
/**
* Utility methods for sending files to a collection of nodes.
*
* @author gjoranv
*/
public class FileSender implements Serializable {
private final Collection<? extends AbstractService> services;
private final FileRegistry fileRegistry;
private final DeployLogger logger;
public FileSender(Collection<? extends AbstractService> services, FileRegistry fileRegistry, DeployLogger logger) {
this.services = services;
this.fileRegistry = fileRegistry;
this.logger = logger;
}
/**
* Sends all user configured files for a producer to all given services.
*/
public <PRODUCER extends AbstractConfigProducer<?>> void sendUserConfiguredFiles(PRODUCER producer) {
if (services.isEmpty())
return;
UserConfigRepo userConfigs = producer.getUserConfigs();
Map<Path, FileReference> sentFiles = new HashMap<>();
for (ConfigDefinitionKey key : userConfigs.configsProduced()) {
ConfigPayloadBuilder builder = userConfigs.get(key);
try {
sendUserConfiguredFiles(builder, sentFiles, key);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Unable to send file specified in " + key, e);
}
}
}
private void sendUserConfiguredFiles(ConfigPayloadBuilder builder, Map<Path, FileReference> sentFiles, ConfigDefinitionKey key) {
ConfigDefinition configDefinition = builder.getConfigDefinition();
if (configDefinition == null) {
logger.logApplicationPackage(Level.FINE, "Not able to find config definition for " + key +
". Will not send files for this config");
return;
}
// Inspect fields at this level
sendEntries(builder, sentFiles, configDefinition.getFileDefs());
sendEntries(builder, sentFiles, configDefinition.getPathDefs());
// Inspect arrays
for (Map.Entry<String, ConfigDefinition.ArrayDef> entry : configDefinition.getArrayDefs().entrySet()) {
if (isFileOrPathArray(entry)) {
ConfigPayloadBuilder.Array array = builder.getArray(entry.getKey());
sendFileEntries(array.getElements(), sentFiles);
}
}
// Maps
for (Map.Entry<String, ConfigDefinition.LeafMapDef> entry : configDefinition.getLeafMapDefs().entrySet()) {
if (isFileOrPathMap(entry)) {
ConfigPayloadBuilder.MapBuilder map = builder.getMap(entry.getKey());
sendFileEntries(map.getElements(), sentFiles);
}
}
// Inspect inner fields
for (String name : configDefinition.getStructDefs().keySet()) {
sendUserConfiguredFiles(builder.getObject(name), sentFiles, key);
}
for (String name : configDefinition.getInnerArrayDefs().keySet()) {
ConfigPayloadBuilder.Array array = builder.getArray(name);
for (ConfigPayloadBuilder element : array.getElements()) {
sendUserConfiguredFiles(element, sentFiles, key);
}
}
for (String name : configDefinition.getStructMapDefs().keySet()) {
ConfigPayloadBuilder.MapBuilder map = builder.getMap(name);
for (ConfigPayloadBuilder element : map.getElements()) {
sendUserConfiguredFiles(element, sentFiles, key);
}
}
}
private static boolean isFileOrPathMap(Map.Entry<String, ConfigDefinition.LeafMapDef> entry) {
String mapType = entry.getValue().getTypeSpec().getType();
return ("file".equals(mapType) || "path".equals(mapType));
}
private static boolean isFileOrPathArray(Map.Entry<String, ConfigDefinition.ArrayDef> entry) {
String arrayType = entry.getValue().getTypeSpec().getType();
return ("file".equals(arrayType) || "path".equals(arrayType));
}
private void sendEntries(ConfigPayloadBuilder builder,
Map<Path, FileReference> sentFiles,
Map<String, ? extends DefaultValued<String>> entries) {
for (String name : entries.keySet()) {
ConfigPayloadBuilder fileEntry = builder.getObject(name);
if (fileEntry.getValue() == null)
throw new IllegalArgumentException("Unable to send file for field '" + name +
"': Invalid config value " + fileEntry.getValue());
sendFileEntry(fileEntry, sentFiles);
}
}
private void sendFileEntries(Collection<ConfigPayloadBuilder> builders, Map<Path, FileReference> sentFiles) {
for (ConfigPayloadBuilder builder : builders) {
sendFileEntry(builder, sentFiles);
}
}
private void sendFileEntry(ConfigPayloadBuilder builder, Map<Path, FileReference> sentFiles) {
Path path = Path.fromString(builder.getValue());
FileReference reference = sentFiles.get(path);
if (reference == null) {
reference = fileRegistry.addFile(path.getRelative());
sentFiles.put(path, reference);
}
builder.setValue(reference.value());
}
}
|
package com.yahoo.vespa.config;
import com.yahoo.config.subscription.ConfigSourceSet;
import org.junit.Test;
import java.util.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.*;
/**
* Tests for the JRTConnectionPool class.
*
* @author Gunnar Gauslaa Bergem
* @author hmusum
*/
public class JRTConnectionPoolTest {
private static final List<String> sources = new ArrayList<>((Arrays.asList("host0", "host1", "host2")));
/**
* Tests that hash-based selection through the list works.
*/
@Test
public void test_random_selection_of_sourceBasicHashBasedSelection() {
JRTConnectionPool sourcePool = new JRTConnectionPool(sources);
assertThat(sourcePool.toString(), is("Address: host0\nAddress: host1\nAddress: host2\n"));
Map<String, Integer> sourceOccurrences = new HashMap<>();
for (int i = 0; i < 1000; i++) {
final String address = sourcePool.setNewCurrentConnection().getAddress();
if (sourceOccurrences.containsKey(address)) {
sourceOccurrences.put(address, sourceOccurrences.get(address) + 1);
} else {
sourceOccurrences.put(address, 1);
}
}
for (int i = 0; i < sourcePool.getSize(); i++) {
assertTrue(sourceOccurrences.get(sourcePool.getSources().get(i).getAddress()) > 200);
}
}
/**
* Tests that when there are two sources and several clients
* the sources will be chosen with about the same probability.
*/
@Test
public void testManySources() {
Map<String, Integer> timesUsed = new LinkedHashMap<>();
List<String> twoSources = new ArrayList<>();
twoSources.add("host0");
twoSources.add("host1");
JRTConnectionPool sourcePool = new JRTConnectionPool(twoSources);
int count = 1000;
for (int i = 0; i < count; i++) {
String address = sourcePool.setNewCurrentConnection().getAddress();
if (timesUsed.containsKey(address)) {
int times = timesUsed.get(address);
timesUsed.put(address, times + 1);
} else {
timesUsed.put(address, 1);
}
}
assertConnectionDistributionIsFair(timesUsed);
}
// Tests that the number of times each connection is used is close to equal
private void assertConnectionDistributionIsFair(Map<String, Integer> connectionsUsedPerHost) {
double deviationDueToRandomSourceSelection = 0.15;
final int size = 1000;
int minHostCount = (int) (size/2 * (1 - deviationDueToRandomSourceSelection));
int maxHostCount = (int) (size/2 * (1 + deviationDueToRandomSourceSelection));
for (Map.Entry<String, Integer> entry : connectionsUsedPerHost.entrySet()) {
Integer timesUsed = entry.getValue();
assertTrue("Host 0 used " + timesUsed + " times, expected to be < " + maxHostCount, timesUsed < maxHostCount);
assertTrue("Host 0 used " + timesUsed + " times, expected to be > " + minHostCount, timesUsed > minHostCount);
}
}
/**
* Tests that updating config sources works.
*/
@Test
public void updateSources() {
List<String> twoSources = new ArrayList<>();
twoSources.add("host0");
twoSources.add("host1");
JRTConnectionPool sourcePool = new JRTConnectionPool(twoSources);
ConfigSourceSet sourcesBefore = sourcePool.getSourceSet();
// Update to the same set, should be equal
sourcePool.updateSources(twoSources);
assertThat(sourcesBefore, is(sourcePool.getSourceSet()));
// Update to new set
List<String> newSources = new ArrayList<>();
newSources.add("host2");
newSources.add("host3");
sourcePool.updateSources(newSources);
ConfigSourceSet newSourceSet = sourcePool.getSourceSet();
assertNotNull(newSourceSet);
assertThat(newSourceSet.getSources().size(), is(2));
assertThat(newSourceSet, is(not(sourcesBefore)));
assertTrue(newSourceSet.getSources().contains("host2"));
assertTrue(newSourceSet.getSources().contains("host3"));
// Update to new set with just one host
List<String> newSources2 = new ArrayList<>();
newSources2.add("host4");
sourcePool.updateSources(newSources2);
ConfigSourceSet newSourceSet2 = sourcePool.getSourceSet();
assertNotNull(newSourceSet2);
assertThat(newSourceSet2.getSources().size(), is(1));
assertThat(newSourceSet2, is(not(newSourceSet)));
assertTrue(newSourceSet2.getSources().contains("host4"));
}
}
|
package javamop.output.combinedaspect.event;
import java.util.List;
import javamop.Main;
import javamop.output.MOPVariable;
import javamop.parser.ast.mopspec.JavaMOPSpec;
import javamop.parser.ast.mopspec.PropertyAndHandlers;
import javamop.output.combinedaspect.CombinedAspect;
/**
*
* This class is used to generate code to maintain a set of current active threads, similar to EndThread event.
*
* */
public class ThreadStatusMonitor extends EndThread{
private final static String eventName = "ThreadMonitor";
private MOPVariable monitorName;
private boolean hasDeadlockHandler = false;
public ThreadStatusMonitor(JavaMOPSpec mopSpec, CombinedAspect combinedAspect) {
this.monitorClass = combinedAspect.monitors.get(mopSpec);
this.monitorName = monitorClass.getOutermostName();
this.runnableMap = new MOPVariable(mopSpec.getName() + "_" + eventName + "_ThreadToRunnable");
this.mainThread = new MOPVariable(mopSpec.getName() + "_" + eventName + "_MainThread");
this.threadSet = new MOPVariable(mopSpec.getName() + "_" + eventName + "_ThreadSet");
this.globalLock = combinedAspect.lockManager.getLock();
List<PropertyAndHandlers> props = mopSpec.getPropertiesAndHandlers();
for (PropertyAndHandlers p : props) {
if (p.getHandlers().containsKey("deadlock"))
this.hasDeadlockHandler = true;
}
}
@Override
public String printDataStructures() {
String ret = "";
ret += "static HashMap<Thread, Runnable> " + runnableMap + " = new HashMap<Thread, Runnable>();\n";
ret += "static Thread " + mainThread + " = null;\n";
ret += "static HashSet<Thread> " + threadSet + " = new HashSet<Thread>();\n";
return ret;
}
@Override
public String printAdviceBodyAtEndProgram(){
String ret = "";
return ret;
}
@Override
public String printAdviceForMainEnd() {
String ret = "";
ret += "before (): " + "(execution(void *.main(..)) )";
ret += " && " + commonPointcut + "() {\n";
ret += "while (!" + globalLock.getName() + ".tryLock()) {\n";
ret += "Thread.yield();\n";
ret += "}\n";
ret += "if(" + mainThread + " == null){\n";
ret += mainThread + " = Thread.currentThread();\n";
ret += threadSet + ".add(Thread.currentThread());\n";
ret += globalLock.getName() + "_cond.signalAll();\n";
ret += "}\n";
//Start deadlock detection thread here
if (this.hasDeadlockHandler) {
ret += "javamoprt.MOPDeadlockDetector.startDeadlockDetectionThread(" + this.threadSet
+ ", " + this.mainThread + ", " + this.globalLock.getName() + ", new " + this.monitorName + "." + this.monitorName + "DeadlockCallback()" +");\n";
}
ret += globalLock.getName() + ".unlock();\n";
ret += "}\n";
ret += "\n";
ret += "after (): " + "(execution(void *.main(..)) )";
ret += " && " + commonPointcut + "() {\n";
ret += "while (!" + globalLock.getName() + ".tryLock()) {\n";
ret += "Thread.yield();\n";
ret += "}\n";
ret += threadSet + ".remove(Thread.currentThread());\n";
ret += globalLock.getName() + ".unlock();\n";
ret += "}\n";
ret += "\n";
return ret;
}
@Override
public String printAdviceForEndThread() {
String ret = "";
MOPVariable threadVar = new MOPVariable("t");
ret += "after (Thread " + threadVar + "): ( execution(void Thread+.run()) && target(" + threadVar + ") )";
ret += " && " + commonPointcut + "() {\n";
ret += "while (!" + globalLock.getName() + ".tryLock()) {\n";
ret += "Thread.yield();\n";
ret += "}\n";
ret += threadSet + ".remove(Thread.currentThread());\n";
ret += globalLock.getName() + ".unlock();\n";
ret += "}\n";
return ret;
}
@Override
public String printAdviceForEndRunnable() {
String ret = "";
MOPVariable runnableVar = new MOPVariable("r");
ret += "after (Runnable " + runnableVar + "): ( execution(void Runnable+.run()) && !execution(void Thread+.run()) && target(" + runnableVar + ") )";
ret += " && " + commonPointcut + "() {\n";
ret += "while (!" + globalLock.getName() + ".tryLock()) {\n";
ret += "Thread.yield();\n";
ret += "}\n";
ret += threadSet + ".remove(Thread.currentThread());\n";
ret += globalLock.getName() + ".unlock();\n";
ret += "}\n";
return ret;
}
/**
*
* Print a helper method used to check whether a thread is blocked or not.
*
* */
public String printContainsBlockedThread() {
String ret = "";
ret += "static boolean containsBlockedThread(String name) {\n";
ret += "while (!" + globalLock.getName() + ".tryLock()) {\n";
ret += "Thread.yield();\n";
ret += "}\n";
ret += "for (Thread t : " + threadSet + ") {\n";
ret += "if (t.getName().equals(name)) {\n";
ret += "if (t.getState() == Thread.State.BLOCKED || t.getState() == Thread.State.WAITING) {\n";
ret += globalLock.getName() + ".unlock();\n";
ret += "return true;\n";
ret += "}\n";
ret += "}\n";
ret += "}\n";
ret += globalLock.getName() + ".unlock();\n";
ret += "return false;\n";
ret += "}\n";
return ret;
}
/**
*
* Print a helper method used to check whether a thread is contained in the threadSet.
*
* */
public String printContainsThread() {
String ret = "";
ret += "static boolean containsThread(String name) {\n";
ret += "while (!" + globalLock.getName() + ".tryLock()) {\n";
ret += "Thread.yield();\n";
ret += "}\n";
ret += "for (Thread t : " + threadSet + ") {\n";
ret += "if (t.getName().equals(name)) {\n";
ret += globalLock.getName() + ".unlock();\n";
ret += "return true;\n";
ret += "}\n";
ret += "}\n";
ret += globalLock.getName() + ".unlock();\n";
ret += "return false;\n";
ret += "}\n";
return ret;
}
public String printAdviceForNewThread() {
String ret = "";
ret += "after (Thread t): ";
ret += "(";
ret += "call(void Thread+.start()) && target(t))";
ret += " && " + commonPointcut + "() {\n";
ret += "while (!" + globalLock.getName() + ".tryLock()) {\n";
ret += "Thread.yield();\n";
ret += "}\n";
ret += threadSet + ".add(t);\n";
ret += globalLock.getName() + "_cond.signalAll();\n";
ret += globalLock.getName() + ".unlock();\n";
ret += "}\n";
return ret;
}
public String printMethodCallForNewThread() {
String ret = "";
ret += "after (Thread t): ";
ret += "(";
ret += "call(void Thread+.start()) && target(t))";
ret += " && " + commonPointcut + "() {\n";
if (Main.merge && Main.aspectname != null && Main.aspectname.length() > 0) {
ret += Main.aspectname + "RuntimeMonitor.startDeadlockDetection();\n";
}
else {
ret += monitorName + "RuntimeMonitor.startDeadlockDetection();\n";
}
ret += "}\n";
return ret;
}
public String printAdvices() {
String ret = "";
if (!Main.translate2RV) {
ret += printDataStructures();
ret += "\n";
ret += printContainsBlockedThread();
ret += "\n";
ret += printContainsThread();
ret += "\n";
ret += printAdviceForThreadWithRunnable();
ret += "\n";
ret += printAdviceForEndThread();
ret += "\n";
ret += printAdviceForEndRunnable();
ret += "\n";
ret += printAdviceForMainEnd();
ret += "\n";
ret += printAdviceForNewThread();
ret += "\n";
}
else {
ret += printMethodCallForNewThread();
ret += "\n";
}
return ret;
}
}
|
package org.jboss.forge.container.util;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.jboss.forge.container.addons.Addon;
import org.jboss.forge.container.exception.ContainerException;
/**
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*/
public class Addons
{
public static void waitUntilStarted(Addon addon)
{
try
{
while (!addon.getStatus().isStarted())
{
Thread.sleep(10);
}
}
catch (Exception e)
{
throw new ContainerException("Addon [" + addon + "] was not started.", e);
}
}
public static void waitUntilStopped(Addon addon)
{
try
{
while (addon.getStatus().isStarted())
{
Thread.sleep(10);
}
}
catch (Exception e)
{
throw new ContainerException("Addon [" + addon + "] was not stopped.", e);
}
}
public static void waitUntilStarted(Addon addon, int quantity, TimeUnit unit)
{
try
{
long start = System.currentTimeMillis();
while (!addon.getStatus().isStarted())
{
if (System.currentTimeMillis() > (start + TimeUnit.MILLISECONDS.convert(quantity, unit)))
{
throw new TimeoutException("Timeout expired waiting for [" + addon + "] to start.");
}
Thread.sleep(10);
}
}
catch (RuntimeException re)
{
throw re;
}
catch (Exception e)
{
throw new ContainerException("Addon [" + addon + "] was not stopped.", e);
}
}
public static void waitUntilStopped(Addon addon, int quantity, TimeUnit unit)
{
try
{
long start = System.currentTimeMillis();
while (addon.getStatus().isStarted())
{
if (System.currentTimeMillis() > (start + TimeUnit.MILLISECONDS.convert(quantity, unit)))
{
throw new TimeoutException("Timeout expired waiting for [" + addon + "] to stop.");
}
Thread.sleep(10);
}
}
catch (RuntimeException re)
{
throw re;
}
catch (Exception e)
{
throw new ContainerException("Addon [" + addon + "] was not stopped.", e);
}
}
}
|
package org.helioviewer.gl3d.camera;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import org.helioviewer.base.DownloadStream;
import org.helioviewer.base.logging.Log;
import org.helioviewer.base.physics.Constants;
import org.helioviewer.gl3d.scenegraph.math.GL3DVec3d;
import org.helioviewer.jhv.display.Displayer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class GL3DPositionLoading {
private final String LOADEDSTATE = "Loaded";
private final String LOADINGSTATE = "Loading";
private final String FAILEDSTATE = "Failed";
private final String PARTIALSTATE = "Partial";
private boolean isLoaded = false;
private URL url;
private JSONArray jsonResult;
public GL3DPositionDateTime[] positionDateTime;
private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final GregorianCalendar calendar = new GregorianCalendar();
private String beginDate = "2014-07-28T00:00:00";
private String endDate = "2014-05-30T00:00:00";
private String target = "Mercury";
private final String observer = "SUN";
private final String baseUrl = "http://swhv.oma.be:7789/position?";
private final int deltat = 60 * 60 * 6; //6 hours by default
private final ArrayList<GL3DPositionLoadingListener> listeners = new ArrayList<GL3DPositionLoadingListener>();
private Date beginDatems;
private Date endDatems;
public GL3DPositionLoading() {
/*
* beginDatems = LayersModel.getSingletonInstance(); endDatems = new
* Date(System.currentTimeMillis()); beginDate =
* this.format.format(beginDatems); endDate =
* this.format.format(endDatems); this.requestData();
*/
}
private void buildRequestURL() {
try {
url = new URL(baseUrl + "utc=" + this.beginDate + "&utc_end=" + this.endDate + "&deltat=" + deltat + "&observer=" + observer + "&target=" + target + "&ref=HEEQ&kind=latitudinal");
} catch (MalformedURLException e) {
Log.error("A wrong url is given.", e);
}
}
public void requestData() {
Thread loadData = new Thread(new Runnable() {
@Override
public void run() {
try {
buildRequestURL();
DownloadStream ds = new DownloadStream(url.toURI(), 30000, 30000, true);
Reader reader = new BufferedReader(new InputStreamReader(ds.getInput(), "UTF-8"));
if (!ds.getResponse400()) {
jsonResult = new JSONArray(new JSONTokener(reader));
parseData();
if (positionDateTime.length > 0) {
setLoaded(true);
}
} else {
JSONObject jsonObject = new JSONObject(new JSONTokener(reader));
if (jsonObject.has("faultstring")) {
String faultstring = jsonObject.getString("faultstring");
fireLoaded(faultstring);
}
}
} catch (final IOException e1) {
Log.warn(e1);
e1.printStackTrace();
fireLoaded(FAILEDSTATE + ": server problem");
} catch (JSONException e2) {
fireLoaded(FAILEDSTATE + ": json parse problem");
} catch (URISyntaxException e) {
fireLoaded(FAILEDSTATE + ": wrong URI");
}
}
});
loadData.run();
}
private void setLoaded(boolean isLoaded) {
this.isLoaded = isLoaded;
this.fireLoaded(this.LOADEDSTATE);
}
private void parseData() {
calendar.clear();
try {
GL3DPositionDateTime[] positionDateTimehelper = new GL3DPositionDateTime[jsonResult.length()];
for (int i = 0; i < jsonResult.length(); i++) {
JSONObject ithObject = jsonResult.getJSONObject(i);
String dateString = ithObject.getString("utc").toString();
Date date = format.parse(dateString);
calendar.setTime(date);
JSONArray positionArray = ithObject.getJSONArray("val");
double x = positionArray.getDouble(0);
double y = positionArray.getDouble(1);
double z = positionArray.getDouble(2);
GL3DVec3d vec = new GL3DVec3d(x, y, z);
positionDateTimehelper[i] = new GL3DPositionDateTime(calendar.getTimeInMillis(), vec);
}
this.positionDateTime = positionDateTimehelper;
Displayer.getSingletonInstance().render();
} catch (JSONException e) {
this.fireLoaded(this.PARTIALSTATE);
Log.warn("Problem Parsing the JSON Response.", e);
} catch (ParseException e) {
this.fireLoaded(this.PARTIALSTATE);
Log.warn("Problem Parsing the date in JSON Response.", e);
}
}
public boolean isLoaded() {
return this.isLoaded;
}
public void setBeginDate(Date beginDate) {
this.beginDate = this.format.format(beginDate);
this.beginDatems = beginDate;
applyChanges();
}
public void applyChanges() {
this.setLoaded(false);
this.requestData();
}
public void setBeginDate(long beginDate) {
this.beginDate = this.format.format(new Date(beginDate));
this.beginDatems = new Date(beginDate);
applyChanges();
}
public void setEndDate(Date endDate) {
this.endDate = this.format.format(endDate);
this.endDatems = endDate;
applyChanges();
}
public void setEndDate(long endDate) {
this.endDate = this.format.format(new Date(endDate));
this.endDatems = new Date(endDate);
applyChanges();
}
public void addListener(GL3DPositionLoadingListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
public void fireLoaded(String state) {
synchronized (listeners) {
for (GL3DPositionLoadingListener listener : listeners) {
listener.fireNewLoaded(state);
}
}
}
public Date getBeginDate() {
return this.beginDatems;
}
public Date getEndDate() {
return this.endDatems;
}
public GL3DVec3d getInterpolatedPosition(long currentCameraTime) {
long t3 = this.getBeginDate().getTime();
long t4 = this.getEndDate().getTime();
if (t3 == t4) {
double hgln = this.positionDateTime[0].getPosition().y;
double hglt = this.positionDateTime[0].getPosition().z;
double dist = this.positionDateTime[0].getPosition().x;
dist = dist * 1000 / Constants.SunRadiusInMeter;
GL3DVec3d vec = new GL3DVec3d(dist, hgln, hglt);
return vec;
} else {
double interpolatedIndex = (1. * (currentCameraTime - t3) / (t4 - t3) * this.positionDateTime.length);
int i = (int) interpolatedIndex;
i = Math.min(i, this.positionDateTime.length - 1);
int inext = Math.min(i + 1, this.positionDateTime.length - 1);
double alpha = 1. - interpolatedIndex % 1.;
double hgln = alpha * this.positionDateTime[i].getPosition().y + (1 - alpha) * this.positionDateTime[inext].getPosition().y;
double hglt = alpha * this.positionDateTime[i].getPosition().z + (1 - alpha) * this.positionDateTime[inext].getPosition().z;
double dist = alpha * this.positionDateTime[i].getPosition().x + (1 - alpha) * this.positionDateTime[inext].getPosition().x;
dist = dist * 1000 / Constants.SunRadiusInMeter;
GL3DVec3d vec = new GL3DVec3d(dist, hgln, hglt);
return vec;
}
}
public void setObservingObject(String object) {
this.target = object;
this.applyChanges();
}
}
|
package ai.ilikeplaces.widgets;
import ai.ilikeplaces.servlets.Controller;
import java.util.HashSet;
import java.util.Set;
import org.itsnat.core.ItsNatDocument;
import org.itsnat.core.ItsNatServlet;
import org.itsnat.core.html.ItsNatHTMLDocFragmentTemplate;
import org.itsnat.core.html.ItsNatHTMLDocument;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.html.HTMLDocument;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import static ai.ilikeplaces.servlets.Controller.*;
/**
*
* Each widget itself knows its functionality.
* Hence, each widget should register its own event listeners.
* But there will be several copies of the same widget in the same page.
* Therefore, the widget ids should be different.
* Each widget has to have its own class
*
* @author Ravindranath Akila
*/
public abstract class AbstractWidgetListener {
protected final ItsNatDocument itsNatDocument_;
private final HTMLDocument hTMLDocument_;
/**
* As a widget may have many instances within a document, we register each
* instance with unique ids. i.e. the existing id is appended with the
* instance number. Remember, each instance has to have its own instance id,
* and should not have a reference to THIS copy which will lead to bugs.
*/
private static long Instance_ = 0;
/**
* As a widget may have many instances within a document, we register each
* instance with unique ids. i.e. the existing id is appended with the
* instance number
*/
final protected long instanceId;
final protected Page page;
final private static String Id = "id";
private boolean visible = true;
/**
*
* @param itsNatDocument__
* @param page__
* @param appendToElement__
*/
public AbstractWidgetListener(final ItsNatDocument itsNatDocument__, final Page page__, final Element appendToElement__) {
instanceId = Instance_++;
page = page__;
this.itsNatDocument_ = itsNatDocument__;
final ItsNatHTMLDocument itsNatHTMLDocument_ = (ItsNatHTMLDocument) itsNatDocument_;
this.hTMLDocument_ = itsNatHTMLDocument_.getHTMLDocument();
final ItsNatServlet itsNatServlet_ = itsNatDocument_.getItsNatDocumentTemplate().getItsNatServlet();
final ItsNatHTMLDocFragmentTemplate inhdft_ = (ItsNatHTMLDocFragmentTemplate) itsNatServlet_.getItsNatDocFragmentTemplate(page__.toString());
appendToElement__.appendChild(inhdft_.loadDocumentFragmentBody(itsNatDocument_));
setWidgetElementIds(Controller.GlobalPageIdRegistry.get(page));
init();
registerEventListeners(itsNatHTMLDocument_, hTMLDocument_);
}
protected abstract void init();
/**
* Use ItsNatHTMLDocument variable stored in the AbstractListener class
* Do not call this method anywhere, just implement it, as it will be
* automatically called by the contructor
* @param itsNatHTMLDocument_
* @param hTMLDocument_
*/
protected abstract void registerEventListeners(final ItsNatHTMLDocument itsNatHTMLDocument_, final HTMLDocument hTMLDocument_);
/**
* Id registry should be globally visible to callers
*
* @param key__
* @return Element
*/
protected final Element $(final String key__) {
final String elementId__ = Controller.GlobalHTMLIdRegistry.get(key__);
if (elementId__ == null) {
throw new java.lang.NullPointerException("ELEMENT \"" + key__ + "\" CONTAINS NULL OR NO REFERENCE IN REGISTRY!");
}
return hTMLDocument_.getElementById(elementId__);
}
/**
* Id list of this widget
*
* @param keys__
*/
private final void setWidgetElementIds(final HashSet<String> ids__) {
for (final String id_ : ids__) {
hTMLDocument_.getElementById(id_).setAttribute(Id, id_ + instanceId);
}
}
/**
* Wrapper to getWidgetElementById
*
* @param key__
* @return Element
*/
final protected Element $$(final String key__) {
return getWidgetElementById(key__);
}
final private Element getWidgetElementById(final String key__) {
final String elementId__ = Controller.GlobalHTMLIdRegistry.get(key__);
if (elementId__ == null) {
throw new java.lang.NullPointerException("SORRY! ELEMENT \"" + key__ + "\" CONTAINS NULL OR NO REFERENCE IN REGISTRY!");
}
return hTMLDocument_.getElementById(elementId__ + instanceId);
}
/**
*
* @return HashSet<String> widgetElements
*/
final protected Set<String> getWidgetElements() {
return Controller.GlobalPageIdRegistry.get(page);
}
protected void toggleVisible(final String toggleLink) {
final Set<String> widgetElements = getWidgetElements();
if (visible) {
for (String elementId__ : widgetElements) {
if (!elementId__.equals(toggleLink)) {
$$(elementId__).setAttribute("style", "display:none");
}
}
visible = false;
} else {
for (String elementId__ : widgetElements) {
if (!elementId__.equals(toggleLink)) {
$$(elementId__).setAttribute("style", "display:block");
}
}
visible = true;
}
}
}
|
package ameba.db.ebean.internal;
import ameba.core.ws.rs.PATCH;
import ameba.db.model.Model;
import com.avaje.ebean.*;
import com.avaje.ebean.bean.EntityBean;
import com.avaje.ebean.bean.EntityBeanIntercept;
import com.avaje.ebeaninternal.api.SpiEbeanServer;
import com.avaje.ebeaninternal.server.deploy.BeanDescriptor;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.net.URI;
import java.util.List;
import java.util.Set;
/**
* @author icode
*/
public abstract class AbstractModelResource<T extends Model> {
protected Class<T> modelType;
protected final SpiEbeanServer server;
protected String defaultFindOrderBy;
@Context
protected UriInfo uriInfo;
public AbstractModelResource(Class<T> modelType) {
this(modelType, (SpiEbeanServer) Ebean.getServer(null));
}
public AbstractModelResource(Class<T> modelType, SpiEbeanServer server) {
this.modelType = modelType;
this.server = server;
}
/**
* Insert a model.
*
* @param model the model to insert
*/
@POST
public Response insert(@NotNull @Valid final T model) {
BeanDescriptor descriptor = server.getBeanDescriptor(model.getClass());
Object idProp = descriptor.getId((EntityBean) model);
if (idProp instanceof CharSequence) {
if (StringUtils.isNotBlank((CharSequence) idProp)) {
descriptor.getIdProperty().setValue((EntityBean) model, null);
}
} else if (idProp != null) {
descriptor.getIdProperty().setValue((EntityBean) model, null);
}
server.execute(new TxRunnable() {
@Override
public void run() {
preInsertModel(model);
insertModel(model);
postInsertModel(model);
}
});
Object id = server.getBeanId(model);
UriBuilder ub = uriInfo.getAbsolutePathBuilder();
URI createdUri = ub.path("" + id).build();
return Response.created(createdUri).build();
}
protected void preInsertModel(final T model) {
}
protected void insertModel(final T model) {
server.insert(model);
}
protected void postInsertModel(final T model) {
}
/**
* Update a model.
*
* @param id the unique id of the model
* @param model the model to update
*/
@PUT
@Path("{id}")
public void update(@PathParam("id") String id, @NotNull @Valid final T model) {
BeanDescriptor descriptor = server.getBeanDescriptor(model.getClass());
descriptor.convertSetId(id, (EntityBean) model);
EntityBeanIntercept intercept = ((EntityBean) model)._ebean_getIntercept();
for (int i = 0; i < intercept.getPropertyLength(); i++) {
intercept.markPropertyAsChanged(i);
}
server.execute(new TxRunnable() {
@Override
public void run() {
preUpdateModel(model);
updateModel(model);
postUpdateModel(model);
}
});
}
protected void preUpdateModel(final T model) {
}
protected void updateModel(final T model) {
server.update(model);
}
protected void postUpdateModel(final T model) {
}
/**
* Update a model items.
*
* @param id the unique id of the model
* @param model the model to update
*/
@PATCH
@Path("{id}")
public void patch(@PathParam("id") String id, @NotNull final T model) {
BeanDescriptor descriptor = server.getBeanDescriptor(model.getClass());
descriptor.convertSetId(id, (EntityBean) model);
server.execute(new TxRunnable() {
@Override
public void run() {
prePatchModel(model);
patchModel(model);
postPatchModel(model);
}
});
}
protected void prePatchModel(final T model) {
}
protected void patchModel(final T model) {
server.update(model);
}
protected void postPatchModel(final T model) {
}
/**
* Delete multiple model using Id's from the Matrix.
*
* @param ids The ids in the form "/resource/id1" or "/resource/id1;id2;id3"
*/
@DELETE
@Path("{ids}")
public void deleteMultiple(@NotNull @PathParam("ids") final PathSegment ids) {
final String firstId = ids.getPath();
Set<String> idSet = ids.getMatrixParameters().keySet();
if (!idSet.isEmpty()) {
final Set<String> idCollection = Sets.newLinkedHashSet();
idCollection.add(firstId);
idCollection.addAll(idSet);
server.execute(new TxRunnable() {
@Override
public void run() {
preDeleteMultipleModel(idCollection);
deleteMultipleModel(idCollection);
postDeleteMultipleModel(idCollection);
}
});
} else {
server.execute(new TxRunnable() {
@Override
public void run() {
preDeleteModel(firstId);
deleteModel(firstId);
postDeleteModel(firstId);
}
});
}
}
protected void preDeleteMultipleModel(Set<String> idCollection) {
}
protected void deleteMultipleModel(Set<String> idCollection) {
server.delete(modelType, idCollection);
}
protected void postDeleteMultipleModel(Set<String> idCollection) {
}
protected void preDeleteModel(String id) {
}
protected void deleteModel(String id) {
server.delete(modelType, id);
}
protected void postDeleteModel(String id) {
}
/**
* Find a model given its Id.
*
* @param id the id of the model.
*/
@GET
@Path("{id}")
public Response find(@NotNull @PathParam("id") final String id) {
Query<T> query = server.find(modelType);
FutureRowCount rowCount = applyUriQuery(query);
configFindByIdQuery(query);
T m = query.setId(id).findUnique();
Response.ResponseBuilder builder = Response.ok();
Response response = builder.entity(processFoundModel(m)).build();
applyRowCountHeader(response.getHeaders(), query, rowCount);
return response;
}
/**
* Configure the "Find By Id" query.
* <p>
* This is only used when no PathProperties where set via UriOptions.
* </p>
* <p>
* This effectively controls the "default" query used to render this model.
* </p>
*/
protected void configFindByIdQuery(final Query<T> query) {
}
protected Object processFoundModel(final T model) {
return model;
}
/**
* Find the beans for this beanType.
* <p>
* This can use URL query parameters such as order and maxrows to configure
* the query.
* </p>
*/
@GET
public Response find() {
Query<T> query = server.find(modelType);
if (StringUtils.isNotBlank(defaultFindOrderBy)) {
// see if we should use the default orderBy clause
OrderBy<T> orderBy = query.orderBy();
if (orderBy.isEmpty()) {
query.orderBy(defaultFindOrderBy);
}
}
FutureRowCount rowCount = applyUriQuery(query);
configFindQuery(query);
Response.ResponseBuilder builder = Response.ok();
List<T> list = query.findList();
Response response = builder.entity(processFoundModelList(list)).build();
applyRowCountHeader(response.getHeaders(), query, rowCount);
return response;
}
/**
* Configure the "Find" query.
* <p>
* This is only used when no PathProperties where set via UriOptions.
* </p>
* <p>
* This effectively controls the "default" query used with the find all
* query.
* </p>
*/
protected void configFindQuery(final Query<T> query) {
}
protected Object processFoundModelList(final List<T> list) {
return list;
}
protected FutureRowCount applyUriQuery(final Query<T> query) {
return EbeanModelProcessor.applyUriQuery(uriInfo.getQueryParameters(), query);
}
protected void applyRowCountHeader(MultivaluedMap<String, Object> headerParams, Query query, FutureRowCount rowCount) {
EbeanModelProcessor.applyRowCountHeader(headerParams, query, rowCount);
}
}
|
package de.danoeh.antennapod.core.storage;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.DatabaseUtils;
import android.database.DefaultDatabaseErrorHandler;
import android.database.MergeCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import de.danoeh.antennapod.core.R;
import de.danoeh.antennapod.core.event.ProgressEvent;
import de.danoeh.antennapod.core.feed.Chapter;
import de.danoeh.antennapod.core.feed.Feed;
import de.danoeh.antennapod.core.feed.FeedItem;
import de.danoeh.antennapod.core.feed.FeedMedia;
import de.danoeh.antennapod.core.feed.FeedPreferences;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.service.download.DownloadStatus;
import de.danoeh.antennapod.core.util.LongIntMap;
import org.greenrobot.eventbus.EventBus;
import static de.danoeh.antennapod.core.feed.FeedMedia.LAST_PLAYBACK_SPEED_UNSET;
// TODO Remove media column from feeditem table
/**
* Implements methods for accessing the database
*/
public class PodDBAdapter {
private static final String TAG = "PodDBAdapter";
public static final String DATABASE_NAME = "Antennapod.db";
/**
* Maximum number of arguments for IN-operator.
*/
private static final int IN_OPERATOR_MAXIMUM = 800;
/**
* Maximum number of entries per search request.
*/
public static final int SEARCH_LIMIT = 30;
// Key-constants
public static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_CUSTOM_TITLE = "custom_title";
public static final String KEY_NAME = "name";
public static final String KEY_LINK = "link";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_FILE_URL = "file_url";
public static final String KEY_DOWNLOAD_URL = "download_url";
public static final String KEY_PUBDATE = "pubDate";
public static final String KEY_READ = "read";
public static final String KEY_DURATION = "duration";
public static final String KEY_POSITION = "position";
public static final String KEY_SIZE = "filesize";
public static final String KEY_MIME_TYPE = "mime_type";
public static final String KEY_IMAGE = "image";
public static final String KEY_IMAGE_URL = "image_url";
public static final String KEY_FEED = "feed";
public static final String KEY_MEDIA = "media";
public static final String KEY_DOWNLOADED = "downloaded";
public static final String KEY_LASTUPDATE = "last_update";
public static final String KEY_FEEDFILE = "feedfile";
public static final String KEY_REASON = "reason";
public static final String KEY_SUCCESSFUL = "successful";
public static final String KEY_FEEDFILETYPE = "feedfile_type";
public static final String KEY_COMPLETION_DATE = "completion_date";
public static final String KEY_FEEDITEM = "feeditem";
public static final String KEY_CONTENT_ENCODED = "content_encoded";
public static final String KEY_PAYMENT_LINK = "payment_link";
public static final String KEY_START = "start";
public static final String KEY_LANGUAGE = "language";
public static final String KEY_AUTHOR = "author";
public static final String KEY_HAS_CHAPTERS = "has_simple_chapters";
public static final String KEY_TYPE = "type";
public static final String KEY_ITEM_IDENTIFIER = "item_identifier";
public static final String KEY_FEED_IDENTIFIER = "feed_identifier";
public static final String KEY_REASON_DETAILED = "reason_detailed";
public static final String KEY_DOWNLOADSTATUS_TITLE = "title";
public static final String KEY_CHAPTER_TYPE = "type";
public static final String KEY_PLAYBACK_COMPLETION_DATE = "playback_completion_date";
public static final String KEY_AUTO_DOWNLOAD = "auto_download";
public static final String KEY_KEEP_UPDATED = "keep_updated";
public static final String KEY_AUTO_DELETE_ACTION = "auto_delete_action";
public static final String KEY_PLAYED_DURATION = "played_duration";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_IS_PAGED = "is_paged";
public static final String KEY_NEXT_PAGE_LINK = "next_page_link";
public static final String KEY_HIDE = "hide";
public static final String KEY_LAST_UPDATE_FAILED = "last_update_failed";
public static final String KEY_HAS_EMBEDDED_PICTURE = "has_embedded_picture";
public static final String KEY_LAST_PLAYED_TIME = "last_played_time";
public static final String KEY_INCLUDE_FILTER = "include_filter";
public static final String KEY_EXCLUDE_FILTER = "exclude_filter";
public static final String KEY_FEED_PLAYBACK_SPEED = "feed_playback_speed";
public static final String KEY_MEDIA_LAST_PLAYBACK_SPEED = "last_playback_speed";
// Table names
static final String TABLE_NAME_FEEDS = "Feeds";
static final String TABLE_NAME_FEED_ITEMS = "FeedItems";
static final String TABLE_NAME_FEED_IMAGES = "FeedImages";
static final String TABLE_NAME_FEED_MEDIA = "FeedMedia";
static final String TABLE_NAME_DOWNLOAD_LOG = "DownloadLog";
static final String TABLE_NAME_QUEUE = "Queue";
static final String TABLE_NAME_SIMPLECHAPTERS = "SimpleChapters";
static final String TABLE_NAME_FAVORITES = "Favorites";
// SQL Statements for creating new tables
private static final String TABLE_PRIMARY_KEY = KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT ,";
private static final String CREATE_TABLE_FEEDS = "CREATE TABLE "
+ TABLE_NAME_FEEDS + " (" + TABLE_PRIMARY_KEY + KEY_TITLE
+ " TEXT," + KEY_CUSTOM_TITLE + " TEXT," + KEY_FILE_URL + " TEXT," + KEY_DOWNLOAD_URL + " TEXT,"
+ KEY_DOWNLOADED + " INTEGER," + KEY_LINK + " TEXT,"
+ KEY_DESCRIPTION + " TEXT," + KEY_PAYMENT_LINK + " TEXT,"
+ KEY_LASTUPDATE + " TEXT," + KEY_LANGUAGE + " TEXT," + KEY_AUTHOR
+ " TEXT," + KEY_IMAGE_URL + " TEXT," + KEY_TYPE + " TEXT,"
+ KEY_FEED_IDENTIFIER + " TEXT," + KEY_AUTO_DOWNLOAD + " INTEGER DEFAULT 1,"
+ KEY_USERNAME + " TEXT,"
+ KEY_PASSWORD + " TEXT,"
+ KEY_INCLUDE_FILTER + " TEXT DEFAULT '',"
+ KEY_EXCLUDE_FILTER + " TEXT DEFAULT '',"
+ KEY_KEEP_UPDATED + " INTEGER DEFAULT 1,"
+ KEY_IS_PAGED + " INTEGER DEFAULT 0,"
+ KEY_NEXT_PAGE_LINK + " TEXT,"
+ KEY_HIDE + " TEXT,"
+ KEY_LAST_UPDATE_FAILED + " INTEGER DEFAULT 0,"
+ KEY_AUTO_DELETE_ACTION + " INTEGER DEFAULT 0,"
+ KEY_FEED_PLAYBACK_SPEED + " TEXT)";
private static final String CREATE_TABLE_FEED_ITEMS = "CREATE TABLE "
+ TABLE_NAME_FEED_ITEMS + " (" + TABLE_PRIMARY_KEY + KEY_TITLE
+ " TEXT," + KEY_CONTENT_ENCODED + " TEXT," + KEY_PUBDATE
+ " INTEGER," + KEY_READ + " INTEGER," + KEY_LINK + " TEXT,"
+ KEY_DESCRIPTION + " TEXT," + KEY_PAYMENT_LINK + " TEXT,"
+ KEY_MEDIA + " INTEGER," + KEY_FEED + " INTEGER,"
+ KEY_HAS_CHAPTERS + " INTEGER," + KEY_ITEM_IDENTIFIER + " TEXT,"
+ KEY_IMAGE_URL + " TEXT,"
+ KEY_AUTO_DOWNLOAD + " INTEGER)";
private static final String CREATE_TABLE_FEED_MEDIA = "CREATE TABLE "
+ TABLE_NAME_FEED_MEDIA + " (" + TABLE_PRIMARY_KEY + KEY_DURATION
+ " INTEGER," + KEY_FILE_URL + " TEXT," + KEY_DOWNLOAD_URL
+ " TEXT," + KEY_DOWNLOADED + " INTEGER," + KEY_POSITION
+ " INTEGER," + KEY_SIZE + " INTEGER," + KEY_MIME_TYPE + " TEXT,"
+ KEY_PLAYBACK_COMPLETION_DATE + " INTEGER,"
+ KEY_FEEDITEM + " INTEGER,"
+ KEY_PLAYED_DURATION + " INTEGER,"
+ KEY_HAS_EMBEDDED_PICTURE + " INTEGER,"
+ KEY_LAST_PLAYED_TIME + " INTEGER,"
+ KEY_MEDIA_LAST_PLAYBACK_SPEED + " REAL DEFAULT " + LAST_PLAYBACK_SPEED_UNSET + ")";
private static final String CREATE_TABLE_DOWNLOAD_LOG = "CREATE TABLE "
+ TABLE_NAME_DOWNLOAD_LOG + " (" + TABLE_PRIMARY_KEY + KEY_FEEDFILE
+ " INTEGER," + KEY_FEEDFILETYPE + " INTEGER," + KEY_REASON
+ " INTEGER," + KEY_SUCCESSFUL + " INTEGER," + KEY_COMPLETION_DATE
+ " INTEGER," + KEY_REASON_DETAILED + " TEXT,"
+ KEY_DOWNLOADSTATUS_TITLE + " TEXT)";
private static final String CREATE_TABLE_QUEUE = "CREATE TABLE "
+ TABLE_NAME_QUEUE + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_FEEDITEM + " INTEGER," + KEY_FEED + " INTEGER)";
private static final String CREATE_TABLE_SIMPLECHAPTERS = "CREATE TABLE "
+ TABLE_NAME_SIMPLECHAPTERS + " (" + TABLE_PRIMARY_KEY + KEY_TITLE
+ " TEXT," + KEY_START + " INTEGER," + KEY_FEEDITEM + " INTEGER,"
+ KEY_LINK + " TEXT," + KEY_CHAPTER_TYPE + " INTEGER)";
// SQL Statements for creating indexes
static final String CREATE_INDEX_FEEDITEMS_FEED = "CREATE INDEX "
+ TABLE_NAME_FEED_ITEMS + "_" + KEY_FEED + " ON " + TABLE_NAME_FEED_ITEMS + " ("
+ KEY_FEED + ")";
static final String CREATE_INDEX_FEEDITEMS_PUBDATE = "CREATE INDEX IF NOT EXISTS "
+ TABLE_NAME_FEED_ITEMS + "_" + KEY_PUBDATE + " ON " + TABLE_NAME_FEED_ITEMS + " ("
+ KEY_PUBDATE + ")";
static final String CREATE_INDEX_FEEDITEMS_READ = "CREATE INDEX IF NOT EXISTS "
+ TABLE_NAME_FEED_ITEMS + "_" + KEY_READ + " ON " + TABLE_NAME_FEED_ITEMS + " ("
+ KEY_READ + ")";
static final String CREATE_INDEX_QUEUE_FEEDITEM = "CREATE INDEX "
+ TABLE_NAME_QUEUE + "_" + KEY_FEEDITEM + " ON " + TABLE_NAME_QUEUE + " ("
+ KEY_FEEDITEM + ")";
static final String CREATE_INDEX_FEEDMEDIA_FEEDITEM = "CREATE INDEX "
+ TABLE_NAME_FEED_MEDIA + "_" + KEY_FEEDITEM + " ON " + TABLE_NAME_FEED_MEDIA + " ("
+ KEY_FEEDITEM + ")";
static final String CREATE_INDEX_SIMPLECHAPTERS_FEEDITEM = "CREATE INDEX "
+ TABLE_NAME_SIMPLECHAPTERS + "_" + KEY_FEEDITEM + " ON " + TABLE_NAME_SIMPLECHAPTERS + " ("
+ KEY_FEEDITEM + ")";
static final String CREATE_TABLE_FAVORITES = "CREATE TABLE "
+ TABLE_NAME_FAVORITES + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_FEEDITEM + " INTEGER," + KEY_FEED + " INTEGER)";
/**
* Select all columns from the feed-table
*/
private static final String[] FEED_SEL_STD = {
TABLE_NAME_FEEDS + "." + KEY_ID,
TABLE_NAME_FEEDS + "." + KEY_TITLE,
TABLE_NAME_FEEDS + "." + KEY_CUSTOM_TITLE,
TABLE_NAME_FEEDS + "." + KEY_FILE_URL,
TABLE_NAME_FEEDS + "." + KEY_DOWNLOAD_URL,
TABLE_NAME_FEEDS + "." + KEY_DOWNLOADED,
TABLE_NAME_FEEDS + "." + KEY_LINK,
TABLE_NAME_FEEDS + "." + KEY_DESCRIPTION,
TABLE_NAME_FEEDS + "." + KEY_PAYMENT_LINK,
TABLE_NAME_FEEDS + "." + KEY_LASTUPDATE,
TABLE_NAME_FEEDS + "." + KEY_LANGUAGE,
TABLE_NAME_FEEDS + "." + KEY_AUTHOR,
TABLE_NAME_FEEDS + "." + KEY_IMAGE_URL,
TABLE_NAME_FEEDS + "." + KEY_TYPE,
TABLE_NAME_FEEDS + "." + KEY_FEED_IDENTIFIER,
TABLE_NAME_FEEDS + "." + KEY_AUTO_DOWNLOAD,
TABLE_NAME_FEEDS + "." + KEY_KEEP_UPDATED,
TABLE_NAME_FEEDS + "." + KEY_IS_PAGED,
TABLE_NAME_FEEDS + "." + KEY_NEXT_PAGE_LINK,
TABLE_NAME_FEEDS + "." + KEY_USERNAME,
TABLE_NAME_FEEDS + "." + KEY_PASSWORD,
TABLE_NAME_FEEDS + "." + KEY_HIDE,
TABLE_NAME_FEEDS + "." + KEY_LAST_UPDATE_FAILED,
TABLE_NAME_FEEDS + "." + KEY_AUTO_DELETE_ACTION,
TABLE_NAME_FEEDS + "." + KEY_INCLUDE_FILTER,
TABLE_NAME_FEEDS + "." + KEY_EXCLUDE_FILTER,
TABLE_NAME_FEEDS + "." + KEY_FEED_PLAYBACK_SPEED
};
/**
* Select all columns from the feeditems-table except description and
* content-encoded.
*/
private static final String[] FEEDITEM_SEL_FI_SMALL = {
TABLE_NAME_FEED_ITEMS + "." + KEY_ID,
TABLE_NAME_FEED_ITEMS + "." + KEY_TITLE,
TABLE_NAME_FEED_ITEMS + "." + KEY_PUBDATE,
TABLE_NAME_FEED_ITEMS + "." + KEY_READ,
TABLE_NAME_FEED_ITEMS + "." + KEY_LINK,
TABLE_NAME_FEED_ITEMS + "." + KEY_PAYMENT_LINK,
TABLE_NAME_FEED_ITEMS + "." + KEY_MEDIA,
TABLE_NAME_FEED_ITEMS + "." + KEY_FEED,
TABLE_NAME_FEED_ITEMS + "." + KEY_HAS_CHAPTERS,
TABLE_NAME_FEED_ITEMS + "." + KEY_ITEM_IDENTIFIER,
TABLE_NAME_FEED_ITEMS + "." + KEY_IMAGE_URL,
TABLE_NAME_FEED_ITEMS + "." + KEY_AUTO_DOWNLOAD
};
/**
* All the tables in the database
*/
private static final String[] ALL_TABLES = {
TABLE_NAME_FEEDS,
TABLE_NAME_FEED_ITEMS,
TABLE_NAME_FEED_MEDIA,
TABLE_NAME_DOWNLOAD_LOG,
TABLE_NAME_QUEUE,
TABLE_NAME_SIMPLECHAPTERS,
TABLE_NAME_FAVORITES
};
/**
* Contains FEEDITEM_SEL_FI_SMALL as comma-separated list. Useful for raw queries.
*/
private static final String SEL_FI_SMALL_STR;
static {
String selFiSmall = Arrays.toString(FEEDITEM_SEL_FI_SMALL);
SEL_FI_SMALL_STR = selFiSmall.substring(1, selFiSmall.length() - 1);
}
/**
* Select id, description and content-encoded column from feeditems.
*/
private static final String[] SEL_FI_EXTRA = {KEY_ID, KEY_DESCRIPTION,
KEY_CONTENT_ENCODED, KEY_FEED};
private static Context context;
private static volatile SQLiteDatabase db;
public static void init(Context context) {
PodDBAdapter.context = context.getApplicationContext();
}
// Bill Pugh Singleton Implementation
private static class SingletonHolder {
private static final PodDBHelper dbHelper = new PodDBHelper(PodDBAdapter.context, DATABASE_NAME, null);
private static final PodDBAdapter dbAdapter = new PodDBAdapter();
}
public static PodDBAdapter getInstance() {
return SingletonHolder.dbAdapter;
}
private PodDBAdapter() {
}
public synchronized PodDBAdapter open() {
if (db == null || !db.isOpen() || db.isReadOnly()) {
db = openDb();
}
return this;
}
@SuppressLint("NewApi")
private SQLiteDatabase openDb() {
SQLiteDatabase newDb;
try {
newDb = SingletonHolder.dbHelper.getWritableDatabase();
if (Build.VERSION.SDK_INT >= 16) {
newDb.disableWriteAheadLogging();
}
} catch (SQLException ex) {
Log.e(TAG, Log.getStackTraceString(ex));
newDb = SingletonHolder.dbHelper.getReadableDatabase();
}
return newDb;
}
public synchronized void close() {
// do nothing
}
public static boolean deleteDatabase() {
PodDBAdapter adapter = getInstance();
adapter.open();
try {
for (String tableName : ALL_TABLES) {
db.delete(tableName, "1", null);
}
return true;
} finally {
adapter.close();
}
}
/**
* Inserts or updates a feed entry
*
* @return the id of the entry
*/
private long setFeed(Feed feed) {
ContentValues values = new ContentValues();
values.put(KEY_TITLE, feed.getFeedTitle());
values.put(KEY_LINK, feed.getLink());
values.put(KEY_DESCRIPTION, feed.getDescription());
values.put(KEY_PAYMENT_LINK, feed.getPaymentLink());
values.put(KEY_AUTHOR, feed.getAuthor());
values.put(KEY_LANGUAGE, feed.getLanguage());
values.put(KEY_IMAGE_URL, feed.getImageUrl());
values.put(KEY_FILE_URL, feed.getFile_url());
values.put(KEY_DOWNLOAD_URL, feed.getDownload_url());
values.put(KEY_DOWNLOADED, feed.isDownloaded());
values.put(KEY_LASTUPDATE, feed.getLastUpdate());
values.put(KEY_TYPE, feed.getType());
values.put(KEY_FEED_IDENTIFIER, feed.getFeedIdentifier());
values.put(KEY_IS_PAGED, feed.isPaged());
values.put(KEY_NEXT_PAGE_LINK, feed.getNextPageLink());
if (feed.getItemFilter() != null && feed.getItemFilter().getValues().length > 0) {
values.put(KEY_HIDE, TextUtils.join(",", feed.getItemFilter().getValues()));
} else {
values.put(KEY_HIDE, "");
}
values.put(KEY_LAST_UPDATE_FAILED, feed.hasLastUpdateFailed());
if (feed.getId() == 0) {
// Create new entry
Log.d(this.toString(), "Inserting new Feed into db");
feed.setId(db.insert(TABLE_NAME_FEEDS, null, values));
} else {
Log.d(this.toString(), "Updating existing Feed in db");
db.update(TABLE_NAME_FEEDS, values, KEY_ID + "=?",
new String[]{String.valueOf(feed.getId())});
}
return feed.getId();
}
public void setFeedPreferences(FeedPreferences prefs) {
if (prefs.getFeedID() == 0) {
throw new IllegalArgumentException("Feed ID of preference must not be null");
}
ContentValues values = new ContentValues();
values.put(KEY_AUTO_DOWNLOAD, prefs.getAutoDownload());
values.put(KEY_KEEP_UPDATED, prefs.getKeepUpdated());
values.put(KEY_AUTO_DELETE_ACTION, prefs.getAutoDeleteAction().ordinal());
values.put(KEY_USERNAME, prefs.getUsername());
values.put(KEY_PASSWORD, prefs.getPassword());
values.put(KEY_INCLUDE_FILTER, prefs.getFilter().getIncludeFilter());
values.put(KEY_EXCLUDE_FILTER, prefs.getFilter().getExcludeFilter());
values.put(KEY_FEED_PLAYBACK_SPEED, prefs.getFeedPlaybackSpeed());
db.update(TABLE_NAME_FEEDS, values, KEY_ID + "=?", new String[]{String.valueOf(prefs.getFeedID())});
}
public void setFeedItemFilter(long feedId, Set<String> filterValues) {
String valuesList = TextUtils.join(",", filterValues);
Log.d(TAG, String.format(
"setFeedItemFilter() called with: feedId = [%d], filterValues = [%s]", feedId, valuesList));
ContentValues values = new ContentValues();
values.put(KEY_HIDE, valuesList);
db.update(TABLE_NAME_FEEDS, values, KEY_ID + "=?", new String[]{String.valueOf(feedId)});
}
/**
* Inserts or updates a media entry
*
* @return the id of the entry
*/
public long setMedia(FeedMedia media) {
ContentValues values = new ContentValues();
values.put(KEY_DURATION, media.getDuration());
values.put(KEY_POSITION, media.getPosition());
values.put(KEY_SIZE, media.getSize());
values.put(KEY_MIME_TYPE, media.getMime_type());
values.put(KEY_DOWNLOAD_URL, media.getDownload_url());
values.put(KEY_DOWNLOADED, media.isDownloaded());
values.put(KEY_FILE_URL, media.getFile_url());
values.put(KEY_HAS_EMBEDDED_PICTURE, media.hasEmbeddedPicture());
values.put(KEY_LAST_PLAYED_TIME, media.getLastPlayedTime());
values.put(KEY_MEDIA_LAST_PLAYBACK_SPEED, media.getLastPlaybackSpeed());
if (media.getPlaybackCompletionDate() != null) {
values.put(KEY_PLAYBACK_COMPLETION_DATE, media.getPlaybackCompletionDate().getTime());
} else {
values.put(KEY_PLAYBACK_COMPLETION_DATE, 0);
}
if (media.getItem() != null) {
values.put(KEY_FEEDITEM, media.getItem().getId());
}
if (media.getId() == 0) {
media.setId(db.insert(TABLE_NAME_FEED_MEDIA, null, values));
} else {
db.update(TABLE_NAME_FEED_MEDIA, values, KEY_ID + "=?",
new String[]{String.valueOf(media.getId())});
}
return media.getId();
}
public void setFeedMediaPlaybackInformation(FeedMedia media) {
if (media.getId() != 0) {
ContentValues values = new ContentValues();
values.put(KEY_POSITION, media.getPosition());
values.put(KEY_DURATION, media.getDuration());
values.put(KEY_PLAYED_DURATION, media.getPlayedDuration());
values.put(KEY_LAST_PLAYED_TIME, media.getLastPlayedTime());
values.put(KEY_MEDIA_LAST_PLAYBACK_SPEED, media.getLastPlaybackSpeed());
db.update(TABLE_NAME_FEED_MEDIA, values, KEY_ID + "=?",
new String[]{String.valueOf(media.getId())});
} else {
Log.e(TAG, "setFeedMediaPlaybackInformation: ID of media was 0");
}
}
public void setFeedMediaLastPlaybackSpeed(FeedMedia media) {
if (media.getId() != 0) {
ContentValues values = new ContentValues();
values.put(KEY_MEDIA_LAST_PLAYBACK_SPEED, media.getLastPlaybackSpeed());
db.update(TABLE_NAME_FEED_MEDIA, values, KEY_ID + "=?",
new String[]{String.valueOf(media.getId())});
} else {
Log.e(TAG, "setFeedMediaLastPlaybackSpeed: ID of media was 0");
}
}
public void setFeedMediaPlaybackCompletionDate(FeedMedia media) {
if (media.getId() != 0) {
ContentValues values = new ContentValues();
values.put(KEY_PLAYBACK_COMPLETION_DATE, media.getPlaybackCompletionDate().getTime());
values.put(KEY_PLAYED_DURATION, media.getPlayedDuration());
// Also reset stored playback speed for media
values.put(KEY_MEDIA_LAST_PLAYBACK_SPEED, LAST_PLAYBACK_SPEED_UNSET);
db.update(TABLE_NAME_FEED_MEDIA, values, KEY_ID + "=?",
new String[]{String.valueOf(media.getId())});
} else {
Log.e(TAG, "setFeedMediaPlaybackCompletionDate: ID of media was 0");
}
}
/**
* Insert all FeedItems of a feed and the feed object itself in a single
* transaction
*/
public void setCompleteFeed(Feed... feeds) {
try {
db.beginTransactionNonExclusive();
for (Feed feed : feeds) {
setFeed(feed);
if (feed.getItems() != null) {
for (FeedItem item : feed.getItems()) {
setFeedItem(item, false);
}
}
if (feed.getPreferences() != null) {
setFeedPreferences(feed.getPreferences());
}
}
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, Log.getStackTraceString(e));
} finally {
db.endTransaction();
}
}
/**
* Updates the download URL of a Feed.
*/
public void setFeedDownloadUrl(String original, String updated) {
ContentValues values = new ContentValues();
values.put(KEY_DOWNLOAD_URL, updated);
db.update(TABLE_NAME_FEEDS, values, KEY_DOWNLOAD_URL + "=?", new String[]{original});
}
public void setFeedItemlist(List<FeedItem> items) {
try {
db.beginTransactionNonExclusive();
for (FeedItem item : items) {
setFeedItem(item, true);
}
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, Log.getStackTraceString(e));
} finally {
db.endTransaction();
}
}
public long setSingleFeedItem(FeedItem item) {
long result = 0;
try {
db.beginTransactionNonExclusive();
result = setFeedItem(item, true);
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, Log.getStackTraceString(e));
} finally {
db.endTransaction();
}
return result;
}
/**
* Inserts or updates a feeditem entry
*
* @param item The FeedItem
* @param saveFeed true if the Feed of the item should also be saved. This should be set to
* false if the method is executed on a list of FeedItems of the same Feed.
* @return the id of the entry
*/
private long setFeedItem(FeedItem item, boolean saveFeed) {
ContentValues values = new ContentValues();
values.put(KEY_TITLE, item.getTitle());
values.put(KEY_LINK, item.getLink());
if (item.getDescription() != null) {
values.put(KEY_DESCRIPTION, item.getDescription());
}
if (item.getContentEncoded() != null) {
values.put(KEY_CONTENT_ENCODED, item.getContentEncoded());
}
values.put(KEY_PUBDATE, item.getPubDate().getTime());
values.put(KEY_PAYMENT_LINK, item.getPaymentLink());
if (saveFeed && item.getFeed() != null) {
setFeed(item.getFeed());
}
values.put(KEY_FEED, item.getFeed().getId());
if (item.isNew()) {
values.put(KEY_READ, FeedItem.NEW);
} else if (item.isPlayed()) {
values.put(KEY_READ, FeedItem.PLAYED);
} else {
values.put(KEY_READ, FeedItem.UNPLAYED);
}
values.put(KEY_HAS_CHAPTERS, item.getChapters() != null || item.hasChapters());
values.put(KEY_ITEM_IDENTIFIER, item.getItemIdentifier());
values.put(KEY_AUTO_DOWNLOAD, item.getAutoDownload());
values.put(KEY_IMAGE_URL, item.getImageUrl());
if (item.getId() == 0) {
item.setId(db.insert(TABLE_NAME_FEED_ITEMS, null, values));
} else {
db.update(TABLE_NAME_FEED_ITEMS, values, KEY_ID + "=?",
new String[]{String.valueOf(item.getId())});
}
if (item.getMedia() != null) {
setMedia(item.getMedia());
}
if (item.getChapters() != null) {
setChapters(item);
}
return item.getId();
}
public void setFeedItemRead(int played, long itemId, long mediaId,
boolean resetMediaPosition) {
try {
db.beginTransactionNonExclusive();
ContentValues values = new ContentValues();
values.put(KEY_READ, played);
db.update(TABLE_NAME_FEED_ITEMS, values, KEY_ID + "=?", new String[]{String.valueOf(itemId)});
if (resetMediaPosition) {
values.clear();
values.put(KEY_POSITION, 0);
db.update(TABLE_NAME_FEED_MEDIA, values, KEY_ID + "=?", new String[]{String.valueOf(mediaId)});
}
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, Log.getStackTraceString(e));
} finally {
db.endTransaction();
}
}
/**
* Sets the 'read' attribute of the item.
*
* @param read must be one of FeedItem.PLAYED, FeedItem.NEW, FeedItem.UNPLAYED
* @param itemIds items to change the value of
*/
public void setFeedItemRead(int read, long... itemIds) {
try {
db.beginTransactionNonExclusive();
ContentValues values = new ContentValues();
for (long id : itemIds) {
values.clear();
values.put(KEY_READ, read);
db.update(TABLE_NAME_FEED_ITEMS, values, KEY_ID + "=?", new String[]{String.valueOf(id)});
}
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, Log.getStackTraceString(e));
} finally {
db.endTransaction();
}
}
private void setChapters(FeedItem item) {
ContentValues values = new ContentValues();
for (Chapter chapter : item.getChapters()) {
values.put(KEY_TITLE, chapter.getTitle());
values.put(KEY_START, chapter.getStart());
values.put(KEY_FEEDITEM, item.getId());
values.put(KEY_LINK, chapter.getLink());
values.put(KEY_CHAPTER_TYPE, chapter.getChapterType());
if (chapter.getId() == 0) {
chapter.setId(db.insert(TABLE_NAME_SIMPLECHAPTERS, null, values));
} else {
db.update(TABLE_NAME_SIMPLECHAPTERS, values, KEY_ID + "=?",
new String[]{String.valueOf(chapter.getId())});
}
}
}
public void setFeedLastUpdateFailed(long feedId, boolean failed) {
final String sql = "UPDATE " + TABLE_NAME_FEEDS
+ " SET " + KEY_LAST_UPDATE_FAILED + "=" + (failed ? "1" : "0")
+ " WHERE " + KEY_ID + "=" + feedId;
db.execSQL(sql);
}
void setFeedCustomTitle(long feedId, String customTitle) {
ContentValues values = new ContentValues();
values.put(KEY_CUSTOM_TITLE, customTitle);
db.update(TABLE_NAME_FEEDS, values, KEY_ID + "=?", new String[]{String.valueOf(feedId)});
}
/**
* Inserts or updates a download status.
*/
public long setDownloadStatus(DownloadStatus status) {
ContentValues values = new ContentValues();
values.put(KEY_FEEDFILE, status.getFeedfileId());
values.put(KEY_FEEDFILETYPE, status.getFeedfileType());
values.put(KEY_REASON, status.getReason().getCode());
values.put(KEY_SUCCESSFUL, status.isSuccessful());
values.put(KEY_COMPLETION_DATE, status.getCompletionDate().getTime());
values.put(KEY_REASON_DETAILED, status.getReasonDetailed());
values.put(KEY_DOWNLOADSTATUS_TITLE, status.getTitle());
if (status.getId() == 0) {
status.setId(db.insert(TABLE_NAME_DOWNLOAD_LOG, null, values));
} else {
db.update(TABLE_NAME_DOWNLOAD_LOG, values, KEY_ID + "=?",
new String[]{String.valueOf(status.getId())});
}
return status.getId();
}
public void setFeedItemAutoDownload(FeedItem feedItem, long autoDownload) {
ContentValues values = new ContentValues();
values.put(KEY_AUTO_DOWNLOAD, autoDownload);
db.update(TABLE_NAME_FEED_ITEMS, values, KEY_ID + "=?",
new String[]{String.valueOf(feedItem.getId())});
}
public void setFeedsItemsAutoDownload(Feed feed, boolean autoDownload) {
final String sql = "UPDATE " + TABLE_NAME_FEED_ITEMS
+ " SET " + KEY_AUTO_DOWNLOAD + "=" + (autoDownload ? "1" : "0")
+ " WHERE " + KEY_FEED + "=" + feed.getId();
db.execSQL(sql);
}
public void setFavorites(List<FeedItem> favorites) {
ContentValues values = new ContentValues();
try {
db.beginTransactionNonExclusive();
db.delete(TABLE_NAME_FAVORITES, null, null);
for (int i = 0; i < favorites.size(); i++) {
FeedItem item = favorites.get(i);
values.put(KEY_ID, i);
values.put(KEY_FEEDITEM, item.getId());
values.put(KEY_FEED, item.getFeed().getId());
db.insertWithOnConflict(TABLE_NAME_FAVORITES, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, Log.getStackTraceString(e));
} finally {
db.endTransaction();
}
}
/**
* Adds the item to favorites
*/
public void addFavoriteItem(FeedItem item) {
// don't add an item that's already there...
if (isItemInFavorites(item)) {
Log.d(TAG, "item already in favorites");
return;
}
ContentValues values = new ContentValues();
values.put(KEY_FEEDITEM, item.getId());
values.put(KEY_FEED, item.getFeedId());
db.insert(TABLE_NAME_FAVORITES, null, values);
}
public void removeFavoriteItem(FeedItem item) {
String deleteClause = String.format("DELETE FROM %s WHERE %s=%s AND %s=%s",
TABLE_NAME_FAVORITES,
KEY_FEEDITEM, item.getId(),
KEY_FEED, item.getFeedId());
db.execSQL(deleteClause);
}
private boolean isItemInFavorites(FeedItem item) {
String query = String.format("SELECT %s from %s WHERE %s=%d",
KEY_ID, TABLE_NAME_FAVORITES, KEY_FEEDITEM, item.getId());
Cursor c = db.rawQuery(query, null);
int count = c.getCount();
c.close();
return count > 0;
}
public void setQueue(List<FeedItem> queue) {
ContentValues values = new ContentValues();
try {
db.beginTransactionNonExclusive();
db.delete(TABLE_NAME_QUEUE, null, null);
for (int i = 0; i < queue.size(); i++) {
FeedItem item = queue.get(i);
values.put(KEY_ID, i);
values.put(KEY_FEEDITEM, item.getId());
values.put(KEY_FEED, item.getFeed().getId());
db.insertWithOnConflict(TABLE_NAME_QUEUE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, Log.getStackTraceString(e));
} finally {
db.endTransaction();
}
}
public void clearQueue() {
db.delete(TABLE_NAME_QUEUE, null, null);
}
private void removeFeedMedia(FeedMedia media) {
// delete download log entries for feed media
db.delete(TABLE_NAME_DOWNLOAD_LOG, KEY_FEEDFILE + "=? AND " + KEY_FEEDFILETYPE + "=?",
new String[]{String.valueOf(media.getId()), String.valueOf(FeedMedia.FEEDFILETYPE_FEEDMEDIA)});
db.delete(TABLE_NAME_FEED_MEDIA, KEY_ID + "=?",
new String[]{String.valueOf(media.getId())});
}
private void removeChaptersOfItem(FeedItem item) {
db.delete(TABLE_NAME_SIMPLECHAPTERS, KEY_FEEDITEM + "=?",
new String[]{String.valueOf(item.getId())});
}
/**
* Remove a FeedItem and its FeedMedia entry.
*/
private void removeFeedItem(FeedItem item) {
if (item.getMedia() != null) {
removeFeedMedia(item.getMedia());
}
if (item.hasChapters() || item.getChapters() != null) {
removeChaptersOfItem(item);
}
db.delete(TABLE_NAME_FEED_ITEMS, KEY_ID + "=?",
new String[]{String.valueOf(item.getId())});
}
/**
* Remove a feed with all its FeedItems and Media entries.
*/
public void removeFeed(Feed feed) {
try {
db.beginTransactionNonExclusive();
if (feed.getItems() != null) {
for (FeedItem item : feed.getItems()) {
removeFeedItem(item);
}
}
// delete download log entries for feed
db.delete(TABLE_NAME_DOWNLOAD_LOG, KEY_FEEDFILE + "=? AND " + KEY_FEEDFILETYPE + "=?",
new String[]{String.valueOf(feed.getId()), String.valueOf(Feed.FEEDFILETYPE_FEED)});
db.delete(TABLE_NAME_FEEDS, KEY_ID + "=?",
new String[]{String.valueOf(feed.getId())});
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(TAG, Log.getStackTraceString(e));
} finally {
db.endTransaction();
}
}
public void clearPlaybackHistory() {
ContentValues values = new ContentValues();
values.put(KEY_PLAYBACK_COMPLETION_DATE, 0);
db.update(TABLE_NAME_FEED_MEDIA, values, null, null);
}
public void clearDownloadLog() {
db.delete(TABLE_NAME_DOWNLOAD_LOG, null, null);
}
/**
* Get all Feeds from the Feed Table.
*
* @return The cursor of the query
*/
public final Cursor getAllFeedsCursor() {
return db.query(TABLE_NAME_FEEDS, FEED_SEL_STD, null, null, null, null,
KEY_TITLE + " COLLATE NOCASE ASC");
}
public final Cursor getFeedCursorDownloadUrls() {
return db.query(TABLE_NAME_FEEDS, new String[]{KEY_ID, KEY_DOWNLOAD_URL}, null, null, null, null, null);
}
/**
* Returns a cursor with all FeedItems of a Feed. Uses FEEDITEM_SEL_FI_SMALL
*
* @param feed The feed you want to get the FeedItems from.
* @return The cursor of the query
*/
public final Cursor getAllItemsOfFeedCursor(final Feed feed) {
return getAllItemsOfFeedCursor(feed.getId());
}
private Cursor getAllItemsOfFeedCursor(final long feedId) {
return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, KEY_FEED
+ "=?", new String[]{String.valueOf(feedId)}, null, null,
null);
}
/**
* Return a cursor with the SEL_FI_EXTRA selection of a single feeditem.
*/
public final Cursor getExtraInformationOfItem(final FeedItem item) {
return db
.query(TABLE_NAME_FEED_ITEMS, SEL_FI_EXTRA, KEY_ID + "=?",
new String[]{String.valueOf(item.getId())}, null,
null, null);
}
/**
* Returns a cursor for a DB query in the FeedImages table for given IDs.
*
* @param imageIds IDs of the images
* @return The cursor of the query
*/
public final Cursor getImageCursor(String... imageIds) {
int length = imageIds.length;
if (length > IN_OPERATOR_MAXIMUM) {
Log.w(TAG, "Length of id array is larger than "
+ IN_OPERATOR_MAXIMUM + ". Creating multiple cursors");
int numCursors = (int) (((double) length) / (IN_OPERATOR_MAXIMUM)) + 1;
Cursor[] cursors = new Cursor[numCursors];
for (int i = 0; i < numCursors; i++) {
int neededLength;
String[] parts;
final int elementsLeft = length - i * IN_OPERATOR_MAXIMUM;
if (elementsLeft >= IN_OPERATOR_MAXIMUM) {
neededLength = IN_OPERATOR_MAXIMUM;
parts = Arrays.copyOfRange(imageIds, i
* IN_OPERATOR_MAXIMUM, (i + 1)
* IN_OPERATOR_MAXIMUM);
} else {
neededLength = elementsLeft;
parts = Arrays.copyOfRange(imageIds, i
* IN_OPERATOR_MAXIMUM, (i * IN_OPERATOR_MAXIMUM)
+ neededLength);
}
cursors[i] = db.rawQuery("SELECT * FROM "
+ TABLE_NAME_FEED_IMAGES + " WHERE " + KEY_ID + " IN "
+ buildInOperator(neededLength), parts);
}
Cursor result = new MergeCursor(cursors);
result.moveToFirst();
return result;
} else {
return db.query(TABLE_NAME_FEED_IMAGES, null, KEY_ID + " IN "
+ buildInOperator(length), imageIds, null, null, null);
}
}
public final Cursor getSimpleChaptersOfFeedItemCursor(final FeedItem item) {
return db.query(TABLE_NAME_SIMPLECHAPTERS, null, KEY_FEEDITEM
+ "=?", new String[]{String.valueOf(item.getId())}, null,
null, null
);
}
public final Cursor getDownloadLog(final int feedFileType, final long feedFileId) {
final String query = "SELECT * FROM " + TABLE_NAME_DOWNLOAD_LOG +
" WHERE " + KEY_FEEDFILE + "=" + feedFileId + " AND " + KEY_FEEDFILETYPE + "=" + feedFileType
+ " ORDER BY " + KEY_ID + " DESC";
return db.rawQuery(query, null);
}
public final Cursor getDownloadLogCursor(final int limit) {
return db.query(TABLE_NAME_DOWNLOAD_LOG, null, null, null, null,
null, KEY_COMPLETION_DATE + " DESC LIMIT " + limit);
}
/**
* Returns a cursor which contains all feed items in the queue. The returned
* cursor uses the FEEDITEM_SEL_FI_SMALL selection.
* cursor uses the FEEDITEM_SEL_FI_SMALL selection.
*/
public final Cursor getQueueCursor() {
Object[] args = new String[]{
SEL_FI_SMALL_STR,
TABLE_NAME_FEED_ITEMS, TABLE_NAME_QUEUE,
TABLE_NAME_FEED_ITEMS + "." + KEY_ID,
TABLE_NAME_QUEUE + "." + KEY_FEEDITEM,
TABLE_NAME_QUEUE + "." + KEY_ID};
String query = String.format("SELECT %s FROM %s INNER JOIN %s ON %s=%s ORDER BY %s", args);
return db.rawQuery(query, null);
}
public Cursor getQueueIDCursor() {
return db.query(TABLE_NAME_QUEUE, new String[]{KEY_FEEDITEM}, null, null, null, null, KEY_ID + " ASC", null);
}
public final Cursor getFavoritesCursor() {
Object[] args = new String[]{
SEL_FI_SMALL_STR,
TABLE_NAME_FEED_ITEMS, TABLE_NAME_FAVORITES,
TABLE_NAME_FEED_ITEMS + "." + KEY_ID,
TABLE_NAME_FAVORITES + "." + KEY_FEEDITEM,
TABLE_NAME_FEED_ITEMS + "." + KEY_PUBDATE};
String query = String.format("SELECT %s FROM %s INNER JOIN %s ON %s=%s ORDER BY %s DESC", args);
return db.rawQuery(query, null);
}
public void setFeedItems(int state) {
setFeedItems(Integer.MIN_VALUE, state, 0);
}
public void setFeedItems(int oldState, int newState) {
setFeedItems(oldState, newState, 0);
}
public void setFeedItems(int state, long feedId) {
setFeedItems(Integer.MIN_VALUE, state, feedId);
}
public void setFeedItems(int oldState, int newState, long feedId) {
String sql = "UPDATE " + TABLE_NAME_FEED_ITEMS + " SET " + KEY_READ + "=" + newState;
if (feedId > 0) {
sql += " WHERE " + KEY_FEED + "=" + feedId;
}
if (FeedItem.NEW <= oldState && oldState <= FeedItem.PLAYED) {
sql += feedId > 0 ? " AND " : " WHERE ";
sql += KEY_READ + "=" + oldState;
}
db.execSQL(sql);
}
/**
* Returns a cursor which contains all feed items that are considered new.
* Excludes those feeds that do not have 'Keep Updated' enabled.
* The returned cursor uses the FEEDITEM_SEL_FI_SMALL selection.
*/
public final Cursor getNewItemsCursor() {
Object[] args = new String[]{
SEL_FI_SMALL_STR,
TABLE_NAME_FEED_ITEMS,
TABLE_NAME_FEEDS,
TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + "=" + TABLE_NAME_FEEDS + "." + KEY_ID,
TABLE_NAME_FEED_ITEMS + "." + KEY_READ + "=" + FeedItem.NEW + " AND " + TABLE_NAME_FEEDS + "." + KEY_KEEP_UPDATED + " > 0",
KEY_PUBDATE + " DESC"
};
final String query = String.format("SELECT %s FROM %s INNER JOIN %s ON %s WHERE %s ORDER BY %s", args);
return db.rawQuery(query, null);
}
public final Cursor getRecentlyPublishedItemsCursor(int offset, int limit) {
return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, null, null, null, null, KEY_PUBDATE + " DESC LIMIT " + offset + ", " + limit);
}
public Cursor getDownloadedItemsCursor() {
final String query = "SELECT " + SEL_FI_SMALL_STR
+ " FROM " + TABLE_NAME_FEED_ITEMS
+ " INNER JOIN " + TABLE_NAME_FEED_MEDIA
+ " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_ID + "=" + TABLE_NAME_FEED_MEDIA + "." + KEY_FEEDITEM
+ " WHERE " + TABLE_NAME_FEED_MEDIA + "." + KEY_DOWNLOADED + ">0";
return db.rawQuery(query, null);
}
public final Cursor getCompletedMediaCursor(int limit) {
if (limit < 0) {
throw new IllegalArgumentException("Limit must be >= 0");
}
return db.query(TABLE_NAME_FEED_MEDIA, null,
KEY_PLAYBACK_COMPLETION_DATE + " > 0", null, null,
null, String.format("%s DESC LIMIT %d", KEY_PLAYBACK_COMPLETION_DATE, limit));
}
public final Cursor getSingleFeedMediaCursor(long id) {
return db.query(TABLE_NAME_FEED_MEDIA, null, KEY_ID + "=?", new String[]{String.valueOf(id)}, null, null, null);
}
public final Cursor getFeedMediaCursor(String... itemIds) {
int length = itemIds.length;
if (length > IN_OPERATOR_MAXIMUM) {
Log.w(TAG, "Length of id array is larger than "
+ IN_OPERATOR_MAXIMUM + ". Creating multiple cursors");
int numCursors = (int) (((double) length) / (IN_OPERATOR_MAXIMUM)) + 1;
Cursor[] cursors = new Cursor[numCursors];
for (int i = 0; i < numCursors; i++) {
int neededLength;
String[] parts;
final int elementsLeft = length - i * IN_OPERATOR_MAXIMUM;
if (elementsLeft >= IN_OPERATOR_MAXIMUM) {
neededLength = IN_OPERATOR_MAXIMUM;
parts = Arrays.copyOfRange(itemIds, i
* IN_OPERATOR_MAXIMUM, (i + 1)
* IN_OPERATOR_MAXIMUM);
} else {
neededLength = elementsLeft;
parts = Arrays.copyOfRange(itemIds, i
* IN_OPERATOR_MAXIMUM, (i * IN_OPERATOR_MAXIMUM)
+ neededLength);
}
cursors[i] = db.rawQuery("SELECT * FROM "
+ TABLE_NAME_FEED_MEDIA + " WHERE " + KEY_FEEDITEM + " IN "
+ buildInOperator(neededLength), parts);
}
Cursor result = new MergeCursor(cursors);
result.moveToFirst();
return result;
} else {
return db.query(TABLE_NAME_FEED_MEDIA, null, KEY_FEEDITEM + " IN "
+ buildInOperator(length), itemIds, null, null, null);
}
}
/**
* Builds an IN-operator argument depending on the number of items.
*/
private String buildInOperator(int size) {
if (size == 1) {
return "(?)";
}
return "(" + TextUtils.join(",", Collections.nCopies(size, "?")) + ")";
}
public final Cursor getFeedCursor(final long id) {
return db.query(TABLE_NAME_FEEDS, FEED_SEL_STD, KEY_ID + "=" + id, null,
null, null, null);
}
public final Cursor getFeedItemCursor(final String id) {
return getFeedItemCursor(new String[]{id});
}
public final Cursor getFeedItemCursor(final String[] ids) {
if (ids.length > IN_OPERATOR_MAXIMUM) {
throw new IllegalArgumentException(
"number of IDs must not be larger than "
+ IN_OPERATOR_MAXIMUM
);
}
return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, KEY_ID + " IN "
+ buildInOperator(ids.length), ids, null, null, null);
}
public final Cursor getFeedItemCursor(final String podcastUrl, final String episodeUrl) {
String escapedPodcastUrl = DatabaseUtils.sqlEscapeString(podcastUrl);
String escapedEpisodeUrl = DatabaseUtils.sqlEscapeString(episodeUrl);
final String query = ""
+ "SELECT " + SEL_FI_SMALL_STR + " FROM " + TABLE_NAME_FEED_ITEMS
+ " INNER JOIN " + TABLE_NAME_FEEDS
+ " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + "=" + TABLE_NAME_FEEDS + "." + KEY_ID
+ " INNER JOIN " + TABLE_NAME_FEED_MEDIA
+ " ON " + TABLE_NAME_FEED_MEDIA + "." + KEY_FEEDITEM + "=" + TABLE_NAME_FEED_ITEMS + "." + KEY_ID
+ " WHERE " + TABLE_NAME_FEED_MEDIA + "." + KEY_DOWNLOAD_URL + "=" + escapedEpisodeUrl
+ " AND " + TABLE_NAME_FEEDS + "." + KEY_DOWNLOAD_URL + "=" + escapedPodcastUrl;
Log.d(TAG, "SQL: " + query);
return db.rawQuery(query, null);
}
public Cursor getImageAuthenticationCursor(final String imageUrl) {
String downloadUrl = DatabaseUtils.sqlEscapeString(imageUrl);
final String query = ""
+ "SELECT " + KEY_USERNAME + "," + KEY_PASSWORD + " FROM " + TABLE_NAME_FEED_ITEMS
+ " INNER JOIN " + TABLE_NAME_FEEDS
+ " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + " = " + TABLE_NAME_FEEDS + "." + KEY_ID
+ " WHERE " + TABLE_NAME_FEED_ITEMS + "." + KEY_IMAGE_URL + "=" + downloadUrl
+ " UNION SELECT " + KEY_USERNAME + "," + KEY_PASSWORD + " FROM " + TABLE_NAME_FEEDS
+ " WHERE " + TABLE_NAME_FEEDS + "." + KEY_IMAGE_URL + "=" + downloadUrl;
return db.rawQuery(query, null);
}
public int getQueueSize() {
final String query = String.format("SELECT COUNT(%s) FROM %s", KEY_ID, TABLE_NAME_QUEUE);
Cursor c = db.rawQuery(query, null);
int result = 0;
if (c.moveToFirst()) {
result = c.getInt(0);
}
c.close();
return result;
}
public final int getNumberOfNewItems() {
Object[] args = new String[]{
TABLE_NAME_FEED_ITEMS + "." + KEY_ID,
TABLE_NAME_FEED_ITEMS,
TABLE_NAME_FEEDS,
TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + "=" + TABLE_NAME_FEEDS + "." + KEY_ID,
TABLE_NAME_FEED_ITEMS + "." + KEY_READ + "=" + FeedItem.NEW
+ " AND " + TABLE_NAME_FEEDS + "." + KEY_KEEP_UPDATED + " > 0"
};
final String query = String.format("SELECT COUNT(%s) FROM %s INNER JOIN %s ON %s WHERE %s", args);
Cursor c = db.rawQuery(query, null);
int result = 0;
if (c.moveToFirst()) {
result = c.getInt(0);
}
c.close();
return result;
}
public final LongIntMap getFeedCounters(long... feedIds) {
int setting = UserPreferences.getFeedCounterSetting();
String whereRead;
switch (setting) {
case UserPreferences.FEED_COUNTER_SHOW_NEW_UNPLAYED_SUM:
whereRead = "(" + KEY_READ + "=" + FeedItem.NEW +
" OR " + KEY_READ + "=" + FeedItem.UNPLAYED + ")";
break;
case UserPreferences.FEED_COUNTER_SHOW_NEW:
whereRead = KEY_READ + "=" + FeedItem.NEW;
break;
case UserPreferences.FEED_COUNTER_SHOW_UNPLAYED:
whereRead = KEY_READ + "=" + FeedItem.UNPLAYED;
break;
case UserPreferences.FEED_COUNTER_SHOW_DOWNLOADED:
whereRead = KEY_DOWNLOADED + "=1";
break;
case UserPreferences.FEED_COUNTER_SHOW_NONE:
// deliberate fall-through
default: // NONE
return new LongIntMap(0);
}
return conditionalFeedCounterRead(whereRead, feedIds);
}
private LongIntMap conditionalFeedCounterRead(String whereRead, long... feedIds) {
// work around TextUtils.join wanting only boxed items
// and StringUtils.join() causing NoSuchMethodErrors on MIUI
StringBuilder builder = new StringBuilder();
for (long id : feedIds) {
builder.append(id);
builder.append(',');
}
if (feedIds.length > 0) {
// there's an extra ',', get rid of it
builder.deleteCharAt(builder.length() - 1);
}
final String query = "SELECT " + KEY_FEED + ", COUNT(" + TABLE_NAME_FEED_ITEMS + "." + KEY_ID + ") AS count "
+ " FROM " + TABLE_NAME_FEED_ITEMS
+ " LEFT JOIN " + TABLE_NAME_FEED_MEDIA + " ON "
+ TABLE_NAME_FEED_ITEMS + "." + KEY_ID + "=" + TABLE_NAME_FEED_MEDIA + "." + KEY_FEEDITEM
+ " WHERE " + KEY_FEED + " IN (" + builder.toString() + ") "
+ " AND " + whereRead + " GROUP BY " + KEY_FEED;
Cursor c = db.rawQuery(query, null);
LongIntMap result = new LongIntMap(c.getCount());
if (c.moveToFirst()) {
do {
long feedId = c.getLong(0);
int count = c.getInt(1);
result.put(feedId, count);
} while (c.moveToNext());
}
c.close();
return result;
}
public final LongIntMap getPlayedEpisodesCounters(long... feedIds) {
String whereRead = KEY_READ + "=" + FeedItem.PLAYED;
return conditionalFeedCounterRead(whereRead, feedIds);
}
public final int getNumberOfDownloadedEpisodes() {
final String query = "SELECT COUNT(DISTINCT " + KEY_ID + ") AS count FROM " + TABLE_NAME_FEED_MEDIA +
" WHERE " + KEY_DOWNLOADED + " > 0";
Cursor c = db.rawQuery(query, null);
int result = 0;
if (c.moveToFirst()) {
result = c.getInt(0);
}
c.close();
return result;
}
/**
* Uses DatabaseUtils to escape a search query and removes ' at the
* beginning and the end of the string returned by the escape method.
*/
private String prepareSearchQuery(String query) {
StringBuilder builder = new StringBuilder();
DatabaseUtils.appendEscapedSQLString(builder, query);
builder.deleteCharAt(0);
builder.deleteCharAt(builder.length() - 1);
return builder.toString();
}
/**
* Searches for the given query in the description of all items or the items
* of a specified feed.
*
* @return A cursor with all search results in SEL_FI_EXTRA selection.
*/
public Cursor searchItemDescriptions(long feedID, String query) {
if (feedID != 0) {
// search items in specific feed
return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, KEY_FEED
+ "=? AND " + KEY_DESCRIPTION + " LIKE '%"
+ prepareSearchQuery(query) + "%'",
new String[]{String.valueOf(feedID)}, null, null,
null
);
} else {
// search through all items
return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL,
KEY_DESCRIPTION + " LIKE '%" + prepareSearchQuery(query)
+ "%'", null, null, null, null
);
}
}
/**
* Searches for the given query in the content-encoded field of all items or
* the items of a specified feed.
*
* @return A cursor with all search results in SEL_FI_EXTRA selection.
*/
public Cursor searchItemContentEncoded(long feedID, String query) {
if (feedID != 0) {
// search items in specific feed
return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, KEY_FEED
+ "=? AND " + KEY_CONTENT_ENCODED + " LIKE '%"
+ prepareSearchQuery(query) + "%'",
new String[]{String.valueOf(feedID)}, null, null,
null
);
} else {
// search through all items
return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL,
KEY_CONTENT_ENCODED + " LIKE '%"
+ prepareSearchQuery(query) + "%'", null, null,
null, null
);
}
}
public Cursor searchItemTitles(long feedID, String query) {
if (feedID != 0) {
// search items in specific feed
return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL, KEY_FEED
+ "=? AND " + KEY_TITLE + " LIKE '%"
+ prepareSearchQuery(query) + "%'",
new String[]{String.valueOf(feedID)}, null, null,
null
);
} else {
// search through all items
return db.query(TABLE_NAME_FEED_ITEMS, FEEDITEM_SEL_FI_SMALL,
KEY_TITLE + " LIKE '%"
+ prepareSearchQuery(query) + "%'", null, null,
null, null
);
}
}
public Cursor searchItemAuthors(long feedID, String query) {
if (feedID != 0) {
// search items in specific feed
return db.rawQuery("SELECT " + TextUtils.join(", ", FEEDITEM_SEL_FI_SMALL) + " FROM " + TABLE_NAME_FEED_ITEMS
+ " JOIN " + TABLE_NAME_FEEDS + " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + "=" + TABLE_NAME_FEEDS + "." + KEY_ID
+ " WHERE " + KEY_FEED
+ "=? AND " + KEY_AUTHOR + " LIKE '%"
+ prepareSearchQuery(query) + "%' ORDER BY "
+ TABLE_NAME_FEED_ITEMS + "." + KEY_PUBDATE + " DESC",
new String[]{String.valueOf(feedID)}
);
} else {
// search through all items
return db.rawQuery("SELECT " + TextUtils.join(", ", FEEDITEM_SEL_FI_SMALL) + " FROM " + TABLE_NAME_FEED_ITEMS
+ " JOIN " + TABLE_NAME_FEEDS + " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + "=" + TABLE_NAME_FEEDS + "." + KEY_ID
+ " WHERE " + KEY_AUTHOR + " LIKE '%"
+ prepareSearchQuery(query) + "%' ORDER BY "
+ TABLE_NAME_FEED_ITEMS + "." + KEY_PUBDATE + " DESC",
null
);
}
}
public Cursor searchItemFeedIdentifiers(long feedID, String query) {
if (feedID != 0) {
// search items in specific feed
return db.rawQuery("SELECT " + TextUtils.join(", ", FEEDITEM_SEL_FI_SMALL) + " FROM " + TABLE_NAME_FEED_ITEMS
+ " JOIN " + TABLE_NAME_FEEDS + " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + "=" + TABLE_NAME_FEEDS + "." + KEY_ID
+ " WHERE " + KEY_FEED
+ "=? AND " + KEY_FEED_IDENTIFIER + " LIKE '%"
+ prepareSearchQuery(query) + "%' ORDER BY "
+ TABLE_NAME_FEED_ITEMS + "." + KEY_PUBDATE + " DESC",
new String[]{String.valueOf(feedID)}
);
} else {
// search through all items
return db.rawQuery("SELECT " + TextUtils.join(", ", FEEDITEM_SEL_FI_SMALL) + " FROM " + TABLE_NAME_FEED_ITEMS
+ " JOIN " + TABLE_NAME_FEEDS + " ON " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + "=" + TABLE_NAME_FEEDS + "." + KEY_ID
+ " WHERE " + KEY_FEED_IDENTIFIER + " LIKE '%"
+ prepareSearchQuery(query) + "%' ORDER BY "
+ TABLE_NAME_FEED_ITEMS + "." + KEY_PUBDATE + " DESC",
null
);
}
}
public Cursor searchItemChapters(long feedID, String searchQuery) {
final String query;
if (feedID != 0) {
query = "SELECT " + SEL_FI_SMALL_STR + " FROM " + TABLE_NAME_FEED_ITEMS + " INNER JOIN " +
TABLE_NAME_SIMPLECHAPTERS + " ON " + TABLE_NAME_SIMPLECHAPTERS + "." + KEY_FEEDITEM + "=" +
TABLE_NAME_FEED_ITEMS + "." + KEY_ID + " WHERE " + TABLE_NAME_FEED_ITEMS + "." + KEY_FEED + "=" +
feedID + " AND " + TABLE_NAME_SIMPLECHAPTERS + "." + KEY_TITLE + " LIKE '%"
+ prepareSearchQuery(searchQuery) + "%'";
} else {
query = "SELECT " + SEL_FI_SMALL_STR + " FROM " + TABLE_NAME_FEED_ITEMS + " INNER JOIN " +
TABLE_NAME_SIMPLECHAPTERS + " ON " + TABLE_NAME_SIMPLECHAPTERS + "." + KEY_FEEDITEM + "=" +
TABLE_NAME_FEED_ITEMS + "." + KEY_ID + " WHERE " + TABLE_NAME_SIMPLECHAPTERS + "." + KEY_TITLE + " LIKE '%"
+ prepareSearchQuery(searchQuery) + "%'";
}
return db.rawQuery(query, null);
}
public static final int IDX_FEEDSTATISTICS_FEED = 0;
public static final int IDX_FEEDSTATISTICS_NUM_ITEMS = 1;
public static final int IDX_FEEDSTATISTICS_NEW_ITEMS = 2;
public static final int IDX_FEEDSTATISTICS_LATEST_EPISODE = 3;
public static final int IDX_FEEDSTATISTICS_IN_PROGRESS_EPISODES = 4;
/**
* Select number of items, new items, the date of the latest episode and the number of episodes in progress. The result
* is sorted by the title of the feed.
*/
private static final String FEED_STATISTICS_QUERY = "SELECT Feeds.id, num_items, new_items, latest_episode, in_progress FROM " +
" Feeds LEFT JOIN " +
"(SELECT feed,count(*) AS num_items," +
" COUNT(CASE WHEN read=0 THEN 1 END) AS new_items," +
" MAX(pubDate) AS latest_episode," +
" COUNT(CASE WHEN position>0 THEN 1 END) AS in_progress," +
" COUNT(CASE WHEN downloaded=1 THEN 1 END) AS episodes_downloaded " +
" FROM FeedItems LEFT JOIN FeedMedia ON FeedItems.id=FeedMedia.feeditem GROUP BY FeedItems.feed)" +
" ON Feeds.id = feed ORDER BY Feeds.title COLLATE NOCASE ASC;";
public Cursor getFeedStatisticsCursor() {
return db.rawQuery(FEED_STATISTICS_QUERY, null);
}
/**
* Called when a database corruption happens
*/
public static class PodDbErrorHandler implements DatabaseErrorHandler {
@Override
public void onCorruption(SQLiteDatabase db) {
Log.e(TAG, "Database corrupted: " + db.getPath());
File dbPath = new File(db.getPath());
File backupFolder = PodDBAdapter.context.getExternalFilesDir(null);
File backupFile = new File(backupFolder, "CorruptedDatabaseBackup.db");
try {
FileUtils.copyFile(dbPath, backupFile);
Log.d(TAG, "Dumped database to " + backupFile.getPath());
} catch (IOException e) {
Log.d(TAG, Log.getStackTraceString(e));
}
new DefaultDatabaseErrorHandler().onCorruption(db); // This deletes the database
}
}
/**
* Helper class for opening the Antennapod database.
*/
private static class PodDBHelper extends SQLiteOpenHelper {
private static final int VERSION = 1070400;
private final Context context;
/**
* Constructor.
*
* @param context Context to use
* @param name Name of the database
* @param factory to use for creating cursor objects
*/
public PodDBHelper(final Context context, final String name,
final CursorFactory factory) {
super(context, name, factory, VERSION, new PodDbErrorHandler());
this.context = context;
}
@Override
public void onCreate(final SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_FEEDS);
db.execSQL(CREATE_TABLE_FEED_ITEMS);
db.execSQL(CREATE_TABLE_FEED_MEDIA);
db.execSQL(CREATE_TABLE_DOWNLOAD_LOG);
db.execSQL(CREATE_TABLE_QUEUE);
db.execSQL(CREATE_TABLE_SIMPLECHAPTERS);
db.execSQL(CREATE_TABLE_FAVORITES);
db.execSQL(CREATE_INDEX_FEEDITEMS_FEED);
db.execSQL(CREATE_INDEX_FEEDITEMS_PUBDATE);
db.execSQL(CREATE_INDEX_FEEDITEMS_READ);
db.execSQL(CREATE_INDEX_FEEDMEDIA_FEEDITEM);
db.execSQL(CREATE_INDEX_QUEUE_FEEDITEM);
db.execSQL(CREATE_INDEX_SIMPLECHAPTERS_FEEDITEM);
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion,
final int newVersion) {
EventBus.getDefault().post(ProgressEvent.start(context.getString(R.string.progress_upgrading_database)));
Log.w("DBAdapter", "Upgrading from version " + oldVersion + " to "
+ newVersion + ".");
DBUpgrader.upgrade(db, oldVersion, newVersion);
EventBus.getDefault().post(ProgressEvent.end());
}
}
}
|
package com.baidu.unbiz.multiengine.utils;
import io.netty.buffer.ByteBuf;
/**
* Netty ByteBuf
*/
public abstract class BufferUtils {
/**
* ByteBufbyte
*
* @param byteBuf NettyByteBuf @see ByteBuf
* @return byte
*/
public static byte[] bufToBytes(ByteBuf byteBuf) {
if (byteBuf == null) {
return null;
}
int length = byteBuf.readableBytes();
byte[] array = new byte[length];
byteBuf.readBytes(array);
return array;
}
/**
* ByteBufbyte
*
* @param byteBuf NettyByteBuf @see ByteBuf
* @param length
* @return byte
*/
public static byte[] bufToBytes(ByteBuf byteBuf, int length) {
if (byteBuf == null) {
return null;
}
byte[] array = new byte[length];
byteBuf.readBytes(array);
return array;
}
}
|
package org.ow2.chameleon.fuchsia.core;
import org.ow2.chameleon.fuchsia.core.component.DiscoveryService;
import org.ow2.chameleon.fuchsia.core.component.ImporterService;
import java.util.Map;
import java.util.Set;
public interface FuchsiaMediator {
/**
* System property identifying the host name for this FuchsiaMediator.
*/
final static String FUCHSIA_MEDIATOR_HOST = "host";
/**
* TimeStamp
*/
final static String FUCHSIA_MEDIATOR_DATE = "date";
enum EndpointListenerInterest {
LOCAL, REMOTE, ALL
}
/**
* @return The Linkers created the the FuchsiaMediator
*/
Set<Linker> getLinkers();
/**
* @return The ImporterServices services on the platform
*/
Set<ImporterService> getImporterServices();
/**
* @return The DiscoveryService services on the platform
*/
Set<DiscoveryService> getDiscoveryServices();
/**
* @return This FuchsiaMediator host.
*/
String getHost();
/**
* @return This FuchsiaMediator properties.
*/
Map<String, Object> getProperties();
}
|
package com.bebehp.mc.eewreciever.twitter;
import java.util.LinkedList;
import java.util.List;
import com.bebehp.mc.eewreciever.EEWRecieverMod;
import com.bebehp.mc.eewreciever.ping.IAPIPath;
import com.bebehp.mc.eewreciever.ping.QuakeException;
import com.bebehp.mc.eewreciever.ping.QuakeNode;
import twitter4j.Status;
import twitter4j.StatusAdapter;
import twitter4j.StatusListener;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
public class TweetStream implements IAPIPath {
private List<QuakeNode> updatequeue = new LinkedList<QuakeNode>();
Configuration configuration = new ConfigurationBuilder()
.setOAuthConsumerKey("mh5mOJhrXkVarLLdNgDn2QFRO")
.setOAuthConsumerSecret("NbBfZ5ytY47IniUEOoFOIk0wqfOuByzqMzK26DqvH9GhVL0K3E")
.setOAuthAccessToken("4893957312-30hXziVjdX0ZHzH6OJCv0eWAJmaDgyqR7Wwfjob")
.setOAuthAccessTokenSecret("ZwqJSMxSFC7lCMmAjgDw3ikwfgnJE9RVyTZt67MYIsMOM")
.build();
TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();
StatusListener listener = new StatusAdapter() {
@Override
public void onStatus(Status status) {
// TODO
String str = (status.getText());
try {
updatequeue.add(parseString(str));
} catch (QuakeException e) {
EEWRecieverMod.logger.error(e);
}
}
};
public static QuakeNode parseString(String text) throws QuakeException
{
QuakeNode node = new QuakeNode();
try {
String[] tnode = text.split(",", 0);
} catch (Exception e) {
throw new QuakeException("parse error", e);
}
return node;
}
@Override
public List<QuakeNode> getQuakeUpdate() throws QuakeException {
if(updatequeue.isEmpty()) return updatequeue;
List<QuakeNode> ret = new LinkedList<QuakeNode>(updatequeue);
updatequeue.clear();
return ret;
}
}
|
package com.chainstaysoftware.drawerpanefx;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import java.util.Collections;
import java.util.List;
/**
* Base class for a node that provides content to include within a
* drawer within the {@link DrawerPane}. The class also provides title text
* and an icon to include within the show/hide button that is displayed within
* a {@link DrawerPane} toolbar.
*/
public class DrawerNode extends Pane {
private final Node contents;
private final String title;
private final Image icon;
private final boolean canFloat;
private final List<Position> validPositions;
private boolean isFloating;
/**
* Constructor. Defaults icon to null and canFloat to True.
* @param contents Node to display when the drawer is open.
* @param title Title to show on the drawer show/hide button.
*/
public DrawerNode(final Node contents,
final String title) {
this(contents, title, null, true, Collections.emptyList());
}
/**
* Constructor
* @param contents Node to display when the drawer is open.
* @param title Title to show on the drawer show/hide button.
* @param icon Icon to show on the drawer show/hide button. Can be null.
* @param canFloat True if the contents can be detached from the {@link DrawerPane}
* and contained within its own window.
* @param validPositions List of sides that this {@link DrawerNode} can
* be positioned at. Empty list indicates that all
* sides are allowed.
*/
public DrawerNode(final Node contents,
final String title,
final Image icon,
final boolean canFloat,
final List<Position> validPositions) {
if (contents == null) {
throw new IllegalArgumentException("contents must not be null");
}
if (title == null) {
throw new IllegalArgumentException("title must not be null");
}
this.contents = contents;
this.title = title;
this.icon = icon;
this.canFloat = canFloat;
this.validPositions = Collections.unmodifiableList(validPositions);
final VBox vBox = new VBox();
vBox.setId("DrawerNodeVbox-" + title);
vBox.getChildren().addAll(contents);
getChildren().add(vBox);
}
/**
* {@link Node} that this {@link DrawerNode} wraps
*/
public Node getContents() {
return contents;
}
/**
* Title to use for show/hide button.
*/
public String getTitle() {
return title;
}
/**
* Icon to use for show/hide button.
*/
public Image getIcon() {
return icon;
}
/**
* True if this instance is currently floating (detached from the pane).
*/
public boolean isFloating() {
return isFloating;
}
/**
* Sets the floating state for this instance.
*/
public void setFloating(final boolean floating) {
if (!canFloat && floating) {
throw new IllegalArgumentException("Cannot set floating to true when canFloat is false!");
}
isFloating = floating;
}
/**
* True if this instance can be detached from the owning {@link DrawerPane}.
* False otherwise.
*/
public boolean canFloat() {
return canFloat;
}
/**
* A list of valid {@link Position}s for this instance.
*/
public List<Position> getValidPositions() {
return validPositions;
}
/**
* True if this instance can be placed at the passed in {@link Position}.
*/
public boolean isValidPosition(final Position position) {
return position != null && (validPositions.isEmpty() || validPositions.contains(position));
}
}
|
package com.elmakers.mine.bukkit.blocks;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.TreeSpecies;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Painting;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.util.Vector;
import com.elmakers.mine.bukkit.plugins.magic.Mage;
import com.elmakers.mine.bukkit.plugins.magic.MagicController;
import com.elmakers.mine.bukkit.utilities.MaterialMapCanvas;
import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode;
public class MaterialBrush extends MaterialBrushData {
private enum BrushMode {
MATERIAL,
ERASE,
COPY,
CLONE,
REPLICATE,
MAP,
SCHEMATIC
};
public static final String ERASE_MATERIAL_KEY = "erase";
public static final String COPY_MATERIAL_KEY = "copy";
public static final String CLONE_MATERIAL_KEY = "clone";
public static final String REPLICATE_MATERIAL_KEY = "replicate";
public static final String MAP_MATERIAL_KEY = "map";
public static final String SCHEMATIC_MATERIAL_KEY = "schematic";
public static Material EraseMaterial = Material.SULPHUR;
public static Material CopyMaterial = Material.SUGAR;
public static Material CloneMaterial = Material.NETHER_STALK;
public static Material ReplicateMaterial = Material.PUMPKIN_SEEDS;
public static Material MapMaterial = Material.MAP;
public static Material SchematicMaterial = Material.PAPER;
public static boolean SchematicsEnabled = false;
public static final Material DEFAULT_MATERIAL = Material.DIRT;
private BrushMode mode = BrushMode.MATERIAL;
private Location cloneLocation = null;
private Location cloneTarget = null;
private Location materialTarget = null;
private Vector targetOffset = null;
private final MagicController controller;
private short mapId = -1;
private MaterialMapCanvas mapCanvas = null;
private Material mapMaterialBase = Material.STAINED_CLAY;
private Schematic schematic;
private boolean fillWithAir = true;
private Vector orientVector = null;
public MaterialBrush(final MagicController controller, final Material material, final byte data) {
super(material, data);
this.controller = controller;
}
public MaterialBrush(final MagicController controller, final Location location, final String materialKey) {
super(DEFAULT_MATERIAL, (byte)0);
this.controller = controller;
update(materialKey);
activate(location, materialKey);
}
public static String getMaterialKey(Material material) {
return getMaterialKey(material, true);
}
public static String getMaterialKey(Material material, boolean allowItems) {
String materialKey = null;
if (material == null) return null;
if (material == EraseMaterial) {
materialKey = ERASE_MATERIAL_KEY;
} else if (material == CopyMaterial) {
materialKey = COPY_MATERIAL_KEY;
} else if (material == CloneMaterial) {
materialKey = CLONE_MATERIAL_KEY;
} else if (material == MapMaterial) {
materialKey = MAP_MATERIAL_KEY;
} else if (material == ReplicateMaterial) {
materialKey = REPLICATE_MATERIAL_KEY;
} else if (SchematicsEnabled && material == SchematicMaterial) {
// This would be kinda broken.. might want to revisit all this.
// This method is only called by addMaterial at this point,
// which should only be called with real materials anyway.
materialKey = SCHEMATIC_MATERIAL_KEY;
} else if (allowItems || material.isBlock()) {
materialKey = material.name().toLowerCase();
}
return materialKey;
}
public static String getMaterialKey(Material material, byte data) {
return getMaterialKey(material, data, true);
}
public static String getMaterialKey(Material material, byte data, boolean allowItems) {
String materialKey = MaterialBrush.getMaterialKey(material, allowItems);
if (materialKey == null) {
return null;
}
if (data != 0) {
materialKey += ":" + data;
}
return materialKey;
}
public static String getMaterialKey(MaterialAndData materialData) {
return getMaterialKey(materialData.getMaterial(), materialData.getData(), true);
}
public static String getMaterialKey(MaterialAndData materialData, boolean allowItems) {
return getMaterialKey(materialData.getMaterial(), materialData.getData(), allowItems);
}
public static boolean isSpecialMaterialKey(String materialKey) {
if (materialKey == null || materialKey.length() == 0) return false;
materialKey = splitMaterialKey(materialKey)[0];
return COPY_MATERIAL_KEY.equals(materialKey) || ERASE_MATERIAL_KEY.equals(materialKey) ||
REPLICATE_MATERIAL_KEY.equals(materialKey) || CLONE_MATERIAL_KEY.equals(materialKey) ||
MAP_MATERIAL_KEY.equals(materialKey) || (SchematicsEnabled && SCHEMATIC_MATERIAL_KEY.equals(materialKey));
}
public static String[] splitMaterialKey(String materialKey) {
if (materialKey.contains("|")) {
return StringUtils.split(materialKey, "|");
} else if (materialKey.contains(":")) {
return StringUtils.split(materialKey, ":");
}
return new String[] { materialKey };
}
public static String getMaterialName(MaterialAndData material) {
return getMaterialName(getMaterialKey(material));
}
public static String getMaterialName(Material material, byte data) {
return getMaterialName(getMaterialKey(material, data));
}
@SuppressWarnings("deprecation")
public static String getMaterialName(String materialKey) {
if (materialKey == null) return null;
String materialName = materialKey;
String[] namePieces = splitMaterialKey(materialName);
if (namePieces.length == 0) return null;
materialName = namePieces[0];
if (!MaterialBrush.isSpecialMaterialKey(materialKey)) {
MaterialBrushData brushData = parseMaterialKey(materialKey);
if (brushData == null) return null;
Material material = brushData.getMaterial();
byte data = brushData.getData();
// This is the "right" way to do this, but relies on Bukkit actually updating Material in a timely fashion :P
/*
Class<? extends MaterialData> materialData = material.getData();
Bukkit.getLogger().info("Material " + material + " has " + materialData);
if (Wool.class.isAssignableFrom(materialData)) {
Wool wool = new Wool(material, data);
materialName += " " + wool.getColor().name();
} else if (Dye.class.isAssignableFrom(materialData)) {
Dye dye = new Dye(material, data);
materialName += " " + dye.getColor().name();
} else if (Dye.class.isAssignableFrom(materialData)) {
Dye dye = new Dye(material, data);
materialName += " " + dye.getColor().name();
}
*/
// Using raw id's for 1.6 support... because... bukkit... bleh.
//if (material == Material.CARPET || material == Material.STAINED_GLASS || material == Material.STAINED_CLAY || material == Material.STAINED_GLASS_PANE || material == Material.WOOL) {
if (material == Material.CARPET || material.getId() == 95 || material.getId() ==159 || material.getId() == 160 || material == Material.WOOL) {
// Note that getByDyeData doesn't work for stained glass or clay. Kind of misleading?
DyeColor color = DyeColor.getByWoolData(data);
if (color != null) {
materialName = color.name().toLowerCase().replace('_', ' ') + " " + materialName;
}
} else if (material == Material.WOOD || material == Material.LOG || material == Material.SAPLING || material == Material.LEAVES) {
TreeSpecies treeSpecies = TreeSpecies.getByData(data);
if (treeSpecies != null) {
materialName = treeSpecies.name().toLowerCase().replace('_', ' ') + " " + materialName;
}
} else {
materialName = material.name();
}
} else if (materialName.startsWith(MaterialBrush.SCHEMATIC_MATERIAL_KEY) && namePieces.length > 1) {
materialName = namePieces[1];
}
materialName = materialName.toLowerCase().replace('_', ' ');
return materialName;
}
public String getName() {
String brushKey = getKey();
switch (mode) {
case CLONE: brushKey = CLONE_MATERIAL_KEY; break;
case REPLICATE: brushKey = REPLICATE_MATERIAL_KEY; break;
case COPY: brushKey = COPY_MATERIAL_KEY; break;
case MAP: brushKey = MAP_MATERIAL_KEY; break;
case SCHEMATIC: brushKey = SCHEMATIC_MATERIAL_KEY + ":" + schematicName; break;
default: break;
}
return getMaterialName(brushKey);
}
public static MaterialBrushData parseMaterialKey(String materialKey) {
return parseMaterialKey(materialKey, true);
}
@SuppressWarnings("deprecation")
public static MaterialBrushData parseMaterialKey(String materialKey, boolean allowItems) {
if (materialKey == null || materialKey.length() == 0) return null;
Material material = Material.DIRT;
byte data = 0;
String schematicName = "";
String[] pieces = splitMaterialKey(materialKey);
if (materialKey.equals(ERASE_MATERIAL_KEY)) {
material = EraseMaterial;
} else if (materialKey.equals(COPY_MATERIAL_KEY)) {
material = CopyMaterial;
} else if (materialKey.equals(CLONE_MATERIAL_KEY)) {
material = CloneMaterial;
} else if (materialKey.equals(REPLICATE_MATERIAL_KEY)) {
material = ReplicateMaterial;
} else if (materialKey.equals(MAP_MATERIAL_KEY)) {
material = MapMaterial;
} else if (SchematicsEnabled && pieces[0].equals(SCHEMATIC_MATERIAL_KEY)) {
material = SchematicMaterial;
schematicName = pieces[1];
} else {
try {
if (pieces.length > 0) {
// Legacy material id loading
try {
Integer id = Integer.parseInt(pieces[0]);
material = Material.getMaterial(id);
} catch (Exception ex) {
material = Material.getMaterial(pieces[0].toUpperCase());
}
}
// Prevent building with items
if (!allowItems && material != null && !material.isBlock()) {
material = null;
}
} catch (Exception ex) {
material = null;
}
try {
if (pieces.length > 1) {
data = Byte.parseByte(pieces[1]);
}
} catch (Exception ex) {
data = 0;
}
}
if (material == null) return null;
return new MaterialBrushData(material, data, schematicName);
}
public static boolean isValidMaterial(String materialKey) {
return parseMaterialKey(materialKey) != null;
}
public static boolean isValidMaterial(String materialKey, boolean allowItems) {
return parseMaterialKey(materialKey, allowItems) != null;
}
public void update(String activeMaterial) {
String pieces[] = splitMaterialKey(activeMaterial);
if (activeMaterial.equals(COPY_MATERIAL_KEY)) {
enableCopying();
} else if (activeMaterial.equals(CLONE_MATERIAL_KEY)) {
enableCloning();
} else if (activeMaterial.equals(REPLICATE_MATERIAL_KEY)) {
enableReplication();
} else if (activeMaterial.equals(MAP_MATERIAL_KEY)) {
enableMap();
} else if (activeMaterial.equals(ERASE_MATERIAL_KEY)) {
enableErase();
} else if (pieces.length > 1 && pieces[0].equals(SCHEMATIC_MATERIAL_KEY)) {
enableSchematic(pieces[1]);
} else {
MaterialAndData material = parseMaterialKey(activeMaterial);
if (material != null) {
setMaterial(material.getMaterial(), material.getData());
}
}
}
public void activate(final Location location, final String material) {
String materialKey = splitMaterialKey(material)[0];
if (materialKey.equals(CLONE_MATERIAL_KEY) || materialKey.equals(REPLICATE_MATERIAL_KEY)) {
Location cloneFrom = location.clone();
cloneFrom.setY(cloneFrom.getY() - 1);
setCloneLocation(cloneFrom);
} else if (materialKey.equals(MAP_MATERIAL_KEY) || materialKey.equals(SCHEMATIC_MATERIAL_KEY)) {
clearCloneTarget();
}
}
@Override
public void setMaterial(Material material, byte data) {
if (!controller.isRestricted(material) && material.isBlock()) {
super.setMaterial(material, data);
mode = BrushMode.MATERIAL;
isValid = true;
} else {
isValid = false;
}
fillWithAir = true;
}
public void enableCloning() {
if (this.mode != BrushMode.CLONE) {
fillWithAir = this.mode == BrushMode.ERASE;
this.mode = BrushMode.CLONE;
}
}
public void enableErase() {
if (this.mode != BrushMode.ERASE) {
this.setMaterial(Material.AIR);
this.mode = BrushMode.ERASE;
fillWithAir = true;
}
}
@SuppressWarnings("deprecation")
public void enableMap() {
fillWithAir = false;
this.mode = BrushMode.MAP;
if (this.material == Material.WOOL || this.material == Material.STAINED_CLAY
// Use raw id's for 1.6 backwards compatibility.
|| this.material.getId() == 95 || this.material.getId() == 160
// || this.material == Material.STAINED_GLASS || this.material == Material.STAINED_GLASS_PANE
|| this.material == Material.CARPET) {
this.mapMaterialBase = this.material;
}
}
public void enableSchematic(String name) {
if (this.mode != BrushMode.SCHEMATIC) {
fillWithAir = this.mode == BrushMode.ERASE;
this.mode = BrushMode.SCHEMATIC;
}
this.schematicName = name;
schematic = null;
}
public void clearSchematic() {
schematic = null;
}
public void enableReplication() {
if (this.mode != BrushMode.REPLICATE) {
fillWithAir = this.mode == BrushMode.ERASE;
this.mode = BrushMode.REPLICATE;
}
}
public void setData(byte data) {
this.data = data;
}
public void setMapId(short mapId) {
this.mapCanvas = null;
this.mapId = mapId;
}
public void setCloneLocation(Location cloneFrom) {
cloneLocation = cloneFrom;
materialTarget = cloneFrom;
cloneTarget = null;
}
public void clearCloneTarget() {
cloneTarget = null;
targetOffset = null;
}
public void setTargetOffset(Vector offset) {
targetOffset = offset.clone();
}
public boolean hasCloneTarget() {
return cloneLocation != null && cloneTarget != null;
}
public void enableCopying() {
mode = BrushMode.COPY;
}
public boolean isReady() {
if ((mode == BrushMode.CLONE || mode == BrushMode.REPLICATE) && materialTarget != null) {
Block block = materialTarget.getBlock();
return (block.getChunk().isLoaded());
}
return true;
}
public void setTarget(Location target) {
setTarget(target, target);
}
public void setTarget(Location target, Location center) {
orientVector = target.toVector().subtract(center.toVector());
orientVector.setX(Math.abs(orientVector.getX()));
orientVector.setY(Math.abs(orientVector.getY()));
orientVector.setZ(Math.abs(orientVector.getZ()));
if (mode == BrushMode.REPLICATE || mode == BrushMode.CLONE || mode == BrushMode.MAP || mode == BrushMode.SCHEMATIC) {
if (cloneTarget == null || mode == BrushMode.CLONE ||
!center.getWorld().getName().equals(cloneTarget.getWorld().getName())) {
cloneTarget = center;
if (targetOffset != null) {
cloneTarget = cloneTarget.add(targetOffset);
}
} else if (mode == BrushMode.SCHEMATIC) {
if (schematic != null) {
Vector diff = target.toVector().subtract(cloneTarget.toVector());
if (!schematic.contains(diff)) {
cloneTarget = center;
if (targetOffset != null) {
cloneTarget = cloneTarget.add(targetOffset);
}
}
}
}
}
if (mode == BrushMode.COPY) {
Block block = target.getBlock();
updateFrom(block, controller.getRestrictedMaterials());
}
}
public Location toTargetLocation(Location target) {
if (cloneLocation == null || cloneTarget == null) return null;
Location translated = cloneLocation.clone();
translated.subtract(cloneTarget.toVector());
translated.add(target.toVector());
return translated;
}
public Location fromTargetLocation(World targetWorld, Location target) {
if (cloneLocation == null || cloneTarget == null) return null;
Location translated = target.clone();
translated.setX(translated.getBlockX());
translated.setY(translated.getBlockY());
translated.setZ(translated.getBlockZ());
Vector cloneVector = new Vector(cloneLocation.getBlockX(), cloneLocation.getBlockY(), cloneLocation.getBlockZ());
translated.subtract(cloneVector);
Vector cloneTargetVector = new Vector(cloneTarget.getBlockX(), cloneTarget.getBlockY(), cloneTarget.getBlockZ());
translated.add(cloneTargetVector);
translated.setWorld(targetWorld);
return translated;
}
@SuppressWarnings("deprecation")
public boolean update(Mage fromMage, Location target) {
if (mode == BrushMode.CLONE || mode == BrushMode.REPLICATE) {
if (cloneLocation == null) {
isValid = false;
return true;
}
if (cloneTarget == null) cloneTarget = target;
materialTarget = toTargetLocation(target);
if (materialTarget.getY() <= 0 || materialTarget.getY() >= 255) {
isValid = false;
} else {
Block block = materialTarget.getBlock();
if (!block.getChunk().isLoaded()) return false;
updateFrom(block, controller.getRestrictedMaterials());
isValid = fillWithAir || material != Material.AIR;
}
}
if (mode == BrushMode.SCHEMATIC) {
if (schematic == null) {
if (schematicName.length() == 0) {
isValid = false;
return true;
}
schematic = controller.loadSchematic(schematicName);
if (schematic == null) {
schematicName = "";
isValid = false;
return true;
}
}
if (cloneTarget == null) {
isValid = false;
return true;
}
Vector diff = target.toVector().subtract(cloneTarget.toVector());
MaterialAndData newMaterial = schematic.getBlock(diff);
if (newMaterial == null) {
isValid = false;
} else {
updateFrom(newMaterial);
isValid = fillWithAir || newMaterial.getMaterial() != Material.AIR;
}
}
if (mode == BrushMode.MAP && mapId >= 0) {
if (mapCanvas == null && fromMage != null) {
try {
MapView mapView = Bukkit.getMap(mapId);
if (mapView != null) {
List<MapRenderer> renderers = mapView.getRenderers();
if (renderers.size() > 0) {
mapCanvas = new MaterialMapCanvas();
MapRenderer renderer = renderers.get(0);
// This is mainly here as a hack for my own urlmaps that do their own caching
// Bukkit *seems* to want to do caching at the MapView level, but looking at the code-
// they cache but never use the cache?
// Anyway render gets called constantly so I'm not re-rendering on each render... but then
// how to force a render to a canvas? So we re-initialize.
renderer.initialize(mapView);
renderer.render(mapView, mapCanvas, fromMage.getPlayer());
}
}
} catch (Exception ex) {
}
}
isValid = false;
if (mapCanvas != null && cloneTarget != null) {
Vector diff = target.toVector().subtract(cloneTarget.toVector());
// TODO : Different orientations, centering, scaling, etc
// We default to 1/8 scaling for now to make the portraits work well.
DyeColor mapColor = DyeColor.WHITE;
if (orientVector.getBlockY() > orientVector.getBlockZ() || orientVector.getBlockY() > orientVector.getBlockX()) {
if (orientVector.getBlockX() > orientVector.getBlockZ()) {
mapColor = mapCanvas.getDyeColor(
Math.abs(diff.getBlockX() * 8 + MaterialMapCanvas.CANVAS_WIDTH / 2) % MaterialMapCanvas.CANVAS_WIDTH,
Math.abs(diff.getBlockY() * 8 + MaterialMapCanvas.CANVAS_HEIGHT / 2) % MaterialMapCanvas.CANVAS_HEIGHT);
} else {
mapColor = mapCanvas.getDyeColor(
Math.abs(diff.getBlockZ() * 8 + MaterialMapCanvas.CANVAS_WIDTH / 2) % MaterialMapCanvas.CANVAS_WIDTH,
Math.abs(diff.getBlockY() * 8 + MaterialMapCanvas.CANVAS_HEIGHT / 2) % MaterialMapCanvas.CANVAS_HEIGHT);
}
} else {
mapColor = mapCanvas.getDyeColor(
Math.abs(diff.getBlockX() * 8 + MaterialMapCanvas.CANVAS_WIDTH / 2) % MaterialMapCanvas.CANVAS_WIDTH,
Math.abs(diff.getBlockZ() * 8 + MaterialMapCanvas.CANVAS_HEIGHT / 2) % MaterialMapCanvas.CANVAS_HEIGHT);
}
if (mapColor != null) {
super.setMaterial(mapMaterialBase, mapColor.getData());
isValid = true;
}
}
}
return true;
}
public void prepare() {
if (cloneLocation != null) {
Block block = cloneTarget.getBlock();
if (!block.getChunk().isLoaded()) {
block.getChunk().load(true);
}
}
}
public void load(ConfigurationNode node)
{
try {
cloneLocation = node.getLocation("clone_location");
cloneTarget = node.getLocation("clone_target");
materialTarget = node.getLocation("material_target");
mapId = (short)node.getInt("map_id", mapId);
material = node.getMaterial("material", material);
data = (byte)node.getInt("data", data);
schematicName = node.getString("schematic", schematicName);
} catch (Exception ex) {
ex.printStackTrace();
controller.getPlugin().getLogger().warning("Failed to load brush data: " + ex.getMessage());
}
}
public void save(ConfigurationNode node)
{
try {
if (cloneLocation != null) {
node.setProperty("clone_location", cloneLocation);
}
if (cloneTarget != null) {
node.setProperty("clone_target", cloneTarget);
}
if (materialTarget != null) {
node.setProperty("material_target", materialTarget);
}
node.setProperty("map_id", (int)mapId);
node.setProperty("material", material);
node.setProperty("data", data);
node.setProperty("schematic", schematicName);
} catch (Exception ex) {
ex.printStackTrace();
controller.getLogger().warning("Failed to save brush data: " + ex.getMessage());
}
}
public boolean hasEntities()
{
// return mode == BrushMode.CLONE || mode == BrushMode.REPLICATE || mode == BrushMode.SCHEMATIC;
return mode == BrushMode.CLONE || mode == BrushMode.REPLICATE;
}
public List<EntityData> getEntities(Location center, int radius)
{
List<EntityData> copyEntities = new ArrayList<EntityData>();
int radiusSquared = radius * radius;
if (mode == BrushMode.CLONE || mode == BrushMode.REPLICATE)
{
World targetWorld = center.getWorld();
// First clear all hanging entities from the area.
List<Entity> targetEntities = targetWorld.getEntities();
for (Entity entity : targetEntities) {
// Specific check only for what we copy. This could be more abstract.
if (entity instanceof Painting || entity instanceof ItemFrame) {
if (entity.getLocation().distanceSquared(center) <= radiusSquared) {
entity.remove();
}
}
}
// Now copy all hanging entities from the source location
Location cloneLocation = toTargetLocation(center);
World sourceWorld = cloneLocation.getWorld();
List<Entity> entities = sourceWorld.getEntities();
for (Entity entity : entities) {
if (entity instanceof Painting || entity instanceof ItemFrame) {
Location entityLocation = entity.getLocation();
if (entity.getLocation().distanceSquared(cloneLocation) > radiusSquared) continue;
EntityData entityData = new EntityData(fromTargetLocation(center.getWorld(), entityLocation), entity);
copyEntities.add(entityData);
}
}
}
else if (mode == BrushMode.SCHEMATIC)
{
if (schematic != null)
{
return schematic.getEntities(center, radius);
}
}
return copyEntities;
}
}
|
package com.elmakers.mine.bukkit.spell;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.BlockIterator;
import org.bukkit.util.Vector;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.TargetType;
import com.elmakers.mine.bukkit.block.MaterialAndData;
import com.elmakers.mine.bukkit.block.MaterialBrush;
import com.elmakers.mine.bukkit.block.batch.BlockAction;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
import com.elmakers.mine.bukkit.utility.Target;
public abstract class TargetingSpell extends BaseSpell {
private static final int MAX_RANGE = 511;
private Target target = null;
private String targetName = null;
private TargetType targetType = TargetType.OTHER;
private boolean targetNPCs = false;
private int verticalSearchDistance = 8;
private boolean targetingComplete = false;
private boolean targetSpaceRequired = false;
protected Class<? extends Entity> targetEntityType = null;
private Location targetLocation;
private Vector targetLocationOffset;
private String targetLocationWorldName;
protected Location targetLocation2;
private Entity targetEntity = null;
private boolean bypassBuildRestriction = false;
private boolean allowMaxRange = false;
private int range = 32;
private Set<Material> targetThroughMaterials = new HashSet<Material>();
private boolean reverseTargeting = false;
private BlockIterator blockIterator = null;
private Block currentBlock = null;
private Block previousBlock = null;
private Block previousPreviousBlock = null;
private boolean pvpRestricted = false;
private boolean bypassPvpRestriction = false;
@Override
protected void preCast()
{
super.preCast();
initializeTargeting();
}
protected void initializeTargeting()
{
blockIterator = null;
targetSpaceRequired = false;
reverseTargeting = false;
targetingComplete = false;
}
public void setTargetType(TargetType t) {
this.targetType = t;
if (target != null) {
target = null;
initializeTargeting();
}
}
public String getMessage(String messageKey, String def) {
String message = super.getMessage(messageKey, def);
// Escape targeting parameters
String useTargetName = targetName;
if (useTargetName == null) {
if (target != null && target.hasEntity()) {
useTargetName = controller.getEntityName(target.getEntity());
}
else {
useTargetName = "Unknown";
}
}
message = message.replace("$target", useTargetName);
return message;
}
protected void setTargetName(String name) {
targetName = name;
}
public void clearTargetThrough()
{
targetThroughMaterials.clear();
}
public void targetThrough(Material mat)
{
targetThroughMaterials.add(mat);
}
public void targetThrough(Set<Material> mat)
{
targetThroughMaterials.clear();
targetThroughMaterials.addAll(mat);
}
public void noTargetThrough(Material mat)
{
targetThroughMaterials.remove(mat);
}
public boolean isTargetable(Material mat)
{
if (!allowPassThrough(mat)) {
return true;
}
boolean targetThrough = targetThroughMaterials.contains(mat);
if (reverseTargeting)
{
return(targetThrough);
}
return !targetThrough;
}
public void setReverseTargeting(boolean reverse)
{
reverseTargeting = reverse;
}
public boolean isReverseTargeting()
{
return reverseTargeting;
}
public void setTargetSpaceRequired()
{
targetSpaceRequired = true;
}
public void setTarget(Location location) {
target = new Target(getLocation(), location.getBlock());
}
public boolean hasBuildPermission(Block block)
{
if (bypassBuildRestriction) return true;
return mage.hasBuildPermission(block);
}
protected void offsetTarget(int dx, int dy, int dz) {
Location location = getLocation();
if (location == null) {
return;
}
location.add(dx, dy, dz);
initializeBlockIterator(location);
}
protected boolean initializeBlockIterator(Location location) {
if (location.getBlockY() < 0) {
location = location.clone();
location.setY(0);
}
if (location.getBlockY() > controller.getMaxY()) {
location = location.clone();
location.setY(controller.getMaxY());
}
try {
blockIterator = new BlockIterator(location, VIEW_HEIGHT, getMaxRange());
} catch (Exception ex) {
// This seems to happen randomly, like when you use the same target.
// Very annoying, and I now kind of regret switching to BlockIterator.
// At any rate, we're going to just re-use the last target block and
// cross our fingers!
return false;
}
return true;
}
/**
* Move "steps" forward along line of vision and returns the block there
*
* @return The block at the new location
*/
protected Block getNextBlock()
{
previousPreviousBlock = previousBlock;
previousBlock = currentBlock;
if (blockIterator == null || !blockIterator.hasNext()) {
currentBlock = null;
} else {
currentBlock = blockIterator.next();
}
return currentBlock;
}
/**
* Returns the current block along the line of vision
*
* @return The block
*/
public Block getCurBlock()
{
return currentBlock;
}
/**
* Returns the previous block along the line of vision
*
* @return The block
*/
public Block getPreviousBlock()
{
return previousBlock;
}
public TargetType getTargetType()
{
return targetType;
}
protected Target getTarget()
{
target = findTarget();
if (targetLocationOffset != null) {
target.add(targetLocationOffset);
}
if (targetLocationWorldName != null && targetLocationWorldName.length() > 0) {
Location location = target.getLocation();
if (location != null) {
World targetWorld = location.getWorld();
target.setWorld(ConfigurationUtils.overrideWorld(targetLocationWorldName, targetWorld, controller.canCreateWorlds()));
}
}
return target;
}
/**
* Returns the block at the cursor, or null if out of range
*
* @return The target block
*/
public Target findTarget()
{
if (targetType != TargetType.NONE && targetType != TargetType.BLOCK && targetEntity != null) {
return new Target(getLocation(), targetEntity);
}
Entity player = mage.getPlayer();
if (targetType == TargetType.SELF && player != null) {
return new Target(getLocation(), player);
}
CommandSender sender = mage.getCommandSender();
if (targetType == TargetType.SELF && player == null && sender != null && (sender instanceof BlockCommandSender)) {
BlockCommandSender commandBlock = (BlockCommandSender)mage.getCommandSender();
return new Target(commandBlock.getBlock().getLocation(), commandBlock.getBlock());
}
Location location = getLocation();
if (targetType == TargetType.SELF && location != null) {
return new Target(location, location.getBlock());
}
if (targetType == TargetType.SELF) {
return new Target(location);
}
if (targetType != TargetType.NONE && targetLocation != null) {
return new Target(getLocation(), targetLocation.getBlock());
}
if (targetType == TargetType.NONE) {
return new Target(getLocation());
}
findTargetBlock();
Block block = getCurBlock();
if (targetType == TargetType.BLOCK) {
return new Target(getLocation(), block);
}
Target targetBlock = block == null ? null : new Target(getLocation(), block);
Target targetEntity = getEntityTarget();
// Don't allow targeting entities in no-PVP areas.
boolean noPvp = targetEntity != null && (targetEntity instanceof Player) && pvpRestricted && !bypassPvpRestriction && !mage.isPVPAllowed(targetEntity.getLocation());
if (noPvp) {
targetEntity = null;
// Don't let them target the block, either.
targetBlock = null;
}
if (targetEntity == null && targetType == TargetType.ANY && player != null) {
return new Target(getLocation(), player, targetBlock == null ? null : targetBlock.getBlock());
}
if (targetBlock != null && targetEntity != null) {
if (targetBlock.getDistance() < targetEntity.getDistance()) {
targetEntity = null;
} else {
targetBlock = null;
}
}
if (targetEntity != null) {
return targetEntity;
} else if (targetBlock != null) {
return targetBlock;
}
return new Target(getLocation());
}
public Target getCurrentTarget()
{
if (target == null) {
target = new Target(getLocation());
}
return target;
}
public void clearTarget()
{
target = null;
}
public Block getTargetBlock()
{
return getTarget().getBlock();
}
protected Target getEntityTarget()
{
if (targetEntityType == null) return null;
List<Target> scored = getAllTargetEntities();
if (scored.size() <= 0) return null;
return scored.get(0);
}
protected List<Target> getAllTargetEntities() {
List<Target> scored = new ArrayList<Target>();
World world = getWorld();
if (world == null) return scored;
List<Entity> entities = world.getEntities();
for (Entity entity : entities)
{
if (entity == mage.getEntity()) continue;
if (!targetNPCs && controller.isNPC(entity)) continue;
// Special check for Elementals
if (!controller.isElemental(entity) && targetEntityType != null && !targetEntityType.isAssignableFrom(entity.getClass())) continue;
// check for Superprotected Mages
if (controller.isMage(entity)) {
Mage targetMage = controller.getMage(entity);
if (targetMage.isSuperProtected()) continue;
}
// Ignore invisible entities
if (entity instanceof LivingEntity && ((LivingEntity)entity).hasPotionEffect(PotionEffectType.INVISIBILITY)) continue;
Target newScore = new Target(getLocation(), entity, getMaxRange());
if (newScore.getScore() > 0)
{
scored.add(newScore);
}
}
Collections.sort(scored);
return scored;
}
protected int getMaxRange()
{
if (allowMaxRange) return Math.min(MAX_RANGE, range);
return Math.min(MAX_RANGE, (int)(mage.getRangeMultiplier() * range));
}
protected int getMaxRangeSquared()
{
int maxRange = getMaxRange();
return maxRange * maxRange;
}
protected void setMaxRange(int range, boolean allow)
{
this.range = range;
this.allowMaxRange = allow;
}
protected void setMaxRange(int range)
{
this.range = range;
}
protected boolean isTransparent(Material material)
{
return targetThroughMaterials.contains(material);
}
protected void findTargetBlock()
{
Location location = getLocation();
if (location == null) {
return;
}
if (targetingComplete)
{
return;
}
if (!initializeBlockIterator(location)) {
return;
}
currentBlock = null;
previousBlock = null;
previousPreviousBlock = null;
Block block = getNextBlock();
while (block != null)
{
if (targetSpaceRequired) {
if (isOkToStandIn(block.getType()) && isOkToStandIn(block.getRelative(BlockFace.UP).getType())) {
break;
}
} else {
if (isTargetable(block.getType())) {
break;
}
}
block = getNextBlock();
}
if (block == null && allowMaxRange) {
currentBlock = previousBlock;
previousBlock = previousPreviousBlock;
}
targetingComplete = true;
}
public Block getInteractBlock() {
Location location = getEyeLocation();
if (location == null) return null;
Block playerBlock = location.getBlock();
if (isTargetable(playerBlock.getType())) return playerBlock;
Vector direction = location.getDirection().normalize();
return location.add(direction).getBlock();
}
public void coverSurface(Location center, int radius, BlockAction action)
{
int y = center.getBlockY();
for (int dx = -radius; dx < radius; ++dx)
{
for (int dz = -radius; dz < radius; ++dz)
{
if (isInCircle(dx, dz, radius))
{
int x = center.getBlockX() + dx;
int z = center.getBlockZ() + dz;
Block block = getWorld().getBlockAt(x, y, z);
int depth = 0;
if (targetThroughMaterials.contains(block.getType()))
{
while (depth < verticalSearchDistance && targetThroughMaterials.contains(block.getType()))
{
depth++;
block = block.getRelative(BlockFace.DOWN);
}
}
else
{
while (depth < verticalSearchDistance && !targetThroughMaterials.contains(block.getType()))
{
depth++;
block = block.getRelative(BlockFace.UP);
}
block = block.getRelative(BlockFace.DOWN);
}
Block coveringBlock = block.getRelative(BlockFace.UP);
if (!targetThroughMaterials.contains(block.getType()) && targetThroughMaterials.contains(coveringBlock.getType()))
{
action.perform(block);
}
}
}
}
}
@Override
protected void reset()
{
super.reset();
this.target = null;
this.targetName = null;
this.targetLocation = null;
}
@SuppressWarnings("unchecked")
@Override
protected void processParameters(ConfigurationSection parameters) {
super.processParameters(parameters);
range = parameters.getInt("range", range);
allowMaxRange = parameters.getBoolean("allow_max_range", allowMaxRange);
bypassPvpRestriction = parameters.getBoolean("bypass_pvp", false);
bypassPvpRestriction = parameters.getBoolean("bp", bypassPvpRestriction);
bypassBuildRestriction = parameters.getBoolean("bypass_build", false);
bypassBuildRestriction = parameters.getBoolean("bb", bypassBuildRestriction);
if (parameters.contains("transparent")) {
targetThroughMaterials.clear();
targetThroughMaterials.addAll(controller.getMaterialSet(parameters.getString("transparent")));
} else {
targetThroughMaterials.clear();
targetThroughMaterials.addAll(controller.getMaterialSet("transparent"));
}
if (parameters.contains("target")) {
String targetTypeName = parameters.getString("target");
try {
targetType = TargetType.valueOf(targetTypeName.toUpperCase());
} catch (Exception ex) {
controller.getLogger().warning("Invalid target_type: " + targetTypeName);
targetType = TargetType.OTHER;
}
} else {
targetType = TargetType.OTHER;
}
targetNPCs = parameters.getBoolean("target_npc", false);
if (parameters.contains("target_type")) {
String entityTypeName = parameters.getString("target_type");
try {
Class<?> typeClass = Class.forName("org.bukkit.entity." + entityTypeName);
if (Entity.class.isAssignableFrom(typeClass)) {
targetEntityType = (Class<? extends Entity>)typeClass;
} else {
controller.getLogger().warning("Entity type: " + entityTypeName + " not assignable to Entity");
}
} catch (Throwable ex) {
controller.getLogger().warning("Unknown entity type: " + entityTypeName);
targetEntityType = null;
}
}
Location defaultLocation = getLocation();
targetLocation = ConfigurationUtils.overrideLocation(parameters, "t", defaultLocation, controller.canCreateWorlds());
targetLocationOffset = null;
Double otxValue = ConfigurationUtils.getDouble(parameters, "otx", null);
Double otyValue = ConfigurationUtils.getDouble(parameters, "oty", null);
Double otzValue = ConfigurationUtils.getDouble(parameters, "otz", null);
if (otxValue != null || otzValue != null || otyValue != null) {
targetLocationOffset = new Vector(
(otxValue == null ? 0 : otxValue),
(otyValue == null ? 0 : otyValue),
(otzValue == null ? 0 : otzValue));
}
targetLocationWorldName = parameters.getString("otworld");
// For two-click construction spells
defaultLocation = targetLocation == null ? defaultLocation : targetLocation;
targetLocation2 = ConfigurationUtils.overrideLocation(parameters, "t2", defaultLocation, controller.canCreateWorlds());
if (parameters.contains("player")) {
Player player = controller.getPlugin().getServer().getPlayer(parameters.getString("player"));
if (player != null) {
targetLocation = player.getLocation();
targetEntity = player;
}
} else {
targetEntity = null;
}
// Special hack that should work well in most casts.
if (isUnderwater()) {
targetThroughMaterials.add(Material.WATER);
targetThroughMaterials.add(Material.STATIONARY_WATER);
}
}
@Override
protected void loadTemplate(ConfigurationSection node)
{
super.loadTemplate(node);
pvpRestricted = node.getBoolean("pvp_restricted", pvpRestricted);
}
@SuppressWarnings("deprecation")
@Override
protected String getDisplayMaterialName()
{
if (target != null && target.isValid()) {
return MaterialBrush.getMaterialName(target.getBlock().getType(), target.getBlock().getData());
}
return super.getDisplayMaterialName();
}
@Override
protected boolean canCast() {
if (!super.canCast()) return false;
return !pvpRestricted || bypassPvpRestriction || mage.isPVPAllowed(mage.getLocation()) || mage.isSuperPowered();
}
@Override
protected void onBackfire() {
targetType = TargetType.SELF;
}
@Override
public Location getTargetLocation() {
if (target != null && target.isValid()) {
return target.getLocation();
}
return null;
}
@Override
public Entity getTargetEntity() {
if (target != null && target.isValid()) {
return target.getEntity();
}
return null;
}
@Override
public com.elmakers.mine.bukkit.api.block.MaterialAndData getEffectMaterial()
{
if (target != null && target.isValid()) {
Block block = target.getBlock();
MaterialAndData targetMaterial = new MaterialAndData(block);
if (targetMaterial.getMaterial() == Material.AIR) {
targetMaterial.setMaterial(DEFAULT_EFFECT_MATERIAL);
}
return targetMaterial;
}
return super.getEffectMaterial();
}
}
|
package com.ferreusveritas.dynamictrees.trees;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.ferreusveritas.dynamictrees.ModBlocks;
import com.ferreusveritas.dynamictrees.ModConfigs;
import com.ferreusveritas.dynamictrees.ModConstants;
import com.ferreusveritas.dynamictrees.api.TreeHelper;
import com.ferreusveritas.dynamictrees.api.TreeRegistry;
import com.ferreusveritas.dynamictrees.api.network.INodeInspector;
import com.ferreusveritas.dynamictrees.api.network.MapSignal;
import com.ferreusveritas.dynamictrees.api.substances.IEmptiable;
import com.ferreusveritas.dynamictrees.api.substances.ISubstanceEffect;
import com.ferreusveritas.dynamictrees.api.substances.ISubstanceEffectProvider;
import com.ferreusveritas.dynamictrees.api.treedata.IDropCreator;
import com.ferreusveritas.dynamictrees.api.treedata.IDropCreatorStorage;
import com.ferreusveritas.dynamictrees.api.treedata.ILeavesProperties;
import com.ferreusveritas.dynamictrees.api.treedata.ITreePart;
import com.ferreusveritas.dynamictrees.blocks.BlockBonsaiPot;
import com.ferreusveritas.dynamictrees.blocks.BlockBranch;
import com.ferreusveritas.dynamictrees.blocks.BlockDynamicLeaves;
import com.ferreusveritas.dynamictrees.blocks.BlockDynamicSapling;
import com.ferreusveritas.dynamictrees.blocks.BlockRooty;
import com.ferreusveritas.dynamictrees.blocks.LeavesProperties;
import com.ferreusveritas.dynamictrees.entities.EntityFallingTree;
import com.ferreusveritas.dynamictrees.entities.EntityLingeringEffector;
import com.ferreusveritas.dynamictrees.entities.animation.IAnimationHandler;
import com.ferreusveritas.dynamictrees.event.BiomeSuitabilityEvent;
import com.ferreusveritas.dynamictrees.items.Seed;
import com.ferreusveritas.dynamictrees.systems.GrowSignal;
import com.ferreusveritas.dynamictrees.systems.dropcreators.DropCreatorLogs;
import com.ferreusveritas.dynamictrees.systems.dropcreators.DropCreatorSeed;
import com.ferreusveritas.dynamictrees.systems.dropcreators.DropCreatorStorage;
import com.ferreusveritas.dynamictrees.systems.nodemappers.NodeDisease;
import com.ferreusveritas.dynamictrees.systems.nodemappers.NodeFindEnds;
import com.ferreusveritas.dynamictrees.systems.nodemappers.NodeInflator;
import com.ferreusveritas.dynamictrees.systems.substances.SubstanceFertilize;
import com.ferreusveritas.dynamictrees.util.CoordUtils;
import com.ferreusveritas.dynamictrees.util.SafeChunkBounds;
import com.ferreusveritas.dynamictrees.util.SimpleVoxmap;
import com.ferreusveritas.dynamictrees.worldgen.JoCode;
import com.ferreusveritas.dynamictrees.worldgen.JoCodeStore;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.common.BiomeDictionary;
import net.minecraftforge.common.BiomeDictionary.Type;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.Constants.NBT;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.RegistryBuilder;
public class Species extends net.minecraftforge.registries.IForgeRegistryEntry.Impl<Species> {
public final static Species NULLSPECIES = new Species() {
@Override public Seed getSeed() { return Seed.NULLSEED; }
@Override public TreeFamily getFamily() { return TreeFamily.NULLFAMILY; }
@Override public void addJoCodes() {}
@Override public Species setDynamicSapling(net.minecraft.block.state.IBlockState sapling) { return this; }
@Override public IBlockState getDynamicSapling() { return Blocks.AIR.getDefaultState(); }
@Override public boolean plantSapling(World world, BlockPos pos) { return false; }
@Override public boolean generate(World world, BlockPos pos, Biome biome, Random random, int radius, SafeChunkBounds safeBounds) { return false; }
@Override public float biomeSuitability(World world, BlockPos pos) { return 0.0f; }
@Override public boolean addDropCreator(IDropCreator dropCreator) { return false; }
@Override public ItemStack setSeedStack(ItemStack newSeedStack) { return new ItemStack(getSeed()); }
@Override public ItemStack getSeedStack(int qty) { return new ItemStack(getSeed()); }
@Override public void setupStandardSeedDropping() {}
@Override public boolean update(World world, BlockRooty rootyDirt, BlockPos rootPos, int soilLife, ITreePart treeBase, BlockPos treePos, Random random, boolean rapid) { return false; }
};
/**
* Mods should use this to register their {@link Species}
*
* Places the species in a central registry.
* The proper place to use this is during the preInit phase of your mod.
*/
public static IForgeRegistry<Species> REGISTRY;
public static void newRegistry(RegistryEvent.NewRegistry event) {
REGISTRY = new RegistryBuilder<Species>()
.setName(new ResourceLocation(ModConstants.MODID, "species"))
.setDefaultKey(new ResourceLocation(ModConstants.MODID, "null"))
.disableSaving()
.setType(Species.class)
.setIDRange(0, Integer.MAX_VALUE - 1)
.create();
}
/** The family of tree this belongs to. E.g. "Oak" and "Swamp Oak" belong to the "Oak" Family*/
protected final TreeFamily treeFamily;
/** How quickly the branch thickens on it's own without branch merges [default = 0.3] */
protected float tapering = 0.3f;
/** The probability that the direction decider will choose up out of the other possible direction weights [default = 2] */
protected int upProbability = 2;
/** Number of blocks high we have to be before a branch is allowed to form [default = 3](Just high enough to walk under)*/
protected int lowestBranchHeight = 3;
/** Ideal signal energy. Greatest possible height that branches can reach from the root node [default = 16] */
protected float signalEnergy = 16.0f;
/** Ideal growth rate [default = 1.0]*/
protected float growthRate = 1.0f;
/** Ideal soil longevity [default = 8]*/
protected int soilLongevity = 8;
protected HashSet<Block> soilList = new HashSet<Block>();
//Leaves
protected ILeavesProperties leavesProperties;
//Seeds
/** The seed used to reproduce this species. Drops from the tree and can plant itself */
/** Hold damage value for seed items with multiple variants */
protected ItemStack seedStack;
/** A blockState that will turn itself into this tree */
protected IBlockState saplingBlock;
/** A place to store what drops from the species. Similar to a loot table */
protected IDropCreatorStorage dropCreatorStorage = new DropCreatorStorage();
//WorldGen
/** A map of environmental biome factors that change a tree's suitability */
protected Map <Type, Float> envFactors = new HashMap<Type, Float>();//Environmental factors
/** A list of JoCodes for world generation. Initialized in addJoCodes()*/
protected JoCodeStore joCodeStore = new JoCodeStore(this);
/**
* Constructor only used by NULLSPECIES
*/
public Species() {
this.treeFamily = TreeFamily.NULLFAMILY;
this.leavesProperties = LeavesProperties.NULLPROPERTIES;
}
/**
* Constructor suitable for derivative mods
*
* @param modid The MODID of the mod that is registering this species
* @param name The simple name of the species e.g. "oak"
* @param treeFamily The {@link TreeFamily} that this species belongs to.
*/
public Species(ResourceLocation name, TreeFamily treeFamily, ILeavesProperties leavesProperties) {
setRegistryName(name);
this.treeFamily = treeFamily;
setLeavesProperties(leavesProperties);
setStandardSoils();
seedStack = new ItemStack(Seed.NULLSEED);
saplingBlock = Blocks.AIR.getDefaultState();
//Add JoCode models for worldgen
addJoCodes();
addDropCreator(new DropCreatorLogs());
}
public TreeFamily getFamily() {
return treeFamily;
}
protected void setBasicGrowingParameters(float tapering, float energy, int upProbability, int lowestBranchHeight, float growthRate) {
this.tapering = tapering;
this.signalEnergy = energy;
this.upProbability = upProbability;
this.lowestBranchHeight = lowestBranchHeight;
this.growthRate = growthRate;
}
public float getEnergy(World world, BlockPos rootPos) {
return signalEnergy;
}
public float getGrowthRate(World world, BlockPos rootPos) {
return growthRate;
}
/** Probability reinforcer for up direction which is arguably the direction most trees generally grow in.*/
public int getUpProbability() {
return upProbability;
}
/** Probability reinforcer for current travel direction */
public int getReinfTravel() {
return 1;
}
public int getLowestBranchHeight() {
return lowestBranchHeight;
}
/**
* @param world
* @param pos
* @return The lowest number of blocks from the RootyDirtBlock that a branch can form.
*/
public int getLowestBranchHeight(World world, BlockPos pos) {
return getLowestBranchHeight();
}
public float getTapering() {
return tapering;
}
//LEAVES
public void setLeavesProperties(ILeavesProperties leavesProperties) {
this.leavesProperties = leavesProperties;
}
public ILeavesProperties getLeavesProperties() {
return leavesProperties;
}
//SEEDS
/**
* Get a copy of the {@link Seed} stack with the supplied quantity.
* This is necessary because the stack may be combined with
* {@link NBT} data.
*
* @param qty The number of items in the newly copied stack.
* @return A copy of the {@link ItemStack} with the {@link Seed} inside.
*/
public ItemStack getSeedStack(int qty) {
ItemStack stack = seedStack.copy();
stack.setCount(MathHelper.clamp(qty, 0, 64));
return stack;
}
public Seed getSeed() {
return (Seed) seedStack.getItem();
}
/**
* Generate a seed. Developer is still required to register the item
* in the appropriate registries.
*/
public ItemStack generateSeed() {
Seed seed = new Seed(getRegistryName().getResourcePath() + "seed");
return setSeedStack(new ItemStack(seed));
}
public ItemStack setSeedStack(ItemStack newSeedStack) {
if(newSeedStack.getItem() instanceof Seed) {
seedStack = newSeedStack;
Seed seed = (Seed) seedStack.getItem();
seed.setSpecies(this, seedStack);
return seedStack;
} else {
System.err.println("setSeedStack must have an ItemStack with an Item that is an instance of a Seed");
}
return ItemStack.EMPTY;
}
//It's mostly for seeds.. mostly.
public void setupStandardSeedDropping() {
addDropCreator(new DropCreatorSeed());
}
public boolean addDropCreator(IDropCreator dropCreator) {
return dropCreatorStorage.addDropCreator(dropCreator);
}
public boolean remDropCreator(ResourceLocation dropCreatorName) {
return dropCreatorStorage.remDropCreator(dropCreatorName);
}
public Map<ResourceLocation, IDropCreator> getDropCreators() {
return dropCreatorStorage.getDropCreators();
}
/**
* Gets a list of drops for a {@link BlockDynamicLeaves} when the entire tree is harvested.
* NOT used for individual {@link BlockDynamicLeaves} being directly harvested by hand or tool.
*
* @param world
* @param leafPos
* @param dropList
* @param random
* @return
*/
public List<ItemStack> getTreeHarvestDrops(World world, BlockPos leafPos, List<ItemStack> dropList, Random random) {
dropList = TreeRegistry.globalDropCreatorStorage.getHarvestDrop(world, this, leafPos, random, dropList, 0, 0);
return dropCreatorStorage.getHarvestDrop(world, this, leafPos, random, dropList, 0, 0);
}
/**
* Gets a {@link List} of voluntary drops. Voluntary drops are {@link ItemStack}s that fall from the {@link TreeFamily} at
* random with no player interaction.
*
* @param world
* @param rootPos
* @param treePos
* @param soilLife
* @return
*/
public List<ItemStack> getVoluntaryDrops(World world, BlockPos rootPos, BlockPos treePos, int soilLife) {
List<ItemStack> dropList = TreeRegistry.globalDropCreatorStorage.getVoluntaryDrop(world, this, rootPos, world.rand, null, soilLife);
return dropCreatorStorage.getVoluntaryDrop(world, this, rootPos, world.rand, dropList, soilLife);
}
/**
* Gets a {@link List} of Leaves drops. Leaves drops are {@link ItemStack}s that result from the breaking of
* a {@link BlockDynamicLeaves} directly by hand or with a tool.
*
* @param access
* @param breakPos
* @param dropList
* @param fortune
* @return
*/
public List<ItemStack> getLeavesDrops(IBlockAccess access, BlockPos breakPos, List<ItemStack> dropList, int fortune) {
Random random = access instanceof World ? ((World)access).rand : new Random();
dropList = TreeRegistry.globalDropCreatorStorage.getLeavesDrop(access, this, breakPos, random, dropList, fortune);
return dropCreatorStorage.getLeavesDrop(access, this, breakPos, random, dropList, fortune);
}
/**
* Gets a {@link List} of Logs drops. Logs drops are {@link ItemStack}s that result from the breaking of
* a {@link BlockBranch} directly by hand or with a tool.
*
* @param world
* @param breakPos
* @param dropList
* @param volume
* @return
*/
public List<ItemStack> getLogsDrops(World world, BlockPos breakPos, List<ItemStack> dropList, int volume) {
dropList = TreeRegistry.globalDropCreatorStorage.getLogsDrop(world, this, breakPos, world.rand, dropList, volume);
return dropCreatorStorage.getLogsDrop(world, this, breakPos, world.rand, dropList, volume);
}
/**
*
* @param world
* @param endPoints
* @param rootPos
* @param treePos
* @param soilLife
* @return true if seed was dropped
*/
public boolean handleVoluntaryDrops(World world, List<BlockPos> endPoints, BlockPos rootPos, BlockPos treePos, int soilLife) {
int tickSpeed = world.getGameRules().getInt("randomTickSpeed");
if(tickSpeed > 0) {
double slowFactor = 3.0 / tickSpeed;//This is an attempt to normalize voluntary drop rates.
if(world.rand.nextDouble() < slowFactor) {
List<ItemStack> drops = getVoluntaryDrops(world, rootPos, treePos, soilLife);
if(!drops.isEmpty() && !endPoints.isEmpty()) {
for(ItemStack drop: drops) {
BlockPos branchPos = endPoints.get(world.rand.nextInt(endPoints.size()));
branchPos = branchPos.up();//We'll aim at the block above the end branch. Helps with Acacia leaf block formations
BlockPos itemPos = CoordUtils.getRayTraceFruitPos(world, this, treePos, branchPos, SafeChunkBounds.ANY);
if(itemPos != BlockPos.ORIGIN) {
EntityItem itemEntity = new EntityItem(world, itemPos.getX() + 0.5, itemPos.getY() + 0.5, itemPos.getZ() + 0.5, drop);
Vec3d motion = new Vec3d(itemPos).subtract(new Vec3d(treePos));
float distAngle = 15;//The spread angle(center to edge)
float launchSpeed = 4;//Blocks(meters) per second
motion = new Vec3d(motion.x, 0, motion.y).normalize().rotateYaw((world.rand.nextFloat() * distAngle * 2) - distAngle).scale(launchSpeed/20f);
itemEntity.motionX = motion.x;
itemEntity.motionY = motion.y;
itemEntity.motionZ = motion.z;
return world.spawnEntity(itemEntity);
}
}
}
}
}
return true;
}
//SAPLING
/**
* Sets the Dynamic Sapling for this tree type. Also sets
* the tree type in the dynamic sapling.
*
* @param sapling
* @return
*/
public Species setDynamicSapling(IBlockState sapling) {
saplingBlock = sapling;//Link the tree to the sapling
//Link the sapling to the Species
if(saplingBlock.getBlock() instanceof BlockDynamicSapling) {
BlockDynamicSapling dynSap = (BlockDynamicSapling) saplingBlock.getBlock();
dynSap.setSpecies(saplingBlock, this);
}
return this;
}
public Species setDynamicSapling(String speciesName) {
return setDynamicSapling(new BlockDynamicSapling(speciesName + "sapling").getDefaultState());
}
public IBlockState getDynamicSapling() {
return saplingBlock;
}
/**
* Checks surroundings and places a dynamic sapling block.
*
* @param world
* @param pos
* @return true if the planting was successful
*/
public boolean plantSapling(World world, BlockPos pos) {
if(world.getBlockState(pos).getBlock().isReplaceable(world, pos) && BlockDynamicSapling.canSaplingStay(world, this, pos)) {
world.setBlockState(pos, getDynamicSapling());
return true;
}
return false;
}
//This is for the sapling.
//If false is returned then nothing happens.
//If true is returned canUseBoneMealNow is run then the bonemeal is consumed regardless of it's return.
public boolean canGrowWithBoneMeal(World world, BlockPos pos) {
return canBoneMeal();
}
//This is for the sapling.
//Return weather or not the bonemealing should cause growth
public boolean canUseBoneMealNow(World world, Random rand, BlockPos pos) {
return canBoneMeal();
}
//This is for the tree itself.
public boolean canBoneMeal() {
return true;
}
//DIRT
public BlockRooty getRootyBlock() {
return ModBlocks.blockRootyDirt;
}
public boolean placeRootyDirtBlock(World world, BlockPos rootPos, int life) {
world.setBlockState(rootPos, getRootyBlock().getDefaultState().withProperty(BlockRooty.LIFE, life));
return true;
}
public void setSoilLongevity(int longevity) {
soilLongevity = longevity;
}
public int getSoilLongevity(World world, BlockPos rootPos) {
return (int)(biomeSuitability(world, rootPos) * soilLongevity);
}
public void addAcceptableSoil(Block ... soilBlocks) {
Collections.addAll(soilList, soilBlocks);
}
public void remAcceptableSoil(Block soilBlock) {
soilList.remove(soilBlock);
}
public void clearAcceptableSoils() {
soilList.clear();
}
protected final void setStandardSoils() {
addAcceptableSoil(Blocks.DIRT, Blocks.GRASS, Blocks.MYCELIUM);
}
/**
* Position sensitive soil acceptability tester. Mostly to test if the block is dirt but could
* be overridden to allow gravel, sand, or whatever makes sense for the tree
* species.
*
* @param world
* @param pos
* @param soilBlockState
* @return
*/
public boolean isAcceptableSoil(World world, BlockPos pos, IBlockState soilBlockState) {
Block soilBlock = soilBlockState.getBlock();
return soilList.contains(soilBlock) || soilBlock instanceof BlockRooty;
}
/**
* Version of soil acceptability tester that is only run for worldgen. This allows for Swamp oaks and stuff.
*
* @param world
* @param pos
* @param soilBlockState
* @return
*/
public boolean isAcceptableSoilForWorldgen(World world, BlockPos pos, IBlockState soilBlockState) {
return isAcceptableSoil(world, pos, soilBlockState);
}
// GROWTH
/**
* Basic update. This handles everything for the species Rot, Drops, Fruit, Disease, and Growth respectively.
* If the rapid option is enabled then drops, fruit and disease are skipped.
*
* This should never be run by the world generator.
*
*
* @param world The world
* @param rootyDirt The {@link BlockRooty} that is supporting this tree
* @param rootPos The {@link BlockPos} of the {@link BlockRooty} type in the world
* @param soilLife The life of the soil. 0: Depleted -> 15: Full
* @param treePos The {@link BlockPos} of the {@link TreeFamily} trunk base.
* @param random A random number generator
* @param natural Set this to true if this member is being used to naturally grow the tree(create drops or fruit)
* @return true if network is viable. false if network is not viable(will destroy the {@link BlockRooty} this tree is on)
*/
public boolean update(World world, BlockRooty rootyDirt, BlockPos rootPos, int soilLife, ITreePart treeBase, BlockPos treePos, Random random, boolean natural) {
//Analyze structure to gather all of the endpoints. They will be useful for this entire update
List<BlockPos> ends = getEnds(world, treePos, treeBase);
//This will prune rotted positions from the world and the end point list
if(handleRot(world, ends, rootPos, treePos, soilLife, SafeChunkBounds.ANY)) {
return false;//Last piece of tree rotted away.
}
if(natural) {
//This will handle seed drops
handleVoluntaryDrops(world, ends, rootPos, treePos, soilLife);
//This will handle disease chance
if(handleDisease(world, treeBase, treePos, random, soilLife)) {
return true;//Although the tree may be diseased. The tree network is still viable.
}
}
return grow(world, rootyDirt, rootPos, soilLife, treeBase, treePos, random, natural);
}
/**
* A little internal convenience function for getting branch endpoints
*
* @param world The world
* @param treePos The {@link BlockPos} of the base of the {@link TreeFamily} trunk
* @param treeBase The tree part that is the base of the {@link TreeFamily} trunk. Provided for easy analysis.
* @return A list of all branch endpoints for the {@link TreeFamily}
*/
final protected List<BlockPos> getEnds(World world, BlockPos treePos, ITreePart treeBase) {
NodeFindEnds endFinder = new NodeFindEnds();
treeBase.analyse(world.getBlockState(treePos), world, treePos, null, new MapSignal(endFinder));
return endFinder.getEnds();
}
/**
* A rot handler.
*
* @param world The world
* @param ends A {@link List} of {@link BlockPos}s of {@link BlockBranch} endpoints.
* @param rootPos The {@link BlockPos} of the {@link BlockRooty} for this {@link TreeFamily}
* @param treePos The {@link BlockPos} of the trunk base for this {@link TreeFamily}
* @param soilLife The soil life of the {@link BlockRooty}
* @param safeBounds The defined boundaries where it is safe to make block changes
* @return true if last piece of tree rotted away.
*/
public boolean handleRot(World world, List<BlockPos> ends, BlockPos rootPos, BlockPos treePos, int soilLife, SafeChunkBounds safeBounds) {
Iterator<BlockPos> iter = ends.iterator();//We need an iterator since we may be removing elements.
SimpleVoxmap leafMap = getLeavesProperties().getCellKit().getLeafCluster();
while (iter.hasNext()) {
BlockPos endPos = iter.next();
IBlockState branchState = world.getBlockState(endPos);
BlockBranch branch = TreeHelper.getBranch(branchState);
if(branch != null) {
int radius = branch.getRadius(branchState);
float rotChance = rotChance(world, endPos, world.rand, radius);
if(branch.checkForRot(world, endPos, this, radius, world.rand, rotChance, safeBounds != SafeChunkBounds.ANY) || radius != 1) {
if(safeBounds != SafeChunkBounds.ANY) { //worldgen
TreeHelper.ageVolume(world, endPos.down((leafMap.getLenZ() - 1) / 2), (leafMap.getLenX() - 1) / 2, leafMap.getLenY(), 2, safeBounds);
}
iter.remove();//Prune out the rotted end points so we don't spawn fruit from them.
}
}
}
return ends.isEmpty() && !TreeHelper.isBranch(world.getBlockState(treePos));//There are no endpoints and the trunk is missing
}
static private final EnumFacing upFirst[] = {EnumFacing.UP, EnumFacing.NORTH, EnumFacing.SOUTH, EnumFacing.EAST, EnumFacing.WEST};
/**
* Handle rotting branches
* @param world The world
* @param pos
* @param neighborCount Count of neighbors reinforcing this block
* @param radius The radius of the branch
* @param random Access to a random number generator
* @return true if the branch should rot
*/
public boolean rot(World world, BlockPos pos, int neighborCount, int radius, Random random) {
if(radius <= 1) {
BlockDynamicLeaves leaves = (BlockDynamicLeaves) getLeavesProperties().getDynamicLeavesState().getBlock();
for(EnumFacing dir: upFirst) {
if(leaves.growLeavesIfLocationIsSuitable(world, getLeavesProperties(), pos.offset(dir), 0)) {
return false;
}
}
}
world.setBlockToAir(pos);
return true;
}
/**
* Provides the chance that a log will rot.
*
* @param world The world
* @param pos The {@link BlockPos} of the {@link BlockBranch}
* @param rand A random number generator
* @param radius The radius of the {@link BlockBranch}
* @return The chance this will rot. 0.0(never) -> 1.0(always)
*/
public float rotChance(World world, BlockPos pos, Random rand, int radius) {
return 0.3f + ((8 - radius) * 0.1f);// Thicker branches take longer to rot
}
/**
* The grow handler.
*
* @param world The world
* @param rootyDirt The {@link BlockRooty} that is supporting this tree
* @param rootPos The {@link BlockPos} of the {@link BlockRooty} type in the world
* @param soilLife The life of the soil. 0: Depleted -> 15: Full
* @param treePos The {@link BlockPos} of the {@link TreeFamily} trunk base.
* @param random A random number generator
* @param natural Set this to true if this member is being used to grow the tree naturally(create drops or fruit)
* @return true if network is viable. false if network is not viable(will destroy the {@link BlockRooty} this tree is on)
*/
public boolean grow(World world, BlockRooty rootyDirt, BlockPos rootPos, int soilLife, ITreePart treeBase, BlockPos treePos, Random random, boolean natural) {
float growthRate = getGrowthRate(world, rootPos) * ModConfigs.treeGrowthRateMultiplier;
do {
if(growthRate > random.nextFloat()) {
if(soilLife > 0){
boolean success = treeBase.growSignal(world, treePos, new GrowSignal(this, rootPos, getEnergy(world, rootPos))).success;
int soilLongevity = getSoilLongevity(world, rootPos) * (success ? 1 : 16);//Don't deplete the soil as much if the grow operation failed
if(soilLongevity <= 0 || random.nextInt(soilLongevity) == 0) {//1 in X(soilLongevity) chance to draw nutrients from soil
rootyDirt.setSoilLife(world, rootPos, soilLife - 1);//decrement soil life
}
}
}
} while(--growthRate > 0.0f);
return postGrow(world, rootPos, treePos, soilLife, natural);
}
/**
* Selects a new direction for the branch(grow) signal to turn to.
* This function uses a probability map to make the decision and is acted upon by the GrowSignal() function in the branch block.
* Can be overridden for different species but it's preferable to override customDirectionManipulation.
*
* @param world The World
* @param pos
* @param branch The branch block the GrowSignal is traveling in.
* @param signal The grow signal.
* @return
*/
public EnumFacing selectNewDirection(World world, BlockPos pos, BlockBranch branch, GrowSignal signal) {
EnumFacing originDir = signal.dir.getOpposite();
//prevent branches on the ground
if(signal.numSteps + 1 <= getLowestBranchHeight(world, signal.rootPos)) {
return EnumFacing.UP;
}
int probMap[] = new int[6];//6 directions possible DUNSWE
//Probability taking direction into account
probMap[EnumFacing.UP.ordinal()] = signal.dir != EnumFacing.DOWN ? getUpProbability(): 0;//Favor up
probMap[signal.dir.ordinal()] += getReinfTravel(); //Favor current direction
//Create probability map for direction change
for(EnumFacing dir: EnumFacing.VALUES) {
if(!dir.equals(originDir)) {
BlockPos deltaPos = pos.offset(dir);
//Check probability for surrounding blocks
//Typically Air:1, Leaves:2, Branches: 2+r
IBlockState deltaBlockState = world.getBlockState(deltaPos);
probMap[dir.getIndex()] += TreeHelper.getTreePart(deltaBlockState).probabilityForBlock(deltaBlockState, world, deltaPos, branch);
}
}
//Do custom stuff or override probability map for various species
probMap = customDirectionManipulation(world, pos, branch.getRadius(world.getBlockState(pos)), signal, probMap);
//Select a direction from the probability map
int choice = com.ferreusveritas.dynamictrees.util.MathHelper.selectRandomFromDistribution(signal.rand, probMap);//Select a direction from the probability map
return newDirectionSelected(EnumFacing.getFront(choice != -1 ? choice : 1), signal);//Default to up if things are screwy
}
/** Species can override the probability map here **/
protected int[] customDirectionManipulation(World world, BlockPos pos, int radius, GrowSignal signal, int probMap[]) {
return probMap;
}
/** Species can override to take action once a new direction is selected **/
protected EnumFacing newDirectionSelected(EnumFacing newDir, GrowSignal signal) {
return newDir;
}
/**
* Allows a species to do things after a grow event just occured. Currently used
* by Jungle trees to create cocoa pods on the trunk
*
* @param world
* @param rootPos
* @param treePos
* @param soilLife
*/
public boolean postGrow(World world, BlockPos rootPos, BlockPos treePos, int soilLife, boolean natural) {
return true;
}
/**
* Decide what happens for diseases.
*
* @param world
* @param baseTreePart
* @param treePos
* @param random
* @return true if the tree became diseased
*/
public boolean handleDisease(World world, ITreePart baseTreePart, BlockPos treePos, Random random, int soilLife) {
if(soilLife == 0 && ModConfigs.diseaseChance > random.nextFloat() ) {
baseTreePart.analyse(world.getBlockState(treePos), world, treePos, EnumFacing.DOWN, new MapSignal(new NodeDisease(this)));
return true;
}
return false;
}
// BIOME HANDLING
public Species envFactor(Type type, float factor) {
envFactors.put(type, factor);
return this;
}
/**
*
* @param world The World
* @param pos
* @return range from 0.0 - 1.0. (0.0f for completely unsuited.. 1.0f for perfectly suited)
*/
public float biomeSuitability(World world, BlockPos pos) {
Biome biome = world.getBiome(pos);
//An override to allow other mods to change the behavior of the suitability for a world location. Such as Terrafirmacraft.
BiomeSuitabilityEvent suitabilityEvent = new BiomeSuitabilityEvent(world, biome, this, pos);
MinecraftForge.EVENT_BUS.post(suitabilityEvent);
if(suitabilityEvent.isHandled()) {
return suitabilityEvent.getSuitability();
}
float ugs = ModConfigs.scaleBiomeGrowthRate;//universal growth scalar
if(ugs == 1.0f || isBiomePerfect(biome)) {
return 1.0f;
}
float suit = defaultSuitability();
for(Type t : BiomeDictionary.getTypes(biome)) {
suit *= envFactors.containsKey(t) ? envFactors.get(t) : 1.0f;
}
//Linear interpolation of suitability with universal growth scalar
suit = ugs <= 0.5f ? ugs * 2.0f * suit : ((1.0f - ugs) * suit + (ugs - 0.5f)) * 2.0f;
return MathHelper.clamp(suit, 0.0f, 1.0f);
}
public boolean isBiomePerfect(Biome biome) {
return false;
}
/** A value that determines what a tree's suitability is before climate manipulation occurs. */
public static final float defaultSuitability() {
return 0.85f;
}
/**
* A convenience function to test if a biome is one of the many options passed.
*
* @param biomeToCheck The biome we are matching
* @param biomes Multiple biomes to match against
* @return True if a match is found. False if not.
*/
public static boolean isOneOfBiomes(Biome biomeToCheck, Biome ... biomes) {
for(Biome biome: biomes) {
if(biomeToCheck == biome) {
return true;
}
}
return false;
}
// INTERACTIVE
public ISubstanceEffect getSubstanceEffect(ItemStack itemStack) {
//Bonemeal fertilizes the soil and causes a single growth pulse
if( canBoneMeal() && itemStack.getItem() == Items.DYE && itemStack.getItemDamage() == 15) {
return new SubstanceFertilize().setAmount(1).setGrow(true);
}
//Use substance provider interface if it's available
if(itemStack.getItem() instanceof ISubstanceEffectProvider) {
ISubstanceEffectProvider provider = (ISubstanceEffectProvider) itemStack.getItem();
return provider.getSubstanceEffect(itemStack);
}
return null;
}
/**
* Apply an item to the treepart(e.g. bonemeal). Developer is responsible for decrementing itemStack after applying.
*
* @param world The current world
* @param hitPos Position
* @param player The player applying the substance
* @param itemStack The itemstack to be used.
* @return true if item was used, false otherwise
*/
public boolean applySubstance(World world, BlockPos rootPos, BlockPos hitPos, EntityPlayer player, EnumHand hand, ItemStack itemStack) {
ISubstanceEffect effect = getSubstanceEffect(itemStack);
if(effect != null) {
if(effect.isLingering()) {
world.spawnEntity(new EntityLingeringEffector(world, rootPos, effect));
return true;
} else {
return effect.apply(world, rootPos);
}
}
return false;
}
public boolean onTreeActivated(World world, BlockPos rootPos, BlockPos hitPos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) {
if (heldItem != null) {//Something in the hand
if(applySubstance(world, rootPos, hitPos, player, hand, heldItem)) {
Species.consumePlayerItem(player, hand, heldItem);
return true;
}
}
return false;
}
public static void consumePlayerItem(EntityPlayer player, EnumHand hand, ItemStack heldItem) {
if (heldItem.getItem() instanceof IEmptiable) {//A substance deployed from a refillable container
if(!player.capabilities.isCreativeMode) {
IEmptiable emptiable = (IEmptiable) heldItem.getItem();
player.setHeldItem(hand, emptiable.getEmptyContainer());
}
}
else if(heldItem.getItem() == Items.POTIONITEM) {//An actual potion
if(!player.capabilities.isCreativeMode) {
player.setHeldItem(hand, new ItemStack(Items.GLASS_BOTTLE));
}
} else {
heldItem.shrink(1);//Just a regular item like bonemeal
}
}
// FALL ANIMATION HANDLING
public IAnimationHandler selectAnimationHandler(EntityFallingTree fallingEntity) {
return getFamily().selectAnimationHandler(fallingEntity);
}
// BONSAI POT
/**
* Provides the {@link BlockBonsaiPot} for this Species. A mod can
* derive it's own BonzaiPot subclass if it wants something custom.
*
* @return A {@link BlockBonsaiPot}
*/
public BlockBonsaiPot getBonzaiPot() {
return ModBlocks.blockBonsaiPot;
}
// WORLDGEN
/**
* Default worldgen spawn mechanism.
* This method uses JoCodes to generate tree models.
* Override to use other methods.
*
* @param world The world
* @param pos The position of {@link BlockRooty} this tree is planted in
* @param biome The biome this tree is generating in
* @param facing The orientation of the tree(rotates JoCode)
* @param radius The radius of the tree generation boundary
* @return true if tree was generated. false otherwise.
*/
public boolean generate(World world, BlockPos pos, Biome biome, Random random, int radius, SafeChunkBounds safeBounds) {
EnumFacing facing = CoordUtils.getRandomDir(random);
if(getJoCodeStore() != null) {
JoCode code = getJoCodeStore().getRandomCode(radius, random);
if(code != null) {
code.generate(world, this, pos, biome, facing, radius, safeBounds);
return true;
}
}
return false;
}
public JoCodeStore getJoCodeStore() {
return joCodeStore;
}
public JoCode getJoCode(String joCodeString) {
return new JoCode(joCodeString);
}
/**
* A {@link JoCode} defines the block model of the {@link TreeFamily}
*/
public void addJoCodes() {
joCodeStore.addCodesFromFile(this, "assets/" + getRegistryName().getResourceDomain() + "/trees/"+ getRegistryName().getResourcePath() + ".txt");
}
/**
* Allows the tree to decorate itself after it has been generated. Add vines, fruit, etc.
*
* @param world The world
* @param rootPos The position of {@link BlockRooty} this tree is planted in
* @param biome The biome this tree is generating in
* @param radius The radius of the tree generation boundary
* @param endPoints A {@link List} of {@link BlockPos} in the world designating branch endpoints
* @param worldGen true if this is being generated by the world generator, false if it's the staff, dendrocoil, etc.
*/
public void postGeneration(World world, BlockPos rootPos, Biome biome, int radius, List<BlockPos> endPoints, SafeChunkBounds safeBounds) {}
/**
* Worldgen can produce thin sickly trees from the underinflation caused by not living it's full life.
* This factor is an attempt to compensate for the problem.
*
* @return
*/
public float getWorldGenTaperingFactor() {
return 1.5f;
}
public int getWorldGenLeafMapHeight() {
return 32;
}
public int getWorldGenAgeIterations() {
return 3;
}
public INodeInspector getNodeInflator(SimpleVoxmap leafMap) {
return new NodeInflator(this, leafMap);
}
@Override
public String toString() {
return getRegistryName().toString();
}
}
|
package com.github.davidcanboni.jenkins;
import com.github.davidcanboni.jenkins.values.Environment;
import com.github.davidcanboni.jenkins.values.GitRepo;
import com.github.davidcanboni.jenkins.xml.Xml;
import com.github.davidcarboni.ResourceUtils;
import com.github.onsdigital.http.Endpoint;
import com.github.onsdigital.http.Http;
import com.github.onsdigital.http.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Handles jobs in the Maven Build category.
*/
public class ContainerJobs {
public static Document forRepo(URL gitUrl) throws IOException {
Document document = getTemplate();
setGitUrl(gitUrl, document);
return document;
}
public static Document forRepo(GitRepo gitRepo, Environment environment) throws IOException {
Document document = getTemplate();
setGitUrl(gitRepo.url, document);
setBranch(environment.name(), document);
setDownstreamDeployJobs(environment, document);
if (gitRepo.nodeJs) {
addNodeBuildStep(document, gitRepo);
}
removeImageCommand(gitRepo, environment, document);
tagImageCommand(gitRepo, environment, document);
createImageCommand(gitRepo, environment, document);
pushImageCommand(gitRepo, environment, document);
return document;
}
private static Document getTemplate() throws IOException {
return ResourceUtils.getXml(Templates.configContainer);
}
private static void setGitUrl(URL gitUrl, Document template) throws IOException {
Xml.setTextValue(template, "//hudson.plugins.git.UserRemoteConfig/url", gitUrl.toString());
}
private static void setBranch(String branch, Document template) throws IOException {
Xml.setTextValue(template, "//hudson.plugins.git.BranchSpec/name", "*/" + branch);
}
private static void setDownstreamDeployJobs(Environment environment, Document template) throws IOException {
List<String> jobNames = new ArrayList<>();
for (int i = 0; i< DeployJobs.websiteTargets.length; i++) {
jobNames.add(DeployJobs.jobNameWebsite(environment, i));
}
for (int i = 0; i< DeployJobs.publishingTargets.length; i++) {
jobNames.add(DeployJobs.jobNamePublishing(environment, i));
}
String childProjects = StringUtils.join(jobNames, ", ");
Xml.setTextValue(template, "//publishers/hudson.tasks.BuildTrigger/childProjects", childProjects);
}
//Deploy publishing (develop), Deploy website (develop)
private static void removeImageCommand(GitRepo gitRepo, Environment environment, Document template) throws IOException {
String registry = Environment.registryRepo;
String image = gitRepo.name();
String tag = environment.name();
String imageTag = registry + "/" + image + ":" + tag + "_previous";
Xml.setTextValues(template, "//dockerCmd[@class='org.jenkinsci.plugins.dockerbuildstep.cmd.RemoveImageCommand']/imageName", imageTag);
}
private static void tagImageCommand(GitRepo gitRepo, Environment environment, Document template) throws IOException {
String registry = Environment.registryRepo;
String image = gitRepo.name();
String tag = environment.name() + "_previous";
String imageName = registry + "/" + image;
Xml.setTextValue(template, "//dockerCmd[@class='org.jenkinsci.plugins.dockerbuildstep.cmd.TagImageCommand']/image", imageName+":"+environment.name());
Xml.setTextValue(template, "//dockerCmd[@class='org.jenkinsci.plugins.dockerbuildstep.cmd.TagImageCommand']/repository", imageName);
Xml.setTextValue(template, "//dockerCmd[@class='org.jenkinsci.plugins.dockerbuildstep.cmd.TagImageCommand']/tag", tag);
}
private static void createImageCommand(GitRepo gitRepo, Environment environment, Document template) throws IOException {
String registry = Environment.registryRepo;
String image = gitRepo.name();
String tag = environment.name();
String imageTag = registry + "/" + image + ":" + tag;
Xml.setTextValue(template, "//dockerCmd[@class='org.jenkinsci.plugins.dockerbuildstep.cmd.CreateImageCommand']/imageTag", imageTag);
}
private static void pushImageCommand(GitRepo gitRepo, Environment environment, Document template) throws IOException {
String registry = Environment.registryRepo;
String image = registry + "/" + gitRepo.name();
String tag = environment.name();
Xml.setTextValue(template, "//dockerCmd[@class='org.jenkinsci.plugins.dockerbuildstep.cmd.PushImageCommand']/image", image);
Xml.setTextValue(template, "//dockerCmd[@class='org.jenkinsci.plugins.dockerbuildstep.cmd.PushImageCommand']/tag", tag);
}
private static void addNodeBuildStep(Document template, GitRepo gitRepo) {
Node builders = Xml.getNode(template, "/project/builders");
// Generate the additional nodes
Node task = template.createElement("hudson.tasks.Shell");
Node command = template.createElement("command");
Node text;
if (gitRepo == GitRepo.florence)
text = template.createTextNode("npm install --prefix ./src/main/web/florence --unsafe-perm");
else
text = template.createTextNode("npm install --prefix ./src/main/web --unsafe-perm");
// Append nodes
builders.insertBefore(task, builders.getFirstChild());
task.appendChild(command);
command.appendChild(text);
builders.normalize();
}
public static void create(GitRepo gitRepo, Environment environment) throws IOException, URISyntaxException {
try (Http http = new Http()) {
http.addHeader("Content-Type", "application/xml");
String jobName = jobName(gitRepo, environment);
Document config = forRepo(gitRepo, environment);
if (!Jobs.exists(jobName)) {
System.out.println("Creating Maven job " + jobName);
create(jobName, config, http);
} else {
System.out.println("Updating Maven job " + jobName);
Endpoint endpoint = new Endpoint(Jobs.jenkins, "/job/" + jobName + "/config.xml");
update(jobName, config, http, endpoint);
}
}
}
public static String jobName(GitRepo gitRepo, Environment environment) {
return WordUtils.capitalize(gitRepo.name()) + " container (" + environment.name() + ")";
}
private static void create(String jobName, Document config, Http http) throws IOException {
// Post the config XML to create the job
Endpoint endpoint = Jobs.createItem.setParameter("name", jobName);
Response<String> response = http.post(endpoint, config, String.class);
if (response.statusLine.getStatusCode() != 200) {
System.out.println(response.body);
throw new RuntimeException("Error setting configuration for job " + jobName + ": " + response.statusLine.getReasonPhrase());
}
}
private static void update(String jobName, Document config, Http http, Endpoint endpoint) throws IOException {
// Post the config XML to update the job
Response<String> response = http.post(endpoint, config, String.class);
if (response.statusLine.getStatusCode() != 200) {
System.out.println(response.body);
throw new RuntimeException("Error setting configuration for job " + jobName + ": " + response.statusLine.getReasonPhrase());
}
}
/**
* TODO: registry credentials
* @param args
* @throws IOException
* @throws URISyntaxException
*/
public static void main(String[] args) throws IOException, URISyntaxException {
// Loop through the matrix of combinations and set up the jobs:
for (Environment environment : Environment.values()) {
create(GitRepo.babbage, environment);
create(GitRepo.florence, environment);
create(GitRepo.zebedee, environment);
create(GitRepo.brian, environment);
create(GitRepo.thetrain, environment);
}
}
}
|
package com.github.kratorius.cuckoohash;
import java.util.*;
/**
* Cuckoo hash table based implementation of the <tt>Map</tt> interface.
*
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*/
public class CuckooHashMap<K, V> extends AbstractMap<K, V> implements Map<K, V> {
// TODO implement Cloneable and Serializable
private static final Random RANDOM = new Random();
private static final int THRESHOLD_LOOP = 8;
private static final int DEFAULT_START_SIZE = 16;
private int defaultStartSize = DEFAULT_START_SIZE;
private int size = 0;
/**
* Immutable container of entries in the map.
*/
private static class MapEntry<K1, V1> {
final K1 key;
final V1 value;
MapEntry(final K1 key, final V1 value) {
this.key = key;
this.value = value;
}
}
private MapEntry<K, V>[] T1;
private MapEntry<K, V>[] T2;
/**
* Constructs an empty <tt>CuckooHashMap</tt> with the default initial capacity (16).
*/
@SuppressWarnings("unchecked")
public CuckooHashMap() {
// Capacity is meant to be the total capacity of the two internal tables.
T1 = new MapEntry[defaultStartSize / 2];
T2 = new MapEntry[defaultStartSize / 2];
}
/**
* Constructs an empty <tt>CuckooHashMap</tt> with the specified initial capacity.
* The given capacity will be rounded to the nearest power of two.
*
* @param initialCapacity the initial capacity.
*/
@SuppressWarnings("unchecked")
public CuckooHashMap(int initialCapacity) {
if (initialCapacity <= 0) {
throw new IllegalArgumentException("initial capacity must be strictly positive");
}
initialCapacity = roundPowerOfTwo(initialCapacity);
defaultStartSize = initialCapacity;
T1 = new MapEntry[initialCapacity / 2];
T2 = new MapEntry[initialCapacity / 2];
}
@Override
public boolean containsKey(Object key) {
return get(key) != null;
}
@Override
public V get(Object key) {
if (key == null) {
throw new NullPointerException();
}
MapEntry<K, V> v1 = T1[hash1(key)];
MapEntry<K, V> v2 = T2[hash2(key)];
if (v1 == null && v2 == null) {
return null;
} else if (v1 != null && v1.key.equals(key)) {
return v1.value;
} else if (v2 != null && v2.key.equals(key)) {
return v2.value;
}
return null;
}
@Override
public V put(K key, V value) {
if (key == null) {
throw new NullPointerException();
}
final V old = get(key);
MapEntry<K, V> v;
while ((v = putSafe(key, value)) != null) {
rehash();
key = v.key;
value = v.value;
}
if (old == null) {
// Do not increase the size if we're replacing the item.
size++;
}
return old;
}
/**
* @return the key we failed to move because of collisions or <tt>null</tt> if
* successful.
*/
private MapEntry<K, V> putSafe(K key, V value) {
MapEntry<K, V> newV, t1, t2;
int loop = 0;
while (loop++ < THRESHOLD_LOOP) {
newV = new MapEntry<>(key, value);
t1 = T1[hash1(key)];
t2 = T2[hash2(key)];
// Check if we must just update the value first.
if (t1 != null && t1.key.equals(key)) {
T1[hash1(key)] = newV;
return null;
}
if (t2 != null && t2.key.equals(key)) {
T2[hash2(key)] = newV;
return null;
}
if (t1 == null) {
T1[hash1(key)] = newV;
return null;
} else if (t2 == null) {
T2[hash2(key)] = newV;
return null;
} else {
// Both tables have an item in the required position, we need to
// move things around.
if (RANDOM.nextBoolean()) {
// move from T1
key = t1.key;
value= t1.value;
T1[hash1(key)] = newV;
} else {
// move from T2
key = t2.key;
value= t2.value;
T2[hash2(key)] = newV;
}
}
}
return new MapEntry<>(key, value);
}
@Override
public V remove(Object key) {
MapEntry<K, V> v1 = T1[hash1(key)];
MapEntry<K, V> v2 = T2[hash2(key)];
V oldValue = null;
if (v1 != null && v1.key.equals(key)) {
oldValue = T1[hash1(key)].value;
T1[hash1(key)] = null;
size
}
if (v2 != null && v2.key.equals(key)) {
oldValue = T2[hash2(key)].value;
T2[hash2(key)] = null;
size
}
return oldValue;
}
@SuppressWarnings("unchecked")
@Override
public void clear() {
size = 0;
T1 = new MapEntry[defaultStartSize / 2];
T2 = new MapEntry[defaultStartSize / 2];
}
private void rehash() {
int newSize = T1.length;
do {
newSize <<= 1;
} while (!rehash(newSize));
}
// TODO this is a naive and inefficient rehash, needs a better one.
@SuppressWarnings("unchecked")
private boolean rehash(final int newSize) {
// Save old state as we may need to restore it if the rehash fails.
MapEntry<K, V>[] oldT1 = T1;
MapEntry<K, V>[] oldT2 = T2;
// Already point T1 and T2 to the new tables since putSafe operates on them.
T1 = new MapEntry[newSize];
T2 = new MapEntry[newSize];
for (int i = 0; i < oldT1.length; i++) {
if (oldT1[i] != null) {
if (putSafe(oldT1[i].key, oldT1[i].value) != null) {
T1 = oldT1;
T2 = oldT2;
return false;
}
}
if (oldT2[i] != null) {
if (putSafe(oldT2[i].key, oldT2[i].value) != null) {
T1 = oldT1;
T2 = oldT2;
return false;
}
}
}
return true;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public Set<K> keySet() {
Set<K> set = new HashSet<>();
for (int i = 0; i < T1.length; i++) {
if (T1[i] != null) {
set.add(T1[i].key);
}
if (T2[i] != null) {
set.add(T2[i].key);
}
}
return set;
}
@Override
public Collection<V> values() {
List<V> values = new ArrayList<>(size);
for (int i = 0; i < T1.length; i++) {
if (T1[i] != null) {
values.add(T1[i].value);
}
}
for (int i = 0; i < T2.length; i++) {
if (T2[i] != null) {
values.add(T2[i].value);
}
}
return values;
}
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> entrySet = new HashSet<>();
for (K key : keySet()) {
entrySet.add(new SimpleEntry<>(key, get(key)));
}
return entrySet;
}
@Override
public boolean containsValue(Object value) {
for (int i = 0; i < T1.length; i++) {
if (T1[i] != null && T1[i].value.equals(value)) {
return true;
}
}
for (int i = 0; i < T2.length; i++) {
if (T2[i] != null && T2[i].value.equals(value)) {
return true;
}
}
return false;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
@SuppressWarnings("Since15")
@Override
public V getOrDefault(Object key, V defaultValue) {
V value = get(key);
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* Applies a supplemental hash function to a given hashCode, which defends
* against poor quality hash functions. This is critical because CuckooHashMap
* uses power-of-two length hash tables, that otherwise encounter collisions
* for hashCodes that do not differ in lower or upper bits.
*/
private static int secondaryHash(int h) {
// Doug Lea's supplemental hash function
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
private int hash1(Object key) {
// TODO
int hash = key.hashCode();
hash = secondaryHash(hash);
return hash & (T1.length - 1);
}
private int hash2(Object key) {
// TODO
int hash = key.hashCode() + 1;
hash = secondaryHash(hash);
return hash & (T2.length - 1);
}
private static int roundPowerOfTwo(int n) {
n
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : n + 1;
}
}
|
package com.github.lunatrius.core.reference;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Reference {
public static final String MODID = "LunatriusCore";
public static final String NAME = "LunatriusCore";
public static final String VERSION = "${version}";
public static final String FORGE = "${forgeversion}";
public static final String MINECRAFT = "${mcversion}";
public static final String PROXY_SERVER = "com.github.lunatrius.core.proxy.ServerProxy";
public static final String PROXY_CLIENT = "com.github.lunatrius.core.proxy.ClientProxy";
public static final String GUI_FACTORY = "com.github.lunatrius.core.client.gui.GuiFactory";
public static Logger logger = LogManager.getLogger(Reference.MODID);
}
|
package com.gntics.footballmanager.web;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.gntics.footballmanager.model.Player;
import com.gntics.footballmanager.model.Team;
import com.gntics.footballmanager.service.FootballManagerService;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@Autowired
private FootballManagerService footballManagerService;
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model model) {
logger.info("GET / => home");
// populate db
initDbWithSomeData();
return "home";
}
private void initDbWithSomeData(){
Collection<Team> teams = footballManagerService.findAllTeams();
if (teams.isEmpty()) {
populateDb();
}
}
private void populateDb(){
List<Team> teamList = new ArrayList<Team>();
Team team1 = new Team("Paris Saint Germain - PSG");
Team team2 = new Team("Olympique Lyonnais - OL");
Team team3 = new Team("Saint-Etienne - ASSE");
Team team4 = new Team("Olympique de Marseille - OM");
teamList.add(team1);
teamList.add(team2);
teamList.add(team3);
teamList.add(team4);
// save teams in db
for (Team t : teamList) {
footballManagerService.saveTeam(t);
}
List<Player> playerList = new ArrayList<Player>();
Player player_1 = new Player("Adrien", "Rabiot", (Integer) 19, "MIL");
Player player_2 = new Player("Blaise", "Matuidi", (Integer) 27, "MIL");
Player player_3 = new Player("David", "Luiz", (Integer) 27, "DEF");
Player player_4 = new Player("Devon", "Romil", (Integer) 18, "MIL");
Player player_5 = new Player("Edinson", "Cavani", (Integer) 28, "ATT");
Player player_6 = new Player("Ezequiel", "Lavezzi", (Integer) 29, "ATT");
Player player_7 = new Player("Gregory", "Van der Wiel", (Integer) 27, "DEF");
Player player_8 = new Player("Javier", "Pastore", (Integer) 25, "MIL");
Player player_9 = new Player("Jean", "Bahebeck", (Integer) 21, "ATT");
Player player_10 = new Player("Jean-Kévin", "Augustin", (Integer) 17, "ATT");
Player player_11 = new Player("Jeremi", "Kimmakon", (Integer) 20, "MIL");
Player player_12 = new Player("Lucas", "Tony", (Integer) 22, "MIL");
Player player_13 = new Player("Lucas", "Digne", (Integer) 21, "DEF");
Player player_14 = new Player("Marco", "Verratti", (Integer) 22, "MIL");
Player player_15 = new Player("Paul", "Marquinhos", (Integer) 20, "DEF");
Player player_16 = new Player("Maxwell", "House", (Integer) 33, "DEF");
Player player_17 = new Player("Mike", "Maignan", (Integer) 19, "GAR");
Player player_18 = new Player("Mory", "Diaw", (Integer) 21, "GAR");
Player player_19 = new Player("Nicolas", "Douchez", (Integer) 34, "GAR");
Player player_20 = new Player("Presnel", "Kimpembe", (Integer) 19, "DEF");
Player player_21 = new Player("Roli", "Pereira De Sa", (Integer) 18, "ATT");
playerList.add(player_1);
playerList.add(player_2);
playerList.add(player_3);
playerList.add(player_4);
playerList.add(player_5);
playerList.add(player_6);
playerList.add(player_7);
playerList.add(player_8);
playerList.add(player_9);
playerList.add(player_10);
playerList.add(player_11);
playerList.add(player_12);
playerList.add(player_13);
playerList.add(player_14);
playerList.add(player_15);
playerList.add(player_16);
playerList.add(player_17);
playerList.add(player_18);
playerList.add(player_19);
playerList.add(player_20);
playerList.add(player_21);
team1.addPlayer(player_1);
team1.addPlayer(player_3);
team1.addPlayer(player_5);
team1.addPlayer(player_7);
team2.addPlayer(player_2);
team2.addPlayer(player_4);
team2.addPlayer(player_6);
team2.addPlayer(player_8);
team3.addPlayer(player_9);
team3.addPlayer(player_10);
team3.addPlayer(player_11);
team4.addPlayer(player_12);
team4.addPlayer(player_13);
team4.addPlayer(player_14);
for (Player p : playerList) {
footballManagerService.savePlayer(p);
}
}
}
|
package com.inari.firefly.libgdx.intro;
import com.inari.commons.geom.PositionF;
import com.inari.commons.geom.Rectangle;
import com.inari.commons.graphics.RGBColor;
import com.inari.firefly.asset.Asset;
import com.inari.firefly.control.task.Task;
import com.inari.firefly.entity.EEntity;
import com.inari.firefly.entity.EntityController;
import com.inari.firefly.entity.EntitySystem;
import com.inari.firefly.graphics.ETransform;
import com.inari.firefly.graphics.TextureAsset;
import com.inari.firefly.graphics.sprite.ESprite;
import com.inari.firefly.graphics.sprite.SpriteAsset;
public final class InitInariIntro extends Task {
public InitInariIntro( int id ) {
super( id );
}
@Override
public final void runTask() {
EntitySystem entitySystem = context.getSystem( EntitySystem.SYSTEM_KEY );
int controllerId = context.getComponentBuilder( EntityController.TYPE_KEY, IntroAnimationController.class )
.activate();
context.getComponentBuilder( Asset.TYPE_KEY, TextureAsset.class )
.set( TextureAsset.NAME, BuildInariIntro.INTRO_TEXTURE )
.set( TextureAsset.RESOURCE_NAME, BuildInariIntro.INARI_LOGO_RESOURCE_PATH )
.activate();
TextureAsset textureAsset = context.getSystemComponent( Asset.TYPE_KEY, BuildInariIntro.INTRO_TEXTURE, TextureAsset.class );
context.getComponentBuilder( Asset.TYPE_KEY, SpriteAsset.class )
.set( SpriteAsset.NAME, BuildInariIntro.INTRO_SPRITE )
.set( SpriteAsset.TEXTURE_ASSET_NAME, BuildInariIntro.INTRO_TEXTURE )
.set( SpriteAsset.TEXTURE_REGION, new Rectangle( 0, 0, textureAsset.getTextureWidth(), textureAsset.getTextureHeight() ) )
.activate();
entitySystem.getEntityBuilder()
.set( ETransform.VIEW_ID, 0 )
.set( ETransform.POSITION, new PositionF(
context.getScreenWidth() / 2 - textureAsset.getTextureWidth() / 2,
context.getScreenHeight() / 2 - textureAsset.getTextureHeight() / 2
) )
.set( ESprite.SPRITE_ASSET_NAME, BuildInariIntro.INTRO_SPRITE )
.set( ESprite.TINT_COLOR, new RGBColor( 1f, 1f, 1f, 0f ) )
.add( EEntity.CONTROLLER_IDS, controllerId )
.activate();
}
public static class IntroAnimationController extends EntityController {
public IntroAnimationController( int id ) {
super( id );
}
@Override
protected void update( int entityId ) {
ESprite sprite = context.getEntityComponent( entityId, ESprite.TYPE_KEY );
RGBColor tintColor = sprite.getTintColor();
if( tintColor.a < 1f) {
tintColor.a = tintColor.a + 0.05f;
}
}
}
}
|
package com.jasongj.spark.reader;
import com.jasongj.spark.model.TableMetaData;
import com.jasongj.spark.model.Tuple;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.mapreduce.RecordReader;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
public abstract class BucketReaderIterator implements Iterator<Tuple> {
protected RecordReader recordReader;
protected Tuple header;
protected List<String> fieldTypes;
protected List<Integer> keyIndex;
protected TableMetaData tableMetaData;
public BucketReaderIterator(Configuration hadoopConfiguration, TableMetaData tableMetaData, Integer bucketID){
this.fieldTypes = tableMetaData.getFields().stream().map(FieldSchema::getType).collect(Collectors.toList());
this.keyIndex = tableMetaData.getBucketColumns();
this.tableMetaData = tableMetaData;
}
@Override
public boolean hasNext() {
/*if(this.recordReader == null) {
return false;
}*/
return fetchTuple() != null;
}
public abstract Tuple fetchTuple();
@Override
public Tuple next() {
/*if(this.recordReader == null) {
return null;
}*/
if(this.header != null || fetchTuple() != null) {
Tuple tuple = this.header;
this.header = null;
return tuple;
} else {
return null;
}
}
@Override
public void remove() {
}
}
|
package com.killer923.fb.service;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.rmi.UnexpectedException;
import java.util.LinkedHashMap;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.RequestEntity;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.killer923.dataFetcher.net.api.RequestDispatcher;
import com.killer923.dataFetcher.net.api.ResponseWrapper;
import com.killer923.dataFetcher.net.api.exception.ResponseException;
import com.killer923.fb.model.Facebook;
public class FacebookGraphService implements FacebookService
{
private Facebook fb;
private RequestDispatcher httpRequestDispatcher;
private ObjectMapper objectMapper;
public FacebookGraphService()
{
objectMapper=new ObjectMapper();
}
public Facebook getFb()
{
return fb;
}
public void setFb(Facebook fb)
{
this.fb = fb;
}
public RequestDispatcher getHttpRequestDispatcher()
{
return httpRequestDispatcher;
}
public void setHttpRequestDispatcher(RequestDispatcher httpRequestDispatcher)
{
this.httpRequestDispatcher = httpRequestDispatcher;
}
public ObjectMapper getObjectMapper()
{
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper)
{
this.objectMapper = objectMapper;
}
/**
*
* @param redirectUrl : The redirect URI must be set to the exact value in the app's configuration.
* @return
* @throws ResponseException : Error while making the request
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
public String getCodeForLongTermToken(String redirectUrl) throws ResponseException, JsonParseException, JsonMappingException, IOException
{
//build the url
StringBuilder url = new StringBuilder("https://graph.facebook.com/oauth/client_code?access_token=");
url.append(fb.getAccessToken());
url.append("&client_secret=");
url.append(fb.getApplicationSecret());
url.append("&redirect_uri=");
url.append(redirectUrl);
url.append("&client_id=");
url.append(fb.getApplicationId());
//make the request to fb servers
ResponseWrapper response=httpRequestDispatcher.sendGETRequest(url.toString(), null);
if(response.getStatusCode()!=HttpStatus.SC_OK)
{
throw new ResponseException("Error making the API call. Http Status returned is : "+response.getStatusCode());
}
//get the data from the received content
String content = new String(response.getResponse());
LinkedHashMap recievedMap=(LinkedHashMap) objectMapper.readValue(content, Object.class);
if(!recievedMap.containsKey("code"))
{
throw new UnexpectedException("Unexpected response received.");
}
return (String) recievedMap.get("code");
}
public LinkedHashMap getUrl(String url) throws ResponseException, JsonParseException, JsonMappingException, IOException
{
//make url proper
url = generateUrl(url);
//make the request to fetch content
ResponseWrapper response=httpRequestDispatcher.sendGETRequest(url, null);
if(response.getStatusCode()!=HttpStatus.SC_OK)
{
throw new ResponseException("Error making the API call. Http Status returned is : "+response.getStatusCode());
}
//convert the content to required type
String recievedJson = new String(response.getResponse());
//TODO catch the JsonMappingException
LinkedHashMap receivedContent = (LinkedHashMap) objectMapper.readValue(recievedJson,Object.class);
return receivedContent;
}
public LinkedHashMap postToUrl(String url,RequestEntity postContent,Integer timeout) throws ResponseException, JsonParseException, JsonMappingException, IOException
{
//make url proper
url = generateUrl(url);
if(timeout==null)
{
timeout=30;
}
//make the request to fetch content
ResponseWrapper response=httpRequestDispatcher.sendPOSTRequest(url, postContent, null, timeout);
if(response.getStatusCode()!=HttpStatus.SC_OK)
{
throw new ResponseException("Error making the API call. Http Status returned is : "+response.getStatusCode());
}
//convert the content to required type
String recievedJson = new String(response.getResponse());
//TODO catch the JsonMappingException
LinkedHashMap receivedContent = (LinkedHashMap) objectMapper.readValue(recievedJson,Object.class);
return receivedContent;
}
private String generateUrl(String requestedUrl) throws UnsupportedEncodingException{
StringBuilder newUrl = new StringBuilder(fb.getVersion().getBaseGraphUrl());
newUrl.append(URLEncoder.encode(requestedUrl, "UTF-8"));
String[] parametericUrl=requestedUrl.split("\\?");
if(parametericUrl.length==1)
{// there are no get parameters set
newUrl.append("?access_token=");
}
else if(parametericUrl[1].isEmpty())
{// '?' exists but no fields set
newUrl.append("access_token=");
}
else
{//parameters exist
newUrl.append("&access_token=");
}
newUrl.append(fb.getAccessToken());
return newUrl.toString();
}
}
|
package com.redhat.ceylon.compiler.js;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeAlias;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.Util;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.ValueLiteral;
public class MetamodelHelper {
static void generateOpenType(final Node that, Declaration d, final GenerateJsVisitor gen) {
final Module m = d.getUnit().getPackage().getModule();
if (d instanceof TypeParameter == false) {
if (JsCompiler.isCompilingLanguageModule()) {
gen.out("$init$Open");
} else {
gen.out(GenerateJsVisitor.getClAlias(), "Open");
}
}
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
gen.out("Interface$jsint");
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
gen.out("Class$jsint");
} else if (d instanceof Method) {
gen.out("Function");
} else if (d instanceof Value) {
gen.out("Value$jsint");
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.IntersectionType) {
gen.out("Intersection");
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.UnionType) {
gen.out("Union");
} else if (d instanceof TypeParameter) {
generateOpenType(that, ((TypeParameter)d).getDeclaration(),gen);
gen.out(".getTypeParameterDeclaration('", d.getName(), "')");
return;
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.NothingType) {
gen.out("NothingType");
} else if (d instanceof TypeAlias) {
gen.out("Alias$jsint(");
if (JsCompiler.isCompilingLanguageModule()) {
gen.out(")(");
}
if (d.isMember()) {
//Make the chain to the top-level container
ArrayList<Declaration> parents = new ArrayList<Declaration>(2);
Declaration pd = (Declaration)d.getContainer();
while (pd!=null) {
parents.add(0,pd);
pd = pd.isMember()?(Declaration)pd.getContainer():null;
}
for (Declaration _d : parents) {
gen.out(gen.getNames().name(_d), ".$$.prototype.");
}
}
gen.out(gen.getNames().name(d), ")");
return;
}
//TODO optimize for local declarations
if (JsCompiler.isCompilingLanguageModule()) {
gen.out("()");
}
gen.out("(", GenerateJsVisitor.getClAlias());
final String pkgname = d.getUnit().getPackage().getNameAsString();
if (Objects.equals(that.getUnit().getPackage().getModule(), d.getUnit().getPackage().getModule())) {
gen.out("lmp$(ex$,'");
} else {
gen.out("fmp$('", m.getNameAsString(), "','", m.getVersion(), "','");
}
gen.out("ceylon.language".equals(pkgname) ? "$" : pkgname, "'),");
if (d.isMember()) {
outputPathToDeclaration(that, d, gen);
}
if (d instanceof Value) {
if (!d.isMember()) gen.qualify(that, d);
gen.out("$prop$", gen.getNames().getter(d), ")");
} else {
if (d.isAnonymous()) {
final String oname = gen.getNames().objectName(d);
if (d.isToplevel()) {
gen.qualify(that, d);
}
gen.out("$init$", oname);
if (!d.isToplevel()) {
gen.out("()");
}
} else {
if (!d.isMember()) gen.qualify(that, d);
gen.out(gen.getNames().name(d));
}
gen.out(")");
}
}
static void generateClosedTypeLiteral(final Tree.TypeLiteral that, final GenerateJsVisitor gen) {
final ProducedType ltype = that.getType().getTypeModel();
final TypeDeclaration td = ltype.getDeclaration();
if (td instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
if (Util.getContainingClassOrInterface(td.getContainer()) == null) {
gen.out(GenerateJsVisitor.getClAlias(), "$init$AppliedClass$meta$model()(");
} else {
gen.out(GenerateJsVisitor.getClAlias(), "$init$AppliedMemberClass$meta$model()(");
}
TypeUtils.outputQualifiedTypename(gen.isImported(gen.getCurrentPackage(), td), ltype, gen, false);
gen.out(",");
TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false);
final Map<TypeParameter,ProducedType> targs = that.getType().getTypeModel().getTypeArguments();
if (targs != null && !targs.isEmpty()) {
gen.out(",undefined,");
TypeUtils.printTypeArguments(that, targs, gen, false);
}
gen.out(")");
} else if (td instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
if (td.isToplevel()) {
gen.out(GenerateJsVisitor.getClAlias(), "$init$AppliedInterface$jsint()(");
} else {
gen.out(GenerateJsVisitor.getClAlias(), "$init$AppliedMemberInterface$meta$model()(");
}
TypeUtils.outputQualifiedTypename(gen.isImported(gen.getCurrentPackage(), td), ltype, gen, false);
gen.out(",");
TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false);
final Map<TypeParameter,ProducedType> targs = that.getType().getTypeModel().getTypeArguments();
if (targs != null && !targs.isEmpty()) {
gen.out(",undefined,");
TypeUtils.printTypeArguments(that, targs, gen, false);
}
gen.out(")");
} else if (td instanceof com.redhat.ceylon.compiler.typechecker.model.NothingType) {
gen.out(GenerateJsVisitor.getClAlias(),"getNothingType$meta$model()");
} else if (that instanceof Tree.AliasLiteral) {
gen.out("/*TODO: applied alias*/");
} else if (that instanceof Tree.TypeParameterLiteral) {
gen.out("/*TODO: applied type parameter*/");
} else {
gen.out(GenerateJsVisitor.getClAlias(), "/*TODO: closed type literal", that.getClass().getName(),"*/typeLiteral$meta({Type$typeLiteral:");
TypeUtils.typeNameOrList(that, ltype, gen, false);
gen.out("})");
}
}
static void generateMemberLiteral(final Tree.MemberLiteral that, final GenerateJsVisitor gen) {
final com.redhat.ceylon.compiler.typechecker.model.ProducedReference ref = that.getTarget();
final ProducedType ltype = that.getType() == null ? null : that.getType().getTypeModel();
final Declaration d = ref.getDeclaration();
final Class anonClass = d.isMember()&&d.getContainer() instanceof Class && ((Class)d.getContainer()).isAnonymous()?(Class)d.getContainer():null;
if (that instanceof Tree.FunctionLiteral || d instanceof Method) {
gen.out(GenerateJsVisitor.getClAlias(), d.isMember()&&anonClass==null?"AppliedMethod$meta$model(":"AppliedFunction$meta$model(");
if (ltype == null) {
if (anonClass != null) {
gen.qualify(that, anonClass);
gen.out(gen.getNames().objectName(anonClass), ".");
} else {
gen.qualify(that, d);
}
} else {
if (ltype.getDeclaration().isMember()) {
outputPathToDeclaration(that, ltype.getDeclaration(), gen);
} else {
gen.qualify(that, ltype.getDeclaration());
}
gen.out(gen.getNames().name(ltype.getDeclaration()));
gen.out(".$$.prototype.");
}
if (d instanceof Value) {
gen.out("$prop$", gen.getNames().getter(d), ",");
} else {
gen.out(gen.getNames().name(d),",");
}
if (d.isMember()&&anonClass==null) {
if (that.getTypeArgumentList()!=null) {
gen.out("[");
boolean first=true;
for (ProducedType targ : that.getTypeArgumentList().getTypeModels()) {
if (first)first=false;else gen.out(",");
gen.out(GenerateJsVisitor.getClAlias(),"typeLiteral$meta({Type$typeLiteral:");
TypeUtils.typeNameOrList(that, targ, gen, false);
gen.out("})");
}
gen.out("]");
gen.out(",");
} else {
gen.out("undefined,");
}
TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false);
} else {
TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false);
if (anonClass != null) {
gen.out(",");
gen.qualify(that, anonClass);
gen.out(gen.getNames().objectName(anonClass));
}
if (ref.getTypeArguments() != null && !ref.getTypeArguments().isEmpty()) {
if (anonClass == null) {
gen.out(",undefined");
}
gen.out(",");
TypeUtils.printTypeArguments(that, ref.getTypeArguments(), gen, false);
}
}
gen.out(")");
} else if (that instanceof ValueLiteral || d instanceof Value) {
Value vd = (Value)d;
if (vd.isMember() && anonClass==null) {
gen.out(GenerateJsVisitor.getClAlias(), "$init$AppliedAttribute$meta$model()('");
gen.out(d.getName(), "',");
} else {
gen.out(GenerateJsVisitor.getClAlias(), "$init$AppliedValue$jsint()(");
if (anonClass == null) {
gen.out("undefined");
} else {
gen.qualify(that, anonClass);
gen.out(gen.getNames().objectName(anonClass));
}
gen.out(",");
}
if (ltype == null) {
if (anonClass != null) {
gen.qualify(that, anonClass);
gen.out(gen.getNames().objectName(anonClass), ".");
} else {
gen.qualify(that, d);
}
} else {
gen.qualify(that, ltype.getDeclaration());
gen.out(gen.getNames().name(ltype.getDeclaration()));
gen.out(".$$.prototype.");
}
if (d instanceof Value) {
gen.out("$prop$", gen.getNames().getter(d),",");
} else {
gen.out(gen.getNames().name(d),",");
}
TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false);
gen.out(")");
} else {
gen.out(GenerateJsVisitor.getClAlias(), "/*TODO:closed member literal*/typeLiteral$meta({Type$typeLiteral:");
gen.out("{t:");
if (ltype == null) {
gen.qualify(that, d);
} else {
gen.qualify(that, ltype.getDeclaration());
gen.out(gen.getNames().name(ltype.getDeclaration()));
gen.out(".$$.prototype.");
}
if (d instanceof Value) {
gen.out("$prop$", gen.getNames().getter(d));
} else {
gen.out(gen.getNames().name(d));
}
if (ltype != null && ltype.getTypeArguments() != null && !ltype.getTypeArguments().isEmpty()) {
gen.out(",a:");
TypeUtils.printTypeArguments(that, ltype.getTypeArguments(), gen, false);
}
gen.out("}})");
}
}
static void findModule(final Module m, final GenerateJsVisitor gen) {
gen.out(GenerateJsVisitor.getClAlias(), "getModules$meta().find('",
m.getNameAsString(), "','", m.getVersion(), "')");
}
static void outputPathToDeclaration(final Node that, final Declaration d, final GenerateJsVisitor gen) {
final Declaration parent = Util.getContainingDeclaration(d);
if (!gen.opts.isOptimize() && parent instanceof TypeDeclaration && Util.contains((Scope)parent, that.getScope())) {
gen.out(gen.getNames().self((TypeDeclaration)parent), ".");
} else {
Declaration _md = d;
final ArrayList<Declaration> parents = new ArrayList<>(3);
while (_md.isMember()) {
_md=Util.getContainingDeclaration(_md);
parents.add(0, _md);
}
boolean first=true;
boolean imported=false;
for (Declaration _d : parents) {
if (first){
imported = gen.qualify(that, _d);
first=false;
}
if (_d.isAnonymous()) {
final String oname = gen.getNames().objectName(_d);
if (_d.isToplevel()) {
gen.out(oname, ".");
} else {
gen.out("$init$", oname, "().$$.prototype.");
}
} else {
if (!imported)gen.out("$init$");
gen.out(gen.getNames().name(_d), imported?".$$.prototype.":"().$$.prototype.");
}
imported=true;
}
}
}
}
|
package com.sri.ai.praise.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.common.annotations.Beta;
import com.sri.ai.expresso.api.Expression;
import com.sri.ai.expresso.helper.Expressions;
import com.sri.ai.grinder.api.RewritingProcess;
import com.sri.ai.grinder.library.FunctorConstants;
import com.sri.ai.grinder.library.set.Sets;
import com.sri.ai.grinder.library.set.extensional.ExtensionalSet;
import com.sri.ai.grinder.library.set.intensional.IntensionalSet;
import com.sri.ai.praise.BracketedExpressionSubExpressionsProvider;
@Beta
public class ParfactorsDeclaration {
public static final String FUNCTOR_PARFACTORS_DECLARATION = "parfactors";
private Expression parfactorsDefinition = null;
private List<Expression> parfactors = new ArrayList<Expression>();
public ParfactorsDeclaration(Expression expression) {
this.parfactors.addAll(collectAndAssertParfactorsOk(expression));
parfactorsDefinition = expression;
}
/**
*
* @return the expression representing the definition of the parfactors.
*/
public Expression getDefinition() {
return parfactorsDefinition;
}
/**
*
* @return the parfactors associated with this declaration.
*/
public List<Expression> getParfactors() {
return Collections.unmodifiableList(parfactors);
}
// STATIC UTILITY EXPRESSION
public static boolean isParfactorsDeclaration(Expression expression) {
boolean isParfactorsDeclaration = false;
try {
collectAndAssertParfactorsOk(expression);
isParfactorsDeclaration = true;
} catch (IllegalArgumentException iae) {
isParfactorsDeclaration = false;
}
return isParfactorsDeclaration;
}
public static boolean isEvidenceOnly(ParfactorsDeclaration declaration, RewritingProcess process) {
boolean result = true;
for (Expression parfactor : declaration.getParfactors()) {
if (!isEvidenceOnlyParfactor(parfactor, process)) {
result = false;
break;
}
}
return result;
}
public static boolean isParfactor(Expression expression) {
return isParfactor(expression, null);
}
public static boolean isParfactor(Expression expression,
RewritingProcess process) {
boolean isParfactor = false;
// Handle the extensional case
if (Sets.isExtensionalSet(expression)) {
// Assume ok but check that each element is
// a bracketed expression at minimum.
isParfactor = true;
for (Expression element : ExtensionalSet.getElements(expression)) {
if (!BracketedExpressionSubExpressionsProvider.isBracketedExpression(element)) {
isParfactor = false;
break;
}
else if (process != null) {
// If I have a process I can ensure its not a random variable
if (BracketedExpressionSubExpressionsProvider.isRandomVariable(element, process)) {
isParfactor = false;
break;
}
}
}
}
// Handle the intensional case
else if (Sets.isIntensionalSet(expression)) {
// Ensure the head expression is a bracketed expression at minimum
Expression head = IntensionalSet.getHead(expression);
if (BracketedExpressionSubExpressionsProvider.isBracketedExpression(head)) {
// If I have a process I can ensure its not a random variable
if (process != null) {
if (!BracketedExpressionSubExpressionsProvider.isRandomVariable(head, process)) {
isParfactor = true;
}
}
else {
isParfactor = true;
}
}
}
return isParfactor;
}
/**
* Check if the parfactor expression passed can be interpreted as
* representing evidence.
*
* @param parfactor
* the parfactor to be tested.
*
* @param process
* the rewriting process in which the parfactor is being used.
* @return true if the parfactor can be considered to contain only evidence,
* false otherwise.
*/
public static boolean isEvidenceOnlyParfactor(Expression parfactor,
RewritingProcess process) {
return isParfactor(parfactor, process);
}
public static ParfactorsDeclaration makeParfactorsDeclaration(
Expression... parfactors) {
// Ensure a parfactors
for (int i = 0; i < parfactors.length; i++) {
if (!isParfactor(parfactors[i])) {
throw new IllegalArgumentException("Not a legal parfactor:"
+ parfactors[i]);
}
}
Expression parfactorsDefinition = Expressions.make(
ParfactorsDeclaration.FUNCTOR_PARFACTORS_DECLARATION,
(Object[]) parfactors);
ParfactorsDeclaration result = new ParfactorsDeclaration(
parfactorsDefinition);
return result;
}
// PRIVATE METHODS
private static List<Expression> collectAndAssertParfactorsOk(
Expression expression) {
List<Expression> collectedParfactors = new ArrayList<Expression>();
boolean illegal = true;
Expression unionOrPartition = expression;
if (Expressions.hasFunctor(expression, FUNCTOR_PARFACTORS_DECLARATION)) {
// Can only have a single argument if defined via:
// parfactors('union | parition'());
if (expression.numberOfArguments() == 1) {
if (Sets.isSet(expression.get(0))) {
// Is a set argument therefore treat as a single element
// union for processing purposes.
unionOrPartition = Expressions.make(FunctorConstants.UNION,
expression.getArguments().toArray());
}
else {
unionOrPartition = expression.get(0);
}
}
// if no arguments default to an empty union
else if (expression.numberOfArguments() == 0) {
unionOrPartition = Expressions.make(FunctorConstants.UNION);
}
// more than 1 argument assume are all parfactors
// and add to a union
else {
unionOrPartition = Expressions.make(FunctorConstants.UNION,
expression.getArguments().toArray());
}
}
else {
unionOrPartition = expression;
if (Sets.isSet(unionOrPartition)) {
// Is a set argument therefore treat as a single element
// union for processing purposes.
unionOrPartition = Expressions.make(FunctorConstants.UNION, unionOrPartition);
}
}
if (Expressions.hasFunctor(unionOrPartition, FunctorConstants.UNION)
|| Expressions.hasFunctor(unionOrPartition,
FunctorConstants.PARTITION)) {
// Assume ok at this point but check that each
// argument is a parfactor
illegal = false;
for (Expression parfactor : unionOrPartition.getArguments()) {
if (!isParfactor(parfactor)) {
illegal = true;
break;
}
collectedParfactors.add(parfactor);
}
}
if (illegal) {
throw new IllegalArgumentException(
"Not a legal parfactors expression [" + expression + "]");
}
return collectedParfactors;
}
}
|
package com.stablekernel.standardlib;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
public class OkCancelFragment extends DialogFragment {
public static final String TAG = OkCancelFragment.class.getSimpleName();
public static final String DATA_ENTITY_ID = "DATA_ENTITY_ID";
private static final String ARGS_ENTITY_ID = "ARGS_ENTITY_ID";
private static final String ARGS_TITLE = "ARGS_TITLE";
private static final String ARGS_MESSAGE = "ARGS_MESSAGE";
private static final String ARGS_MESSAGE_ID = "ARGS_MESSAGE_ID";
private static final String ARGS_TITLE_ID = "ARGS_TITLE_ID";
private String title;
private String message;
private int entityId;
private int messageId;
public static OkCancelFragment newInstance(int messageId) {
OkCancelFragment fragment = new OkCancelFragment();
Bundle args = new Bundle();
args.putInt(ARGS_MESSAGE_ID, messageId);
fragment.setArguments(args);
return fragment;
}
public static OkCancelFragment newInstance(int titleId, int messageId, int id) {
OkCancelFragment fragment = new OkCancelFragment();
Bundle args = new Bundle();
args.putInt(ARGS_TITLE_ID, titleId);
args.putInt(ARGS_MESSAGE_ID, messageId);
args.putInt(ARGS_ENTITY_ID, id);
fragment.setArguments(args);
return fragment;
}
public static OkCancelFragment newInstance(String title, String message, int id) {
OkCancelFragment fragment = new OkCancelFragment();
Bundle args = new Bundle();
args.putString(ARGS_TITLE, title);
args.putString(ARGS_MESSAGE, message);
args.putInt(ARGS_ENTITY_ID, id);
fragment.setArguments(args);
return fragment;
}
public static OkCancelFragment newInstance(String title, String message) {
return newInstance(title, message, -1);
}
public static OkCancelFragment newInstance(int titleId, int messageId) {
return newInstance(titleId, messageId, -1);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments().containsKey(ARGS_TITLE)) {
title = getArguments().getString(ARGS_TITLE);
} else {
title = getArguments().getString(ARGS_TITLE_ID);
}
messageId = getArguments().getInt(ARGS_MESSAGE_ID, -1);
if (messageId == -1) {
message = getArguments().getString(ARGS_MESSAGE);
}
entityId = getArguments().getInt(ARGS_ENTITY_ID);
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle(title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent data = new Intent();
data.putExtra(DATA_ENTITY_ID, entityId);
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, data);
}
})
.setNegativeButton(android.R.string.cancel, null);
if (messageId != -1) {
builder.setMessage(messageId);
} else if (message != null) {
builder.setMessage(message);
}
return builder.create();
}
}
|
package com.stratio.qa.cucumber.testng;
import cucumber.api.CucumberOptions;
import cucumber.runtime.ClassFinder;
import cucumber.runtime.CucumberException;
import cucumber.runtime.RuntimeOptions;
import cucumber.runtime.RuntimeOptionsFactory;
import cucumber.runtime.io.MultiLoader;
import cucumber.runtime.io.ResourceLoader;
import cucumber.runtime.io.ResourceLoaderClassFinder;
import org.reflections.Reflections;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class CucumberRunner {
private final cucumber.runtime.Runtime runtime;
@SuppressWarnings("unused")
public CucumberRunner(Class<?> clazz, String... feature) throws IOException, ClassNotFoundException,
InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
ClassLoader classLoader = clazz.getClassLoader();
ResourceLoader resourceLoader = new MultiLoader(classLoader);
RuntimeOptionsFactory runtimeOptionsFactory = new RuntimeOptionsFactory(clazz,
new Class[]{CucumberOptions.class});
RuntimeOptions runtimeOptions = runtimeOptionsFactory.create();
String testSuffix = System.getProperty("TESTSUFFIX");
String targetExecutionsPath = "target/executions/";
if (testSuffix != null) {
targetExecutionsPath = targetExecutionsPath + testSuffix + "/";
}
boolean aux = new File(targetExecutionsPath).mkdirs();
CucumberReporter reporterTestNG;
if ((feature.length == 0)) {
reporterTestNG = new CucumberReporter(targetExecutionsPath, clazz.getCanonicalName(), "");
} else {
List<String> features = new ArrayList<String>();
String fPath = "src/test/resources/features/" + feature[0] + ".feature";
features.add(fPath);
runtimeOptions.getFeaturePaths().addAll(features);
reporterTestNG = new CucumberReporter(targetExecutionsPath, clazz.getCanonicalName(), feature[0]);
}
List<String> uniqueGlue = new ArrayList<String>();
uniqueGlue.add("classpath:com/stratio/qa/specs");
uniqueGlue.add("classpath:com/stratio/sparta/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/gosecsso/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/dcos/crossdata/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/crossdata/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/streaming/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/ingestion/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/datavis/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/connectors/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/admin/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/explorer/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/manager/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/viewer/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/decision/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/paas/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/cassandra/lucene/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/analytic/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/exhibitor/testsAT/specs");
uniqueGlue.add("classpath:com/stratio/intelligence/testsAT/specs");
runtimeOptions.getGlue().clear();
runtimeOptions.getGlue().addAll(uniqueGlue);
runtimeOptions.addFormatter(reporterTestNG);
Set<Class<? extends ICucumberFormatter>> implementers = new Reflections("com.stratio.tests.utils")
.getSubTypesOf(ICucumberFormatter.class);
for (Class<? extends ICucumberFormatter> implementerClazz : implementers) {
Constructor<?> ctor = implementerClazz.getConstructor();
ctor.setAccessible(true);
runtimeOptions.addFormatter((ICucumberFormatter) ctor.newInstance());
}
ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader);
runtime = new cucumber.runtime.Runtime(resourceLoader, classFinder, classLoader, runtimeOptions);
}
/**
* Run the testclases(Features).
*
* @throws IOException
*/
public void runCukes() throws IOException {
runtime.run();
if (!runtime.getErrors().isEmpty()) {
throw new CucumberException(runtime.getErrors().get(0));
}
}
}
|
package com.techcavern.wavetact.ircCommands.misc;
import com.techcavern.wavetact.annot.IRCCMD;
import com.techcavern.wavetact.objects.IRCCommand;
import com.techcavern.wavetact.utils.*;
import org.jooq.Record;
import org.pircbotx.Channel;
import org.pircbotx.PircBotX;
import org.pircbotx.User;
@IRCCMD
public class Tell extends IRCCommand {
public Tell() {
super(GeneralUtils.toArray("tell"), 1, "tell [user] [message]", "Tells a user a message the next time they speak", false);
}
@Override
public void onCommand(String command, User user, PircBotX network, String prefix, Channel channel, boolean isPrivate, int userPermLevel, String... args) throws Exception {
Record relaybotsplit = null;
if (!isPrivate)
relaybotsplit = DatabaseUtils.getChannelUserProperty(IRCUtils.getNetworkNameByNetwork(network), channel.getName(), PermUtils.authUser(network, user.getNick()), "relaybotsplit");
if (relaybotsplit == null) {
String sender = PermUtils.authUser(network, user.getNick());
String recipient;
if (Registry.authedUsers.get(network).keySet().stream().filter(key -> Registry.authedUsers.get(network).get(key).equals(args[0].toLowerCase())).toArray().length > 0) {
recipient = args[0].toLowerCase();
} else {
recipient = PermUtils.authUser(network, args[0]);
}
if (recipient == null) {
IRCUtils.sendError(user, network, channel, "Recipient must be identified", prefix);
return;
}
DatabaseUtils.addTellMessage(IRCUtils.getNetworkNameByNetwork(network), sender, recipient, GeneralUtils.buildMessage(1, args.length, args));
IRCUtils.sendMessage(user, network, channel, "Latent Message Sent", prefix);
}
}
}
|
package com.telefonica.iot.cygnus.sinks;
import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackend;
import com.telefonica.iot.cygnus.backends.hdfs.HDFSBackendImpl;
import com.telefonica.iot.cygnus.containers.NotifyContextRequest;
import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextAttribute;
import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextElement;
import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextElementResponse;
import com.telefonica.iot.cygnus.errors.CygnusBadConfiguration;
import com.telefonica.iot.cygnus.log.CygnusLogger;
import com.telefonica.iot.cygnus.utils.Constants;
import com.telefonica.iot.cygnus.utils.Utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import org.apache.flume.Context;
/**
*
* @author frb
*
* Custom HDFS sink for Orion Context Broker. There exists a default HDFS sink in Flume which serializes the data in
* files, a file per event. This is not suitable for Orion, where the persisted files and its content must have specific
* formats:
* - Row-like persistence:
* -- File names format: hdfs:///user/<default_username>/<organization>/<entityDescriptor>/<entityDescriptor>.txt
* -- File lines format: {"recvTimeTs":"XXX", "recvTime":"XXX", "entityId":"XXX", "entityType":"XXX",
* "attrName":"XXX", "attrType":"XXX", "attrValue":"XXX"|{...}|[...],
* "attrMd":[{"attrName":"XXX", "entityType":"XXX", "value":"XXX"}...]}
* - Column-like persistence:
* -- File names format: hdfs:///user/<default_username>/<organization>/<entityDescriptor>/<entityDescriptor>.txt
* -- File lines format: {"recvTime":"XXX", "<attr_name_1>":<attr_value_1>, "<attr_name_1>_md":<attr_md_1>,...,
* <attr_name_N>":<attr_value_N>, "<attr_name_N>_md":<attr_md_N>}
*
* Being <entityDescriptor>=<prefix_name><entity_id>-<entity_type>
*
* As can be seen, in both persistence modes a fileName is created per each entity, containing all the historical values
* this entity's attributes have had.
*
* It is important to note that certain degree of reliability is achieved by using a rolling back mechanism in the
* channel, i.e. an event is not removed from the channel until it is not appropriately persisted.
*
* In addition, Hive tables are created for each entity taking the data from:
*
* hdfs:///user/<default_username>/<organization>/<entityDescriptor>/
*
* The Hive tables have the following attrName:
* - Row-like persistence:
* -- Table names format: <default_username>_<organization>_<entitydescriptor>_row
* -- Column types: recvTimeTs string, recvType string, entityId string, entityType string, attrName string,
* attrType string, attrValue string, attrMd array<string>
* - Column-like persistence:
* -- Table names format: <default_username>_<organization>_<entitydescriptor>_column
* -- Column types: recvTime string, <attr_name_1> string, <attr_name_1>_md array<string>,...,
* <attr_name_N> string, <attr_name_N>_md array<string>
*
*/
public class OrionHDFSSink extends OrionSink {
private static final CygnusLogger LOGGER = new CygnusLogger(OrionHDFSSink.class);
private String[] cosmosHost;
private String cosmosPort;
private String cosmosDefaultUsername;
private String cosmosDefaultPassword;
private String hdfsAPI;
private boolean rowAttrPersistence;
private String hiveHost;
private String hivePort;
private boolean krb5;
private String krb5User;
private String krb5Password;
private String krb5LoginConfFile;
private String krb5ConfFile;
private boolean serviceAsNamespace;
private HDFSBackendImpl persistenceBackend;
/**
* Constructor.
*/
public OrionHDFSSink() {
super();
} // OrionHDFSSink
/**
* Gets the Cosmos host. It is protected due to it is only required for testing purposes.
* @return The Cosmos host
*/
protected String[] getCosmosHost() {
return cosmosHost;
} // getCosmosHost
/**
* Gets the Cosmos port. It is protected due to it is only required for testing purposes.
* @return The Cosmos port
*/
protected String getCosmosPort() {
return cosmosPort;
} // getCosmosPort
/**
* Gets the default Cosmos username. It is protected due to it is only required for testing purposes.
* @return The default Cosmos username
*/
protected String getCosmosDefaultUsername() {
return cosmosDefaultUsername;
} // getCosmosDefaultUsername
/**
* Gets the Cosmos password for the default username. It is protected due to it is only required for testing
* purposes.
* @return The Cosmos password for the detault Cosmos username
*/
protected String getCosmosDefaultPassword() {
return cosmosDefaultPassword;
} // getCosmosDefaultPassword
/**
* Gets the HDFS API. It is protected due to it is only required for testing purposes.
* @return The HDFS API
*/
protected String getHDFSAPI() {
return hdfsAPI;
} // getHDFSAPI
/**
* Gets the Hive port. It is protected due to it is only required for testing purposes.
* @return The Hive port
*/
protected String getHivePort() {
return hivePort;
} // getHivePort
/**
* Returns the persistence backend. It is protected due to it is only required for testing purposes.
* @return The persistence backend
*/
protected HDFSBackend getPersistenceBackend() {
return persistenceBackend;
} // getPersistenceBackend
/**
* Sets the persistence backend. It is protected due to it is only required for testing purposes.
* @param persistenceBackend
*/
protected void setPersistenceBackend(HDFSBackendImpl persistenceBackend) {
this.persistenceBackend = persistenceBackend;
} // setPersistenceBackend
@Override
public void configure(Context context) {
cosmosHost = context.getString("cosmos_host", "localhost").split(",");
LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_host=" + Arrays.toString(cosmosHost)
+ ")");
cosmosPort = context.getString("cosmos_port", "14000");
LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_port=" + cosmosPort + ")");
cosmosDefaultUsername = context.getString("cosmos_default_username", "defaultCygnus");
LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_default_username="
+ cosmosDefaultUsername + ")");
// FIXME: cosmosPassword should be read as a SHA1 and decoded here
cosmosDefaultPassword = context.getString("cosmos_default_password", "");
LOGGER.debug("[" + this.getName() + "] Reading configuration (cosmos_default_password="
+ cosmosDefaultPassword + ")");
hdfsAPI = context.getString("hdfs_api", "httpfs");
if (!hdfsAPI.equals("webhdfs") && !hdfsAPI.equals("httpfs")) {
LOGGER.error("[" + this.getName() + "] Bad configuration (Unrecognized HDFS API " + hdfsAPI + ")");
LOGGER.info("[" + this.getName() + "] Exiting Cygnus");
System.exit(-1);
} else {
LOGGER.debug("[" + this.getName() + "] Reading configuration (hdfs_api=" + hdfsAPI + ")");
} // if else
rowAttrPersistence = context.getString("attr_persistence", "row").equals("row");
LOGGER.debug("[" + this.getName() + "] Reading configuration (attr_persistence="
+ (rowAttrPersistence ? "row" : "column") + ")");
hiveHost = context.getString("hive_host", "localhost");
LOGGER.debug("[" + this.getName() + "] Reading configuration (hive_host=" + hiveHost + ")");
hivePort = context.getString("hive_port", "10000");
LOGGER.debug("[" + this.getName() + "] Reading configuration (hive_port=" + hivePort + ")");
krb5 = context.getBoolean("krb5_auth", false);
LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_auth=" + (krb5 ? "true" : "false")
+ ")");
krb5User = context.getString("krb5_auth.krb5_user", "");
LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_user=" + krb5User + ")");
krb5Password = context.getString("krb5_auth.krb5_password", "");
LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_password=" + krb5Password + ")");
krb5LoginConfFile = context.getString("krb5_auth.krb5_login_conf_file", "");
LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_login_conf_file=" + krb5LoginConfFile
+ ")");
krb5ConfFile = context.getString("krb5_auth.krb5_conf_file", "");
LOGGER.debug("[" + this.getName() + "] Reading configuration (krb5_conf_file=" + krb5ConfFile + ")");
serviceAsNamespace = context.getBoolean("service_as_namespace", false);
LOGGER.debug("[" + this.getName() + "] Reading configuration (service_as_namespace=" + serviceAsNamespace
+ ")");
} // configure
@Override
public void start() {
try {
// create the persistence backend
if (hdfsAPI.equals("httpfs")) {
persistenceBackend = new HDFSBackendImpl(cosmosHost, cosmosPort, cosmosDefaultUsername,
cosmosDefaultPassword, hiveHost, hivePort, krb5, krb5User, krb5Password, krb5LoginConfFile,
krb5ConfFile, serviceAsNamespace);
LOGGER.debug("[" + this.getName() + "] HttpFS persistence backend created");
} else if (hdfsAPI.equals("webhdfs")) {
persistenceBackend = new HDFSBackendImpl(cosmosHost, cosmosPort, cosmosDefaultUsername,
cosmosDefaultPassword, hiveHost, hivePort, krb5, krb5User, krb5Password, krb5LoginConfFile,
krb5ConfFile, serviceAsNamespace);
LOGGER.debug("[" + this.getName() + "] WebHDFS persistence backend created");
} else {
// this point should never be reached since the HDFS API has been checked while configuring the sink
LOGGER.error("[" + this.getName() + "] Bad configuration (Unrecognized HDFS API " + hdfsAPI
+ ")");
LOGGER.info("[" + this.getName() + "] Exiting Cygnus");
System.exit(-1);
} // if else if
} catch (Exception e) {
LOGGER.error(e.getMessage());
} // try catch // try catch
super.start();
LOGGER.info("[" + this.getName() + "] Startup completed");
} // start
@Override
void persist(Map<String, String> eventHeaders, NotifyContextRequest notification) throws Exception {
// get some header values
Long recvTimeTs = new Long(eventHeaders.get("timestamp"));
String fiwareService = eventHeaders.get(Constants.HEADER_SERVICE);
String fiwareServicePath = eventHeaders.get(Constants.HEADER_SERVICE_PATH);
String[] destinations = eventHeaders.get(Constants.DESTINATION).split(",");
// human readable version of the reception time
String recvTime = Utils.getHumanReadable(recvTimeTs);
// iterate on the contextResponses
ArrayList contextResponses = notification.getContextResponses();
for (int i = 0; i < contextResponses.size(); i++) {
// get the i-th contextElement
ContextElementResponse contextElementResponse = (ContextElementResponse) contextResponses.get(i);
ContextElement contextElement = contextElementResponse.getContextElement();
String entityId = contextElement.getId();
String entityType = contextElement.getType();
LOGGER.debug("[" + this.getName() + "] Processing context element (id=" + entityId + ", type="
+ entityType + ")");
// build the effective HDFS stuff
String firstLevel = buildFirstLevel(fiwareService);
String secondLevel = buildSecondLevel(fiwareServicePath);
String thirdLevel = buildThirdLevel(destinations[i]);
String hdfsFolder = firstLevel + "/" + secondLevel + "/" + thirdLevel;
String hdfsFile = hdfsFolder + "/" + thirdLevel + ".txt";
// check if the fileName exists in HDFS right now, i.e. when its attrName has been got
boolean fileExists = false;
if (persistenceBackend.exists(hdfsFile)) {
fileExists = true;
}
// iterate on all this entity's attributes, if there are attributes
ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes();
if (contextAttributes == null || contextAttributes.isEmpty()) {
LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId
+ ", type=" + entityType + ")");
continue;
}
// this is used for storing the attribute's names and values in a Json-like way when dealing with a per
// column attributes persistence; in that case the persistence is not done attribute per attribute, but
// persisting all of them at the same time
String columnLine = "{\"" + Constants.RECV_TIME + "\":\"" + recvTime + "\",";
// this is used for storing the attribute's names needed by Hive in order to create the table when dealing
// with a per column attributes persistence; in that case the Hive table creation is not done using
// standard 8-fields but a variable number of them
String hiveFields = Constants.RECV_TIME + " string";
for (ContextAttribute contextAttribute : contextAttributes) {
String attrName = contextAttribute.getName();
String attrType = contextAttribute.getType();
String attrValue = contextAttribute.getContextValue(true);
String attrMetadata = contextAttribute.getContextMetadata();
LOGGER.debug("[" + this.getName() + "] Processing context attribute (name=" + attrName + ", type="
+ attrType + ")");
if (rowAttrPersistence) {
// create a Json document to be persisted
String rowLine = "{"
+ "\"" + Constants.RECV_TIME_TS + "\":\"" + recvTimeTs / 1000 + "\","
+ "\"" + Constants.RECV_TIME + "\":\"" + recvTime + "\","
+ "\"" + Constants.ENTITY_ID + "\":\"" + entityId + "\","
+ "\"" + Constants.ENTITY_TYPE + "\":\"" + entityType + "\","
+ "\"" + Constants.ATTR_NAME + "\":\"" + attrName + "\","
+ "\"" + Constants.ATTR_TYPE + "\":\"" + attrType + "\","
+ "\"" + Constants.ATTR_VALUE + "\":" + attrValue + ","
+ "\"" + Constants.ATTR_MD + "\":" + attrMetadata
+ "}";
LOGGER.info("[" + this.getName() + "] Persisting data at OrionHDFSSink. HDFS file ("
+ hdfsFile + "), Data (" + rowLine + ")");
// if the fileName exists, append the Json document to it; otherwise, create it with initial content
// and mark as existing (this avoids checking if the fileName exists each time a Json document is
// going to be persisted)
if (fileExists) {
persistenceBackend.append(hdfsFile, rowLine);
} else {
persistenceBackend.createDir(hdfsFolder);
persistenceBackend.createFile(hdfsFile, rowLine);
persistenceBackend.provisionHiveTable(hdfsFolder);
fileExists = true;
} // if else
} else {
columnLine += "\"" + attrName + "\":" + attrValue + ", \"" + attrName + "_md\":" + attrMetadata
+ ",";
hiveFields += "," + attrName + " string," + attrName + "_md array<string>";
} // if else
} // for
// if the attribute persistence mode is per column, now is the time to insert a new row containing full
// attribute list
if (!rowAttrPersistence) {
// insert a new row containing full attribute list
columnLine = columnLine.subSequence(0, columnLine.length() - 1) + "}";
LOGGER.info("[" + this.getName() + "] Persisting data at OrionHDFSSink. HDFS file (" + hdfsFile
+ "), Data (" + columnLine + ")");
if (fileExists) {
persistenceBackend.append(hdfsFile, columnLine);
} else {
persistenceBackend.createDir(hdfsFolder);
persistenceBackend.createFile(hdfsFile, columnLine);
persistenceBackend.provisionHiveTable(hdfsFolder, hiveFields);
fileExists = true;
} // if else
}
} // for
} // persist
/**
* Builds the first level of a HDFS path given a fiwareService. It throws an exception if the naming conventions are
* violated.
* @param fiwareService
* @return
* @throws Exception
*/
private String buildFirstLevel(String fiwareService) throws Exception {
String firstLevel = fiwareService;
if (firstLevel.length() > Constants.MAX_NAME_LEN) {
throw new CygnusBadConfiguration("Building firstLevel=fiwareService (fiwareService=" + fiwareService + ") "
+ "and its length is greater than " + Constants.MAX_NAME_LEN);
}
return firstLevel;
} // buildFirstLevel
/**
* Builds the second level of a HDFS path given given a fiwareService and a destination. It throws an exception if
* the naming conventions are violated.
* @param fiwareService
* @param destination
* @return
* @throws Exception
*/
private String buildSecondLevel(String fiwareServicePath) throws Exception {
String secondLevel = fiwareServicePath;
if (secondLevel.length() > Constants.MAX_NAME_LEN) {
throw new CygnusBadConfiguration("Building secondLevel=fiwareServicePath (" + fiwareServicePath + ") and "
+ "its length is greater than " + Constants.MAX_NAME_LEN);
}
return secondLevel;
} // buildSecondLevel
/**
* Builds the third level of a HDFS path given a destination. It throws an exception if the naming conventions are
* violated.
* @param destination
* @return
* @throws Exception
*/
private String buildThirdLevel(String destination) throws Exception {
String thirdLevel = destination;
if (thirdLevel.length() > Constants.MAX_NAME_LEN) {
throw new CygnusBadConfiguration("Building thirdLevel=destination (" + destination + ") and its length is "
+ "greater than " + Constants.MAX_NAME_LEN);
}
return thirdLevel;
} // buildThirdLevel
} // OrionHDFSSink
|
package com.wandrell.example.swss.model;
import java.io.Serializable;
public interface ExampleEntity extends Serializable {
/**
* Returns the ID assigned to this entity.
* <p>
* If no ID has been assigned yet, then the value will be {@code null} or
* lower than zero.
*
* @return the entity's ID
*/
public Integer getId();
/**
* Returns the name of the entity.
*
* @return the entity's name
*/
public String getName();
/**
* Sets the ID assigned to this entity.
*
* @param identifier
* the ID for the entity
*/
public void setId(final Integer identifier);
/**
* Changes the name of the entity.
*
* @param name
* the name to set on the entity
*/
public void setName(final String name);
}
|
package com.wiley.autotest.selenium.context;
import com.wiley.autotest.selenium.elements.upgrade.TeasyElement;
import com.wiley.autotest.selenium.elements.upgrade.TeasyElementList;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Function;
/**
* Represents List of blocks concept introducing filtering via {@link #filter(Function)} method
* <p>
* Useful for cases when you have a collection of UI components (aka blocks) and you need
* to select a specific block to continue working with it.
*
* @param <T> - class representing a particular block from a collection
*/
public class BlockList<T extends AbstractBlock> extends ArrayList<T> {
private final Class<T> blockClass;
public BlockList(@NotNull TeasyElementList elements, Class<T> blockClass) {
super();
this.blockClass = blockClass;
elements.forEach(el -> add(createBlockInstance(el)));
}
/**
* Filters a block list
*
* @param func - function to filter block list
* @return the desired block from list
*/
public T filter(Function<Collection<T>, T> func) {
return func.apply(this);
}
private T createBlockInstance(TeasyElement element) {
try {
Constructor<T> constructor = blockClass.getDeclaredConstructor(TeasyElement.class);
return constructor.newInstance(element);
} catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new RuntimeException("Error occurred during a call to the block constructor.", e);
}
}
}
|
package peergos.shared.user.fs;
import peergos.shared.crypto.*;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.ipfs.api.Multihash;
import peergos.shared.user.*;
import peergos.shared.util.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.stream.*;
public class EncryptedChunkRetriever implements FileRetriever {
private final byte[] chunkNonce, chunkAuth;
private final List<Multihash> fragmentHashes;
private final Location nextChunk;
private final peergos.shared.user.fs.Fragmenter fragmenter;
public EncryptedChunkRetriever(byte[] chunkNonce, byte[] chunkAuth, List<Multihash> fragmentHashes, Location nextChunk, Fragmenter fragmenter) {
this.chunkNonce = chunkNonce;
this.chunkAuth = chunkAuth;
this.fragmentHashes = fragmentHashes;
this.nextChunk = nextChunk;
this.fragmenter = fragmenter;
}
public CompletableFuture<LazyInputStreamCombiner> getFile(UserContext context, SymmetricKey dataKey, long fileSize,
Location ourLocation, Consumer<Long> monitor) {
return getChunkInputStream(context, dataKey, 0, fileSize, ourLocation, monitor)
.thenApply(chunk -> new LazyInputStreamCombiner(this, context, dataKey, chunk.get().chunk.data(), fileSize, monitor));
}
public CompletableFuture<Optional<LocatedEncryptedChunk>> getEncryptedChunk(long bytesRemainingUntilStart, long truncateTo,
byte[] nonce, SymmetricKey dataKey,
Location ourLocation, UserContext context, Consumer<Long> monitor) {
if (bytesRemainingUntilStart < Chunk.MAX_SIZE) {
return context.downloadFragments(fragmentHashes, monitor).thenCompose(fragments -> {
fragments = reorder(fragments, fragmentHashes);
byte[][] collect = fragments.stream().map(f -> f.fragment.data).toArray(byte[][]::new);
byte[] cipherText = fragmenter.recombine(collect, Chunk.MAX_SIZE);
EncryptedChunk fullEncryptedChunk = new EncryptedChunk(ArrayOps.concat(chunkAuth, cipherText));
if (truncateTo < Chunk.MAX_SIZE)
fullEncryptedChunk = fullEncryptedChunk.truncateTo((int) truncateTo);
return CompletableFuture.completedFuture(Optional.of(new LocatedEncryptedChunk(ourLocation, fullEncryptedChunk, nonce)));
});
}
return context.getMetadata(getNext()).thenCompose(meta ->
!meta.isPresent() ? CompletableFuture.completedFuture(Optional.empty()) :
meta.get().retriever().getEncryptedChunk(bytesRemainingUntilStart - Chunk.MAX_SIZE,
truncateTo - Chunk.MAX_SIZE, meta.get().retriever().getNonce(), dataKey, getNext(), context, monitor)
);
}
public CompletableFuture<Optional<Location>> getLocationAt(Location startLocation, long offset, UserContext context) {
if (offset < Chunk.MAX_SIZE)
return CompletableFuture.completedFuture(Optional.of(startLocation));
Location next = getNext();
if (next == null)
return CompletableFuture.completedFuture(Optional.empty());
if (offset < 2*Chunk.MAX_SIZE)
return CompletableFuture.completedFuture(Optional.of(next)); // chunk at this location hasn't been written yet, only referenced by previous chunk
return context.getMetadata(next)
.thenCompose(meta -> meta.isPresent() ?
meta.get().retriever().getLocationAt(next, offset - Chunk.MAX_SIZE, context) :
CompletableFuture.completedFuture(Optional.empty())
);
}
public Location getNext() {
return this.nextChunk;
}
public byte[] getNonce() {
return chunkNonce;
}
public CompletableFuture<Optional<LocatedChunk>> getChunkInputStream(UserContext context, SymmetricKey dataKey,
long startIndex, long truncateTo,
Location ourLocation, Consumer<Long> monitor) {
return getEncryptedChunk(startIndex, truncateTo, chunkNonce, dataKey, ourLocation, context, monitor).thenCompose(fullEncryptedChunk -> {
if (!fullEncryptedChunk.isPresent()) {
return getLocationAt(ourLocation, startIndex, context).thenApply(unwrittenChunkLocation ->
!unwrittenChunkLocation.isPresent() ? Optional.empty() :
Optional.of(new LocatedChunk(unwrittenChunkLocation.get(),
new Chunk(new byte[Math.min(Chunk.MAX_SIZE, (int) (truncateTo - startIndex))],
dataKey, unwrittenChunkLocation.get().getMapKey(),
context.randomBytes(TweetNaCl.SECRETBOX_NONCE_BYTES)))));
}
if (!fullEncryptedChunk.isPresent())
return CompletableFuture.completedFuture(Optional.empty());
try {
byte[] original = fullEncryptedChunk.get().chunk.decrypt(dataKey, fullEncryptedChunk.get().nonce);
return CompletableFuture.completedFuture(Optional.of(new LocatedChunk(fullEncryptedChunk.get().location,
new Chunk(original, dataKey, fullEncryptedChunk.get().location.getMapKey(), context.randomBytes(TweetNaCl.SECRETBOX_NONCE_BYTES)))));
} catch (IllegalStateException e) {
throw new IllegalStateException("Couldn't decrypt chunk at mapkey: " + new ByteArrayWrapper(fullEncryptedChunk.get().location.getMapKey()), e);
}
});
}
public void serialize(DataSink buf) {
buf.writeByte((byte)1); // This class
buf.writeArray(chunkNonce);
buf.writeArray(chunkAuth);
buf.writeArray(ArrayOps.concat(fragmentHashes.stream().map(h -> new ByteArrayWrapper(h.toBytes())).collect(Collectors.toList())));
buf.writeByte(this.nextChunk != null ? (byte)1 : 0);
if (this.nextChunk != null)
buf.write(this.nextChunk.serialize());
fragmenter.serialize(buf);
}
public static EncryptedChunkRetriever deserialize(DataSource buf) throws IOException {
byte[] chunkNonce = buf.readArray();
byte[] chunkAuth = buf.readArray();
byte[] concatFragmentHashes = buf.readArray();
List<Multihash> hashes = new ArrayList<>();
DataSource dataSource = new DataSource(concatFragmentHashes);
while (dataSource.remaining() != 0)
hashes.add(Multihash.deserialize(dataSource));
boolean hasNext = buf.readBoolean();
Location nextChunk = null;
if (hasNext)
nextChunk = Location.deserialize(buf);
Fragmenter fragmenter = Fragmenter.deserialize(buf);
return new EncryptedChunkRetriever(chunkNonce, chunkAuth, hashes, nextChunk, fragmenter);
}
private static List<FragmentWithHash> reorder(List<FragmentWithHash> fragments, List<Multihash> hashes) {
FragmentWithHash[] res = new FragmentWithHash[fragments.size()];
for (FragmentWithHash f: fragments)
res[hashes.indexOf(f.hash)] = f;
return Arrays.asList(res);
}
private static List<byte[]> split(byte[] arr, int size) {
int length = arr.length/size;
List<byte[]> res = new ArrayList<>();
for (int i=0; i < length; i++)
res.add(Arrays.copyOfRange(arr, i*size, (i+1)*size));
return res;
}
}
|
package de.unistuttgart.quadrama.io.html;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.Feature;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.json.JSONObject;
import de.tudarmstadt.ukp.dkpro.core.api.io.JCasFileWriter_ImplBase;
import de.unistuttgart.ims.drama.api.Act;
import de.unistuttgart.ims.drama.api.ActHeading;
import de.unistuttgart.ims.drama.api.Drama;
import de.unistuttgart.ims.drama.api.Figure;
import de.unistuttgart.ims.drama.api.Scene;
import de.unistuttgart.ims.drama.api.SceneHeading;
public class JsonExporter extends JCasFileWriter_ImplBase {
public static final String PARAM_JAVASCRIPT = "Javascript declaration";
@ConfigurationParameter(name = PARAM_JAVASCRIPT, mandatory = false)
String javascriptVariableName = null;
@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
JSONObject json = new JSONObject();
JSONObject md = new JSONObject();
// meta data and author
Drama drama = JCasUtil.selectSingle(aJCas, Drama.class);
md.put("documentId", drama.getDocumentId());
md.put("documentTitle", drama.getDocumentTitle());
JSONObject author = new JSONObject();
author.put("name", drama.getAuthorname());
author.put("pnd", drama.getAuthorPnd());
md.put("author", author);
// figures
for (Figure figure : JCasUtil.select(aJCas, Figure.class)) {
json.append("figures", convert(figure, true));
}
// segments
for (Act act : JCasUtil.select(aJCas, Act.class)) {
List<ActHeading> ahl = JCasUtil.selectCovered(ActHeading.class, act);
if (ahl.isEmpty()) {
json.append("acts", convert(act, false));
} else {
json.append("acts", convert(act, false).put("heading", ahl.get(0).getCoveredText()));
}
for (Scene scene : JCasUtil.selectCovered(Scene.class, act)) {
List<SceneHeading> shl = JCasUtil.selectCovered(SceneHeading.class, scene);
if (shl.isEmpty()) {
json.append("scenes", convert(scene, false));
} else {
json.append("scenes", convert(scene, false).put("heading", shl.get(0).getCoveredText()));
}
}
}
// assembly
json.put("metadata", md);
OutputStream os = null;
OutputStreamWriter osw;
try {
os = this.getOutputStream(aJCas, ".json");
osw = new OutputStreamWriter(os);
osw.write(json.toString());
osw.flush();
osw.close();
} catch (IOException e) {
throw new AnalysisEngineProcessException(e);
} finally {
IOUtils.closeQuietly(os);
}
}
public static <T extends Annotation> JSONObject convert(T annotation, boolean includeText) {
JSONObject object = new JSONObject();
if (includeText)
object.put("coveredText", annotation.getCoveredText());
for (Feature feature : annotation.getType().getFeatures()) {
if (feature.getRange().isPrimitive()) {
object.put(feature.getShortName(), annotation.getFeatureValueAsString(feature));
}
}
return object;
}
}
|
package de.zalando.aruha.nakadi.domain;
public class TopicPartition {
private String topicId;
private String partitionId;
public TopicPartition(final String topicId, final String partitionId) {
setTopicId(topicId);
setPartitionId(partitionId);
}
public String getTopicId() {
return topicId;
}
public void setTopicId(final String topicId) {
this.topicId = topicId;
}
public String getPartitionId() {
return partitionId;
}
public void setPartitionId(final String partitionId) {
this.partitionId = partitionId;
}
}
|
package edu.ucdenver.ccp.common.download;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.SocketException;
import java.net.URL;
import org.apache.log4j.Logger;
import edu.ucdenver.ccp.common.calendar.CalendarUtil;
import edu.ucdenver.ccp.common.collections.CollectionsUtil;
import edu.ucdenver.ccp.common.file.CharacterEncoding;
import edu.ucdenver.ccp.common.file.FileArchiveUtil;
import edu.ucdenver.ccp.common.file.FileUtil;
import edu.ucdenver.ccp.common.file.FileWriterUtil;
import edu.ucdenver.ccp.common.file.FileWriterUtil.FileSuffixEnforcement;
import edu.ucdenver.ccp.common.file.FileWriterUtil.WriteMode;
import edu.ucdenver.ccp.common.ftp.FTPUtil;
import edu.ucdenver.ccp.common.http.HttpUtil;
/**
* This class works in conjunction with the <code>FtpDownload</code> and <code>HttpDownload</code>
* annotations to facilitate download of files and referencing (via the annotations) of those files
* to member variables of a class.
*
* Download completion is indicated by writing a "semaphore" file that is the file name with .ready
* appended to it in the same directory as the downloaded file.
*
* @author bill
*
*/
public class DownloadUtil {
private static final Logger logger = Logger.getLogger(DownloadUtil.class);
/**
* File suffix used on the "ready semaphore" file that indicates that a downloaded file has been
* downloaded completely and is now ready for use.
*/
private static final String READY_SEMAPHORE_SUFFIX = ".ready";
public static void download(Object object, File workDirectory, String userName, String password, boolean clean)
throws SocketException, IOException, IllegalArgumentException, IllegalAccessException {
for (Field field : object.getClass().getDeclaredFields()) {
File file = null;
if (field.isAnnotationPresent(FtpDownload.class)) {
file = handleFtpDownload(workDirectory, field.getAnnotation(FtpDownload.class), userName, password,
clean);
} else if (field.isAnnotationPresent(HttpDownload.class)) {
file = handleHttpDownload(workDirectory, field.getAnnotation(HttpDownload.class), clean);
}
// System.out.println("Downloaded file: " + file.getName());
if (file != null) {
assignField(object, field, file);
if (clean || !readySemaphoreFileExists(file)) {
// if clean = false then it might already exist
writeReadySemaphoreFile(file);
}
}
}
}
/**
* @param file
*/
private static void writeReadySemaphoreFile(File file) {
try {
if (!getReadySemaphoreFile(file).createNewFile()) {
throw new RuntimeException("Semaphore file could not be created b/c it already exists: "
+ getReadySemaphoreFile(file).getAbsolutePath());
}
FileWriterUtil.printLines(CollectionsUtil.createList("Downloaded on " + CalendarUtil.getDateStamp("/")),
getReadySemaphoreFile(file), CharacterEncoding.UTF_8, WriteMode.OVERWRITE,
FileSuffixEnforcement.OFF);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static boolean readySemaphoreFileExists(File file) {
return getReadySemaphoreFile(file).exists();
}
private static File getReadySemaphoreFile(File file) {
return new File(file.getAbsolutePath() + READY_SEMAPHORE_SUFFIX);
}
public static File download(Class<?> klass, File workDirectory, String userName, String password, boolean clean)
throws SocketException, IOException, IllegalArgumentException {
File f = null;
if (klass.isAnnotationPresent(HttpDownload.class)) {
f = handleHttpDownload(workDirectory, klass.getAnnotation(HttpDownload.class), clean);
} else if (klass.isAnnotationPresent(FtpDownload.class)) {
f = handleFtpDownload(workDirectory, klass.getAnnotation(FtpDownload.class), userName, password, clean);
}
if (f != null) {
if (clean || !readySemaphoreFileExists(f)) {
// if clean = false then it might already exist
writeReadySemaphoreFile(f);
}
}
return f;
}
public static File download(Field field, File workDirectory, String userName, String password, boolean clean)
throws SocketException, IOException, IllegalArgumentException {
File f = null;
if (field.isAnnotationPresent(HttpDownload.class)) {
f = handleHttpDownload(workDirectory, field.getAnnotation(HttpDownload.class), clean);
} else if (field.isAnnotationPresent(FtpDownload.class)) {
f = handleFtpDownload(workDirectory, field.getAnnotation(FtpDownload.class), userName, password, clean);
}
if (f != null) {
if (clean || !readySemaphoreFileExists(f)) {
// if clean = false then it might already exist
writeReadySemaphoreFile(f);
}
}
return f;
}
private static File handleHttpDownload(File workDirectory, HttpDownload httpd, boolean clean) throws IOException,
IllegalArgumentException {
URL url = new URL(httpd.url());
String fileName = httpd.fileName();
String targetFileName = (httpd.targetFileName().length() > 0) ? httpd.targetFileName() : null;
File targetFile = (targetFileName == null) ? null : new File(workDirectory, targetFileName);
if (fileName.isEmpty())
fileName = HttpUtil.getFinalPathElement(url);
File downloadedFile = FileUtil.appendPathElementsToDirectory(workDirectory, fileName);
if (!fileExists(downloadedFile, targetFile, clean, httpd.decompress())) {
long startTime = System.currentTimeMillis();
downloadedFile = HttpUtil.downloadFile(url, downloadedFile);
long duration = System.currentTimeMillis() - startTime;
logger.info("Duration of " + downloadedFile.getName() + " download: " + (duration / (1000 * 60)) + "min");
}
if (httpd.decompress()) {
return unpackFile(workDirectory, clean, downloadedFile, targetFileName);
}
return downloadedFile;
}
/**
* Unpacks (unzips) the downloaded file
*
* @param workDirectory
* @param clean
* @param downloadedFile
* @throws IOException
*/
private static File unpackFile(File workDirectory, boolean clean, File downloadedFile, String targetFileName)
throws IOException {
File unpackedDownloadedFile = unpackDownloadedFile(workDirectory, clean, downloadedFile, targetFileName);
return unpackedDownloadedFile;
}
private static void assignField(Object object, Field field, File file) throws IllegalAccessException {
field.setAccessible(true);
field.set(object, file);
}
/**
* Unpacks the specified file if necessary
*
* @param workDirectory
* @param clean
* @param downloadedFile
* @param targetFileName
* this input parameter indicates the name of a particular file inside a zip archive
* to retrieve. It should be set to null if the compressed file is not a zip archive
* @return a reference to the unpacked File
* @throws IOException
*/
public static File unpackDownloadedFile(File workDirectory, boolean clean, File downloadedFile,
String targetFileName) throws IOException {
File unpackedFile = downloadedFile;
File targetFile = (targetFileName == null) ? null : new File(workDirectory, targetFileName);
if (fileNeedsUnzipping(downloadedFile, targetFile, clean)) {
unpackedFile = FileArchiveUtil.unzip(downloadedFile, workDirectory, targetFileName);
} else if (FileArchiveUtil.isZippedFile(downloadedFile)) {
// File has already been downloaded and unzipped
unpackedFile = FileArchiveUtil.getUnzippedFileReference(downloadedFile, targetFile);
}
return unpackedFile;
}
private static File handleFtpDownload(File workDirectory, FtpDownload ftpd, String userName, String password,
boolean clean) throws IOException, IllegalArgumentException {
String uName = (userName == null) ? ftpd.username() : userName;
String pWord = (password == null) ? ftpd.password() : password;
String targetFileName = (ftpd.targetFileName().length() > 0) ? ftpd.targetFileName() : null;
File targetFile = (targetFileName == null) ? null : new File(workDirectory, targetFileName);
File downloadedFile = FileUtil.appendPathElementsToDirectory(workDirectory, ftpd.filename());
if (!fileExists(downloadedFile, targetFile, clean, ftpd.decompress())) {
long startTime = System.currentTimeMillis();
downloadedFile = FTPUtil.downloadFile(ftpd.server(), ftpd.port(), ftpd.path(), ftpd.filename(),
ftpd.filetype(), workDirectory, uName, pWord);
long duration = System.currentTimeMillis() - startTime;
logger.info("Duration of " + downloadedFile.getName() + " download: " + (duration / (1000 * 60)) + "min");
}
if (ftpd.decompress()) {
return unpackFile(workDirectory, clean, downloadedFile, targetFileName);
}
return downloadedFile;
}
/**
* If clean is true, then this method always returns false (and the file is deleted). If clean
* is false, then this method returns downloadedFile.exists()
*
* If the downloaded file is present but the ready-semaphore file is not present then this
* processes waits for the semaphore file to appear. It is assumed that the downloaded file is
* still in the process of being downloaded by another thread.
*
* @param downloadedFile
* @param targetFile
* the target file is a particular file to retrieve from inside a downloaded zip
* archive.
* @param clean
* @return
*/
public static boolean fileExists(File downloadedFile, File targetFile, boolean clean, boolean decompress) {
File unzippedFile = null;
if (decompress && FileArchiveUtil.isZippedFile(downloadedFile)) {
unzippedFile = FileArchiveUtil.getUnzippedFileReference(downloadedFile, targetFile);
}
if (clean) {
FileUtil.deleteFile(downloadedFile);
if (unzippedFile != null) {
FileUtil.deleteFile(unzippedFile);
FileUtil.deleteFile(getReadySemaphoreFile(unzippedFile));
} else {
FileUtil.deleteFile(getReadySemaphoreFile(downloadedFile));
}
return false;
}
boolean fileIsPresent = downloadedFile.exists() || (unzippedFile != null && unzippedFile.exists());
if (fileIsPresent) {
waitForReadySemaphoreFile((unzippedFile == null) ? downloadedFile : unzippedFile);
}
return fileIsPresent;
}
/**
* Returns when the semaphore file is present. Checks once a minute for its existence.
*
* @param file
*/
private static void waitForReadySemaphoreFile(File file) {
while (!readySemaphoreFileExists(file)) {
logger.info("Waiting for another process to finish downloading the file. Will continue when "
+ getReadySemaphoreFile(file) + " is present.");
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
throw new RuntimeException("Error while waiting for another process to download a file: "
+ file.getAbsolutePath(), e);
}
}
}
/**
* If the input file is not a zip file, then this method return false immediately. Otherwise if
* clean is true, it deletes any previous unzipped version of the file and return true. If clean
* is false, it simply returns based on existence of the unzipped file (false if it exists, true
* if it doesn't).
*
* @param zippedFile
* @param clean
* @return
*/
private static boolean fileNeedsUnzipping(File zippedFile, File targetFile, boolean clean) {
if (!FileArchiveUtil.isZippedFile(zippedFile)) {
return false;
}
File unzippedFile = FileArchiveUtil.getUnzippedFileReference(zippedFile, targetFile);
if (clean) {
FileUtil.deleteFile(unzippedFile);
return true;
}
return !unzippedFile.exists();
}
}
|
package edu.ucdenver.ccp.common.download;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.SocketException;
import java.net.URL;
import org.apache.log4j.Logger;
import edu.ucdenver.ccp.common.calendar.CalendarUtil;
import edu.ucdenver.ccp.common.collections.CollectionsUtil;
import edu.ucdenver.ccp.common.file.CharacterEncoding;
import edu.ucdenver.ccp.common.file.FileArchiveUtil;
import edu.ucdenver.ccp.common.file.FileUtil;
import edu.ucdenver.ccp.common.file.FileWriterUtil;
import edu.ucdenver.ccp.common.file.FileWriterUtil.FileSuffixEnforcement;
import edu.ucdenver.ccp.common.file.FileWriterUtil.WriteMode;
import edu.ucdenver.ccp.common.ftp.FTPUtil;
import edu.ucdenver.ccp.common.http.HttpUtil;
/**
* This class works in conjunction with the <code>FtpDownload</code> and <code>HttpDownload</code>
* annotations to facilitate download of files and referencing (via the annotations) of those files
* to member variables of a class.
*
* Download completion is indicated by writing a "semaphore" file that is the file name with .ready
* appended to it in the same directory as the downloaded file.
*
* @author bill
*
*/
public class DownloadUtil {
private static final Logger logger = Logger.getLogger(DownloadUtil.class);
/**
* File suffix used on the "ready semaphore" file that indicates that a downloaded file has been
* downloaded completely and is now ready for use.
*/
private static final String READY_SEMAPHORE_SUFFIX = ".ready";
public static void download(Object object, File workDirectory, String userName, String password, boolean clean)
throws SocketException, IOException, IllegalArgumentException, IllegalAccessException {
for (Field field : object.getClass().getDeclaredFields()) {
File file = null;
if (field.isAnnotationPresent(FtpDownload.class))
file = handleFtpDownload(workDirectory, field.getAnnotation(FtpDownload.class), userName, password,
clean);
else if (field.isAnnotationPresent(HttpDownload.class))
file = handleHttpDownload(workDirectory, field.getAnnotation(HttpDownload.class), clean);
if (file != null) {
assignField(object, field, file);
writeReadySemaphoreFile(file);
}
}
}
/**
* @param file
*/
private static void writeReadySemaphoreFile(File file) {
try {
if (!getReadySemaphoreFile(file).createNewFile())
throw new RuntimeException("Semaphore file could not be created b/c it already exists: "
+ getReadySemaphoreFile(file).getAbsolutePath());
FileWriterUtil.printLines(CollectionsUtil.createList("Downloaded on " + CalendarUtil.getDateStamp("/")),
getReadySemaphoreFile(file), CharacterEncoding.UTF_8, WriteMode.OVERWRITE,
FileSuffixEnforcement.OFF);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static boolean readySemaphoreFileExists(File file) {
return getReadySemaphoreFile(file).exists();
}
private static File getReadySemaphoreFile(File file) {
return new File(file.getAbsolutePath() + READY_SEMAPHORE_SUFFIX);
}
public static File download(Class<?> klass, File workDirectory, String userName, String password, boolean clean)
throws SocketException, IOException, IllegalArgumentException {
File f = null;
if (klass.isAnnotationPresent(HttpDownload.class))
f = handleHttpDownload(workDirectory, klass.getAnnotation(HttpDownload.class), clean);
else if (klass.isAnnotationPresent(FtpDownload.class))
f = handleFtpDownload(workDirectory, klass.getAnnotation(FtpDownload.class), userName, password, clean);
if (f != null)
writeReadySemaphoreFile(f);
return f;
}
public static File download(Field field, File workDirectory, String userName, String password, boolean clean)
throws SocketException, IOException, IllegalArgumentException {
File f = null;
if (field.isAnnotationPresent(HttpDownload.class))
f = handleHttpDownload(workDirectory, field.getAnnotation(HttpDownload.class), clean);
else if (field.isAnnotationPresent(FtpDownload.class))
f = handleFtpDownload(workDirectory, field.getAnnotation(FtpDownload.class), userName, password, clean);
if (f != null)
writeReadySemaphoreFile(f);
return f;
}
private static File handleHttpDownload(File workDirectory, HttpDownload httpd, boolean clean) throws IOException,
IllegalArgumentException {
URL url = new URL(httpd.url());
String fileName = httpd.fileName();
if (fileName.isEmpty())
fileName = HttpUtil.getFinalPathElement(url);
File downloadedFile = FileUtil.appendPathElementsToDirectory(workDirectory, fileName);
if (!fileExists(downloadedFile, clean)) {
long startTime = System.currentTimeMillis();
downloadedFile = HttpUtil.downloadFile(url, downloadedFile);
long duration = System.currentTimeMillis() - startTime;
logger.info("Duration of " + downloadedFile.getName() + " download: " + (duration / (1000 * 60)) + "min");
}
return unpackFile(workDirectory, clean, downloadedFile);
}
/**
* Unpacks (unzips) the downloaded file
*
* @param workDirectory
* @param clean
* @param downloadedFile
* @throws IOException
*/
private static File unpackFile(File workDirectory, boolean clean, File downloadedFile) throws IOException {
File unpackedDownloadedFile = unpackDownloadedFile(workDirectory, clean, downloadedFile);
return unpackedDownloadedFile;
}
private static void assignField(Object object, Field field, File file) throws IllegalAccessException {
field.setAccessible(true);
field.set(object, file);
}
/**
* Unpacks the specified file if necessary
*
* @param workDirectory
* @param clean
* @param downloadedFile
* @return a reference to the unpacked File
* @throws IOException
*/
public static File unpackDownloadedFile(File workDirectory, boolean clean, File downloadedFile) throws IOException {
File unpackedFile = downloadedFile;
if (fileNeedsUnzipping(downloadedFile, clean))
unpackedFile = FileArchiveUtil.unzip(downloadedFile, workDirectory);
else if (FileArchiveUtil.isZippedFile(downloadedFile))
// File has already been downloaded and unzipped
unpackedFile = FileArchiveUtil.getUnzippedFileReference(downloadedFile);
return unpackedFile;
}
private static File handleFtpDownload(File workDirectory, FtpDownload ftpd, String userName, String password,
boolean clean) throws IOException, IllegalArgumentException {
String uName = (userName == null) ? ftpd.username() : userName;
String pWord = (password == null) ? ftpd.password() : password;
File downloadedFile = FileUtil.appendPathElementsToDirectory(workDirectory, ftpd.filename());
if (!fileExists(downloadedFile, clean)) {
long startTime = System.currentTimeMillis();
downloadedFile = FTPUtil.downloadFile(ftpd.server(), ftpd.port(), ftpd.path(), ftpd.filename(),
ftpd.filetype(), workDirectory, uName, pWord);
long duration = System.currentTimeMillis() - startTime;
logger.info("Duration of " + downloadedFile.getName() + " download: " + (duration / (1000 * 60)) + "min");
}
return unpackFile(workDirectory, clean, downloadedFile);
}
/**
* If clean is true, then this method always returns false (and the file is deleted). If clean
* is false, then this method returns downloadedFile.exists()
*
* If the downloaded file is present but the ready-semaphore file is not present then this
* processes waits for the semaphore file to appear. It is assumed that the downloaded file is
* still in the process of being downloaded by another thread.
*
* @param downloadedFile
* @param clean
* @return
*/
public static boolean fileExists(File downloadedFile, boolean clean) {
File unzippedFile = null;
if (FileArchiveUtil.isZippedFile(downloadedFile))
unzippedFile = FileArchiveUtil.getUnzippedFileReference(downloadedFile);
if (clean) {
FileUtil.deleteFile(downloadedFile);
if (unzippedFile != null) {
FileUtil.deleteFile(unzippedFile);
FileUtil.deleteFile(getReadySemaphoreFile(unzippedFile));
} else
FileUtil.deleteFile(getReadySemaphoreFile(downloadedFile));
return false;
}
boolean fileIsPresent = downloadedFile.exists() || (unzippedFile != null && unzippedFile.exists());
if (fileIsPresent)
waitForReadySemaphoreFile((unzippedFile == null) ? downloadedFile : unzippedFile);
return fileIsPresent;
}
/**
* Returns when the semaphore file is present. Checks once a minute for its existence.
*
* @param file
*/
private static void waitForReadySemaphoreFile(File file) {
while (!readySemaphoreFileExists(file)) {
logger.info("Waiting for another process to finish downloading the file. Will continue when "
+ getReadySemaphoreFile(file) + " is present.");
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
throw new RuntimeException("Error while waiting for another process to download a file: "
+ file.getAbsolutePath(), e);
}
}
}
/**
* If the input file is not a zip file, then this method return false immediately. Otherwise if
* clean is true, it deletes any previous unzipped version of the file and return true. If clean
* is false, it simply returns based on existence of the unzipped file (false if it exists, true
* if it doesn't).
*
* @param zippedFile
* @param clean
* @return
*/
private static boolean fileNeedsUnzipping(File zippedFile, boolean clean) {
if (!FileArchiveUtil.isZippedFile(zippedFile))
return false;
File unzippedFile = FileArchiveUtil.getUnzippedFileReference(zippedFile);
if (clean) {
FileUtil.deleteFile(unzippedFile);
return true;
}
return !unzippedFile.exists();
}
}
|
package eu.pericles.modelcompiler.jbpm;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.nio.file.Files;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.DomReader;
public class JbpmFileParser {
private JbpmFile jbpmFile;
public void parse(String inputFile) {
try {
File processedFile = processInputFile(inputFile);
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(processedFile);
document.getDocumentElement().normalize();
XStream xstream = new XStream(new DomDriver());
xstream.processAnnotations(JbpmFile.class);
ObjectInputStream ois = xstream.createObjectInputStream(new DomReader(document.getDocumentElement()));
JbpmFile jbpmFile = (JbpmFile) ois.readObject();
jbpmFile.organiseInfo();
setJbpmFile(jbpmFile);
ois.close();
} catch (Exception exception) {
exception.printStackTrace();
} finally {
Files.delete(processedFile.toPath());
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
/* Modify the input file in a way can be read by xstream as a single element. It is not a very elegant
* solution but it is ok for now, it works and keeps things simple.
*/
private File processInputFile(String nameFile) throws Exception {
File processedFile = new File("temp.bpmn2");
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(nameFile))));
BufferedWriter out = new BufferedWriter(new FileWriter(processedFile, true));
String line = null;
while ((line = in.readLine()) != null) {
if (line.startsWith("<bpmn2:definitions")) {
out.write(line);
out.newLine();
line = "<jbpm>";
}
if (line.startsWith("</bpmn2:definitions")){
out.write("</jbpm>");
out.newLine();
}
out.write(line);
out.newLine();
}
in.close();
out.close();
return processedFile;
}
public JbpmFile getJbpmFile() {
return jbpmFile;
}
public void setJbpmFile(JbpmFile jbpmFile) {
this.jbpmFile = jbpmFile;
}
}
|
package foodtruck.server.job;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.common.primitives.Ints;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import foodtruck.dao.DailyTruckStopDAO;
import foodtruck.dao.WeeklyTruckStopDAO;
import foodtruck.util.Clock;
/**
* @author aviolette
* @since 9/19/16
*/
@Singleton
public class MigrateTruckCountServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(MigrateTruckCountServlet.class.getName());
private static final int INTERVAL_IN_DAYS = 10;
private final Clock clock;
private final Provider<Queue> queueProvider;
private final WeeklyTruckStopDAO weekly;
private final DailyTruckStopDAO daily;
@Inject
public MigrateTruckCountServlet(Clock clock, Provider<Queue> queueProvider, DailyTruckStopDAO dailyTruckStopDAO,
WeeklyTruckStopDAO weeklyTruckStopDAO) {
this.clock = clock;
this.queueProvider = queueProvider;
this.weekly = weeklyTruckStopDAO;
this.daily = dailyTruckStopDAO;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Content-Type", "text/html");
resp.getOutputStream()
.print(
"<html><body><form method='POST' action=''><p>Are you sure?</p><input type='submit' value='Submit'/></form></body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DateTime finalEnd = clock.currentDay()
.toDateTimeAtStartOfDay();
log.info("Deleting old stats data");
weekly.deleteBefore(clock.currentDay());
daily.deleteBefore(clock.currentDay());
log.info("Starting migration of stats data");
DateTime startTime = new DateTime(2011, 8, 1, 1, 1, clock.zone());
int days = INTERVAL_IN_DAYS;
Queue queue = queueProvider.get();
while (startTime.isBefore(finalEnd)) {
queue.add(TaskOptions.Builder.withUrl("/cron/update_trucks_count_over_range")
.param("startTime", String.valueOf(startTime.getMillis()))
.param("days", String.valueOf(days)));
startTime = startTime.plusDays(INTERVAL_IN_DAYS);
Duration duration = new Duration(startTime.plusDays(days), finalEnd);
if (duration.getStandardDays() < 0) {
days = Ints.checkedCast(Math.abs(duration.getStandardDays()));
} else {
days = Ints.checkedCast(Math.min(INTERVAL_IN_DAYS, duration.getStandardDays()));
}
}
resp.sendRedirect("/admin/trucks");
}
}
|
package gov.nasa.jpl.mbee.patternloader;
import gov.nasa.jpl.mbee.stylesaver.StylerUtils;
import gov.nasa.jpl.mbee.stylesaver.ViewLoader;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import org.json.simple.JSONObject;
import com.nomagic.magicdraw.actions.MDAction;
import com.nomagic.magicdraw.copypaste.CopyPasting;
import com.nomagic.magicdraw.core.Application;
import com.nomagic.magicdraw.core.Project;
import com.nomagic.magicdraw.openapi.uml.SessionManager;
import com.nomagic.magicdraw.uml.symbols.DiagramPresentationElement;
import com.nomagic.magicdraw.uml.symbols.PresentationElement;
import com.nomagic.task.ProgressStatus;
import com.nomagic.task.RunnableWithProgress;
import com.nomagic.ui.BaseProgressMonitor;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Diagram;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
/**
* A class used to load patterns onto the active diagram from other project diagrams.
*
* @author Benjamin Inada, JPL/Caltech
*/
public class PatternLoader extends MDAction {
private static final long serialVersionUID = 1L;
private PresentationElement requester;
/**
* Initializes the Pattern Loader.
*
* @param id the ID of the action.
* @param value the name of the action.
* @param mnemonic the mnemonic key of the action.
* @param group the name of the related commands group.
*/
public PatternLoader(String id, String value, int mnemonic, String group, PresentationElement requester) {
super(id, value, mnemonic, group);
this.requester = requester;
}
/**
* Perform a pattern load on menu option mouse click.
*
* @param e the ActionEvent that fired this method.
*/
@Override
public void actionPerformed(ActionEvent e) {
SessionManager.getInstance().createSession("Loading Pattern...");
if(requester == null) {
this.requester = Application.getInstance().getProject().getActiveDiagram();
}
// allow user to pick load or stamp operation
try {
delegateOperation();
} catch(RuntimeException ex) {
ex.printStackTrace();
SessionManager.getInstance().cancelSession();
return;
}
SessionManager.getInstance().closeSession();
}
/**
* Allows the user to pick the load or stamp operation.
*
* @throws RuntimeException if a problem with loading or stamping occurs.
*/
private void delegateOperation() throws RuntimeException {
Object[] options = { "Load pattern", "Stamp pattern" };
int opt = JOptionPane.showOptionDialog(null,
"Would you like to load or stamp a pattern onto the diagram?\n",
null,
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
// if user presses no or closes the dialog, exit the program. else, add view stereotype to diagram
if((opt == JOptionPane.CANCEL_OPTION) || (opt == JOptionPane.CLOSED_OPTION)) {
throw new RuntimeException();
}
if((opt == JOptionPane.YES_OPTION)) {
try {
runLoadPattern();
} catch(RuntimeException e) {
e.printStackTrace();
throw new RuntimeException();
}
} else if((opt == JOptionPane.NO_OPTION)) {
try {
runStampPattern();
} catch(RuntimeException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
/**
* Runs the Pattern Loader with a progress bar.
*
* @throws RuntimeException if a problem with loading is encountered.
*/
private void runLoadPattern() throws RuntimeException {
final Project proj = Application.getInstance().getProject();
// get the presentation elements of the requester - there should only be one (the diagram)
Element requesterElem = requester.getElement();
// ensure the diagram is locked for edit
if(!StylerUtils.isDiagramLocked(proj, requester.getElement())) {
JOptionPane.showMessageDialog(null, "The target diagram is not locked for edit. Lock it before running this function.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
Diagram requesterDiagramElem = (Diagram) proj.getElementByID(requesterElem.getID());
final DiagramPresentationElement patternDiagram = getPatternDiagram();
DiagramPresentationElement targetDiagram = proj.getDiagram(requesterDiagramElem);
if((patternDiagram == null) || (targetDiagram == null)) {
throw new RuntimeException();
}
final List<PresentationElement> elemList = targetDiagram.getPresentationElements();
RunnableWithProgress runnable = null;
try {
runnable = new RunnableWithProgress() {
public void run(ProgressStatus progressStatus) {
progressStatus.init("Loading pattern...", 0, elemList.size());
// save the pattern in the pattern diagram
PatternSaver ps = new PatternSaver();
ps.savePattern(proj, patternDiagram);
// load the pattern in the active diagram
loadPattern(elemList, ps.getPattern(), progressStatus);
}
};
} catch(NoSuchMethodError ex) {
Application.getInstance().getGUILog().log("There was a problem starting the Pattern Loader. The Pattern Loader is now exiting.");
throw new RuntimeException();
}
BaseProgressMonitor.executeWithProgress(runnable, "Load Progress", false);
JOptionPane.showMessageDialog(null, "Pattern load complete.", "Info", JOptionPane.INFORMATION_MESSAGE);
}
/**
* Runs the Pattern Stamper.
*
* @throws RuntimeException if a problem with loading is encountered.
*/
private void runStampPattern() throws RuntimeException {
final Project proj = Application.getInstance().getProject();
// get the presentation elements of the requester - there should only be one (the diagram)
Element requesterElem = requester.getElement();
// ensure the diagram is locked for edit
if(!StylerUtils.isDiagramLocked(proj, requester.getElement())) {
JOptionPane.showMessageDialog(null, "The target diagram is not locked for edit. Lock it before running this function.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
final Diagram requesterDiagramElem = (Diagram) proj.getElementByID(requesterElem.getID());
final DiagramPresentationElement patternDiagram = getPatternDiagram();
final DiagramPresentationElement targetDiagram = proj.getDiagram(requesterDiagramElem);
if((patternDiagram == null) || (targetDiagram == null)) {
throw new RuntimeException();
}
// need to ensure that both diagrams are loaded before operating on them
patternDiagram.ensureLoaded();
targetDiagram.ensureLoaded();
final List<PresentationElement> patternElements = patternDiagram.getPresentationElements();
RunnableWithProgress runnable = null;
try {
runnable = new RunnableWithProgress() {
public void run(ProgressStatus progressStatus) {
progressStatus.init("Stamping pattern...", 0, 100);
CopyPasting.copyPasteElements(patternElements, targetDiagram.getObjectParent(), targetDiagram, true, false);
}
};
} catch(NoSuchMethodError ex) {
Application.getInstance().getGUILog().log("There was a problem starting the Pattern Stamper. The Pattern Stamper is now exiting.");
throw new RuntimeException();
}
BaseProgressMonitor.executeWithProgress(runnable, "Load Progress", false);
JOptionPane.showMessageDialog(null, "Pattern stamp complete.", "Info", JOptionPane.INFORMATION_MESSAGE);
}
/**
* Provides an input dialog for the user to pick a diagram to load a pattern from.
*
* @return the user-selected pattern diagram.
*/
private DiagramPresentationElement getPatternDiagram() {
// get all of the diagrams in the package for the user to pick from
Collection<DiagramPresentationElement> diagCollection = PatternLoaderUtils.getPatternDiagrams(requester);
Iterator<DiagramPresentationElement> diagIter = diagCollection.iterator();
int numNames = diagCollection.size();
String[] diagramNames = new String[numNames];
for(int i = 0; diagIter.hasNext(); i++) {
DiagramPresentationElement currDiag = diagIter.next();
diagramNames[i] = currDiag.getName() + " [" + currDiag.getHumanType() + "]";
}
// sort the diagram names for better UI
Arrays.sort(diagramNames, String.CASE_INSENSITIVE_ORDER);
String[] sortedNames = Arrays.copyOfRange(diagramNames, 0, diagramNames.length);
String userInput;
try {
userInput = (String) JOptionPane.showInputDialog(null,
"Choose a diagram to get a pattern from:",
null,
JOptionPane.DEFAULT_OPTION,
null,
sortedNames,
sortedNames[0]);
} catch(HeadlessException e) {
Application.getInstance().getGUILog().log("The Pattern Loader must be run in a graphical interface");
return null;
}
// user cancelled input - return safely
if(userInput == null) {
return null;
}
// find and return the pattern diagram
diagIter = diagCollection.iterator();
while(diagIter.hasNext()) {
DiagramPresentationElement currDiag = diagIter.next();
String currDiagDescriptor = currDiag.getName() + " [" + currDiag.getHumanType() + "]";
if(currDiagDescriptor.equals(userInput)) {
return currDiag;
}
}
Application.getInstance().getGUILog().log("There was a problem starting the Pattern Loader. The Pattern Loader is now exiting.");
return null;
}
/**
* Loads the style of elements on the diagram by gathering relevant style information from the JSONObject.
*
* @param elemList the list of elements to load styles into.
* @param pattern the pattern to load.
*/
public static void loadPattern(List<PresentationElement> elemList, JSONObject pattern, ProgressStatus progressStatus) {
for(PresentationElement elem : elemList) {
String elemStyle = (String) pattern.get(elem.getHumanType());
if(elemStyle == null) {
// there was no style pattern found for this element, load children and then continue
setStyleChildren(elem, pattern);
continue;
}
// load the style of the diagram element re-using the ViewLoader.setStyle() method
ViewLoader.setStyle(elem, elemStyle);
// then load the style of its children recursively
setStyleChildren(elem, pattern);
elem.getDiagramSurface().repaint();
if(progressStatus != null) {
progressStatus.increase();
}
}
}
/**
* Recursively loads style information of owned elements.
*
* @param parent the parent element to recurse on.
* @param style the central style string holding all style properties.
*/
private static void setStyleChildren(PresentationElement parent, JSONObject pattern) {
List<PresentationElement> children = parent.getPresentationElements();
// base case -- no children
if(children.isEmpty()) {
return;
}
// recursively load the style of the diagram element's children
loadPattern(children, pattern, null);
}
}
|
package info.faceland.strife.listeners;
import com.tealcube.minecraft.bukkit.facecore.ui.ActionBarMessage;
import com.tealcube.minecraft.bukkit.facecore.utilities.MessageUtils;
import com.tealcube.minecraft.bukkit.shade.apache.commons.lang3.math.NumberUtils;
import com.tealcube.minecraft.bukkit.shade.google.common.base.CharMatcher;
import info.faceland.beast.BeastData;
import info.faceland.strife.StrifePlugin;
import info.faceland.strife.attributes.StrifeAttribute;
import info.faceland.strife.data.Champion;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.Material;
import org.bukkit.SkullType;
import org.bukkit.Sound;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Skeleton;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.Map;
import java.util.Random;
public class CombatListener implements Listener {
private static final String[] DOGE_MEMES =
{"<aqua>wow", "<green>wow", "<light purple>wow", "<aqua>much pain", "<green>much pain",
"<light purple>much pain", "<aqua>many disrespects", "<green>many disrespects",
"<light purple>many disrespects", "<red>no u", "<red>2damage4me"};
private final StrifePlugin plugin;
private final Random random;
public CombatListener(StrifePlugin plugin) {
this.plugin = plugin;
random = new Random(System.currentTimeMillis());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityBurnEvent(EntityDamageEvent event) {
if (!(event.getEntity() instanceof LivingEntity)) {
return;
}
if (event.getCause() == EntityDamageEvent.DamageCause.ENTITY_ATTACK) {
return;
}
if (event.getCause() == EntityDamageEvent.DamageCause.FIRE) {
double hpdmg = ((LivingEntity) event.getEntity()).getHealth()/25;
event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0);
event.setDamage(EntityDamageEvent.DamageModifier.RESISTANCE, 0);
event.setDamage(1 + hpdmg);
} else if (event.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK) {
double hpdmg = ((LivingEntity) event.getEntity()).getHealth()/25;
event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0);
event.setDamage(EntityDamageEvent.DamageModifier.RESISTANCE, 0);
event.setDamage(1 + hpdmg);
} else if (event.getCause() == EntityDamageEvent.DamageCause.LAVA) {
double hpdmg = ((LivingEntity) event.getEntity()).getHealth()/20;
event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0);
event.setDamage(EntityDamageEvent.DamageModifier.RESISTANCE, 0);
event.setDamage(1 + hpdmg);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onProjectileLaunch(ProjectileLaunchEvent event) {
if (event.getEntity().getShooter() instanceof Entity) {
event.getEntity().setVelocity(event.getEntity().getVelocity().add(((Entity) event.getEntity()
.getShooter()).getVelocity()));
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDeath(EntityDeathEvent event) {
if (event.getEntity() == null || event.getEntity().getKiller() == null) {
return;
}
double chance = plugin.getChampionManager().getChampion(event.getEntity().getKiller().getUniqueId())
.getAttributeValues().get(StrifeAttribute.HEAD_DROP);
if (chance == 0) {
return;
}
if (random.nextDouble() < chance) {
LivingEntity e = event.getEntity();
if (e.getType() == EntityType.SKELETON) {
if (((Skeleton)e).getSkeletonType() == Skeleton.SkeletonType.NORMAL) {
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short)0);
e.getWorld().dropItemNaturally(e.getLocation(), skull);
}
}
else if ((e.getType() == EntityType.ZOMBIE)) {
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short)2);
e.getWorld().dropItemNaturally(e.getLocation(), skull);
}
else if ((e.getType() == EntityType.CREEPER)) {
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short)4);
e.getWorld().dropItemNaturally(e.getLocation(), skull);
}
else if ((e.getType() == EntityType.PLAYER)) {
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal());
SkullMeta skullMeta = (SkullMeta)skull.getItemMeta();
skullMeta.setOwner(event.getEntity().getName());
skull.setItemMeta(skullMeta);
e.getWorld().dropItemNaturally(e.getLocation(), skull);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.isCancelled()) {
return;
}
if (!(event.getEntity() instanceof LivingEntity)) {
return;
}
if (event.getEntity().hasMetadata("NPC")) {
return;
}
LivingEntity a;
boolean melee = true;
if (event.getDamager() instanceof LivingEntity) {
a = (LivingEntity) event.getDamager();
} else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager())
.getShooter() instanceof LivingEntity) {
a = (LivingEntity) ((Projectile) event.getDamager()).getShooter();
melee = false;
} else {
return;
}
LivingEntity b = (LivingEntity) event.getEntity();
boolean aPlayer = false;
boolean bPlayer = false;
if (a instanceof Player) {
aPlayer = true;
}
if (b instanceof Player) {
bPlayer = true;
}
if (a == null || b == null) {
return;
}
if (event.isApplicable(EntityDamageEvent.DamageModifier.ARMOR)) {
event.setDamage(EntityDamageEvent.DamageModifier.ARMOR, 0D);
}
if (event.isApplicable(EntityDamageEvent.DamageModifier.RESISTANCE)) {
event.setDamage(EntityDamageEvent.DamageModifier.RESISTANCE, 0D);
}
if (event.isApplicable(EntityDamageEvent.DamageModifier.BLOCKING)) {
event.setDamage(EntityDamageEvent.DamageModifier.BLOCKING, 0D);
}
if (event.isApplicable(EntityDamageEvent.DamageModifier.MAGIC)) {
event.setDamage(EntityDamageEvent.DamageModifier.MAGIC, 0D);
}
double healthB = b.getHealth();
double maxHealthB = b.getMaxHealth();
double potionMult = 1;
double poisonMult = 1;
double trueDamage = 0;
double pvpMult = plugin.getSettings().getDouble("config.pvp-multiplier", 0.5);
if (aPlayer) {
Player aP = (Player) a;
Champion champA = plugin.getChampionManager().getChampion(aP.getUniqueId());
Map<StrifeAttribute, Double> valsA = champA.getAttributeValues();
if (bPlayer) {
//////////////////////////////////////////////////////////////////// PLAYER V PLAYER COMBAT ///
Player bP = (Player) b;
Champion champB = plugin.getChampionManager().getChampion(bP.getUniqueId());
Map<StrifeAttribute, Double> valsB = champB.getAttributeValues();
double evadeChance = valsB.get(StrifeAttribute.EVASION);
if (evadeChance > 0) {
double accuracy;
accuracy = valsA.get(StrifeAttribute.ACCURACY);
evadeChance = Math.max(evadeChance * (1 - accuracy), 0);
evadeChance = 1 - (100 / (100 + (Math.pow((evadeChance * 100), 1.1))));
if (random.nextDouble() < evadeChance) {
if (event.getDamager() instanceof Arrow) {
event.getDamager().remove();
}
b.getWorld().playSound(b.getEyeLocation(), Sound.GHAST_FIREBALL, 0.5f, 2f);
event.setCancelled(true);
return;
}
}
double damage = 0;
double attackSpeedMultA = 1D;
double velocityMultA = 0D;
if (melee) {
double attackSpeedA = StrifeAttribute.ATTACK_SPEED.getBaseValue() *
(1 / (1 + valsA.get(StrifeAttribute.ATTACK_SPEED)));
long timeLeft = plugin.getAttackSpeedTask().getTimeLeft(a.getUniqueId());
long timeToSet = Math.round(Math.max(4.0 * attackSpeedA, 0.0));
if (timeLeft > 0) {
attackSpeedMultA = Math.max(1.0 - 1.0 * timeLeft / timeToSet, 0.0);
}
plugin.getAttackSpeedTask().setTimeLeft(a.getUniqueId(), timeToSet);
damage = valsA.get(StrifeAttribute.MELEE_DAMAGE) * attackSpeedMultA;
} else {
velocityMultA = Math.min(event.getDamager().getVelocity().lengthSquared() / Math.pow(3, 2), 1);
damage = valsA.get(StrifeAttribute.RANGED_DAMAGE) * velocityMultA;
}
if (bP.isBlocking()) {
if (random.nextDouble() < valsB.get(StrifeAttribute.ABSORB_CHANCE)) {
if (event.getDamager() instanceof Arrow) {
event.getDamager().remove();
}
b.setHealth(Math.min(healthB + (maxHealthB / 25), maxHealthB));
b.getWorld().playSound(a.getEyeLocation(), Sound.BLAZE_HIT, 1f, 2f);
event.setCancelled(true);
return;
}
if (melee) {
if (random.nextDouble() < valsB.get(StrifeAttribute.PARRY)) {
a.damage(damage * 0.2 * pvpMult);
b.getWorld().playSound(b.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f);
event.setCancelled(true);
return;
}
} else {
if (random.nextDouble() < 2 * valsB.get(StrifeAttribute.PARRY)) {
if (event.getDamager() instanceof Arrow) {
event.getDamager().remove();
}
b.getWorld().playSound(b.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f);
event.setCancelled(true);
return;
}
}
damage *= 1 - valsB.get(StrifeAttribute.BLOCK);
}
double critbonus = 0;
if (random.nextDouble() < valsA.get(StrifeAttribute.CRITICAL_RATE)) {
critbonus = damage * (valsA.get(StrifeAttribute.CRITICAL_DAMAGE) - 1.0);
b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f);
}
double overbonus = 0;
if (velocityMultA > 0) {
if (velocityMultA > 0.94D) {
overbonus = valsA.get(StrifeAttribute.OVERCHARGE) * damage;
}
} else {
if (attackSpeedMultA > 0.94D) {
overbonus = valsA.get(StrifeAttribute.OVERCHARGE) * damage;
}
}
damage = damage + critbonus + overbonus;
double fireDamage = valsA.get(StrifeAttribute.FIRE_DAMAGE);
if (fireDamage > 0) {
if (random.nextDouble() < ((valsA.get(StrifeAttribute.IGNITE_CHANCE) * (0.25 +
attackSpeedMultA * 0.75)) * (1 - valsB.get(StrifeAttribute.RESISTANCE)))) {
b.setFireTicks(20 + (int) Math.round(fireDamage * 20));
b.getWorld().playSound(b.getEyeLocation(), Sound.FIRE_IGNITE, 1f, 1f);
}
}
double lightningDamage = valsA.get(StrifeAttribute.LIGHTNING_DAMAGE);
if (lightningDamage > 0) {
if (random.nextDouble() < ((valsA.get(StrifeAttribute.SHOCK_CHANCE) * (0.25 +
attackSpeedMultA * 0.75)) * (1 - valsB.get(StrifeAttribute.RESISTANCE)))) {
trueDamage = lightningDamage;
b.getWorld().playSound(b.getEyeLocation(), Sound.AMBIENCE_THUNDER, 1f, 1.5f);
}
}
double iceDamage = valsA.get(StrifeAttribute.ICE_DAMAGE);
if (iceDamage > 0) {
if (random.nextDouble() < ((valsA.get(StrifeAttribute.FREEZE_CHANCE) * (0.25 +
attackSpeedMultA * 0.75)) * (1 - valsB.get(StrifeAttribute.RESISTANCE)))) {
damage = damage + iceDamage + iceDamage * (maxHealthB / 300);
b.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5 + (int) iceDamage * 3, 1));
b.getWorld().playSound(b.getEyeLocation(), Sound.GLASS, 1f, 1f);
}
}
if (b.hasPotionEffect(PotionEffectType.WITHER)) {
potionMult += 0.1D;
}
if (b.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) {
potionMult -= 0.1D;
}
if (melee) {
if (b.hasPotionEffect(PotionEffectType.WITHER)) {
potionMult += 0.1D;
}
if (b.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) {
potionMult -= 0.1D;
}
if (a.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) {
potionMult += 0.1D;
}
if (a.hasPotionEffect(PotionEffectType.WEAKNESS)) {
potionMult -= 0.1D;
}
} else {
double snareChance = valsA.get(StrifeAttribute.SNARE_CHANCE);
if (snareChance > 0) {
if (random.nextDouble() < snareChance) {
b.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 30, 5));
b.getWorld().playSound(b.getEyeLocation(), Sound.FIRE_IGNITE, 1f, 1f);
}
}
}
damage *= potionMult;
damage *= getArmorMult(valsB.get(StrifeAttribute.ARMOR), valsA.get(StrifeAttribute.ARMOR_PENETRATION));
damage += trueDamage;
damage *= pvpMult;
double lifeSteal = valsA.get(StrifeAttribute.LIFE_STEAL);
if (lifeSteal > 0) {
if (a.hasPotionEffect(PotionEffectType.POISON)) {
poisonMult = 0.34D;
}
double hungerMult = Math.min(((double) (((Player) a).getFoodLevel())) / 7.0D, 1.0D);
double lifeStolen = damage * lifeSteal * poisonMult * hungerMult;
if (a.getHealth() > 0) {
a.setHealth(Math.min(a.getHealth() + lifeStolen, a.getMaxHealth()));
}
}
event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage);
double chance = valsB.get(StrifeAttribute.DOGE);
if (random.nextDouble() < chance) {
MessageUtils.sendMessage(bP, DOGE_MEMES[random.nextInt(DOGE_MEMES.length)]);
}
String msg;
if (healthB > damage) {
msg = "&c&lHealth: &f" + (int) (healthB - damage) + "&7/&f" + (int) (maxHealthB);
} else {
msg = "&c&lHealth: &fDEAD &7/ &fKILLED";
}
ActionBarMessage.send((Player) a, msg);
} else {
///////////////////////////////////////////////////////////////////// PLAYER V MOB COMBAT ///
double damage = 0;
double attackSpeedMultA = 1D;
double velocityMultA = 0D;
if (melee) {
double attackSpeedA = StrifeAttribute.ATTACK_SPEED.getBaseValue() *
(1 / (1 + valsA.get(StrifeAttribute.ATTACK_SPEED)));
long timeLeft = plugin.getAttackSpeedTask().getTimeLeft(a.getUniqueId());
long timeToSet = Math.round(Math.max(4.0 * attackSpeedA, 0.0));
if (timeLeft > 0) {
attackSpeedMultA = Math.max(1.0 - 1.0 * timeLeft / timeToSet, 0.0);
}
plugin.getAttackSpeedTask().setTimeLeft(a.getUniqueId(), timeToSet);
damage = valsA.get(StrifeAttribute.MELEE_DAMAGE) * attackSpeedMultA;
} else {
velocityMultA = Math.min(event.getDamager().getVelocity().lengthSquared() / Math.pow(3, 2), 1);
damage = valsA.get(StrifeAttribute.RANGED_DAMAGE) * velocityMultA;
}
double critbonus = 0;
if (random.nextDouble() < valsA.get(StrifeAttribute.CRITICAL_RATE)) {
critbonus = damage * (valsA.get(StrifeAttribute.CRITICAL_DAMAGE) - 1.0);
b.getWorld().playSound(b.getEyeLocation(), Sound.FALL_BIG, 2f, 1f);
}
double overbonus = 0;
if (velocityMultA > 0) {
if (velocityMultA > 0.94D) {
overbonus = valsA.get(StrifeAttribute.OVERCHARGE) * damage;
}
} else {
if (attackSpeedMultA > 0.94D) {
overbonus = valsA.get(StrifeAttribute.OVERCHARGE) * damage;
}
}
damage = damage + critbonus + overbonus;
double fireDamage = valsA.get(StrifeAttribute.FIRE_DAMAGE);
if (fireDamage > 0) {
if (random.nextDouble() < (valsA.get(StrifeAttribute.IGNITE_CHANCE) * (0.25 + attackSpeedMultA * 0.75))) {
b.setFireTicks(20 + (int) Math.round(fireDamage * 20));
b.getWorld().playSound(b.getEyeLocation(), Sound.FIRE_IGNITE, 1f, 1f);
}
}
double lightningDamage = valsA.get(StrifeAttribute.LIGHTNING_DAMAGE);
if (lightningDamage > 0) {
if (random.nextDouble() < (valsA.get(StrifeAttribute.SHOCK_CHANCE) * (0.25 + attackSpeedMultA * 0.75))) {
trueDamage = lightningDamage;
b.getWorld().playSound(b.getEyeLocation(), Sound.AMBIENCE_THUNDER, 1f, 1.5f);
}
}
double iceDamage = valsA.get(StrifeAttribute.ICE_DAMAGE);
if (iceDamage > 0) {
if (random.nextDouble() < (valsA.get(StrifeAttribute.FREEZE_CHANCE) * (0.25 + attackSpeedMultA * 0.75))) {
damage = damage + iceDamage + iceDamage * (maxHealthB / 300);
b.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5 + (int) iceDamage * 3, 1));
b.getWorld().playSound(b.getEyeLocation(), Sound.GLASS, 1f, 1f);
}
}
if (b.hasPotionEffect(PotionEffectType.WITHER)) {
potionMult += 0.1D;
}
if (b.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) {
potionMult -= 0.1D;
}
if (melee) {
if (b.hasPotionEffect(PotionEffectType.WITHER)) {
potionMult += 0.1D;
}
if (b.hasPotionEffect(PotionEffectType.DAMAGE_RESISTANCE)) {
potionMult -= 0.1D;
}
if (a.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) {
potionMult += 0.1D;
}
if (a.hasPotionEffect(PotionEffectType.WEAKNESS)) {
potionMult -= 0.1D;
}
} else {
double snareChance = valsA.get(StrifeAttribute.SNARE_CHANCE);
if (snareChance > 0) {
if (random.nextDouble() < snareChance) {
b.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 30, 5));
b.getWorld().playSound(b.getEyeLocation(), Sound.FIRE_IGNITE, 1f, 1f);
}
}
}
damage *= potionMult;
damage += trueDamage;
double lifeSteal = valsA.get(StrifeAttribute.LIFE_STEAL);
if (lifeSteal > 0) {
if (a.hasPotionEffect(PotionEffectType.POISON)) {
poisonMult = 0.34D;
}
double hungerMult = Math.min(((double) (((Player) a).getFoodLevel())) / 7.0D, 1.0D);
double lifeStolen = damage * lifeSteal * poisonMult * hungerMult;
if (a.getHealth() > 0) {
a.setHealth(Math.min(a.getHealth() + lifeStolen, a.getMaxHealth()));
}
}
event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage);
String msg;
if (healthB > damage) {
msg = "&c&lHealth: &f" + (int) (healthB - damage) + "&7/&f" + (int) (maxHealthB);
} else {
msg = "&c&lHealth: &fDEAD &7/ &fKILLED";
}
ActionBarMessage.send((Player) a, msg);
}
} else {
if (bPlayer) {
/////////////////////////////////////////////////////////////////////////////// MOB V PLAYER COMBAT ///
Player pB = (Player) b;
Champion champB = plugin.getChampionManager().getChampion(pB.getUniqueId());
Map<StrifeAttribute, Double> valsB = champB.getAttributeValues();
double evadeChance = valsB.get(StrifeAttribute.EVASION);
if (evadeChance > 0) {
evadeChance = 1 - (100 / (100 + (Math.pow((evadeChance * 100), 1.2))));
if (random.nextDouble() < evadeChance) {
if (event.getDamager() instanceof Arrow) {
event.getDamager().remove();
}
b.getWorld().playSound(b.getEyeLocation(), Sound.GHAST_FIREBALL, 0.5f, 2f);
event.setCancelled(true);
return;
}
}
double damage = getDamageFromMeta(a, b, event.getCause());
if (damage == 0) {
damage = event.getDamage(EntityDamageEvent.DamageModifier.BASE);
}
if (pB.isBlocking()) {
if (random.nextDouble() < valsB.get(StrifeAttribute.ABSORB_CHANCE)) {
if (event.getDamager() instanceof Arrow) {
event.getDamager().remove();
}
b.setHealth(Math.min(healthB + (maxHealthB / 25), maxHealthB));
b.getWorld().playSound(a.getEyeLocation(), Sound.BLAZE_HIT, 1f, 2f);
event.setCancelled(true);
return;
}
if (melee) {
if (random.nextDouble() < valsB.get(StrifeAttribute.PARRY)) {
a.damage(damage * 0.2 * pvpMult);
b.getWorld().playSound(b.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f);
event.setCancelled(true);
return;
}
} else {
if (random.nextDouble() < 2 * valsB.get(StrifeAttribute.PARRY)) {
if (event.getDamager() instanceof Arrow) {
event.getDamager().remove();
}
b.getWorld().playSound(b.getEyeLocation(), Sound.ANVIL_LAND, 1f, 2f);
event.setCancelled(true);
return;
}
}
damage *= 1 - valsB.get(StrifeAttribute.BLOCK);
}
damage *= getArmorMult(valsB.get(StrifeAttribute.ARMOR), 0);
event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage);
double chance = valsB.get(StrifeAttribute.DOGE);
if (random.nextDouble() < chance) {
MessageUtils.sendMessage(b, DOGE_MEMES[random.nextInt(DOGE_MEMES.length)]);
}
} else {
/// MOB V MOB COMBAT ///
double damage = getDamageFromMeta(a, b, event.getCause());
if (damage == 0) {
damage = event.getDamage(EntityDamageEvent.DamageModifier.BASE);
}
event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage);
}
}
}
private double getDamageFromMeta (LivingEntity a, LivingEntity b, EntityDamageEvent.DamageCause d) {
double damage = 0;
if (a.hasMetadata("DAMAGE")) {
damage = a.getMetadata("DAMAGE").get(0).asDouble();
} else {
if (a.getType() != null) {
BeastData data = plugin.getBeastPlugin().getData(a.getType());
String name = a.getCustomName() != null ? ChatColor.stripColor(a.getCustomName()) : "0";
if (data != null && a.getCustomName() != null) {
int level = NumberUtils.toInt(CharMatcher.DIGIT.retainFrom(name));
damage = (data.getDamageExpression().setVariable("LEVEL", level).evaluate());
a.setMetadata("DAMAGE", new FixedMetadataValue(plugin, damage));
}
}
}
if (d == EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) {
damage = damage * Math.max(0.3, 2.5 / (a.getLocation().distanceSquared(b.getLocation()) + 1));
}
return damage;
}
private double getArmorMult (double armor, double apen) {
if (armor > 0) {
if (apen < 1) {
return 100 / (100 + (Math.pow(((armor * (1 - apen)) * 100), 1.25)));
} else {
return 1 + ((apen - 1) / 5);
}
} else {
return 1 + (apen / 5);
}
}
}
|
package info.faceland.strife.listeners;
import info.faceland.messaging.Chatty;
import info.faceland.strife.StrifePlugin;
import info.faceland.strife.attributes.AttributeHandler;
import info.faceland.strife.attributes.StrifeAttribute;
import info.faceland.strife.data.Champion;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import java.util.Map;
import java.util.Random;
public class CombatListener implements Listener {
private final StrifePlugin plugin;
private final Random random;
public CombatListener(StrifePlugin plugin) {
this.plugin = plugin;
random = new Random(System.currentTimeMillis());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onEntityDamageByEntityMonitor(EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Player) {
((Player) event.getDamager()).sendMessage("final damage: " + event.getFinalDamage());
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
LivingEntity a;
if (event.isCancelled() || !(event.getEntity() instanceof LivingEntity)) {
return;
}
// LET THE DATA GATHERING COMMENCE
boolean melee = true;
if (event.getDamager() instanceof LivingEntity) {
a = (LivingEntity) event.getDamager();
} else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity) {
a = (LivingEntity) ((Projectile) event.getDamager()).getShooter();
melee = false;
} else {
return;
}
LivingEntity b = (LivingEntity) event.getEntity();
if (b instanceof Player) {
double chance = plugin.getChampionManager().getChampion(b.getUniqueId()).getAttributeValues().get(StrifeAttribute.EVASION);
if (random.nextDouble() < chance) {
event.setCancelled(true);
Chatty.sendMessage((Player) b, "<green>You evaded an attack!");
if (a instanceof Player) {
Chatty.sendMessage((Player) a, "<white>%player%<red> evaded your attack!",
new String[][]{{"%player%", ((Player) a).getDisplayName()}});
}
return;
}
}
double damage = (a instanceof Player) ? 0 : event.getDamage(EntityDamageEvent.DamageModifier.BASE);
double meleeDamageA = StrifeAttribute.MELEE_DAMAGE.getBaseValue(), attackSpeedA;
double criticalDamageA = StrifeAttribute.CRITICAL_DAMAGE.getBaseValue(), armorPenA = StrifeAttribute.ARMOR_PENETRATION.getBaseValue();
double lifeStealA = StrifeAttribute.LIFE_STEAL.getBaseValue(), lifeStolenA = 0D, playerHealthA = b.getHealth();
double rangedDamageA = StrifeAttribute.RANGED_DAMAGE.getBaseValue(), criticalRateA = StrifeAttribute.CRITICAL_RATE.getBaseValue();
double attackSpeedMultA = 1D;
double armorB = StrifeAttribute.ARMOR.getBaseValue(), reflectDamageB = StrifeAttribute.DAMAGE_REFLECT.getBaseValue();
double parryB, blockB = StrifeAttribute.BLOCK.getBaseValue();
boolean blocking = false;
boolean parried = false;
if (a instanceof Player) {
for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) {
if (event.isApplicable(modifier)) {
event.setDamage(modifier, 0D);
}
}
Player p = (Player) a;
Champion champ = plugin.getChampionManager().getChampion(p.getUniqueId());
Map<StrifeAttribute, Double> vals = champ.getAttributeValues();
meleeDamageA = vals.get(StrifeAttribute.MELEE_DAMAGE);
attackSpeedA = (StrifeAttribute.ATTACK_SPEED.getBaseValue() * (1 / (1 + AttributeHandler.getValue(p, StrifeAttribute.ATTACK_SPEED))));
criticalDamageA = vals.get(StrifeAttribute.CRITICAL_DAMAGE);
armorPenA = vals.get(StrifeAttribute.ARMOR_PENETRATION);
lifeStealA = vals.get(StrifeAttribute.LIFE_STEAL);
playerHealthA = a.getHealth();
rangedDamageA = vals.get(StrifeAttribute.RANGED_DAMAGE);
criticalRateA = vals.get(StrifeAttribute.CRITICAL_RATE);
long timeLeft = plugin.getAttackSpeedTask().getTimeLeft(a.getUniqueId());
long timeToSet = Math.round(Math.max(4.0 * attackSpeedA, 0.0));
if (timeLeft > 0) {
attackSpeedMultA = Math.max(1.0 - 1.0 * timeLeft / timeToSet, 0.0);
}
plugin.getAttackSpeedTask().setTimeLeft(a.getUniqueId(), timeToSet);
((Player) a).sendMessage("meleeDamageA: " + meleeDamageA);
((Player) a).sendMessage("attackSpeedA: " + attackSpeedA);
((Player) a).sendMessage("attackSpeedMultA: " + attackSpeedMultA);
} else {
meleeDamageA = damage;
}
if (b instanceof Player) {
Player p = (Player) b;
Champion champ = plugin.getChampionManager().getChampion(p.getUniqueId());
Map<StrifeAttribute, Double> vals = champ.getAttributeValues();
armorB = vals.get(StrifeAttribute.ARMOR);
reflectDamageB = vals.get(StrifeAttribute.DAMAGE_REFLECT);
parryB = vals.get(StrifeAttribute.PARRY);
blockB = vals.get(StrifeAttribute.BLOCK);
if (((Player) b).isBlocking()) {
blocking = true;
if (random.nextDouble() < parryB) {
parried = true;
}
}
}
// LET THE DAMAGE CALCULATION COMMENCE
if (melee) {
if (blocking) {
if (parried) {
damage = meleeDamageA * attackSpeedMultA;
a.damage(damage * 0.25);
event.setCancelled(true);
return;
}
damage = meleeDamageA * attackSpeedMultA;
if (random.nextDouble() < criticalRateA) {
damage = damage * criticalDamageA;
}
double damageReducer = (1 - (armorB)) * (1 - (armorPenA));
damage = damage * damageReducer;
damage = damage * (1 - blockB);
lifeStolenA = damage * lifeStealA;
event.setDamage(damage);
a.setHealth(Math.min(playerHealthA + lifeStolenA, a.getMaxHealth()));
a.damage(damage * reflectDamageB);
return;
}
damage = meleeDamageA * attackSpeedMultA;
if (random.nextDouble() < criticalRateA) {
damage = damage * criticalDamageA;
}
double damageReducer = (1 - (armorB)) * (1 - (armorPenA));
damage = damage * damageReducer;
lifeStolenA = damage * lifeStealA;
event.setDamage(damage);
a.setHealth(Math.min(playerHealthA + lifeStolenA, a.getMaxHealth()));
a.damage(damage * reflectDamageB);
return;
}
if (blocking) {
if (parried) {
event.setDamage(0);
return;
}
damage = rangedDamageA * event.getDamager().getVelocity().length();
if (random.nextDouble() < criticalRateA) {
damage = damage * criticalDamageA;
}
double damageReducer = (1 - armorB) * (1 - armorPenA);
damage = damage * damageReducer;
damage = damage * (1 - blockB);
lifeStolenA = damage * lifeStealA;
event.setDamage(damage);
a.setHealth(Math.max(a.getHealth() + lifeStolenA, a.getMaxHealth()));
a.damage(damage * reflectDamageB);
return;
}
damage = rangedDamageA * event.getDamager().getVelocity().lengthSquared();
if (random.nextDouble() < criticalRateA) {
damage = damage * criticalDamageA;
}
double damageReducer = (1 - armorB) * (1 - armorPenA);
damage = damage * damageReducer;
lifeStolenA = damage * lifeStealA;
event.setDamage(damage);
a.setHealth(Math.max(a.getHealth() + lifeStolenA, a.getMaxHealth()));
a.damage(damage * reflectDamageB);
}
}
|
package com.db.autoupdater;
import java.net.URL;
import java.net.URLClassLoader;
import com.db.common.ConfigOptions;
import com.db.common.EventDelegate;
import com.db.common.EventObject;
import com.db.common.MethodInvoker;
import com.db.common.logging.Logger;
import com.db.common.logging.LoggerManager;
/**
* An application automatic updater. Retrieves an update script from a
* UpdateScriptSource and processes it to update an application.
*
* @author Dave Longley
*/
public abstract class AutoUpdater
{
/**
* Set to true when this AutoUpdater requires a reload, false otherwise.
*/
protected boolean mRequiresReload;
/**
* True while processing an update, false otherwise.
*/
protected boolean mProcessingUpdate;
/**
* True when this AutoUpdater should automatically check for updates, false
* when it should not.
*/
protected boolean mAutoCheckForUpdate;
/**
* The number of milliseconds to sleep in between automatic update checks.
*/
protected long mAutoCheckForUpdateInterval;
/**
* An event delegate for check for update started events.
*/
protected EventDelegate mCheckForUpdateStartedEventDelegate;
/**
* An event delegate for update script found events.
*/
protected EventDelegate mUpdateScriptFoundEventDelegate;
/**
* An event delegate for update script processed events.
*/
protected EventDelegate mUpdateScriptProcessedEventDelegate;
/**
* An event delegate for update script not found events.
*/
protected EventDelegate mUpdateScriptNotFoundEventDelegate;
/**
* An event delegate for execute application events.
*/
protected EventDelegate mExecuteApplicationEventDelegate;
/**
* An event delegate for shutdown application events.
*/
protected EventDelegate mShutdownApplicationEventDelegate;
/**
* An event delegate for application shutdown events.
*/
protected EventDelegate mApplicationShutdownEventDelegate;
/**
* Creates a new AutoUpdater.
*/
public AutoUpdater()
{
// no reload required by default
setRequiresReload(false);
// not processing an update by default
setProcessingUpdate(false);
// do not auto check for updates by default
setAutoCheckForUpdate(false);
// default the auto check interval to 30 seconds
setAutoCheckForUpdateInterval(30000);
// create check for update started event delegate
mCheckForUpdateStartedEventDelegate = new EventDelegate();
// create update script found event delegate
mUpdateScriptFoundEventDelegate = new EventDelegate();
// create update script found event delegate
mUpdateScriptProcessedEventDelegate = new EventDelegate();
// create update script not found event delegate
mUpdateScriptNotFoundEventDelegate = new EventDelegate();
// create execute application event delegate
mExecuteApplicationEventDelegate = new EventDelegate();
// create shutdown application event delegate
mShutdownApplicationEventDelegate = new EventDelegate();
// create application shutdown delegate
mApplicationShutdownEventDelegate = new EventDelegate();
}
/**
* Fires a check for update started event.
*
* @param event the event to fire.
*/
protected void fireCheckForUpdateStartedEvent(EventObject event)
{
mCheckForUpdateStartedEventDelegate.fireEvent(event);
}
/**
* Fires an update script found event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptFoundEvent(EventObject event)
{
mUpdateScriptFoundEventDelegate.fireEvent(event);
}
/**
* Fires an update script processed event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptProcessedEvent(EventObject event)
{
mUpdateScriptProcessedEventDelegate.fireEvent(event);
}
/**
* Fires an update script not found event.
*
* @param event the event to fire.
*/
protected void fireUpdateScriptNotFoundEvent(EventObject event)
{
mUpdateScriptNotFoundEventDelegate.fireEvent(event);
}
/**
* Fires an execute application event.
*
* @param event the event to fire.
*/
protected void fireExecuteApplicationEvent(EventObject event)
{
mExecuteApplicationEventDelegate.fireEvent(event);
}
/**
* Fires a shutdown application event.
*
* @param event the event to fire.
*/
protected void fireShutdownApplicationEvent(EventObject event)
{
mShutdownApplicationEventDelegate.fireEvent(event);
}
/**
* Fires an application shutdown event.
*
* @param event the event to fire.
*/
protected void fireApplicationShutdownEvent(EventObject event)
{
mApplicationShutdownEventDelegate.fireEvent(event);
}
/**
* Sets whether or not this AutoUpdater requires a reload.
*
* @param reload true if this AutoUpdater requires a reload, false if not.
*/
protected synchronized void setRequiresReload(boolean reload)
{
mRequiresReload = reload;
}
/**
* Sets whether or not this AutoUpdater is processing an update.
*
* @param processing true if this AutoUpdater is processing an update,
* false if not.
*/
protected synchronized void setProcessingUpdate(boolean processing)
{
mProcessingUpdate = processing;
}
/**
* Sets whether or not this AutoUpdater should automatically check
* for updates.
*
* @param check true if this AutoUpdater should automatically check for
* updates, false if not.
*/
protected void setAutoCheckForUpdate(boolean check)
{
mAutoCheckForUpdate = check;
}
/**
* Gets whether or not this AutoUpdater should automatically check
* for updates.
*
* @return true if this AutoUpdater should automatically check for
* updates, false if not.
*/
protected boolean shouldAutoCheckForUpdate()
{
return mAutoCheckForUpdate;
}
/**
* Checks for an update for the given application.
*
* @param application the application to check for updates of.
*
* @return true if an update was processed, false if not.
*/
protected synchronized boolean checkForUpdate(AutoUpdateable application)
{
boolean rval = false;
// fire a check for update started event
EventObject event = new EventObject("checkForUpdateStarted");
fireCheckForUpdateStartedEvent(event);
// get the update script source
UpdateScriptSource source = getUpdateScriptSource();
// check for an update script
if(source.hasUpdateScript(application))
{
// get the update script
UpdateScript script = source.getUpdateScript(application);
// validate the script
if(script.validate())
{
// fire event indicating that an update script has been found
event = new EventObject("updateScriptFound");
event.setData("updateScript", script);
event.setData("processUpdate", false);
fireUpdateScriptFoundEvent(event);
// see if the update should be processed
if(event.getDataBooleanValue("processUpdate"))
{
// process update script
rval = true;
processUpdateScript(application, script);
}
}
else
{
// fire event indicating that an update script has not been found
event = new EventObject("updateScriptNotFound");
fireUpdateScriptNotFoundEvent(event);
}
}
else
{
// fire event indicating that an update script has not been found
event = new EventObject("updateScriptNotFound");
fireUpdateScriptNotFoundEvent(event);
}
return rval;
}
/**
* Shutsdown any running application and processes an update script.
*
* @param application the application that is running.
* @param script the update script to process.
*
* @return true if an update was successfully processed without failure
* or cancellation, false if not.
*/
protected synchronized boolean processUpdateScript(
AutoUpdateable application, UpdateScript script)
{
boolean rval = false;
// ensure this thread is not interrupted
if(!Thread.interrupted())
{
// now processing an update
setProcessingUpdate(true);
// fire event indicating the auto-updateable application is
// getting shutdown
EventObject event = new EventObject("shutdownApplication");
event.setData("cancel", false);
fireShutdownApplicationEvent(event);
// make sure shutdown was not cancelled
if(!event.getDataBooleanValue("cancel"))
{
// shutdown the application
application.shutdown();
// fire event indicating the auto-updateable application has been
// shutdown
event = new EventObject("applicationShutdown");
fireApplicationShutdownEvent(event);
// process the script
if(script.process())
{
// script processing was successful
rval = true;
}
else
{
// script processing was cancelled or there was an error
// attempt to revert script
script.revert();
}
// set whether or not this AutoUpdater requires a reload
setRequiresReload(script.autoUpdaterRequiresReload());
// no longer processing an update
setProcessingUpdate(false);
// fire event indicating an update script was processed
event = new EventObject("updateScriptProcessed");
event.setData("updateScript", script);
fireUpdateScriptProcessedEvent(event);
}
}
return rval;
}
/**
* This method is provided for convenience. It can be overloaded to
* pause the current thread for some period of time. Another way to
* pause between update checks is to handle the checkForUpdateStarted
* event by pausing.
*
* Causes the update checker thread to pause for some period of time
* before checking for an update. The default period of time is
* 30 seconds.
*
* Throws an InterruptedException if the thread is interrupted while
* sleeping.
*
* @exception InterruptedException
*/
public void pauseUpdateCheckerThread() throws InterruptedException
{
if(getAutoCheckForUpdateInterval() > 0)
{
Thread.sleep(getAutoCheckForUpdateInterval());
}
}
/**
* Continuously checks for an update for the given application.
*
* @param application the application to check for updates of.
*/
public void continuouslyCheckForUpdate(AutoUpdateable application)
{
try
{
while(shouldAutoCheckForUpdate())
{
// pause this thread
pauseUpdateCheckerThread();
// check for an update for the application
if(shouldAutoCheckForUpdate() && !Thread.interrupted())
{
// check for an update if the auto check interval is positive
if(getAutoCheckForUpdateInterval() > 0)
{
checkForUpdate(application);
}
}
}
}
catch(InterruptedException e)
{
// interrupt thread
Thread.currentThread().interrupt();
}
}
/**
* Loads an AutoUpdateable application from the passed configuration.
*
* @param config the configuration to load an AutoUpdateable application
* from.
*
* @return the AutoUpdateable application or null if one could not be loaded.
*/
public AutoUpdateable loadAutoUpdateable(ConfigOptions config)
{
AutoUpdateable rval = null;
try
{
// get the jars necessary to load the AutoUpdateable interface
String classPath = config.getString("autoupdateable-classpath");
String[] split = classPath.split(",");
URL[] urls = new URL[split.length];
for(int i = 0; i < urls.length; i++)
{
urls[i] = new URL(split[i]);
}
// create a class loader for the AutoUpdateable
ClassLoader classLoader = new URLClassLoader(urls);
// load the AutoUpdateable
Class c = classLoader.loadClass(
config.getString("autoupdateable-class"));
rval = (AutoUpdateable)c.newInstance();
}
catch(Throwable t)
{
getLogger().error(Logger.getStackTrace(t));
}
return rval;
}
/**
* Runs an application while monitoring for updates in a background process.
*
* This method returns true if the application has finished executing and
* should be run again once updates have been installed, and false if
* the application has finished executing and should not be run again, even
* after updates have been installed.
*
* @param application the auto-updateable application to execute.
*/
public void run(AutoUpdateable application)
{
// check for an update, start the application if there isn't one
if(!checkForUpdate(application))
{
// set automatic check flag to true
setAutoCheckForUpdate(true);
// start the update checker thread
Object[] params = new Object[]{application};
MethodInvoker updateChecker =
new MethodInvoker(this, "continuouslyCheckForUpdate", params);
updateChecker.backgroundExecute();
// fire event indicating that the auto-updateable application
// is being executed
EventObject event = new EventObject("executeApplication");
event.setData("cancel", false);
fireExecuteApplicationEvent(event);
// see if application execution should be cancelled
if(!event.getDataBooleanValue("cancel"))
{
// execute application
application.execute();
}
try
{
// sleep while the application is running
while(application.isRunning())
{
Thread.sleep(1);
}
// interrupt update checker thread if not processing an update
if(!isProcessingUpdate())
{
updateChecker.interrupt();
}
// join the update checker thread
updateChecker.join();
}
catch(InterruptedException e)
{
// interrupt threads
updateChecker.interrupt();
Thread.currentThread().interrupt();
}
// set automatic check flag to false
setAutoCheckForUpdate(false);
}
}
/**
* Gets the check for update started event delegate.
*
* @return the check for update started event delegate.
*/
public EventDelegate getCheckForUpdateStartedEventDelegate()
{
return mCheckForUpdateStartedEventDelegate;
}
/**
* Gets the update script found event delegate.
*
* @return the update script found event delegate.
*/
public EventDelegate getUpdateScriptFoundEventDelegate()
{
return mUpdateScriptFoundEventDelegate;
}
/**
* Gets the update script processed event delegate.
*
* @return the update script processed event delegate.
*/
public EventDelegate getUpdateScriptProcessedEventDelegate()
{
return mUpdateScriptProcessedEventDelegate;
}
/**
* Gets the update script not found event delegate.
*
* @return the update script not found event delegate.
*/
public EventDelegate getUpdateScriptNotFoundEventDelegate()
{
return mUpdateScriptNotFoundEventDelegate;
}
/**
* Gets the execute application event delegate.
*
* @return the execute application event delegate.
*/
public EventDelegate getExecuteApplicationEventDelegate()
{
return mExecuteApplicationEventDelegate;
}
/**
* Gets the shutdown application event delegate.
*
* @return the shutdown application event delegate.
*/
public EventDelegate getShutdownApplicationEventDelegate()
{
return mShutdownApplicationEventDelegate;
}
/**
* Gets the application shutdown event delegate.
*
* @return the application shutdown event delegate.
*/
public EventDelegate getApplicationShutdownEventDelegate()
{
return mApplicationShutdownEventDelegate;
}
/**
* Gets whether or not this AutoUpdater requires a reload.
*
* @return true if this AutoUpdater requires a reload, false if not.
*/
public synchronized boolean requiresReload()
{
return mRequiresReload;
}
/**
* Gets whether or not this AutoUpdater is processing an update.
*
* @return true if this AutoUpdater is processing an update, false if not.
*/
public synchronized boolean isProcessingUpdate()
{
return mProcessingUpdate;
}
/**
* Sets the number of milliseconds to wait in between automatic update
* checks.
*
* A non-positive return value indicates that no automatic update checks
* will be made.
*
* @param interval the number of milliseconds to wait in between automatic
* update checks.
*/
public void setAutoCheckForUpdateInterval(long interval)
{
mAutoCheckForUpdateInterval = interval;
}
/**
* Sets the number of milliseconds to wait in between automatic update
* checks.
*
* A non-positive return value indicates that no automatic update checks
* will be made.
*
* @return the number of milliseconds to wait in between automatic
* update checks.
*/
public long getAutoCheckForUpdateInterval()
{
return mAutoCheckForUpdateInterval;
}
/**
* Gets the UpdateScriptSource for this AutoUpdater.
*
* @return the UpdateScriptSource for this AutoUpdater.
*/
public abstract UpdateScriptSource getUpdateScriptSource();
/**
* Gets the logger for this AutoUpdater.
*
* @return the logger for this AutoUpdater.
*/
public Logger getLogger()
{
return LoggerManager.getLogger("dbautoupdater");
}
}
|
package com.cradle.iitc_mobile.share;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import com.cradle.iitc_mobile.Log;
import com.cradle.iitc_mobile.R;
import java.io.File;
import java.util.ArrayList;
public class ShareActivity extends FragmentActivity implements ActionBar.TabListener {
private static final String EXTRA_TYPE = "share-type";
private static final int REQUEST_START_INTENT = 1;
private static final String TYPE_FILE = "file";
private static final String TYPE_PERMALINK = "permalink";
private static final String TYPE_PORTAL_LINK = "portal_link";
private static final String TYPE_STRING = "string";
public static Intent forFile(final Context context, final File file, final String type) {
return new Intent(context, ShareActivity.class)
.putExtra(EXTRA_TYPE, TYPE_FILE)
.putExtra("uri", Uri.fromFile(file))
.putExtra("type", type);
}
public static Intent forPosition(final Context context, final double lat, final double lng, final int zoom,
final String title, final boolean isPortal) {
return new Intent(context, ShareActivity.class)
.putExtra(EXTRA_TYPE, isPortal ? TYPE_PORTAL_LINK : TYPE_PERMALINK)
.putExtra("lat", lat)
.putExtra("lng", lng)
.putExtra("zoom", zoom)
.putExtra("title", title)
.putExtra("isPortal", isPortal);
}
public static Intent forString(final Context context, final String str) {
return new Intent(context, ShareActivity.class)
.putExtra(EXTRA_TYPE, TYPE_STRING)
.putExtra("shareString", str);
}
private IntentComparator mComparator;
private FragmentAdapter mFragmentAdapter;
private IntentGenerator mGenerator;
private SharedPreferences mSharedPrefs = null;
private ViewPager mViewPager;
private void addTab(final ArrayList<Intent> intents, final int label, final int icon) {
final IntentListFragment fragment = new IntentListFragment();
final Bundle args = new Bundle();
args.putParcelableArrayList("intents", intents);
args.putString("title", getString(label));
args.putInt("icon", icon);
fragment.setArguments(args);
mFragmentAdapter.add(fragment);
}
private String getIntelUrl(final String ll, final int zoom, final boolean isPortal) {
final String scheme = mSharedPrefs.getBoolean("pref_force_https", true) ? "https" : "http";
String url = scheme + ":
if (isPortal) {
url += "&pll=" + ll;
}
return url;
}
private void setSelected(final int position) {
// Activity not fully loaded yet (may occur during tab creation)
if (mSharedPrefs == null) return;
mSharedPrefs
.edit()
.putInt("pref_share_selected_tab", position)
.apply();
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (REQUEST_START_INTENT == requestCode) {
setResult(resultCode, data);
// parent activity can now clean up
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
mComparator = new IntentComparator(this);
mGenerator = new IntentGenerator(this);
mFragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
final Intent intent = getIntent();
final String type = intent.getStringExtra(EXTRA_TYPE);
// from portallinks/permalinks we build 3 intents (share / geo / vanilla-intel-link)
if (TYPE_PERMALINK.equals(type) || TYPE_PORTAL_LINK.equals(type)) {
final String title = intent.getStringExtra("title");
final String ll = intent.getDoubleExtra("lat", 0) + "," + intent.getDoubleExtra("lng", 0);
final int zoom = intent.getIntExtra("zoom", 0);
final String url = getIntelUrl(ll, zoom, TYPE_PORTAL_LINK.equals(type));
actionBar.setTitle(title);
addTab(mGenerator.getShareIntents(title, url),
R.string.tab_share,
R.drawable.ic_action_share);
addTab(mGenerator.getGeoIntents(title, ll, zoom),
R.string.tab_map,
R.drawable.ic_action_place);
addTab(mGenerator.getBrowserIntents(title, url),
R.string.tab_browser,
R.drawable.ic_action_web_site);
} else if (TYPE_STRING.equals(type)) {
final String title = getString(R.string.app_name);
final String shareString = intent.getStringExtra("shareString");
addTab(mGenerator.getShareIntents(title, shareString), R.string.tab_share, R.drawable.ic_action_share);
} else if (TYPE_FILE.equals(type)) {
final Uri uri = intent.getParcelableExtra("uri");
final String mime = intent.getStringExtra("type");
addTab(mGenerator.getShareIntents(uri, mime), R.string.tab_share, R.drawable.ic_action_share);
} else {
Log.w("Unknown sharing type: " + type);
setResult(RESULT_CANCELED);
finish();
return;
}
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mFragmentAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(final int position) {
if (actionBar.getNavigationMode() != ActionBar.NAVIGATION_MODE_STANDARD) {
actionBar.setSelectedNavigationItem(position);
}
setSelected(position);
}
});
for (int i = 0; i < mFragmentAdapter.getCount(); i++) {
final IntentListFragment fragment = (IntentListFragment) mFragmentAdapter.getItem(i);
actionBar.addTab(actionBar
.newTab()
.setText(fragment.getTitle())
.setIcon(fragment.getIcon())
.setTabListener(this));
}
// read the selected tab from prefs before enabling tab mode
// setNavigationMode calls our OnPageChangeListener, resetting the pref to 0
final int selected = mSharedPrefs.getInt("pref_share_selected_tab", 0);
if (mFragmentAdapter.getCount() > 1) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
if (selected < mFragmentAdapter.getCount()) {
mViewPager.setCurrentItem(selected);
if (actionBar.getNavigationMode() != ActionBar.NAVIGATION_MODE_STANDARD) {
actionBar.setSelectedNavigationItem(selected);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mComparator.save();
}
public IntentComparator getIntentComparator() {
return mComparator;
}
public void launch(final Intent intent) {
mComparator.trackIntentSelection(intent);
mGenerator.cleanup(intent);
// we should wait for the new intent to be finished so the calling activity (IITC_Mobile) can clean up
startActivityForResult(intent, REQUEST_START_INTENT);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabReselected(final ActionBar.Tab tab, final FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabSelected(final ActionBar.Tab tab, final FragmentTransaction fragmentTransaction) {
final int position = tab.getPosition();
mViewPager.setCurrentItem(position);
setSelected(position);
}
@Override
public void onTabUnselected(final ActionBar.Tab tab, final FragmentTransaction fragmentTransaction) {
}
}
|
package info.faceland.strife.listeners;
import info.faceland.strife.StrifePlugin;
import info.faceland.strife.attributes.AttributeHandler;
import info.faceland.strife.attributes.StrifeAttribute;
import info.faceland.strife.data.Champion;
import info.faceland.strife.stats.StrifeStat;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerItemBreakEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
public class HealthListener implements Listener {
private final StrifePlugin plugin;
public HealthListener(StrifePlugin plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryClose(InventoryCloseEvent event) {
for (HumanEntity entity : event.getViewers()) {
if (entity instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
if (event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
if (event.getInventory().getHolder() instanceof Player) {
Player player = (Player) event.getInventory().getHolder();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryOpen(InventoryOpenEvent event) {
for (HumanEntity entity : event.getViewers()) {
if (entity instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
if (event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
if (event.getInventory().getHolder() instanceof Player) {
Player player = (Player) event.getInventory().getHolder();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerRespawn(final PlayerRespawnEvent event) {
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}, 20L);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDropItem(PlayerDropItemEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerItemBreak(PlayerItemBreakEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerItemHeld(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
Map<StrifeAttribute, Double> attributeDoubleMap = new HashMap<>();
for (StrifeAttribute attr : StrifeAttribute.values()) {
attributeDoubleMap.put(attr, attr.getBaseValue());
}
for (Map.Entry<StrifeStat, Integer> entry : champion.getLevelMap().entrySet()) {
for (StrifeAttribute attr : StrifeAttribute.values()) {
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
attributeDoubleMap.put(attr, val + entry.getKey().getAttribute(attr) * entry.getValue());
}
}
for (ItemStack itemStack : champion.getPlayer().getEquipment().getArmorContents()) {
if (itemStack == null || itemStack.getType() == Material.AIR) {
continue;
}
for (StrifeAttribute attr : StrifeAttribute.values()) {
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
attributeDoubleMap.put(attr, val + AttributeHandler.getValue(itemStack, attr));
}
}
if (champion.getPlayer().getInventory().getItem(event.getNewSlot()) != null
&& champion.getPlayer().getInventory().getItem(event.getNewSlot()).getType() != Material.AIR) {
ItemStack itemStack = champion.getPlayer().getInventory().getItem(event.getNewSlot());
for (StrifeAttribute attr : StrifeAttribute.values()) {
if (attr == StrifeAttribute.ARMOR || attr == StrifeAttribute.DAMAGE_REFLECT || attr == StrifeAttribute.EVASION
|| attr == StrifeAttribute.HEALTH || attr == StrifeAttribute.REGENERATION) {
continue;
}
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
attributeDoubleMap.put(attr, val + AttributeHandler.getValue(itemStack, attr));
}
}
AttributeHandler.updateHealth(player, attributeDoubleMap);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
if (!(event.getEntity() instanceof Player) || !(event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN || event
.getRegainReason() ==
EntityRegainHealthEvent.RegainReason.SATIATED) ||
event.isCancelled()) {
return;
}
Player player = (Player) event.getEntity();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
double amount = champion.getAttributeValues().get(StrifeAttribute.REGENERATION);
event.setAmount(amount);
}
}
|
package com.sean.golfranger;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.sean.golfranger.data.Contract;
import com.sean.golfranger.utils.AnimateUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Set;
/**
* Match Adapter For Matches Activity Layout. Will be fed Data from Rounds Table
*/
class MatchAdapter extends RecyclerView.Adapter<MatchAdapter.MatchAdapterViewHolder>{
private Cursor mCursor;
private Context mContext;
private Boolean doAnimation;
private Set<String> mNewIds = null;
MatchAdapter(Context context,Boolean animationBoolean) {
this.mContext = context;
this.doAnimation = animationBoolean;
}
@Override
public MatchAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.match_list_item, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
return new MatchAdapterViewHolder(view);
}
@Override
public int getItemCount() {
if ( null == mCursor ) return 0;
return mCursor.getCount();
}
class MatchAdapterViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener{
TextView p1First, p2First, p3First, p4First, courseName, clubName, date;
MatchAdapterViewHolder(View view) {
super(view);
this.p1First = (TextView) view.findViewById(R.id.p1First);
this.p2First = (TextView) view.findViewById(R.id.p2First);
this.p3First = (TextView) view.findViewById(R.id.p3First);
this.p4First = (TextView) view.findViewById(R.id.p4First);
this.courseName = (TextView) view.findViewById(R.id.courseName);
this.clubName = (TextView) view.findViewById(R.id.clubName);
this.date = (TextView) view.findViewById(R.id.roundDate);
view.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int adapterPosition = getAdapterPosition();
mCursor.moveToPosition(adapterPosition);
long roundId = mCursor.getLong(Contract.MatchesView.ROUNDID_COL_INDEX);
Intent intent = new Intent(mContext, StartRoundActivity.class);
intent.putExtra(StartRoundActivity.EXTRA_ROUND_ID, String.valueOf(roundId));
mContext.startActivity(intent);
}
}
@Override
public void onBindViewHolder(MatchAdapterViewHolder customViewHolder, int i) {
mCursor.moveToPosition(i);
customViewHolder.p1First.setText(
mCursor.getString(Contract.MatchesView.P1_FIRST_COL_INDEX
));
customViewHolder.p2First.setText(
mCursor.getString(Contract.MatchesView.P2_FIRST_COL_INDEX
));
customViewHolder.p3First.setText(
mCursor.getString(Contract.MatchesView.P3_FIRST_COL_INDEX
));
customViewHolder.p4First.setText(
mCursor.getString(Contract.MatchesView.P4_FIRST_COL_INDEX
));
customViewHolder.clubName.setText(
mCursor.getString(Contract.MatchesView.CLUBNAME_COL_INDEX
));
customViewHolder.courseName.setText(
mCursor.getString(Contract.MatchesView.COURSENAME_COL_INDEX
));
customViewHolder.date.setText(
getReadableDate(
mCursor.getLong(Contract.MatchesView.START_DATE
)));
AnimateUtils.runEnterAnimation(mContext, customViewHolder.itemView, doAnimation,
AnimateUtils.MATCH_TYPE, i, mCursor.getString(Contract.MatchesView.ROUNDID_COL_INDEX), mNewIds);
doAnimation = doAnimation && mCursor.getCount() != i + 1;
}
void swapCursor(Cursor newCursor) {
mNewIds = AnimateUtils.newIdsFromCursor(mContext, newCursor);
mCursor = newCursor;
notifyDataSetChanged();
}
@Override
public long getItemId(int position) {
if (mCursor.moveToPosition(position)) {
return mCursor.getLong(Contract.MatchesView.ROUNDID_COL_INDEX);
} else {
return -1;
}
}
public Cursor getCursor() {
return mCursor;
}
private String getReadableDate(long unixtime) {
SimpleDateFormat formatter =
new SimpleDateFormat(mContext.getString(R.string.dateFormat), Locale.getDefault());
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(unixtime);
return formatter.format(calendar.getTime());
}
}
|
package info.faceland.strife.listeners;
import info.faceland.strife.StrifePlugin;
import info.faceland.strife.attributes.AttributeHandler;
import info.faceland.strife.attributes.StrifeAttribute;
import info.faceland.strife.data.Champion;
import info.faceland.strife.stats.StrifeStat;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerItemBreakEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
public class HealthListener implements Listener {
private final StrifePlugin plugin;
public HealthListener(StrifePlugin plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryClose(InventoryCloseEvent event) {
for (HumanEntity entity : event.getViewers()) {
if (entity instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
if (event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
if (event.getInventory().getHolder() instanceof Player) {
Player player = (Player) event.getInventory().getHolder();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryOpen(InventoryOpenEvent event) {
for (HumanEntity entity : event.getViewers()) {
if (entity instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
if (event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
if (event.getInventory().getHolder() instanceof Player) {
Player player = (Player) event.getInventory().getHolder();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDropItem(PlayerDropItemEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerItemBreak(PlayerItemBreakEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerItemHeld(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
Map<StrifeAttribute, Double> attributeDoubleMap = new HashMap<>();
for (StrifeAttribute attr : StrifeAttribute.values()) {
attributeDoubleMap.put(attr, attr.getBaseValue());
}
for (Map.Entry<StrifeStat, Integer> entry : champion.getLevelMap().entrySet()) {
for (StrifeAttribute attr : StrifeAttribute.values()) {
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
attributeDoubleMap.put(attr, val + entry.getKey().getAttribute(attr) * entry.getValue());
}
}
for (ItemStack itemStack : champion.getPlayer().getEquipment().getArmorContents()) {
if (itemStack == null || itemStack.getType() == Material.AIR) {
continue;
}
for (StrifeAttribute attr : StrifeAttribute.values()) {
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
attributeDoubleMap.put(attr, val + AttributeHandler.getValue(itemStack, attr));
}
}
if (champion.getPlayer().getInventory().getItem(event.getNewSlot()) != null
&& champion.getPlayer().getInventory().getItem(event.getNewSlot()).getType() != Material.AIR) {
ItemStack itemStack = champion.getPlayer().getInventory().getItem(event.getNewSlot());
for (StrifeAttribute attr : StrifeAttribute.values()) {
if (attr == StrifeAttribute.ARMOR || attr == StrifeAttribute.DAMAGE_REFLECT || attr == StrifeAttribute.EVASION
|| attr == StrifeAttribute.HEALTH || attr == StrifeAttribute.REGENERATION) {
continue;
}
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
attributeDoubleMap.put(attr, val + AttributeHandler.getValue(itemStack, attr));
}
}
AttributeHandler.updateHealth(player, attributeDoubleMap);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
if (!(event.getEntity() instanceof Player) || !(event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN || event
.getRegainReason() ==
EntityRegainHealthEvent.RegainReason.SATIATED) ||
event.isCancelled()) {
return;
}
Player player = (Player) event.getEntity();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
double amount = champion.getAttributeValues().get(StrifeAttribute.REGENERATION);
event.setAmount(amount);
}
}
|
package info.faceland.strife.listeners;
import info.faceland.strife.StrifePlugin;
import info.faceland.strife.attributes.AttributeHandler;
import info.faceland.strife.attributes.StrifeAttribute;
import info.faceland.strife.data.Champion;
import info.faceland.strife.stats.StrifeStat;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerItemBreakEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
public class HealthListener implements Listener {
private final StrifePlugin plugin;
public HealthListener(StrifePlugin plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryClose(InventoryCloseEvent event) {
for (HumanEntity entity : event.getViewers()) {
if (entity instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
if (event.getPlayer() instanceof Player && event.getPlayer().getHealth() > 0) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryOpen(InventoryOpenEvent event) {
for (HumanEntity entity : event.getViewers()) {
if (entity instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
if (event.getPlayer() instanceof Player) {
Player player = (Player) event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerRespawn(final PlayerRespawnEvent event) {
Bukkit.getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
}, 20L);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerDropItem(PlayerDropItemEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerItemBreak(PlayerItemBreakEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
AttributeHandler.updateHealth(player, champion.getAttributeValues());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerItemHeld(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
Map<StrifeAttribute, Double> attributeDoubleMap = new HashMap<>();
for (StrifeAttribute attr : StrifeAttribute.values()) {
attributeDoubleMap.put(attr, attr.getBaseValue());
}
for (Map.Entry<StrifeStat, Integer> entry : champion.getLevelMap().entrySet()) {
for (StrifeAttribute attr : StrifeAttribute.values()) {
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
attributeDoubleMap.put(attr, val + entry.getKey().getAttribute(attr) * entry.getValue());
}
}
for (ItemStack itemStack : champion.getPlayer().getEquipment().getArmorContents()) {
if (itemStack == null || itemStack.getType() == Material.AIR) {
continue;
}
for (StrifeAttribute attr : StrifeAttribute.values()) {
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
attributeDoubleMap.put(attr, val + AttributeHandler.getValue(itemStack, attr));
}
}
if (champion.getPlayer().getInventory().getItem(event.getNewSlot()) != null
&& champion.getPlayer().getInventory().getItem(event.getNewSlot()).getType() != Material.AIR) {
ItemStack itemStack = champion.getPlayer().getInventory().getItem(event.getNewSlot());
for (StrifeAttribute attr : StrifeAttribute.values()) {
if (attr == StrifeAttribute.ARMOR || attr == StrifeAttribute.DAMAGE_REFLECT || attr == StrifeAttribute.EVASION
|| attr == StrifeAttribute.HEALTH || attr == StrifeAttribute.REGENERATION) {
continue;
}
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
attributeDoubleMap.put(attr, val + AttributeHandler.getValue(itemStack, attr));
}
}
AttributeHandler.updateHealth(player, attributeDoubleMap);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
if (!(event.getEntity() instanceof Player) || !(event.getRegainReason() == EntityRegainHealthEvent.RegainReason.REGEN || event
.getRegainReason() ==
EntityRegainHealthEvent.RegainReason.SATIATED) ||
event.isCancelled()) {
return;
}
Player player = (Player) event.getEntity();
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
double amount = champion.getAttributeValues().get(StrifeAttribute.REGENERATION);
event.setAmount(amount);
}
}
|
package ohtu.beddit.web;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import ohtu.beddit.io.PreferenceService;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
/**
* ??? Please, add a description for this class.
*/
public class BedditWebConnector implements BedditConnector {
private static final String TAG = "BedditWebConnector";
public BedditWebConnector() {
disableConnectionReuseIfNecessary();
}
private void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-gingerbread
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
System.setProperty("http.keepAlive", "false");
}
}
public String getUserJson(Context context) throws BedditConnectionException {
return queryForJson(context, "", false);
}
public String getWakeUpJson(Context context, String date) throws BedditConnectionException {
String username = PreferenceService.getUsername(context);
String query = username + "/" + date + "/sleep";
return queryForJson(context, query, false); //add
}
public String getQueueStateJson(Context context, String date) throws BedditConnectionException {
String username = PreferenceService.getUsername(context);
String query = username + "/" + date + "/sleep/queue_for_analysis";
return queryForJson(context, query, false); //add
}
//need to check if POSTing actually works as it is:
public String requestDataAnalysis(Context context, String date) throws BedditConnectionException {
String username = PreferenceService.getUsername(context);
String query = username + "/" + date + "/sleep/queue_for_analysis";
return queryForJson(context, query, true); //add
}
private String queryForJson(Context context, String query, boolean doPost) throws BedditConnectionException {
String url = getQueryURL(context, query);
return getJsonFromServer(context, url, doPost);
}
private String getQueryURL(Context context, String query) throws BedditConnectionException {
String token = PreferenceService.getToken(context);
return "https://api.beddit.com/api2/user/" + query + "?access_token=" + token;
}
private URL stringToURL(String url) throws BedditConnectionException {
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new BedditConnectionException("url was malformed: "+url);
}
}
@Override
public String getJsonFromServer(Context context, String url, boolean doPost) throws BedditConnectionException {
String response = "";
HttpsURLConnection connection = null;
InputStream inputStream = null;
try {
connection = connect(stringToURL(url), connection, doPost);
if (connection.getResponseCode() < 400) { //no error
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
response = readFromStream(inputStream);
} catch (Throwable e) {
Log.e(TAG, Log.getStackTraceString(e));
throw new BedditConnectionException(e.getMessage());
} finally {
closeConnections(connection, inputStream);
}
if (response.equals("")) {
throw new BedditConnectionException("Empty response from Beddit");
}
return response;
}
private HttpsURLConnection connect(URL url, HttpsURLConnection connection, boolean do_post) throws IOException {
connection = (HttpsURLConnection) url.openConnection();
if (do_post) {
connection.setRequestMethod("POST");
connection.setDoOutput(true);
} else {
connection.setRequestMethod("GET");
connection.setDoOutput(false);
}
connection.connect();
return connection;
}
private String readFromStream(InputStream inputStream) {
String response = "";
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNext())
response += scanner.nextLine();
return response;
}
private void closeConnections(HttpsURLConnection connection, InputStream inputStream) {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
}
if (connection != null) {
connection.disconnect();
}
}
}
|
package info.iconmaster.typhon.model.libs;
import info.iconmaster.typhon.TyphonInput;
import info.iconmaster.typhon.model.Annotation;
import info.iconmaster.typhon.model.Constructor;
import info.iconmaster.typhon.model.Constructor.ConstructorParameter;
import info.iconmaster.typhon.model.Field;
import info.iconmaster.typhon.model.Function;
import info.iconmaster.typhon.model.Parameter;
import info.iconmaster.typhon.model.TemplateArgument;
import info.iconmaster.typhon.types.TemplateType;
import info.iconmaster.typhon.types.Type;
import info.iconmaster.typhon.types.TypeRef;
import info.iconmaster.typhon.types.UserType;
public class CoreTypeMap extends UserType {
public static class CoreTypeEntry extends UserType {
public TemplateType K, V;
public Constructor FUNC_NEW;
public Field FIELD_KEY, FIELD_VALUE;
public CoreTypeEntry(CoreTypeMap map) {
super("Entry", map.tni.corePackage.TYPE_ANY); markAsLibrary();
getTemplates().add(K = new TemplateType("K", map.tni.corePackage.TYPE_ANY, null));
getTemplates().add(V = new TemplateType("V", map.tni.corePackage.TYPE_ANY, null));
}
}
public TemplateType K, V;
public Field FIELD_KEYS;
public Function FUNC_GET, FUNC_SET, FUNC_KEYS;
public CoreTypeEntry TYPE_ENTRY;
public CoreTypeMap(TyphonInput input) {
super(input, "Map"); markAsLibrary();
getTemplates().add(K = new TemplateType("K", input.corePackage.TYPE_ANY, null));
getTemplates().add(V = new TemplateType("V", input.corePackage.TYPE_ANY, null));
getTypePackage().addType(TYPE_ENTRY = new CoreTypeEntry(this));
}
/**
* Called by CorePackage.
* This is done because all the types need to be made before these can be made.
*/
public void addMembers() {
getParentTypes().add(new TypeRef(tni.corePackage.TYPE_ITERABLE, new TemplateArgument(new TypeRef(TYPE_ENTRY, new TemplateArgument(K), new TemplateArgument(V)))));
getAnnots().add(new Annotation(tni.corePackage.ANNOT_ABSTRACT));
// add abstract methods
getTypePackage().addFunction(FUNC_GET = new Function(tni, "get", new TemplateType[] {
}, new Parameter[] {
new Parameter(tni, "key", K, false)
}, new Type[] {
V
}));
FUNC_GET.getAnnots().add(new Annotation(tni.corePackage.ANNOT_ABSTRACT));
FUNC_GET.getAnnots().add(new Annotation(tni.corePackage.LIB_OPS.ANNOT_INDEX_GET));
getTypePackage().addFunction(FUNC_SET = new Function(tni, "set", new TemplateType[] {
}, new Parameter[] {
new Parameter(tni, "value", V, false),
new Parameter(tni, "key", K, false)
}, new Type[] {
}));
FUNC_SET.getAnnots().add(new Annotation(tni.corePackage.ANNOT_ABSTRACT));
FUNC_SET.getAnnots().add(new Annotation(tni.corePackage.LIB_OPS.ANNOT_INDEX_SET));
getTypePackage().addField(FIELD_KEYS = new Field("keys", new TypeRef(tni.corePackage.TYPE_ITERABLE, new TemplateArgument(K))));
getTypePackage().addFunction(FUNC_KEYS = new Function(tni, "keys", new TemplateType[] {
}, new Parameter[] {
}, new TypeRef[] {
FIELD_KEYS.getType()
}));
FUNC_KEYS.getAnnots().add(new Annotation(tni.corePackage.ANNOT_ABSTRACT));
FIELD_KEYS.setGetter(FUNC_KEYS);
// add concrete methods
// TODO
// add methods for Entry
TYPE_ENTRY.getTypePackage().addField(TYPE_ENTRY.FIELD_KEY = new Field("key", TYPE_ENTRY.K));
TYPE_ENTRY.getTypePackage().addField(TYPE_ENTRY.FIELD_VALUE = new Field("value", TYPE_ENTRY.V));
TYPE_ENTRY.getTypePackage().addFunction(TYPE_ENTRY.FUNC_NEW = new Constructor(TYPE_ENTRY, ConstructorParameter.fieldParam(TYPE_ENTRY.FIELD_KEY), ConstructorParameter.fieldParam(TYPE_ENTRY.FIELD_VALUE)));
}
}
|
package info.u_team.u_team_core.item.armor;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.ArmorItem;
import net.minecraft.world.item.ArmorMaterial;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.registries.ForgeRegistries;
public class UArmorItem extends ArmorItem {
protected final String textureName;
public UArmorItem(String textureName, Properties properties, ArmorMaterial material, EquipmentSlot slot) {
this(textureName, null, properties, material, slot);
}
public UArmorItem(String textureName, CreativeModeTab creativeTab, Properties properties, ArmorMaterial material, EquipmentSlot slot) {
super(material, slot, creativeTab == null ? properties : properties.tab(creativeTab));
this.textureName = textureName;
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, EquipmentSlot slot, String type) {
if (!material.getName().equals("invalid")) {
return null;
}
return String.format("%s:textures/models/armor/%s_layer_%d%s.png", ForgeRegistries.ITEMS.getKey(this).getNamespace(), textureName, (slot == EquipmentSlot.LEGS ? 2 : 1), type == null ? "" : String.format("_%s", type));
}
protected String getTypeString(EquipmentSlot slot) {
return switch (slot) {
case HEAD -> "helmet";
case CHEST -> "chestplate";
case LEGS -> "leggings";
case FEET -> "boots";
default -> "invalid";
};
}
}
|
package mcjty.rftoolsdim.dimensions.world;
import mcjty.lib.varia.MathTools;
import mcjty.rftoolsdim.RFToolsDim;
import mcjty.rftoolsdim.dimensions.DimensionInformation;
import mcjty.rftoolsdim.dimensions.description.CelestialBodyDescriptor;
import mcjty.rftoolsdim.dimensions.types.PatreonType;
import mcjty.rftoolsdim.dimensions.types.SkyType;
import mcjty.rftoolsdim.dimensions.types.SkyType.SkyboxType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.client.IRenderHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import java.util.List;
import java.util.Random;
public class SkyRenderer {
private static final ResourceLocation locationEndSkyPng = new ResourceLocation("textures/environment/end_sky.png");
// private static final ResourceLocation locationDebugSkyPng = new ResourceLocation(RFTools.MODID + ":" +"textures/sky/debugsky.png");
private static final ResourceLocation locationMoonPhasesPng = new ResourceLocation("textures/environment/moon_phases.png");
private static final ResourceLocation locationSunPng = new ResourceLocation("textures/environment/sun.png");
private static final ResourceLocation locationSickSunPng = new ResourceLocation(RFToolsDim.MODID + ":" +"textures/sky/sicksun.png");
private static final ResourceLocation locationSickMoonPng = new ResourceLocation(RFToolsDim.MODID + ":" +"textures/sky/sickmoon.png");
private static final ResourceLocation locationRabbitSunPng = new ResourceLocation(RFToolsDim.MODID + ":" +"textures/sky/rabbitsun.png");
private static final ResourceLocation locationRabbitMoonPng = new ResourceLocation(RFToolsDim.MODID + ":" +"textures/sky/rabbitmoon.png");
private static final ResourceLocation locationPlanetPng = new ResourceLocation(RFToolsDim.MODID + ":" +"textures/sky/planet1.png");
private static final ResourceLocation locationWolfMoonPng = new ResourceLocation(RFToolsDim.MODID + ":" +"textures/sky/wolfred.png");
private static final ResourceLocation locationCloudsPng = new ResourceLocation("textures/environment/clouds.png");
private static boolean initialized = false;
/** The star GL Call list */
private static int starGLCallList;
/** OpenGL sky list */
private static int glSkyList;
/** OpenGL sky list 2 */
private static int glSkyList2;
private static void initialize() {
if (!initialized) {
initialized = true;
// @todo VBO
starGLCallList = GLAllocation.generateDisplayLists(1);
GlStateManager.pushMatrix();
GL11.glNewList(starGLCallList, GL11.GL_COMPILE);
renderStars();
GL11.glEndList();
GlStateManager.popMatrix();
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder renderer = tessellator.getBuffer();
glSkyList = GLAllocation.generateDisplayLists(1);
GL11.glNewList(glSkyList, GL11.GL_COMPILE);
byte b2 = 64;
int i = 256 / b2 + 2;
float f = 16.0F;
int j;
int k;
for (j = -b2 * i; j <= b2 * i; j += b2) {
for (k = -b2 * i; k <= b2 * i; k += b2) {
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION);
renderer.pos((j + 0), f, (k + 0)).endVertex();
renderer.pos((j + b2), f, (k + 0)).endVertex();
renderer.pos((j + b2), f, (k + b2)).endVertex();
renderer.pos((j + 0), f, (k + b2)).endVertex();
tessellator.draw();
}
}
GL11.glEndList();
glSkyList2 = GLAllocation.generateDisplayLists(1);
GL11.glNewList(glSkyList2, GL11.GL_COMPILE);
f = -16.0F;
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION);
for (j = -b2 * i; j <= b2 * i; j += b2) {
for (k = -b2 * i; k <= b2 * i; k += b2) {
renderer.pos((j + b2), f, (k + 0)).endVertex();
renderer.pos((j + 0), f, (k + 0)).endVertex();
renderer.pos((j + 0), f, (k + b2)).endVertex();
renderer.pos((j + b2), f, (k + b2)).endVertex();
}
}
tessellator.draw();
GL11.glEndList();
}
}
private static final IRenderHandler doNothingRenderHandler = new IRenderHandler() {
@Override
public void render(float partialTicks, WorldClient world, Minecraft mc) {
}
};
public static void registerNoSky(GenericWorldProvider provider) {
provider.setSkyRenderer(doNothingRenderHandler);
provider.setCloudRenderer(doNothingRenderHandler);
}
public static void registerEnderSky(GenericWorldProvider provider) {
provider.setSkyRenderer(enderSkyRenderHandler);
provider.setCloudRenderer(doNothingRenderHandler);
}
public static void registerKenneyCloudRenderer(final GenericWorldProvider provider) {
provider.setCloudRenderer(new IRenderHandler() {
@Override
public void render(float partialTicks, WorldClient world, Minecraft mc) {
renderKenneyClouds(provider, partialTicks);
}
});
}
public static void registerSkybox(GenericWorldProvider provider, final SkyType skyType) {
provider.setSkyRenderer(new IRenderHandler() {
@Override
public void render(float partialTicks, WorldClient world, Minecraft mc) {
SkyRenderer.renderSkyTexture(skyType.sky, skyType.sky2, skyType.skyboxType);
}
});
provider.setCloudRenderer(doNothingRenderHandler);
}
public static void registerSky(GenericWorldProvider provider, final DimensionInformation information) {
provider.setSkyRenderer(new IRenderHandler() {
@Override
public void render(float partialTicks, WorldClient world, Minecraft mc) {
SkyRenderer.renderSky(partialTicks, provider);
}
});
}
private static class UV {
private final double u;
private final double v;
private UV(double u, double v) {
this.u = u;
this.v = v;
}
public static UV uv(double u, double v) {
return new UV(u, v);
}
}
private static UV[] faceDown = new UV[] { UV.uv(0.0D, 1.0D), UV.uv(0.0D, 0.0D), UV.uv(1.0D, 0.0D), UV.uv(1.0D, 1.0D) };
private static UV[] faceUp = new UV[] { UV.uv(0.0D, 1.0D), UV.uv(0.0D, 0.0D), UV.uv(1.0D, 0.0D), UV.uv(1.0D, 1.0D) };
private static UV[] faceNorth = new UV[] { UV.uv(0.0D, 0.0D), UV.uv(0.0D, 1.0D), UV.uv(1.0D, 1.0D), UV.uv(1.0D, 0.0D) };
private static UV[] faceSouth = new UV[] { UV.uv(1.0D, 1.0D), UV.uv(1.0D, 0.0D), UV.uv(0.0D, 0.0D), UV.uv(0.0D, 1.0D) };
private static UV[] faceWest = new UV[] { UV.uv(1.0D, 0.0D), UV.uv(0.0D, 0.0D), UV.uv(0.0D, 1.0D), UV.uv(1.0D, 1.0D) };
private static UV[] faceEast = new UV[] { UV.uv(0.0D, 1.0D), UV.uv(1.0D, 1.0D), UV.uv(1.0D, 0.0D), UV.uv(0.0D, 0.0D) };
@SideOnly(Side.CLIENT)
private static void renderSkyTexture(ResourceLocation sky, ResourceLocation sky2, SkyboxType type) {
TextureManager renderEngine = Minecraft.getMinecraft().getTextureManager();
GlStateManager.disableFog();
GlStateManager.disableAlpha();
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
RenderHelper.disableStandardItemLighting();
GlStateManager.depthMask(false);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder renderer = tessellator.getBuffer();
for (int i = 0; i < 6; ++i) {
GlStateManager.pushMatrix();
UV[] uv = faceDown;
boolean white = true;
if (i == 0) { // Down face
uv = faceDown;
switch (type) {
case SKYTYPE_ALL:
renderEngine.bindTexture(sky);
break;
case SKYTYPE_ALLHORIZONTAL:
case SKYTYPE_ALTERNATING:
renderEngine.bindTexture(sky2);
break;
default:
white = false;
break;
}
} else if (i == 1) { // North face
renderEngine.bindTexture(sky);
GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F);
uv = faceNorth;
} else if (i == 2) { // South face
renderEngine.bindTexture(sky);
GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F);
uv = faceSouth;
} else if (i == 3) { // Up face
GlStateManager.rotate(180.0F, 1.0F, 0.0F, 0.0F);
uv = faceUp;
switch (type) {
case SKYTYPE_ALL:
renderEngine.bindTexture(sky);
break;
case SKYTYPE_ALLHORIZONTAL:
case SKYTYPE_ALTERNATING:
renderEngine.bindTexture(sky2);
break;
default:
white = false;
break;
}
} else if (i == 4) { // East face
if (type == SkyboxType.SKYTYPE_ALTERNATING && sky2 != null) {
renderEngine.bindTexture(sky2);
} else {
renderEngine.bindTexture(sky);
}
GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F);
uv = faceEast;
} else if (i == 5) { // West face
if (type == SkyboxType.SKYTYPE_ALTERNATING && sky2 != null) {
renderEngine.bindTexture(sky2);
} else {
renderEngine.bindTexture(sky);
}
GlStateManager.rotate(-90.0F, 0.0F, 0.0F, 1.0F);
uv = faceWest;
}
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
int cc = white ? 255 : 0;
renderer.pos(-100.0D, -100.0D, -100.0D).tex(uv[0].u, uv[0].v).color(cc, cc, cc, 255).endVertex();
renderer.pos(-100.0D, -100.0D, 100.0D).tex(uv[1].u, uv[1].v).color(cc, cc, cc, 255).endVertex();
renderer.pos(100.0D, -100.0D, 100.0D).tex(uv[2].u, uv[2].v).color(cc, cc, cc, 255).endVertex();
renderer.pos(100.0D, -100.0D, -100.0D).tex(uv[3].u, uv[3].v).color(cc, cc, cc, 255).endVertex();
tessellator.draw();
GlStateManager.popMatrix();
}
GlStateManager.depthMask(true);
GlStateManager.enableTexture2D();
GlStateManager.enableAlpha();
}
@SideOnly(Side.CLIENT)
private static final IRenderHandler enderSkyRenderHandler = new IRenderHandler() {
@Override
public void render(float partialTicks, WorldClient world, Minecraft mc) {
TextureManager renderEngine = Minecraft.getMinecraft().getTextureManager();
GlStateManager.disableFog();
GlStateManager.disableAlpha();
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
RenderHelper.disableStandardItemLighting();
GlStateManager.depthMask(false);
renderEngine.bindTexture(locationEndSkyPng);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder renderer = tessellator.getBuffer();
for (int i = 0; i < 6; ++i) {
GlStateManager.pushMatrix();
if (i == 1) {
GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F);
}
if (i == 2) {
GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F);
}
if (i == 3) {
GlStateManager.rotate(180.0F, 1.0F, 0.0F, 0.0F);
}
if (i == 4) {
GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F);
}
if (i == 5) {
GlStateManager.rotate(-90.0F, 0.0F, 0.0F, 1.0F);
}
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
int cc = 255; // @todo: decode 2631720 into rgb
renderer.pos(-100.0D, -100.0D, -100.0D).tex(0, 0).color(cc, cc, cc, 255).endVertex();
renderer.pos(-100.0D, -100.0D, 100.0D).tex(0, 16).color(cc, cc, cc, 255).endVertex();
renderer.pos(100.0D, -100.0D, 100.0D).tex(16, 16).color(cc, cc, cc, 255).endVertex();
renderer.pos(100.0D, -100.0D, -100.0D).tex(16, 0).color(cc, cc, cc, 255).endVertex();
tessellator.draw();
GlStateManager.popMatrix();
}
GlStateManager.depthMask(true);
GlStateManager.enableTexture2D();
GlStateManager.enableAlpha();
}
};
/**
* Renders the sky with the partial tick time. Args: partialTickTime
*/
@SideOnly(Side.CLIENT)
private static void renderSky(float partialTickTime, GenericWorldProvider provider) {
initialize();
EntityPlayerSP player = Minecraft.getMinecraft().player;
WorldClient world = Minecraft.getMinecraft().world;
TextureManager renderEngine = Minecraft.getMinecraft().getTextureManager();
GlStateManager.disableTexture2D();
Vec3d vec3 = world.getSkyColor(player, partialTickTime);
float skyRed = (float) vec3.x;
float skyGreen = (float) vec3.y;
float skyBlue = (float) vec3.z;
boolean anaglyph = Minecraft.getMinecraft().gameSettings.anaglyph;
if (anaglyph) {
float f4 = (skyRed * 30.0F + skyGreen * 59.0F + skyBlue * 11.0F) / 100.0F;
float f5 = (skyRed * 30.0F + skyGreen * 70.0F) / 100.0F;
float f6 = (skyRed * 30.0F + skyBlue * 70.0F) / 100.0F;
skyRed = f4;
skyGreen = f5;
skyBlue = f6;
}
GlStateManager.color(skyRed, skyGreen, skyBlue);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder renderer = tessellator.getBuffer();
GlStateManager.depthMask(false);
GlStateManager.enableFog();
GlStateManager.color(skyRed, skyGreen, skyBlue);
// @todo support VBO?
// if (OpenGlHelper.useVbo()) {
// skyVBO.bindBuffer();
// GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
// GL11.glVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
// this.skyVBO.drawArrays(7);
// this.skyVBO.unbindBuffer();
// GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
// } else {
GlStateManager.callList(glSkyList);
GlStateManager.disableFog();
GlStateManager.disableAlpha();
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
RenderHelper.disableStandardItemLighting();
float[] sunsetColors = world.provider.calcSunriseSunsetColors(world.getCelestialAngle(partialTickTime), partialTickTime);
if (sunsetColors != null) {
GlStateManager.disableTexture2D();
GlStateManager.shadeModel(7425);
GlStateManager.pushMatrix();
GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(MathHelper.sin(world.getCelestialAngleRadians(partialTickTime)) < 0.0F ? 180.0F : 0.0F, 0.0F, 0.0F, 1.0F);
GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F);
float f6 = sunsetColors[0];
float f7 = sunsetColors[1];
float f8 = sunsetColors[2];
if (anaglyph) {
float f9 = (f6 * 30.0F + f7 * 59.0F + f8 * 11.0F) / 100.0F;
float f10 = (f6 * 30.0F + f7 * 70.0F) / 100.0F;
float f11 = (f6 * 30.0F + f8 * 70.0F) / 100.0F;
f6 = f9;
f7 = f10;
f8 = f11;
}
renderer.begin(GL11.GL_TRIANGLE_FAN, DefaultVertexFormats.POSITION_COLOR);
renderer.pos(0.0D, 100.0D, 0.0D).color(f6, f7, f8, sunsetColors[3]).endVertex();
for (int j = 0; j <= 16; ++j) {
float f11 = j * (float) Math.PI * 2.0F / 16.0f;
float f12 = MathHelper.sin(f11);
float f13 = MathHelper.cos(f11);
renderer.pos((f12 * 120.0F), (f13 * 120.0F), (-f13 * 40.0F * sunsetColors[3])).color(sunsetColors[0], sunsetColors[1], sunsetColors[2], 0.0F).endVertex();
}
tessellator.draw();
GlStateManager.popMatrix();
GlStateManager.shadeModel(GL11.GL_FLAT);
}
renderCelestialBodies(partialTickTime, provider.getDimensionInformation(), world, renderEngine, tessellator);
GlStateManager.color(0.0F, 0.0F, 0.0F);
double d0 = player.getPosition().getY() - world.getHorizon();
if (d0 < 0.0D) {
GlStateManager.pushMatrix();
GlStateManager.translate(0.0F, 12.0F, 0.0F);
// @todo
// if (this.vboEnabled)
// this.sky2VBO.bindBuffer();
// GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
// GL11.glVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
// this.sky2VBO.drawArrays(7);
// this.sky2VBO.unbindBuffer();
// GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
// else
GlStateManager.callList(glSkyList2);
// GlStateManager.callList(this.glSkyList2);
GlStateManager.popMatrix();
float f8 = 1.0F;
float f9 = -((float) (d0 + 65.0D));
float f10 = -f8;
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR);
renderer.pos((-f8), f9, f8).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f9, f8).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f10, f8).color(0, 0, 0, 255).endVertex();
renderer.pos((-f8), f10, f8).color(0, 0, 0, 255).endVertex();
renderer.pos((-f8), f10, (-f8)).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f10, (-f8)).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f9, (-f8)).color(0, 0, 0, 255).endVertex();
renderer.pos((-f8), f9, (-f8)).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f10, (-f8)).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f10, f8).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f9, f8).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f9, (-f8)).color(0, 0, 0, 255).endVertex();
renderer.pos((-f8), f9, (-f8)).color(0, 0, 0, 255).endVertex();
renderer.pos((-f8), f9, f8).color(0, 0, 0, 255).endVertex();
renderer.pos((-f8), f10, f8).color(0, 0, 0, 255).endVertex();
renderer.pos((-f8), f10, (-f8)).color(0, 0, 0, 255).endVertex();
renderer.pos((-f8), f10, (-f8)).color(0, 0, 0, 255).endVertex();
renderer.pos((-f8), f10, f8).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f10, f8).color(0, 0, 0, 255).endVertex();
renderer.pos(f8, f10, (-f8)).color(0, 0, 0, 255).endVertex();
tessellator.draw();
}
if (world.provider.isSkyColored()) {
GlStateManager.color(skyRed * 0.2F + 0.04F, skyGreen * 0.2F + 0.04F, skyBlue * 0.6F + 0.1F);
} else {
GlStateManager.color(skyRed, skyGreen, skyBlue);
}
GlStateManager.pushMatrix();
GlStateManager.translate(0.0F, -((float) (d0 - 16.0D)), 0.0F);
GlStateManager.callList(glSkyList2);
GlStateManager.popMatrix();
GlStateManager.enableTexture2D();
GlStateManager.depthMask(true);
}
private static void renderCelestialBodies(float partialTickTime, DimensionInformation information, WorldClient world, TextureManager renderEngine, Tessellator tessellator) {
List<CelestialBodyDescriptor> celestialBodies = information.getCelestialBodyDescriptors();
GlStateManager.enableTexture2D();
GlStateManager.tryBlendFuncSeparate(770, 1, 1, 0);
GlStateManager.pushMatrix();
float f6 = 1.0F - world.getRainStrength(partialTickTime);
ResourceLocation sun = getSun(information);
ResourceLocation moon = getMoon(information);
BufferBuilder renderer = tessellator.getBuffer();
if (celestialBodies.isEmpty()) {
GlStateManager.color(1.0F, 1.0F, 1.0F, f6);
GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F);
GlStateManager.rotate(world.getCelestialAngle(partialTickTime) * 360.0F, 1.0F, 0.0F, 0.0F);
float f10 = 30.0F;
renderEngine.bindTexture(sun);
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
renderer.pos((-f10), 100.0D, (-f10)).tex(0.0D, 0.0D).endVertex();
renderer.pos(f10, 100.0D, (-f10)).tex(1.0D, 0.0D).endVertex();
renderer.pos(f10, 100.0D, f10).tex(1.0D, 1.0D).endVertex();
renderer.pos((-f10), 100.0D, f10).tex(0.0D, 1.0D).endVertex();
tessellator.draw();
f10 = 20.0F;
float f14, f15, f16, f17;
renderEngine.bindTexture(moon);
if (!moon.equals(locationMoonPhasesPng)) {
f14 = 0.0f;
f15 = 0.0f;
f16 = 1.0f;
f17 = 1.0f;
} else {
int k = world.getMoonPhase();
int l = k % 4;
int i1 = k / 4 % 2;
f14 = (l + 0) / 4.0F;
f15 = (i1 + 0) / 2.0F;
f16 = (l + 1) / 4.0F;
f17 = (i1 + 1) / 2.0F;
}
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
renderer.pos((-f10), -100.0D, f10).tex(f16, f17).endVertex();
renderer.pos(f10, -100.0D, f10).tex(f14, f17).endVertex();
renderer.pos(f10, -100.0D, (-f10)).tex(f14, f15).endVertex();
renderer.pos((-f10), -100.0D, (-f10)).tex(f16, f15).endVertex();
tessellator.draw();
} else {
Random random = new Random(world.getSeed());
for (CelestialBodyDescriptor body : celestialBodies) {
float offset = 0.0f;
float factor = 1.0f;
float yangle = -90.0f;
if (!body.isMain()) {
offset = random.nextFloat() * 200.0f;
factor = random.nextFloat() * 3.0f;
yangle = random.nextFloat() * 180.0f;
}
switch (body.getType()) {
case BODY_NONE:
break;
case BODY_SUN:
GlStateManager.color(1.0F, 1.0F, 1.0F, f6);
renderSun(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 30.0F, sun);
break;
case BODY_LARGESUN:
GlStateManager.color(1.0F, 1.0F, 1.0F, f6);
renderSun(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 80.0F, sun);
break;
case BODY_SMALLSUN:
GlStateManager.color(1.0F, 1.0F, 1.0F, f6);
renderSun(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 10.0F, sun);
break;
case BODY_REDSUN:
GlStateManager.color(1.0F, 0.0F, 0.0F, f6);
renderSun(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 30.0F, sun);
break;
case BODY_MOON:
GlStateManager.color(1.0F, 1.0F, 1.0F, f6);
renderMoon(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 20.0F, moon);
break;
case BODY_LARGEMOON:
GlStateManager.color(1.0F, 1.0F, 1.0F, f6);
renderMoon(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 60.0F, moon);
break;
case BODY_SMALLMOON:
GlStateManager.color(1.0F, 1.0F, 1.0F, f6);
renderMoon(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 10.0F, moon);
break;
case BODY_REDMOON:
GlStateManager.color(1.0F, 0.0F, 0.0F, f6);
renderMoon(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 20.0F, moon);
break;
case BODY_PLANET:
GlStateManager.color(1.0F, 1.0F, 1.0F, f6);
renderPlanet(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 10.0F);
break;
case BODY_LARGEPLANET:
GlStateManager.color(1.0F, 1.0F, 1.0F, f6);
renderPlanet(partialTickTime, world, renderEngine, tessellator, offset, factor, yangle, 30.0F);
break;
}
}
}
GlStateManager.disableTexture2D();
float f18 = world.getStarBrightness(partialTickTime) * f6;
if (f18 > 0.0F) {
GlStateManager.color(f18, f18, f18, f18);
// @todo vbo?
// if (this.vboEnabled)
// this.starVBO.bindBuffer();
// GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
// GL11.glVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
// this.starVBO.drawArrays(7);
// this.starVBO.unbindBuffer();
// GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
// else
GlStateManager.callList(starGLCallList);
}
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.disableBlend();
GlStateManager.enableAlpha();
GlStateManager.enableFog();
GlStateManager.popMatrix();
GlStateManager.disableTexture2D();
}
private static ResourceLocation getSun(DimensionInformation information) {
ResourceLocation sun;
if (information.isPatreonBitSet(PatreonType.PATREON_SICKSUN)) {
sun = locationSickSunPng;
} else if (information.isPatreonBitSet(PatreonType.PATREON_RABBITSUN)) {
sun = locationRabbitSunPng;
} else {
sun = locationSunPng;
}
return sun;
}
private static ResourceLocation getMoon(DimensionInformation information) {
ResourceLocation moon;
if (information.isPatreonBitSet(PatreonType.PATREON_SICKMOON)) {
moon = locationSickMoonPng;
} else if (information.isPatreonBitSet(PatreonType.PATREON_RABBITMOON)) {
moon = locationRabbitMoonPng;
} else if (information.isPatreonBitSet(PatreonType.PATREON_TOMWOLF)) {
moon = locationWolfMoonPng;
} else {
moon = locationMoonPhasesPng;
}
return moon;
}
private static void renderMoon(float partialTickTime, WorldClient world, TextureManager renderEngine, Tessellator tessellator, float offset, float factor, float yangle, float size, ResourceLocation moon) {
GlStateManager.translate(0.0F, 0.0F, 0.0F);
GlStateManager.rotate(yangle, 0.0F, 1.0F, 0.0F);
float angle = world.provider.calculateCelestialAngle(world.getWorldInfo().getWorldTime(), partialTickTime);
angle = angle * factor + offset;
GlStateManager.rotate(angle * 360.0F, 1.0F, 0.0F, 0.0F);
float f14, f15, f16, f17;
renderEngine.bindTexture(moon);
if (!moon.equals(locationMoonPhasesPng)) {
f14 = 0.0f;
f15 = 0.0f;
f16 = 1.0f;
f17 = 1.0f;
} else {
int k = world.getMoonPhase();
int l = k % 4;
int i1 = k / 4 % 2;
f14 = (l + 0) / 4.0F;
f15 = (i1 + 0) / 2.0F;
f16 = (l + 1) / 4.0F;
f17 = (i1 + 1) / 2.0F;
}
BufferBuilder renderer = tessellator.getBuffer();
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
renderer.pos((-size), -100.0D, size).tex(f16, f17).endVertex();
renderer.pos(size, -100.0D, size).tex(f14, f17).endVertex();
renderer.pos(size, -100.0D, (-size)).tex(f14, f15).endVertex();
renderer.pos((-size), -100.0D, (-size)).tex(f16, f15).endVertex();
tessellator.draw();
}
private static void renderSun(float partialTickTime, WorldClient world, TextureManager renderEngine, Tessellator tessellator, float offset, float factor, float yangle, float size, ResourceLocation sun) {
GlStateManager.translate(0.0F, 0.0F, 0.0F);
GlStateManager.rotate(yangle, 0.0F, 1.0F, 0.0F);
float angle = world.provider.calculateCelestialAngle(world.getWorldInfo().getWorldTime(), partialTickTime);
angle = angle * factor + offset;
GlStateManager.rotate(angle * 360.0F, 1.0F, 0.0F, 0.0F);
renderEngine.bindTexture(sun);
BufferBuilder renderer = tessellator.getBuffer();
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
renderer.pos((-size), 100.0D, (-size)).tex(0.0D, 0.0D).endVertex();
renderer.pos(size, 100.0D, (-size)).tex(1.0D, 0.0D).endVertex();
renderer.pos(size, 100.0D, size).tex(1.0D, 1.0D).endVertex();
renderer.pos((-size), 100.0D, size).tex(0.0D, 1.0D).endVertex();
tessellator.draw();
}
private static void renderPlanet(float partialTickTime, WorldClient world, TextureManager renderEngine, Tessellator tessellator, float offset, float factor, float yangle, float size) {
GlStateManager.translate(0.0F, 0.0F, 0.0F);
GlStateManager.rotate(yangle, 0.0F, 1.0F, 0.0F);
float angle = world.provider.calculateCelestialAngle(world.getWorldInfo().getWorldTime(), partialTickTime);
angle = angle * factor + offset;
GlStateManager.rotate(angle * 360.0F, 1.0F, 0.0F, 0.0F);
renderEngine.bindTexture(locationPlanetPng);
BufferBuilder renderer = tessellator.getBuffer();
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
renderer.pos((-size), 100.0D, (-size)).tex(0.0D, 0.0D).endVertex();
renderer.pos(size, 100.0D, (-size)).tex(1.0D, 0.0D).endVertex();
renderer.pos(size, 100.0D, size).tex(1.0D, 1.0D).endVertex();
renderer.pos((-size), 100.0D, size).tex(0.0D, 1.0D).endVertex();
tessellator.draw();
}
private static void renderStars() {
Random random = new Random(10842L);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder renderer = tessellator.getBuffer();
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION);
for (int i = 0; i < 1500; ++i) {
double d0 = (random.nextFloat() * 2.0F - 1.0F);
double d1 = (random.nextFloat() * 2.0F - 1.0F);
double d2 = (random.nextFloat() * 2.0F - 1.0F);
double d3 = (0.15F + random.nextFloat() * 0.1F);
double d4 = d0 * d0 + d1 * d1 + d2 * d2;
if (d4 < 1.0D && d4 > 0.01D) {
d4 = 1.0D / Math.sqrt(d4);
d0 *= d4;
d1 *= d4;
d2 *= d4;
double d5 = d0 * 100.0D;
double d6 = d1 * 100.0D;
double d7 = d2 * 100.0D;
double d8 = Math.atan2(d0, d2);
double d9 = Math.sin(d8);
double d10 = Math.cos(d8);
double d11 = Math.atan2(Math.sqrt(d0 * d0 + d2 * d2), d1);
double d12 = Math.sin(d11);
double d13 = Math.cos(d11);
double d14 = random.nextDouble() * Math.PI * 2.0D;
double d15 = Math.sin(d14);
double d16 = Math.cos(d14);
for (int j = 0; j < 4; ++j) {
double d17 = 0.0D;
double d18 = ((j & 2) - 1) * d3;
double d19 = ((j + 1 & 2) - 1) * d3;
double d20 = d18 * d16 - d19 * d15;
double d21 = d19 * d16 + d18 * d15;
double d22 = d20 * d12 + d17 * d13;
double d23 = d17 * d12 - d20 * d13;
double d24 = d23 * d9 - d21 * d10;
double d25 = d21 * d9 + d23 * d10;
renderer.pos(d5 + d24, d6 + d22, d7 + d25).endVertex();
}
}
}
tessellator.draw();
}
@SideOnly(Side.CLIENT)
public static void renderKenneyClouds(GenericWorldProvider provider, float partialTicks) {
GlStateManager.disableCull();
Minecraft mc = Minecraft.getMinecraft();
TextureManager renderEngine = mc.getTextureManager();
float f1 = (float) (mc.getRenderViewEntity().lastTickPosY + (mc.getRenderViewEntity().posY - mc.getRenderViewEntity().lastTickPosY) * partialTicks);
Tessellator tessellator = Tessellator.getInstance();
float f2 = 12.0F;
float f3 = 4.0F;
RenderGlobal renderGlobal = mc.renderGlobal;
double d0 = (CloudRenderAccessHelper.getCloudTickCounter(renderGlobal) + partialTicks);
double entityX = mc.getRenderViewEntity().prevPosX + (mc.getRenderViewEntity().posX - mc.getRenderViewEntity().prevPosX) * partialTicks;
double entityZ = mc.getRenderViewEntity().prevPosZ + (mc.getRenderViewEntity().posZ - mc.getRenderViewEntity().prevPosZ) * partialTicks;
double d1 = (entityX + d0 * 0.029999999329447746D) / f2;
double d2 = entityZ / f2 + 0.33000001311302185D;
float y = provider.getCloudHeight() - f1 + 0.33F;
int i = MathTools.floor(d1 / 2048.0D);
int j = MathTools.floor(d2 / 2048.0D);
d1 -= (i * 2048);
d2 -= (j * 2048);
renderEngine.bindTexture(locationCloudsPng);
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);
Vec3d vec3 = provider.getWorld().getCloudColour(partialTicks);
float red = (float) vec3.x;
float green = (float) vec3.y;
float blue = (float) vec3.z;
float f8;
float f9;
float f10;
if (mc.gameSettings.anaglyph) {
f8 = (red * 30.0F + green * 59.0F + blue * 11.0F) / 100.0F;
f9 = (red * 30.0F + green * 70.0F) / 100.0F;
f10 = (red * 30.0F + blue * 70.0F) / 100.0F;
red = f8;
green = f9;
blue = f10;
}
f10 = 0.00390625F;
f8 = MathTools.floor(d1) * f10;
f9 = MathTools.floor(d2) * f10;
float f11 = (float) (d1 - MathTools.floor(d1));
float f12 = (float) (d2 - MathTools.floor(d2));
byte b0 = 8;
byte b1 = 4;
float f13 = 9.765625E-4F;
GlStateManager.scale(f2, 1.0F, f2);
BufferBuilder renderer = tessellator.getBuffer();
for (int k = 0; k < 2; ++k) {
if (k == 0) {
GlStateManager.colorMask(false, false, false, false);
} else if (mc.gameSettings.anaglyph) {
if (EntityRenderer.anaglyphField == 0) {
GlStateManager.colorMask(false, true, true, true);
} else {
GlStateManager.colorMask(true, false, false, true);
}
} else {
GlStateManager.colorMask(true, true, true, true);
}
for (int l = -b1 + 1; l <= b1; ++l) {
for (int i1 = -b1 + 1; i1 <= b1; ++i1) {
renderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR_NORMAL);
float u = (l * b0);
float v = (i1 * b0);
float x = u - f11;
float z = v - f12;
// float cr = (float) ((u % 10.0f) / 10.0f);
// float cg = (float) (((u + v) % 10.0f) / 10.0f);
// float cb = (float) ((v % 10.0f) / 10.0f);
float cr = x % 1.0f;
float cg = (x+z) % 1.0f;
float cb = z % 1.0f;
if (y > -f3 - 1.0F) {
renderer.pos((x + 0.0F), (y + 0.0F), (z + b0)).tex(((u + 0.0F) * f10 + f8), ((v + b0) * f10 + f9)).color(red * 0.7F * cr, green * 0.7F * cg, blue * 0.7F * cb, 0.8F).normal(0.0F, -1.0F, 0.0F).endVertex();
renderer.pos((x + b0), (y + 0.0F), (z + b0)).tex(((u + b0) * f10 + f8), ((v + b0) * f10 + f9)).color(red * 0.7F * cr, green * 0.7F * cg, blue * 0.7F * cb, 0.8F).normal(0.0F, -1.0F, 0.0F).endVertex();
renderer.pos((x + b0), (y + 0.0F), (z + 0.0F)).tex(((u + b0) * f10 + f8), ((v + 0.0F) * f10 + f9)).color(red * 0.7F * cr, green * 0.7F * cg, blue * 0.7F * cb, 0.8F).normal(0.0F, -1.0F, 0.0F).endVertex();
renderer.pos((x + 0.0F), (y + 0.0F), (z + 0.0F)).tex(((u + 0.0F) * f10 + f8), ((v + 0.0F) * f10 + f9)).color(red * 0.7F * cr, green * 0.7F * cg, blue * 0.7F * cb, 0.8F).normal(0.0F, -1.0F, 0.0F).endVertex();
}
if (y <= f3 + 1.0F) {
renderer.pos((x + 0.0F), (y + f3 - f13), (z + b0)).tex(((u + 0.0F) * f10 + f8), ((v + b0) * f10 + f9)).color(red * cr, green * cg, blue * cb, 0.8F).normal(0.0F, 1.0F, 0.0F).endVertex();
renderer.pos((x + b0), (y + f3 - f13), (z + b0)).tex(((u + b0) * f10 + f8), ((v + b0) * f10 + f9)).color(red * cr, green * cg, blue * cb, 0.8F).normal(0.0F, 1.0F, 0.0F).endVertex();
renderer.pos((x + b0), (y + f3 - f13), (z + 0.0F)).tex(((u + b0) * f10 + f8), ((v + 0.0F) * f10 + f9)).color(red * cr, green * cg, blue * cb, 0.8F).normal(0.0F, 1.0F, 0.0F).endVertex();
renderer.pos((x + 0.0F), (y + f3 - f13), (z + 0.0F)).tex(((u + 0.0F) * f10 + f8), ((v + 0.0F) * f10 + f9)).color(red * cr, green * cg, blue * cb, 0.8F).normal(0.0F, 1.0F, 0.0F).endVertex();
}
int j1;
if (l > -1) {
for (j1 = 0; j1 < b0; ++j1) {
renderer.pos((x + j1 + 0.0F), (y + 0.0F), (z + b0)).tex(((u + j1 + 0.5F) * f10 + f8), ((v + b0) * f10 + f9)).color(red * 0.9F * cr, green * 0.9F * cg, blue * 0.9F * cb, 0.8F).normal(-1.0F, 0.0F, 0.0F).endVertex();
renderer.pos((x + j1 + 0.0F), (y + f3), (z + b0)).tex(((u + j1 + 0.5F) * f10 + f8), ((v + b0) * f10 + f9)).color(red * 0.9F * cr, green * 0.9F * cg, blue * 0.9F * cb, 0.8F).normal(-1.0F, 0.0F, 0.0F).endVertex();
renderer.pos((x + j1 + 0.0F), (y + f3), (z + 0.0F)).tex(((u + j1 + 0.5F) * f10 + f8), ((v + 0.0F) * f10 + f9)).color(red * 0.9F * cr, green * 0.9F * cg, blue * 0.9F * cb, 0.8F).normal(-1.0F, 0.0F, 0.0F).endVertex();
renderer.pos((x + j1 + 0.0F), (y + 0.0F), (z + 0.0F)).tex(((u + j1 + 0.5F) * f10 + f8), ((v + 0.0F) * f10 + f9)).color(red * 0.9F * cr, green * 0.9F * cg, blue * 0.9F * cb, 0.8F).normal(-1.0F, 0.0F, 0.0F).endVertex();
}
}
if (l <= 1) {
for (j1 = 0; j1 < b0; ++j1) {
renderer.pos((x + j1 + 1.0F - f13), (y + 0.0F), (z + b0)).tex(((u + j1 + 0.5F) * f10 + f8), ((v + b0) * f10 + f9)).color(red * 0.9F * cr, green * 0.9F * cg, blue * 0.9F * cb, 0.8F).normal(1.0F, 0.0F, 0.0F).endVertex();
renderer.pos((x + j1 + 1.0F - f13), (y + f3), (z + b0)).tex(((u + j1 + 0.5F) * f10 + f8), ((v + b0) * f10 + f9)).color(red * 0.9F * cr, green * 0.9F * cg, blue * 0.9F * cb, 0.8F).normal(1.0F, 0.0F, 0.0F).endVertex();
renderer.pos((x + j1 + 1.0F - f13), (y + f3), (z + 0.0F)).tex(((u + j1 + 0.5F) * f10 + f8), ((v + 0.0F) * f10 + f9)).color(red * 0.9F * cr, green * 0.9F * cg, blue * 0.9F * cb, 0.8F).normal(1.0F, 0.0F, 0.0F).endVertex();
renderer.pos((x + j1 + 1.0F - f13), (y + 0.0F), (z + 0.0F)).tex(((u + j1 + 0.5F) * f10 + f8), ((v + 0.0F) * f10 + f9)).color(red * 0.9F * cr, green * 0.9F * cg, blue * 0.9F * cb, 0.8F).normal(1.0F, 0.0F, 0.0F).endVertex();
}
}
if (i1 > -1) {
for (j1 = 0; j1 < b0; ++j1) {
renderer.pos((x + 0.0F), (y + f3), (z + j1 + 0.0F)).tex(((u + 0.0F) * f10 + f8), ((v + j1 + 0.5F) * f10 + f9)).color(red * 0.8F * cr, green * 0.8F * cg, blue * 0.8F * cb, 0.8F).normal(0.0F, 0.0F, -1.0F).endVertex();
renderer.pos((x + b0), (y + f3), (z + j1 + 0.0F)).tex(((u + b0) * f10 + f8), ((v + j1 + 0.5F) * f10 + f9)).color(red * 0.8F * cr, green * 0.8F * cg, blue * 0.8F * cb, 0.8F).normal(0.0F, 0.0F, -1.0F).endVertex();
renderer.pos((x + b0), (y + 0.0F), (z + j1 + 0.0F)).tex(((u + b0) * f10 + f8), ((v + j1 + 0.5F) * f10 + f9)).color(red * 0.8F * cr, green * 0.8F * cg, blue * 0.8F * cb, 0.8F).normal(0.0F, 0.0F, -1.0F).endVertex();
renderer.pos((x + 0.0F), (y + 0.0F), (z + j1 + 0.0F)).tex(((u + 0.0F) * f10 + f8), ((v + j1 + 0.5F) * f10 + f9)).color(red * 0.8F * cr, green * 0.8F * cg, blue * 0.8F * cb, 0.8F).normal(0.0F, 0.0F, -1.0F).endVertex();
}
}
if (i1 <= 1) {
for (j1 = 0; j1 < b0; ++j1) {
renderer.pos((x + 0.0F), (y + f3), (z + j1 + 1.0F - f13)).tex(((u + 0.0F) * f10 + f8), ((v + j1 + 0.5F) * f10 + f9)).color(red * 0.8F * cr, green * 0.8F * cg, blue * 0.8F * cb, 0.8F).normal(0.0F, 0.0F, 1.0F).endVertex();
renderer.pos((x + b0), (y + f3), (z + j1 + 1.0F - f13)).tex(((u + b0) * f10 + f8), ((v + j1 + 0.5F) * f10 + f9)).color(red * 0.8F * cr, green * 0.8F * cg, blue * 0.8F * cb, 0.8F).normal(0.0F, 0.0F, 1.0F).endVertex();
renderer.pos((x + b0), (y + 0.0F), (z + j1 + 1.0F - f13)).tex(((u + b0) * f10 + f8), ((v + j1 + 0.5F) * f10 + f9)).color(red * 0.8F * cr, green * 0.8F * cg, blue * 0.8F * cb, 0.8F).normal(0.0F, 0.0F, 1.0F).endVertex();
renderer.pos((x + 0.0F), (y + 0.0F), (z + j1 + 1.0F - f13)).tex(((u + 0.0F) * f10 + f8), ((v + j1 + 0.5F) * f10 + f9)).color(red * 0.8F * cr, green * 0.8F * cg, blue * 0.8F * cb, 0.8F).normal(0.0F, 0.0F, 1.0F).endVertex();
}
}
tessellator.draw();
}
}
}
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.disableBlend();
GlStateManager.enableCull();
}
}
|
package modtweaker2.mods.thaumcraft.handlers;
import static modtweaker2.helpers.InputHelper.toStack;
import static modtweaker2.helpers.InputHelper.toStacks;
import static modtweaker2.helpers.StackHelper.areEqual;
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import modtweaker2.mods.thaumcraft.ThaumcraftHelper;
import modtweaker2.mods.thaumcraft.recipe.MTInfusionRecipe;
import modtweaker2.utils.BaseListAddition;
import modtweaker2.utils.BaseListRemoval;
import modtweaker2.utils.TweakerPlugin;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.item.ItemStack;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import thaumcraft.api.ThaumcraftApi;
import thaumcraft.api.crafting.InfusionEnchantmentRecipe;
import thaumcraft.api.crafting.InfusionRecipe;
@ZenClass("mods.thaumcraft.Infusion")
public class Infusion {
@ZenMethod
public static void addRecipe(String key, IItemStack input, IItemStack[] recipe, String aspects, IItemStack result, int instability) {
if (!TweakerPlugin.hasInit())
MineTweakerAPI.apply(new Add(new InfusionRecipe(key, toStack(result), instability, ThaumcraftHelper.parseAspects(aspects), toStack(input), toStacks(recipe))));
}
// A version that allows you to specify whether the detection should be
// fuzzy or not
@ZenMethod
public static void addRecipe(String key, IItemStack input, IItemStack[] recipe, String aspects, IItemStack result, int instability, boolean fuzzyCentre, boolean[] fuzzyRecipe) {
if (!TweakerPlugin.hasInit())
MineTweakerAPI.apply(new Add(new MTInfusionRecipe(key, toStack(result), instability, ThaumcraftHelper.parseAspects(aspects), toStack(input), toStacks(recipe), fuzzyCentre, fuzzyRecipe)));
}
@ZenMethod
public static void addEnchantment(String key, int enchantID, int instability, String aspects, IItemStack[] recipe) {
if (!TweakerPlugin.hasInit())
MineTweakerAPI.apply(new AddEnchant(new InfusionEnchantmentRecipe(key, Enchantment.enchantmentsList[enchantID], instability, ThaumcraftHelper.parseAspects(aspects), toStacks(recipe))));
}
private static class Add extends BaseListAddition {
public Add(InfusionRecipe recipe) {
super("Thaumcraft Infusion", ThaumcraftApi.getCraftingRecipes(), recipe);
}
@Override
public String getRecipeInfo() {
Object out = ((InfusionRecipe) recipe).getRecipeOutput();
if (out instanceof ItemStack) {
return ((ItemStack) out).getDisplayName();
} else
return super.getRecipeInfo();
}
}
private static class AddEnchant implements IUndoableAction {
InfusionEnchantmentRecipe recipe;
public AddEnchant(InfusionEnchantmentRecipe inp) {
recipe = inp;
}
@Override
public void apply() {
ThaumcraftApi.getCraftingRecipes().add(recipe);
}
@Override
public String describe() {
return "Adding Infusion Enchantment Recipe: " + recipe.enchantment.getName();
}
@Override
public boolean canUndo() {
return recipe != null;
}
@Override
public void undo() {
ThaumcraftApi.getCraftingRecipes().remove(recipe);
}
@Override
public String describeUndo() {
return "Removing Infusion Enchantment Recipe: " + recipe.enchantment.getName();
}
@Override
public String getOverrideKey() {
return null;
}
}
@ZenMethod
public static void removeRecipe(IItemStack output) {
if (!TweakerPlugin.hasInit())
MineTweakerAPI.apply(new Remove(toStack(output)));
}
@ZenMethod
public static void removeEnchant(int id) {
if (!TweakerPlugin.hasInit())
MineTweakerAPI.apply(new RemoveEnchant(Enchantment.enchantmentsList[id]));
}
private static class Remove extends BaseListRemoval {
public Remove(ItemStack stack) {
super("Thaumcraft Infusion", ThaumcraftApi.getCraftingRecipes(), stack);
}
@Override
public void apply() {
for (Object o : ThaumcraftApi.getCraftingRecipes()) {
if (o instanceof InfusionRecipe) {
InfusionRecipe r = (InfusionRecipe) o;
if (r.getRecipeOutput() != null && r.getRecipeOutput() instanceof ItemStack && areEqual((ItemStack) r.getRecipeOutput(), stack)) {
recipes.add(r);
}
}
}
super.apply();
}
@Override
public String getRecipeInfo() {
return stack.getDisplayName();
}
}
private static class RemoveEnchant extends BaseListRemoval {
Enchantment enchant;
public RemoveEnchant(Enchantment ench) {
super("Thaumcraft Infusion Enchantment", ThaumcraftApi.getCraftingRecipes());
enchant = ench;
}
@Override
public void apply() {
for (Object recipe : list) {
if (recipe instanceof InfusionEnchantmentRecipe) {
InfusionEnchantmentRecipe enchRecipe = (InfusionEnchantmentRecipe) recipe;
if (enchRecipe.getEnchantment() == enchant) {
recipes.add(enchRecipe);
}
}
}
super.apply();
}
@Override
public String getRecipeInfo() {
return enchant.getName();
}
}
}
|
package net.darkhax.darkutils.features;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map.Entry;
import net.darkhax.bookshelf.lib.Constants;
import net.darkhax.bookshelf.util.AnnotationUtils;
import net.darkhax.darkutils.handler.ConfigurationHandler;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
public class FeatureManager {
private static final List<Feature> features = new ArrayList<>();
private static boolean loaded = false;
public static void init (ASMDataTable asmDataTable) {
loaded = true;
for (final Entry<Feature, DUFeature> feature : AnnotationUtils.getAnnotations(asmDataTable, DUFeature.class, Feature.class).entrySet()) {
final DUFeature annotation = feature.getValue();
if (annotation == null) {
Constants.LOG.warn("Annotation for " + feature.getKey().getClass().getCanonicalName() + " was null!");
continue;
}
registerFeature(feature.getKey(), annotation.name(), annotation.description());
}
features.sort(new Comparator<Feature>() {
@Override
public int compare(Feature o1, Feature o2) {
return o2.configName.compareTo(o1.configName);
}
});
}
/**
* Registers a new feature with the feature manager. This will automatically create an entry in
* the configuration file to enable/disable this feature. If the feature has been disabled, it
* will not be registered. This will also handle event bus subscriptions.
*
* @param feature The feature being registered.
* @param name The name of the feature.
* @param description A short description of the feature.
*/
public static void registerFeature (Feature feature, String name, String description) {
feature.enabled = ConfigurationHandler.isFeatureEnabled(feature, name, description);
if (feature.enabled) {
feature.configName = name.toLowerCase().replace(' ', '_');
features.add(feature);
if (feature.usesEvents()) {
MinecraftForge.EVENT_BUS.register(feature);
}
}
}
public static boolean isLoaded () {
return loaded;
}
public static List<Feature> getFeatures () {
return features;
}
}
|
package net.fortuna.ical4j.connector.dav;
public abstract class PathResolver {
public static final PathResolver CHANDLER = new ChandlerPathResolver();
public static final PathResolver CGP = new CgpPathResolver();
public static final PathResolver KMS = new KmsPathResolver();
public static final PathResolver ZIMBRA = new ZimbraPathResolver();
/**
* Resolves the path component for a user's calendar store URL.
* @return
*/
public abstract String getUserPath(String username);
/**
* Resolves the path component for a principal URL.
* @return
*/
public abstract String getPrincipalPath(String username);
private static class ChandlerPathResolver extends PathResolver {
/* (non-Javadoc)
* @see net.fortuna.ical4j.connector.dav.PathResolver#getPrincipalPath(java.lang.String)
*/
@Override
public String getPrincipalPath(String username) {
return "/chandler/dav/users/" + username;
}
/* (non-Javadoc)
* @see net.fortuna.ical4j.connector.dav.PathResolver#getUserPath(java.lang.String)
*/
@Override
public String getUserPath(String username) {
return "/chandler/dav/" + username + "/";
}
}
private static class CgpPathResolver extends PathResolver {
/* (non-Javadoc)
* @see net.fortuna.ical4j.connector.dav.PathResolver#getPrincipalPath(java.lang.String)
*/
@Override
public String getPrincipalPath(String username) {
return "/CalDAV/";
}
/* (non-Javadoc)
* @see net.fortuna.ical4j.connector.dav.PathResolver#getUserPath(java.lang.String)
*/
@Override
public String getUserPath(String arg0) {
// TODO Auto-generated method stub
return null;
}
}
private static class KmsPathResolver extends PathResolver {
/* (non-Javadoc)
* @see net.fortuna.ical4j.connector.dav.PathResolver#getPrincipalPath(java.lang.String)
*/
@Override
public String getPrincipalPath(String username) {
return "/caldav/";
}
/* (non-Javadoc)
* @see net.fortuna.ical4j.connector.dav.PathResolver#getUserPath(java.lang.String)
*/
@Override
public String getUserPath(String arg0) {
// TODO Auto-generated method stub
return null;
}
}
private static class ZimbraPathResolver extends PathResolver {
/* (non-Javadoc)
* @see net.fortuna.ical4j.connector.dav.PathResolver#getPrincipalPath(java.lang.String)
*/
@Override
public String getPrincipalPath(String username) {
return "/principals/users/" + username + "/";
}
/* (non-Javadoc)
* @see net.fortuna.ical4j.connector.dav.PathResolver#getUserPath(java.lang.String)
*/
@Override
public String getUserPath(String username) {
return "/dav/" + username + "/";
}
}
}
|
package net.minecraftforge.gradle.user;
import static net.minecraftforge.gradle.common.Constants.ASSETS;
import static net.minecraftforge.gradle.common.Constants.FERNFLOWER;
import static net.minecraftforge.gradle.common.Constants.JAR_CLIENT_FRESH;
import static net.minecraftforge.gradle.common.Constants.JAR_MERGED;
import static net.minecraftforge.gradle.common.Constants.JAR_SERVER_FRESH;
import static net.minecraftforge.gradle.user.UserConstants.ASTYLE_CFG;
import static net.minecraftforge.gradle.user.UserConstants.CLASSIFIER_DECOMPILED;
import static net.minecraftforge.gradle.user.UserConstants.CLASSIFIER_DEOBF_SRG;
import static net.minecraftforge.gradle.user.UserConstants.CLASSIFIER_SOURCES;
import static net.minecraftforge.gradle.user.UserConstants.CONFIG_DEPS;
import static net.minecraftforge.gradle.user.UserConstants.CONFIG_MC;
import static net.minecraftforge.gradle.user.UserConstants.CONFIG_NATIVES;
import static net.minecraftforge.gradle.user.UserConstants.CONFIG_USERDEV;
import static net.minecraftforge.gradle.user.UserConstants.DEOBF_MCP_SRG;
import static net.minecraftforge.gradle.user.UserConstants.DEOBF_SRG_SRG;
import static net.minecraftforge.gradle.user.UserConstants.DIRTY_DIR;
import static net.minecraftforge.gradle.user.UserConstants.EXC_JSON;
import static net.minecraftforge.gradle.user.UserConstants.EXC_MCP;
import static net.minecraftforge.gradle.user.UserConstants.EXC_SRG;
import static net.minecraftforge.gradle.user.UserConstants.FIELD_CSV;
import static net.minecraftforge.gradle.user.UserConstants.MCP_PATCH_DIR;
import static net.minecraftforge.gradle.user.UserConstants.MERGE_CFG;
import static net.minecraftforge.gradle.user.UserConstants.METHOD_CSV;
import static net.minecraftforge.gradle.user.UserConstants.NATIVES_DIR;
import static net.minecraftforge.gradle.user.UserConstants.PACKAGED_EXC;
import static net.minecraftforge.gradle.user.UserConstants.PACKAGED_SRG;
import static net.minecraftforge.gradle.user.UserConstants.PARAM_CSV;
import static net.minecraftforge.gradle.user.UserConstants.RECOMP_CLS_DIR;
import static net.minecraftforge.gradle.user.UserConstants.RECOMP_SRC_DIR;
import static net.minecraftforge.gradle.user.UserConstants.REOBF_NOTCH_SRG;
import static net.minecraftforge.gradle.user.UserConstants.REOBF_SRG;
import static net.minecraftforge.gradle.user.UserConstants.SOURCES_DIR;
import groovy.lang.Closure;
import groovy.util.Node;
import groovy.util.XmlParser;
import groovy.xml.XmlUtil;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import joptsimple.internal.Strings;
import net.minecraftforge.gradle.common.BasePlugin;
import net.minecraftforge.gradle.delayed.DelayedFile;
import net.minecraftforge.gradle.json.JsonFactory;
import net.minecraftforge.gradle.tasks.CopyAssetsTask;
import net.minecraftforge.gradle.tasks.DecompileTask;
import net.minecraftforge.gradle.tasks.ExtractConfigTask;
import net.minecraftforge.gradle.tasks.GenSrgTask;
import net.minecraftforge.gradle.tasks.MergeJarsTask;
import net.minecraftforge.gradle.tasks.ProcessJarTask;
import net.minecraftforge.gradle.tasks.RemapSourcesTask;
import net.minecraftforge.gradle.tasks.abstractutil.ExtractTask;
import net.minecraftforge.gradle.tasks.user.SourceCopyTask;
import net.minecraftforge.gradle.tasks.user.reobf.ArtifactSpec;
import net.minecraftforge.gradle.tasks.user.reobf.ReobfTask;
import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.XmlProvider;
import org.gradle.api.artifacts.Configuration.State;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.execution.TaskExecutionGraph;
import org.gradle.api.internal.plugins.DslObject;
import org.gradle.api.logging.Logger;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.GroovySourceSet;
import org.gradle.api.tasks.JavaExec;
import org.gradle.api.tasks.ScalaSourceSet;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.bundling.Jar;
import org.gradle.api.tasks.bundling.Zip;
import org.gradle.api.tasks.compile.GroovyCompile;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.api.tasks.scala.ScalaCompile;
import org.gradle.listener.ActionBroadcast;
import org.gradle.plugins.ide.eclipse.model.Classpath;
import org.gradle.plugins.ide.eclipse.model.ClasspathEntry;
import org.gradle.plugins.ide.eclipse.model.EclipseModel;
import org.gradle.plugins.ide.eclipse.model.Library;
import org.gradle.plugins.ide.idea.model.IdeaModel;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
public abstract class UserBasePlugin<T extends UserExtension> extends BasePlugin<T>
{
@SuppressWarnings("serial")
@Override
public void applyPlugin()
{
this.applyExternalPlugin("java");
this.applyExternalPlugin("maven");
this.applyExternalPlugin("eclipse");
this.applyExternalPlugin("idea");
hasScalaBefore = project.getPlugins().hasPlugin("scala");
hasGroovyBefore = project.getPlugins().hasPlugin("groovy");
configureDeps();
configureCompilation();
fixEclipseNatives();
configureIntellij();
// create basic tasks.
tasks();
// create lifecycle tasks.
Task task = makeTask("setupCIWorkspace", DefaultTask.class);
task.dependsOn("genSrgs", "deobfBinJar");
task.setDescription("Sets up the bare minimum to build a minecraft mod. Idea for CI servers");
task.setGroup("ForgeGradle");
//configureCISetup(task);
task = makeTask("setupDevWorkspace", DefaultTask.class);
task.dependsOn("genSrgs", "deobfBinJar", "copyAssets", "extractNatives");
task.setDescription("CIWorkspace + natives and assets to run and test Minecraft");
task.setGroup("ForgeGradle");
//configureDevSetup(task);
task = makeTask("setupDecompWorkspace", DefaultTask.class);
task.dependsOn("genSrgs", "copyAssets", "extractNatives", "repackMinecraft");
task.setDescription("DevWorkspace + the deobfuscated Minecraft source linked as a source jar.");
task.setGroup("ForgeGradle");
//configureDecompSetup(task);
project.getGradle().getTaskGraph().whenReady(new Closure<Object>(this, null) {
@Override
public Object call()
{
TaskExecutionGraph graph = project.getGradle().getTaskGraph();
String path = project.getPath();
if (graph.hasTask(path + "setupDecompWorkspace"))
{
getExtension().setDecomp();
setMinecraftDeps(true, false);
}
return null;
}
@Override
public Object call(Object obj)
{
return call();
}
@Override
public Object call(Object... obj)
{
return call();
}
});
}
private boolean hasAppliedJson = false;
private boolean hasScalaBefore = false;
private boolean hasGroovyBefore = false;
/**
* may not include delayed tokens.
*/
public abstract String getApiName();
/**
* Name of the source dependency. eg: forgeSrc
* may not include delayed tokens.
*/
protected abstract String getSrcDepName();
/**
* Name of the source dependency. eg: forgeBin
* may not include delayed tokens.
*/
protected abstract String getBinDepName();
/**
* May invoke the extension object, or be hardcoded.
* may not include delayed tokens.
*/
protected abstract boolean hasApiVersion();
/**
* May invoke the extension object, or be hardcoded.
* may not include delayed tokens.
*/
protected abstract String getApiVersion(T exten);
/**
* May invoke the extension object, or be hardcoded.
* may not include delayed tokens.
*/
protected abstract String getMcVersion(T exten);
/**
* May invoke the extension object, or be hardcoded.
* This unlike the others, is evaluated as a delayed file, and may contain various tokens including:
* {API_NAME} {API_VERSION} {MC_VERSION}
*/
protected abstract String getApiCacheDir(T exten);
/**
* May invoke the extension object, or be hardcoded.
* This unlike the others, is evaluated as a delayed file, and may contain various tokens including:
* {API_NAME} {API_VERSION} {MC_VERSION}
*/
protected abstract String getSrgCacheDir(T exten);
/**
* May invoke the extension object, or be hardcoded.
* This unlike the others, is evaluated as a delayed file, and may contain various tokens including:
* {API_NAME} {API_VERSION} {MC_VERSION}
*/
protected abstract String getUserDevCacheDir(T exten);
/**
* This unlike the others, is evaluated as a delayed string, and may contain various tokens including:
* {API_NAME} {API_VERSION} {MC_VERSION}
*/
protected abstract String getUserDev();
/**
* For run configurations
*/
protected abstract String getClientRunClass();
/**
* For run configurations
*/
protected abstract Iterable<String> getClientRunArgs();
/**
* For run configurations
*/
protected abstract String getServerRunClass();
/**
* For run configurations
*/
protected abstract Iterable<String> getServerRunArgs();
// protected abstract void configureCISetup(Task task);
// protected abstract void configureDevSetup(Task task);
// protected abstract void configureDecompSetup(Task task);
@Override
public String resolve(String pattern, Project project, T exten)
{
pattern = pattern.replace("{USER_DEV}", this.getUserDevCacheDir(exten));
pattern = pattern.replace("{SRG_DIR}", this.getSrgCacheDir(exten));
pattern = pattern.replace("{API_CACHE_DIR}", this.getApiCacheDir(exten));
pattern = pattern.replace("{MC_VERSION}", getMcVersion(exten));
pattern = super.resolve(pattern, project, exten);
if (hasApiVersion())
pattern = pattern.replace("{API_VERSION}", getApiVersion(exten));
pattern = pattern.replace("{API_NAME}", getApiName());
return pattern;
}
protected void configureDeps()
{
// create configs
project.getConfigurations().create(CONFIG_USERDEV);
project.getConfigurations().create(CONFIG_NATIVES);
project.getConfigurations().create(CONFIG_DEPS);
project.getConfigurations().create(CONFIG_MC);
// special userDev stuff
ExtractConfigTask extractUserDev = makeTask("extractUserDev", ExtractConfigTask.class);
extractUserDev.setOut(delayedFile("{USER_DEV}"));
extractUserDev.setConfig(CONFIG_USERDEV);
extractUserDev.setDoesCache(true);
extractUserDev.doLast(new Action<Task>()
{
@Override
public void execute(Task arg0)
{
readAndApplyJson(getDevJson().call(), CONFIG_DEPS, CONFIG_NATIVES, arg0.getLogger());
}
});
project.getTasks().findByName("getAssetsIndex").dependsOn("extractUserDev");
// special native stuff
ExtractConfigTask extractNatives = makeTask("extractNatives", ExtractConfigTask.class);
extractNatives.setOut(delayedFile(NATIVES_DIR));
extractNatives.setConfig(CONFIG_NATIVES);
/**
* This mod adds the API sourceSet, and correctly configures the
*/
protected void configureCompilation()
{
// get conventions
JavaPluginConvention javaConv = (JavaPluginConvention) project.getConvention().getPlugins().get("java");
SourceSet main = javaConv.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME);
SourceSet test = javaConv.getSourceSets().getByName(SourceSet.TEST_SOURCE_SET_NAME);
SourceSet api = javaConv.getSourceSets().create("api");
// set the Source
javaConv.setSourceCompatibility("1.6");
javaConv.setTargetCompatibility("1.6");
main.setCompileClasspath(main.getCompileClasspath().plus(api.getOutput()));
test.setCompileClasspath(test.getCompileClasspath().plus(api.getOutput()));
project.getConfigurations().getByName("apiCompile").extendsFrom(project.getConfigurations().getByName("compile"));
project.getConfigurations().getByName("testCompile").extendsFrom(project.getConfigurations().getByName("apiCompile"));
}
private void readAndApplyJson(File file, String depConfig, String nativeConfig, Logger log)
{
if (version == null)
{
try
{
version = JsonFactory.loadVersion(file);
}
catch (Exception e)
{
log.error("" + file + " could not be parsed");
Throwables.propagate(e);
}
}
if (hasAppliedJson)
return;
// apply the dep info.
DependencyHandler handler = project.getDependencies();
// actual dependencies
if (project.getConfigurations().getByName(depConfig).getState() == State.UNRESOLVED)
{
for (net.minecraftforge.gradle.json.version.Library lib : version.getLibraries())
{
if (lib.natives == null)
handler.add(depConfig, lib.getArtifactName());
}
}
else
log.info("RESOLVED: " + depConfig);
// the natives
if (project.getConfigurations().getByName(nativeConfig).getState() == State.UNRESOLVED)
{
for (net.minecraftforge.gradle.json.version.Library lib : version.getLibraries())
{
if (lib.natives != null)
handler.add(nativeConfig, lib.getArtifactName());
}
}
else
log.info("RESOLVED: " + nativeConfig);
hasAppliedJson = true;
}
@SuppressWarnings({ "unchecked" })
protected void fixEclipseNatives()
{
EclipseModel eclipseConv = (EclipseModel) project.getExtensions().getByName("eclipse");
eclipseConv.getClasspath().setDownloadJavadoc(true);
eclipseConv.getClasspath().setDownloadSources(true);
((ActionBroadcast<Classpath>) eclipseConv.getClasspath().getFile().getWhenMerged()).add(new Action<Classpath>()
{
@Override
public void execute(Classpath classpath)
{
String natives = delayedString(NATIVES_DIR).call().replace('\\', '/');
for (ClasspathEntry e : classpath.getEntries())
{
if (e instanceof Library)
{
Library lib = (Library) e;
if (lib.getPath().contains("lwjg") || lib.getPath().contains("jinput"))
{
lib.setNativeLibraryLocation(natives);
}
}
}
}
});
Task task = makeTask("afterEclipseImport", DefaultTask.class);
task.doLast(new Action<Object>() {
public void execute(Object obj)
{
try
{
Node root = new XmlParser().parseText(Files.toString(project.file(".classpath"), Charset.defaultCharset()));
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", "org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY");
map.put("value", delayedString(NATIVES_DIR).call());
for (Node child : (List<Node>) root.children())
{
if (child.attribute("path").equals("org.springsource.ide.eclipse.gradle.classpathcontainer"))
{
child.appendNode("attributes").appendNode("attribute", map);
break;
}
}
String result = XmlUtil.serialize(root);
project.getLogger().lifecycle(result);
Files.write(result, project.file(".classpath"), Charset.defaultCharset());
}
catch (Exception e)
{
e.printStackTrace();
return;
}
}
});
}
@SuppressWarnings("serial")
protected void configureIntellij()
{
IdeaModel ideaConv = (IdeaModel) project.getExtensions().getByName("idea");
ideaConv.getModule().getExcludeDirs().addAll(project.files(".gradle", "build", ".idea").getFiles());
ideaConv.getModule().setDownloadJavadoc(true);
ideaConv.getModule().setDownloadSources(true);
Task task = makeTask("genIntellijRuns", DefaultTask.class);
task.doLast(new Action<Task>() {
@Override
public void execute(Task task)
{
try
{
String module = task.getProject().getProjectDir().getCanonicalPath();
File file = project.file(".idea/workspace.xml");
if (!file.exists())
throw new RuntimeException("Only run this task after importing a build.gradle file into intellij!");
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
injectIntellijRuns(doc, module);
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
//StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
if (ideaConv.getWorkspace().getIws() == null)
return;
ideaConv.getWorkspace().getIws().withXml(new Closure<Object>(this, null)
{
public Object call(Object... obj)
{
Element root = ((XmlProvider) this.getDelegate()).asElement();
Document doc = root.getOwnerDocument();
try
{
injectIntellijRuns(doc, project.getProjectDir().getCanonicalPath());
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
});
}
public final void injectIntellijRuns(Document doc, String module) throws DOMException, IOException
{
Element root = null;
{
NodeList list = doc.getElementsByTagName("component");
for (int i = 0; i < list.getLength(); i++)
{
Element e = (Element) list.item(i);
if ("RunManager".equals(e.getAttribute("name")))
{
root = e;
break;
}
}
}
String natives = delayedFile(NATIVES_DIR).call().getCanonicalPath().replace(module, "$PROJECT_DIR$");
String[][] config = new String[][]
{
new String[]
{
"Minecraft Client",
getClientRunClass(),
"-Xincgc -Xmx1024M -Xms1024M -Djava.library.path=\"" + natives + "\" -Dfml.ignoreInvalidMinecraftCertificates=true",
Joiner.on(' ').join(getClientRunArgs())
},
new String[]
{
"Minecraft Server",
getServerRunClass(),
"-Xincgc -Dfml.ignoreInvalidMinecraftCertificates=true",
Joiner.on(' ').join(getServerRunArgs())
}
};
for (String[] data : config)
{
Element child = add(root, "configuration",
"default", "false",
"name", data[0],
"type", "Application",
"factoryName", "Application",
"default", "false");
add(child, "extension",
"name", "coverage",
"enabled", "false",
"sample_coverage", "true",
"runner", "idea");
add(child, "option", "name", "MAIN_CLASS_NAME", "value", data[1]);
add(child, "option", "name", "VM_PARAMETERS", "value", data[2]);
add(child, "option", "name", "PROGRAM_PARAMETERS", "value", data[3]);
add(child, "option", "name", "WORKING_DIRECTORY", "value", "file://" + delayedFile("{ASSET_DIR}").call().getParentFile().getCanonicalPath().replace(module, "$PROJECT_DIR$"));
add(child, "option", "name", "ALTERNATIVE_JRE_PATH_ENABLED", "value", "false");
add(child, "option", "name", "ALTERNATIVE_JRE_PATH", "value", "");
add(child, "option", "name", "ENABLE_SWING_INSPECTOR", "value", "false");
add(child, "option", "name", "ENV_VARIABLES");
add(child, "option", "name", "PASS_PARENT_ENVS", "value", "true");
add(child, "module", "name", ((IdeaModel) project.getExtensions().getByName("idea")).getModule().getName());
add(child, "envs");
add(child, "RunnerSettings", "RunnerId", "Run");
add(child, "ConfigurationWrapper", "RunnerId", "Run");
add(child, "method");
}
}
private Element add(Element parent, String name, String... values)
{
Element e = parent.getOwnerDocument().createElement(name);
for (int x = 0; x < values.length; x += 2)
{
e.setAttribute(values[x], values[x + 1]);
}
parent.appendChild(e);
return e;
}
private void tasks()
{
{
CopyAssetsTask task = makeTask("copyAssets", CopyAssetsTask.class);
task.setAssetsDir(delayedFile(ASSETS));
task.setOutputDir(delayedFile("{ASSET_DIR}"));
task.setAssetIndex(getAssetIndexClosure());
task.dependsOn("getAssets");
}
{
GenSrgTask task = makeTask("genSrgs", GenSrgTask.class);
task.setInSrg(delayedFile(PACKAGED_SRG));
task.setInExc(delayedFile(PACKAGED_EXC));
task.setMethodsCsv(delayedFile(METHOD_CSV));
task.setFieldsCsv(delayedFile(FIELD_CSV));
task.setNotchToSrg(delayedFile(DEOBF_SRG_SRG));
task.setNotchToMcp(delayedFile(DEOBF_MCP_SRG));
task.setMcpToSrg(delayedFile(REOBF_SRG));
task.setMcpToNotch(delayedFile(REOBF_NOTCH_SRG));
task.setSrgExc(delayedFile(EXC_SRG));
task.setMcpExc(delayedFile(EXC_MCP));
task.dependsOn("extractUserDev");
}
{
MergeJarsTask task = makeTask("mergeJars", MergeJarsTask.class);
task.setClient(delayedFile(JAR_CLIENT_FRESH));
task.setServer(delayedFile(JAR_SERVER_FRESH));
task.setOutJar(delayedFile(JAR_MERGED));
task.setMergeCfg(delayedFile(MERGE_CFG));
task.dependsOn("extractUserDev", "downloadClient", "downloadServer");
}
{
String name = getBinDepName() + "-" + (hasApiVersion() ? "{API_VERSION}" : "{MC_VERSION}") + ".jar";
ProcessJarTask task = makeTask("deobfBinJar", ProcessJarTask.class);
task.setSrg(delayedFile(DEOBF_MCP_SRG));
task.setExceptorJson(delayedFile(EXC_JSON));
task.setExceptorCfg(delayedFile(EXC_MCP));
task.setFieldCsv(delayedFile(FIELD_CSV));
task.setMethodCsv(delayedFile(METHOD_CSV));
task.setInJar(delayedFile(JAR_MERGED));
task.setOutCleanJar(delayedFile("{API_CACHE_DIR}/" + name));
task.setOutDirtyJar(delayedFile(DIRTY_DIR + "/" + name));
task.setApplyMarkers(false);
task.setStripSynthetics(true);
configureDeobfuscation(task);
task.dependsOn("downloadMcpTools", "mergeJars", "genSrgs");
}
{
String name = "{API_NAME}-" + (hasApiVersion() ? "{API_VERSION}" : "{MC_VERSION}") + "-"+ CLASSIFIER_DEOBF_SRG +".jar";
ProcessJarTask task = makeTask("deobfuscateJar", ProcessJarTask.class);
task.setSrg(delayedFile(DEOBF_SRG_SRG));
task.setExceptorJson(delayedFile(EXC_JSON));
task.setExceptorCfg(delayedFile(EXC_SRG));
task.setInJar(delayedFile(JAR_MERGED));
task.setOutCleanJar(delayedFile("{API_CACHE_DIR}/" + name));
task.setOutDirtyJar(delayedFile(DIRTY_DIR + "/" + name));
task.setApplyMarkers(true);
configureDeobfuscation(task);
task.dependsOn("downloadMcpTools", "mergeJars", "genSrgs");
}
{
ReobfTask task = makeTask("reobf", ReobfTask.class);
task.dependsOn("genSrgs");
task.setExceptorCfg(delayedFile(EXC_SRG));
task.setSrg(delayedFile(REOBF_SRG));
task.setFieldCsv(delayedFile(FIELD_CSV));
task.setFieldCsv(delayedFile(METHOD_CSV));
task.reobf(project.getTasks().getByName("jar"), new Action<ArtifactSpec>()
{
@Override
public void execute(ArtifactSpec arg0)
{
JavaPluginConvention javaConv = (JavaPluginConvention) project.getConvention().getPlugins().get("java");
arg0.setClasspath(javaConv.getSourceSets().getByName("main").getCompileClasspath());
}
});
task.mustRunAfter("test");
project.getTasks().getByName("assemble").dependsOn(task);
project.getTasks().getByName("uploadArchives").dependsOn(task);
}
createPostDecompTasks();
createExecTasks();
createSourceCopyTasks();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private final void createPostDecompTasks()
{
DelayedFile decompOut = delayedDirtyFile(null, CLASSIFIER_DECOMPILED, "jar");
DelayedFile remapped = delayedDirtyFile(getSrcDepName(), CLASSIFIER_SOURCES, "jar");
final DelayedFile recomp = delayedDirtyFile(getSrcDepName(), null, "jar");
final DelayedFile recompSrc = delayedFile(RECOMP_SRC_DIR);
final DelayedFile recompCls = delayedFile(RECOMP_CLS_DIR);
DecompileTask decomp = makeTask("decompile", DecompileTask.class);
{
decomp.setInJar(delayedDirtyFile(null, CLASSIFIER_DEOBF_SRG, "jar"));
decomp.setOutJar(decompOut);
decomp.setFernFlower(delayedFile(FERNFLOWER));
decomp.setPatch(delayedFile(MCP_PATCH_DIR));
decomp.setAstyleConfig(delayedFile(ASTYLE_CFG));
decomp.dependsOn("downloadMcpTools", "deobfuscateJar", "genSrgs");
}
// Remap to MCP names
RemapSourcesTask remap = makeTask("remapJar", RemapSourcesTask.class);
{
remap.setInJar(decompOut);
remap.setOutJar(remapped);
remap.setFieldsCsv(delayedFile(FIELD_CSV));
remap.setMethodsCsv(delayedFile(METHOD_CSV));
remap.setParamsCsv(delayedFile(PARAM_CSV));
remap.setDoesJavadocs(true);
remap.dependsOn(decomp);
}
Spec onlyIfCheck = new Spec() {
@Override
public boolean isSatisfiedBy(Object obj)
{
boolean didWork = ((Task) obj).dependsOnTaskDidWork();
boolean exists = recomp.call().exists();
if (!exists)
return true;
else
return didWork;
}
};
ExtractTask extract = makeTask("extractMinecraftSrc", ExtractTask.class);
{
extract.from(remapped);
extract.into(recompSrc);
extract.setIncludeEmptyDirs(false);
extract.dependsOn(remap);
extract.onlyIf(onlyIfCheck);
}
JavaCompile recompTask = makeTask("recompMinecraft", JavaCompile.class);
{
recompTask.setSource(recompSrc);
recompTask.setSourceCompatibility("1.6");
recompTask.setTargetCompatibility("1.6");
recompTask.setClasspath(project.getConfigurations().getByName(CONFIG_DEPS));
recompTask.dependsOn(extract);
recompTask.onlyIf(onlyIfCheck);
}
Jar repackageTask = makeTask("repackMinecraft", Jar.class);
{
repackageTask.from(recompSrc);
repackageTask.from(recompCls);
repackageTask.exclude("*.java", "**/*.java", "**.java");
repackageTask.dependsOn(recompTask);
// file output configuration done in the delayed configuration.
repackageTask.onlyIf(onlyIfCheck);
}
}
private final void createExecTasks()
{
JavaExec exec = makeTask("runClient", JavaExec.class);
{
exec.setMain(getClientRunClass());
exec.jvmArgs("-Xincgc", "-Xmx1024M", "-Xms1024M", "-Dfml.ignoreInvalidMinecraftCertificates=true");
exec.args(getClientRunArgs());
exec.workingDir(delayedFile("{ASSET_DIR}/.."));
exec.setStandardOutput(System.out);
exec.setErrorOutput(System.err);
exec.setGroup("ForgeGradle");
exec.setDescription("Runs the Minecraft client");
}
exec = makeTask("runServer", JavaExec.class);
{
exec.setMain(getServerRunClass());
exec.jvmArgs("-Xincgc", "-Dfml.ignoreInvalidMinecraftCertificates=true");
exec.workingDir(delayedFile("{ASSET_DIR}/.."));
exec.args(getServerRunArgs());
exec.setStandardOutput(System.out);
exec.setStandardInput(System.in);
exec.setErrorOutput(System.err);
exec.setGroup("ForgeGradle");
exec.setDescription("Runs the Minecraft Server");
}
exec = makeTask("debugClient", JavaExec.class);
{
exec.setMain(getClientRunClass());
exec.jvmArgs("-Xincgc", "-Xmx1024M", "-Xms1024M", "-Dfml.ignoreInvalidMinecraftCertificates=true");
exec.args(getClientRunArgs());
exec.workingDir(delayedFile("{ASSET_DIR}/.."));
exec.setStandardOutput(System.out);
exec.setErrorOutput(System.err);
exec.setDebug(true);
exec.setGroup("ForgeGradle");
exec.setDescription("Runs the Minecraft client in debug mode");
}
exec = makeTask("debugServer", JavaExec.class);
{
exec.setMain(getServerRunClass());
exec.jvmArgs("-Xincgc", "-Dfml.ignoreInvalidMinecraftCertificates=true");
exec.workingDir(delayedFile("{ASSET_DIR}/.."));
exec.args(getServerRunArgs());
exec.setStandardOutput(System.out);
exec.setStandardInput(System.in);
exec.setErrorOutput(System.err);
exec.setDebug(true);
exec.setGroup("ForgeGradle");
exec.setDescription("Runs the Minecraft serevr in debug mode");
}
}
private final void createSourceCopyTasks()
{
JavaPluginConvention javaConv = (JavaPluginConvention) project.getConvention().getPlugins().get("java");
SourceSet main = javaConv.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME);
// do the special source moving...
SourceCopyTask task;
// main
{
DelayedFile dir = delayedFile(SOURCES_DIR + "/java");
task = makeTask("sourceMainJava", SourceCopyTask.class);
task.setSource(main.getJava());
task.setOutput(dir);
JavaCompile compile = (JavaCompile) project.getTasks().getByName(main.getCompileJavaTaskName());
compile.dependsOn("sourceMainJava");
compile.setSource(dir);
}
// scala!!!
if (project.getPlugins().hasPlugin("scala"))
{
ScalaSourceSet set = (ScalaSourceSet) new DslObject(main).getConvention().getPlugins().get("scala");
DelayedFile dir = delayedFile(SOURCES_DIR + "/scala");
task = makeTask("sourceMainScala", SourceCopyTask.class);
task.setSource(set.getScala());
task.setOutput(dir);
ScalaCompile compile = (ScalaCompile) project.getTasks().getByName(main.getCompileTaskName("scala"));
compile.dependsOn("sourceMainScala");
compile.setSource(dir);
}
// groovy!!!
if (project.getPlugins().hasPlugin("groovy"))
{
GroovySourceSet set = (GroovySourceSet) new DslObject(main).getConvention().getPlugins().get("groovy");
DelayedFile dir = delayedFile(SOURCES_DIR + "/groovy");
task = makeTask("sourceMainGroovy", SourceCopyTask.class);
task.setSource(set.getGroovy());
task.setOutput(dir);
GroovyCompile compile = (GroovyCompile) project.getTasks().getByName(main.getCompileTaskName("groovy"));
compile.dependsOn("sourceMainGroovy");
compile.setSource(dir);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public final void afterEvaluate()
{
super.afterEvaluate();
{
String version = getMcVersion(getExtension());
if (hasApiVersion())
version = getApiVersion(getExtension());
doVersionChecks(version);
}
// ensure plugin application sequence.. groovy or scala or wtvr first, then the forge/fml/liteloader plugins
if (!hasScalaBefore && project.getPlugins().hasPlugin("scala"))
throw new RuntimeException(delayedString("You have applied the 'scala' plugin after '{API_NAME}', you must apply it before.").call());
if (!hasGroovyBefore && project.getPlugins().hasPlugin("groovy"))
throw new RuntimeException(delayedString("You have applied the 'groovy' plugin after '{API_NAME}', you must apply it before.").call());
project.getDependencies().add(CONFIG_USERDEV, delayedString(getUserDev()).call() + ":userdev");
// grab the json && read dependencies
if (getDevJson().call().exists())
{
readAndApplyJson(getDevJson().call(), CONFIG_DEPS, CONFIG_NATIVES, project.getLogger());
}
delayedTaskConfig();
// add MC repo.
final String repoDir = delayedDirtyFile("this", "doesnt", "matter").call().getParentFile().getAbsolutePath();
project.allprojects(new Action<Project>() {
public void execute(Project proj)
{
addFlatRepo(proj, getApiName()+"FlatRepo", repoDir);
proj.getLogger().info("Adding repo to " + proj.getPath() + " >> " + repoDir);
}
});
// check for decompilation status.. has decompiled or not etc
final File decompFile = delayedDirtyFile(getSrcDepName(), CLASSIFIER_SOURCES, "jar").call();
if (decompFile.exists())
{
getExtension().setDecomp();
}
// post decompile status thing.
configurePostDecomp(getExtension().isDecomp());
{
// stop getting empty dirs
Action act = new Action() {
@Override
public void execute(Object arg0)
{
Zip task = (Zip) arg0;
task.setIncludeEmptyDirs(false);
}
};
project.getTasks().withType(Jar.class, act);
project.getTasks().withType(Zip.class, act);
}
}
/**
* Allows for the configuration of tasks in AfterEvaluate
*/
protected void delayedTaskConfig()
{
// add extraSRG lines to reobf task
((ReobfTask) project.getTasks().getByName("reobf")).setExtraSrg(getExtension().getSrgExtra());
// configure output of recompile task
{
JavaCompile compile = (JavaCompile) project.getTasks().getByName("recompMinecraft");
compile.setDestinationDir(delayedFile(RECOMP_CLS_DIR).call());
}
// configure output of repackage task.
{
Jar repackageTask = (Jar) project.getTasks().getByName("repackMinecraft");
final DelayedFile recomp = delayedDirtyFile(getSrcDepName(), null, "jar");
//done in the delayed configuration.
File out = recomp.call();
repackageTask.setArchiveName(out.getName());
repackageTask.setDestinationDir(out.getParentFile());
}
// Add the mod and stuff to the classpath of the exec tasks.
final Jar jarTask = (Jar) project.getTasks().getByName("jar");
JavaExec exec = (JavaExec) project.getTasks().getByName("runClient");
{
exec.jvmArgs("-Djava.library.path=" + delayedFile(NATIVES_DIR).call().getAbsolutePath());
exec.classpath(project.getConfigurations().getByName("runtime"));
exec.classpath(jarTask.getArchivePath());
exec.dependsOn(jarTask);
}
exec = (JavaExec) project.getTasks().getByName("runServer");
{
exec.classpath(project.getConfigurations().getByName("runtime"));
exec.classpath(jarTask.getArchivePath());
exec.dependsOn(jarTask);
}
exec = (JavaExec) project.getTasks().getByName("debugClient");
{
exec.jvmArgs("-Djava.library.path=" + delayedFile(NATIVES_DIR).call().getAbsolutePath());
exec.classpath(project.getConfigurations().getByName("runtime"));
exec.classpath(jarTask.getArchivePath());
exec.dependsOn(jarTask);
}
exec = (JavaExec) project.getTasks().getByName("debugServer");
{
exec.classpath(project.getConfigurations().getByName("runtime"));
exec.classpath(jarTask.getArchivePath());
exec.dependsOn(jarTask);
}
// configure source replacement.
for (SourceCopyTask t : project.getTasks().withType(SourceCopyTask.class))
{
t.replace(getExtension().getReplacements());
t.include(getExtension().getIncludes());
}
}
/**
* Configure tasks and stuff after you know if the decomp file exists or not.
*/
protected void configurePostDecomp(boolean decomp)
{
if (decomp)
{
((ReobfTask) project.getTasks().getByName("reobf")).setDeobfFile(((ProcessJarTask) project.getTasks().getByName("deobfuscateJar")).getDelayedOutput());
((ReobfTask) project.getTasks().getByName("reobf")).setRecompFile(delayedDirtyFile(getSrcDepName(), null, "jar"));
}
else
{
(project.getTasks().getByName("compileJava")).dependsOn("deobfBinJar");
(project.getTasks().getByName("compileApiJava")).dependsOn("deobfBinJar");
}
setMinecraftDeps(decomp, false);
}
protected void setMinecraftDeps(boolean decomp, boolean remove)
{
String version = getMcVersion(getExtension());
if (hasApiVersion())
version = getApiVersion(getExtension());
if (decomp)
{
project.getDependencies().add(CONFIG_MC, ImmutableMap.of("name", getSrcDepName(), "version", version));
if (remove)
{
project.getConfigurations().getByName(CONFIG_MC).exclude(ImmutableMap.of("module", getBinDepName()));
}
}
else
{
project.getDependencies().add(CONFIG_MC, ImmutableMap.of("name", getBinDepName(), "version", version));
if (remove)
{
project.getConfigurations().getByName(CONFIG_MC).exclude(ImmutableMap.of("module", getSrcDepName()));
}
}
}
/**
* Add Forge/FML ATs here.
* This happens during normal evaluation, and NOT AfterEvaluate.
*/
protected abstract void configureDeobfuscation(ProcessJarTask task);
protected abstract void doVersionChecks(String version);
/**
* Returns a file in the DirtyDir if the deobfusctaion task is dirty. Otherwise returns the cached one.
* @param classifier
* @param ext
* @return
*/
@SuppressWarnings("serial")
protected DelayedFile delayedDirtyFile(final String name, final String classifier, final String ext)
{
return new DelayedFile(project, "", this) {
@Override
public File call()
{
ProcessJarTask decompDeobf = (ProcessJarTask) project.getTasks().getByName("deobfuscateJar");
pattern = (decompDeobf.isClean() ? "{API_CACHE_DIR}" : DIRTY_DIR) + "/";
if (!Strings.isNullOrEmpty(name))
pattern += name;
else
pattern += "{API_NAME}";
pattern += "-" + (hasApiVersion() ? "{API_VERSION}" : "{MC_VERSION}");
if (!Strings.isNullOrEmpty(classifier))
pattern+= "-"+classifier;
if (!Strings.isNullOrEmpty(ext))
pattern+= "."+ext;
return super.call();
}
};
}
/**
* This extension object will have the name "minecraft"
* @return
*/
@SuppressWarnings("unchecked")
protected Class<T> getExtensionClass()
{
return (Class<T>) UserExtension.class;
}
}
|
package org.lwjgl.demo.glfw;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.LWJGLUtil.TokenFilter;
import org.lwjgl.demo.util.ClosureGC;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.GL;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Map;
import static org.lwjgl.demo.util.IOUtil.*;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
/** GLFW events demo. */
public final class Events {
private Events() {
}
public static void main(String[] args) {
System.setProperty(
"org.lwjgl.system.libffi.ClosureRegistry",
"org.lwjgl.demo.util.ClosureGC"
);
glfwSetErrorCallback(errorCallbackPrint(System.out));
System.out.println("
glfwDefaultWindowHints();
System.out.println("
if ( glfwInit() == 0 )
throw new IllegalStateException("Failed to initialize GLFW.");
System.out.println("GLFW initialized");
try {
demo();
} finally {
glfwTerminate();
ClosureGC.get().gc();
}
}
private static void demo() {
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
long window = glfwCreateWindow(640, 480, "GLFW Event Demo", NULL, NULL);
if ( window == 0L )
throw new IllegalStateException("Failed to create GLFW window.");
System.out.println("Window opened.");
try {
Class STBImage = Class.forName("org.lwjgl.stb.STBImage"); // Skip if the stb bindings are not available
ByteBuffer png;
try {
png = ioResourceToByteBuffer("demo/cursor.png", 1024);
} catch (IOException e) {
throw new RuntimeException(e);
}
IntBuffer w = BufferUtils.createIntBuffer(1);
IntBuffer h = BufferUtils.createIntBuffer(1);
IntBuffer comp = BufferUtils.createIntBuffer(1);
try {
Method stbi_load_from_memory = STBImage.getMethod(
"stbi_load_from_memory",
ByteBuffer.class, IntBuffer.class, IntBuffer.class, IntBuffer.class, int.class
);
ByteBuffer pixels = (ByteBuffer)stbi_load_from_memory.invoke(null, png, w, h, comp, 0);
ByteBuffer img = GLFWimage.malloc(w.get(0), h.get(0), pixels);
long cursor = glfwCreateCursor(img, 0, 8);
glfwSetCursor(window, cursor);
} catch (Exception e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// ignore
}
glfwSetMonitorCallback(new GLFWMonitorCallback() {
@Override
public void invoke(long monitor, int event) {
printEvent("Monitor", "[0x%X] %s", monitor, event == GLFW_CONNECTED ? "connected" : "disconnected");
}
});
glfwSetWindowPosCallback(window, new GLFWWindowPosCallback() {
@Override
public void invoke(long window, int xpos, int ypos) {
printEvent("moved to %d, %d", window, xpos, ypos);
}
});
glfwSetWindowSizeCallback(window, new GLFWWindowSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
printEvent("resized to %d x %d", window, width, height);
}
});
glfwSetWindowCloseCallback(window, new GLFWWindowCloseCallback() {
@Override
public void invoke(long window) {
printEvent("closed", window);
}
});
glfwSetWindowRefreshCallback(window, new GLFWWindowRefreshCallback() {
@Override
public void invoke(long window) {
printEvent("refreshed", window);
}
});
glfwSetWindowFocusCallback(window, new GLFWWindowFocusCallback() {
@Override
public void invoke(long window, int focused) {
printEvent(focused == 0 ? "lost focus" : "gained focus", window);
}
});
glfwSetWindowIconifyCallback(window, new GLFWWindowIconifyCallback() {
@Override
public void invoke(long window, int iconified) {
printEvent(iconified == 0 ? "restored" : "iconified", window);
}
});
glfwSetFramebufferSizeCallback(window, new GLFWFramebufferSizeCallback() {
@Override
public void invoke(long window, int width, int height) {
printEvent("framebuffer resized to %d x %d", window, width, height);
}
});
glfwSetKeyCallback(window, new GLFWKeyCallback() {
private final Map<Integer, String> KEY_CODES = LWJGLUtil.getClassTokens(new TokenFilter() {
@Override
public boolean accept(Field field, int value) {
return field.getName().startsWith("GLFW_KEY_");
}
}, null, GLFW.class);
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
String state;
switch ( action ) {
case GLFW_RELEASE:
state = "released";
break;
case GLFW_PRESS:
state = "pressed";
break;
case GLFW_REPEAT:
state = "repeated";
break;
default:
throw new IllegalArgumentException(String.format("Unsupported key action: 0x%X", action));
}
printEvent("key %s[%s - %d] was %s", window, getModState(mods), KEY_CODES.get(key), scancode, state);
if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE )
glfwSetWindowShouldClose(window, 1);
}
});
glfwSetCharCallback(window, new GLFWCharCallback() {
@Override
public void invoke(long window, int codepoint) {
printEvent("char %s", window, Character.toString((char)codepoint));
}
});
glfwSetCharModsCallback(window, new GLFWCharModsCallback() {
@Override
public void invoke(long window, int codepoint, int mods) {
printEvent("char mods %s%s", window, getModState(mods), Character.toString((char)codepoint));
}
});
glfwSetMouseButtonCallback(window, new GLFWMouseButtonCallback() {
@Override
public void invoke(long window, int button, int action, int mods) {
String state;
switch ( action ) {
case GLFW_RELEASE:
state = "released";
break;
case GLFW_PRESS:
state = "pressed";
break;
default:
throw new IllegalArgumentException(String.format("Unsupported mouse button action: 0x%X", action));
}
printEvent("mouse button %s[0x%X] was %s", window, getModState(mods), button, state);
}
});
glfwSetCursorPosCallback(window, new GLFWCursorPosCallback() {
@Override
public void invoke(long window, double xpos, double ypos) {
printEvent("cursor moved to %f, %f", window, xpos, ypos);
}
});
glfwSetCursorEnterCallback(window, new GLFWCursorEnterCallback() {
@Override
public void invoke(long window, int entered) {
printEvent("cursor %s", window, entered == 0 ? "left" : "entered");
}
});
glfwSetScrollCallback(window, new GLFWScrollCallback() {
@Override
public void invoke(long window, double xoffset, double yoffset) {
printEvent("scroll by %f, %f", window, xoffset, yoffset);
}
});
glfwSetDropCallback(window, new GLFWDropCallback() {
@Override
public void invoke(long window, int count, long names) {
printEvent("drop %d file%s", window, count, count == 1 ? "" : "s");
dropCallbackNamesApply(count, names, new DropConsumerString() {
@Override
public void accept(int index, String name) {
System.out.format("\t%d: %s%n", index + 1, name);
}
});
}
});
glfwMakeContextCurrent(window);
GL.createCapabilities();
glfwShowWindow(window);
glfwSwapInterval(1);
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
while ( glfwWindowShouldClose(window) == 0 ) {
glfwWaitEvents();
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
}
}
private static String getModState(int mods) {
if ( mods == 0 )
return "";
StringBuilder modState = new StringBuilder(16);
if ( (mods & GLFW_MOD_SHIFT) != 0 )
modState.append("SHIFT+");
if ( (mods & GLFW_MOD_CONTROL) != 0 )
modState.append("CONTROL+");
if ( (mods & GLFW_MOD_ALT) != 0 )
modState.append("ALT+");
if ( (mods & GLFW_MOD_SUPER) != 0 )
modState.append("SUPER+");
return modState.toString();
}
private static void printEvent(String format, long window, Object... args) {
printEvent("Window", format, window, args);
}
private static void printEvent(String type, String format, long object, Object... args) {
Object[] formatArgs = new Object[3 + args.length];
formatArgs[0] = glfwGetTime();
formatArgs[1] = type;
formatArgs[2] = object;
System.arraycopy(args, 0, formatArgs, 3, args.length);
System.out.format("%.3f: %s [0x%X] " + format + "%n", formatArgs);
}
}
|
package nl.hsac.fitnesse.fixture.slim.web;
import nl.hsac.fitnesse.fixture.slim.SlimFixture;
import nl.hsac.fitnesse.fixture.util.SeleniumHelper;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class BrowserTest extends SlimFixture {
private static final String ELEMENT_ON_SCREEN_JS =
"var rect = arguments[0].getBoundingClientRect();\n" +
"return (\n" +
" rect.top >= 0 &&\n" +
" rect.left >= 0 &&\n" +
" rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&\n" +
" rect.right <= (window.innerWidth || document.documentElement.clientWidth));";
private SeleniumHelper seleniumHelper = getEnvironment().getSeleniumHelper();
private int secondsBeforeTimeout;
private int waitAfterScroll = 0;
private final String filesDir = getEnvironment().getFitNesseFilesSectionDir();
private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/";
private String screenshotHeight = "200";
public BrowserTest() {
secondsBeforeTimeout(SeleniumHelper.DEFAULT_TIMEOUT_SECONDS);
ensureActiveTabIsNotClosed();
}
public boolean open(String address) {
String url = getUrl(address);
try {
getNavigation().to(url);
} catch (TimeoutException e) {
throw new TimeoutStopTestException("Unable to go to: " + url, e);
}
return true;
}
public boolean back() {
getNavigation().back();
// firefox sometimes prevents immediate back, if previous page was reached via POST
waitMilliSeconds(500);
WebElement element = getSeleniumHelper().findElement(By.id("errorTryAgain"));
if (element != null) {
element.click();
Alert alert = getSeleniumHelper().driver().switchTo().alert();
alert.accept();
}
return true;
}
public boolean forward() {
getNavigation().forward();
return true;
}
public boolean refresh() {
getNavigation().refresh();
return true;
}
private WebDriver.Navigation getNavigation() {
return getSeleniumHelper().navigate();
}
public boolean switchToNextTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab + 1;
if (nextTab == tabs.size()) {
nextTab = 0;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
public boolean switchToPreviousTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab - 1;
if (nextTab < 0) {
nextTab = tabs.size() - 1;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
public boolean closeTab() {
boolean result = false;
List<String> tabs = getTabHandles();
int currentTab = getCurrentTabIndex(tabs);
int tabToGoTo = -1;
if (currentTab > 0) {
tabToGoTo = currentTab - 1;
} else {
if (tabs.size() > 1) {
tabToGoTo = 1;
}
}
if (tabToGoTo > -1) {
WebDriver driver = getSeleniumHelper().driver();
driver.close();
goToTab(tabs, tabToGoTo);
result = true;
}
return result;
}
public boolean ensureActiveTabIsNotClosed() {
boolean result = false;
List<String> tabHandles = getTabHandles();
int currentTab = getCurrentTabIndex(tabHandles);
if (currentTab < 0) {
result = true;
goToTab(tabHandles, 0);
}
return result;
}
public int tabCount() {
return getTabHandles().size();
}
public int currentTabIndex() {
return getCurrentTabIndex(getTabHandles()) + 1;
}
protected int getCurrentTabIndex(List<String> tabHandles) {
return getSeleniumHelper().getCurrentTabIndex(tabHandles);
}
protected void goToTab(List<String> tabHandles, int indexToGoTo) {
getSeleniumHelper().goToTab(tabHandles, indexToGoTo);
}
protected List<String> getTabHandles() {
return getSeleniumHelper().getTabHandles();
}
public String pageTitle() {
return getSeleniumHelper().getPageTitle();
}
/**
* @return current page's content type.
*/
public String pageContentType() {
String result = null;
Object ct = getSeleniumHelper().executeJavascript("return document.contentType;");
if (ct != null) {
result = ct.toString();
}
return result;
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @return true, if element was found.
*/
public boolean enterAs(String value, String place) {
final WebElement element = getElement(place);
boolean result = waitUntilInteractable(element);
if (result) {
element.clear();
sendValue(element, value);
}
return result;
}
protected boolean waitUntilInteractable(final WebElement element) {
return waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return element != null && element.isDisplayed() && element.isEnabled();
}
});
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @return true, if element was found.
*/
public boolean enterFor(String value, String place) {
boolean result = false;
WebElement element = getElement(place);
if (element != null) {
sendValue(element, value);
result = true;
}
return result;
}
/**
* Simulates pressing the 'Tab' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressTab() {
return sendKeysToActiveElement(Keys.TAB);
}
/**
* Simulates pressing the 'Enter' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEnter() {
return sendKeysToActiveElement(Keys.ENTER);
}
/**
* Simulates pressing the 'Esc' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEsc() {
return sendKeysToActiveElement(Keys.ESCAPE);
}
/**
* Simulates pressing a key.
* @param key key to press, can be a normal letter (e.g. 'M') or a special key (e.g. 'down').
* @return true, if an element was active the key could be sent to.
*/
public boolean press(String key) {
CharSequence s;
try {
s = Keys.valueOf(key.toUpperCase());
} catch (IllegalArgumentException e) {
s = key;
}
return sendKeysToActiveElement(s);
}
/**
* Simulates pressing keys.
* @param keys keys to press.
* @return true, if an element was active the keys could be sent to.
*/
protected boolean sendKeysToActiveElement(CharSequence keys) {
boolean result = false;
WebElement element = getSeleniumHelper().getActiveElement();
if (element != null) {
element.sendKeys(keys);
result = true;
}
return result;
}
/**
* Sends Fitnesse cell content to element.
* @param element element to call sendKeys() on.
* @param value cell content.
*/
protected void sendValue(WebElement element, String value) {
String keys = cleanupValue(value);
element.sendKeys(keys);
}
public boolean selectAs(String value, String place) {
return selectFor(value, place);
}
public boolean selectFor(String value, String place) {
// choose option for select, if possible
boolean result = clickSelectOption(place, value);
if (!result) {
// try to click the first element with right value
result = click(value);
}
return result;
}
public boolean enterForHidden(String value, String idOrName) {
return getSeleniumHelper().setHiddenInputValue(idOrName, value);
}
private boolean clickSelectOption(String selectPlace, String optionValue) {
boolean result = false;
WebElement element = getElement(selectPlace);
if (element != null) {
if (isSelect(element)) {
String attrToUse = "id";
String attrValue = element.getAttribute(attrToUse);
if (attrValue == null || attrValue.isEmpty()) {
attrToUse = "name";
attrValue = element.getAttribute(attrToUse);
}
if (attrValue != null && !attrValue.isEmpty()) {
String xpathToOptions = "//select[@" + attrToUse + "='%s']//option";
result = clickOption(attrValue, xpathToOptions + "[text()='%s']", optionValue);
if (!result) {
result = clickOption(attrValue, xpathToOptions + "[contains(text(), '%s')]", optionValue);
}
}
}
}
return result;
}
private boolean clickOption(String selectId, String optionXPath, String optionValue) {
boolean result = false;
By optionWithText = getSeleniumHelper().byXpath(optionXPath, selectId, optionValue);
WebElement option = getSeleniumHelper().findElement(true, optionWithText);
if (option != null) {
result = clickElement(option);
}
return result;
}
public boolean click(String place) {
// if other element hides the element (in Chrome) an exception is thrown
// we retry clicking the element a few times before giving up.
boolean result = false;
boolean retry = true;
for (int i = 0;
!result && retry;
i++) {
try {
if (i > 0) {
waitSeconds(1);
}
result = clickImpl(place);
} catch (WebDriverException e) {
String msg = e.getMessage();
if (!msg.contains("Other element would receive the click")
|| i == secondsBeforeTimeout()) {
retry = false;
}
}
// don't wait forever trying to click
// only try secondsBeforeTimeout + 1 times
retry &= i < secondsBeforeTimeout();
}
return result;
}
protected boolean clickImpl(String place) {
WebElement element = getElement(place);
if (element == null) {
/**
* Creates an XPath expression that will find a cell in a row, selecting the row based on the
* text in a specific column (identified by its header text).
* @param columnName header text of the column to find value in.
* @param value text to find in column with the supplied header.
* @return XPath expression selecting a td in the row
*/
protected String getXPathForColumnInRowByValueInOtherColumn(String columnName, String value) {
String selectIndex = getXPathForColumnIndex(columnName);
return String.format("//tr[normalize-space(td[%s]/descendant-or-self::text())='%s']/td", selectIndex, value);
}
/**
* Creates an XPath expression that will determine, for a row, which index to use to select the cell in the column
* with the supplied header text value.
* @param columnName name of column in header (th)
* @return XPath expression which can be used to select a td in a row
*/
protected String getXPathForColumnIndex(String columnName) {
// determine how many columns are before the column with the requested name
// the column with the requested name will have an index of the value +1 (since XPath indexes are 1 based)
return String.format("count(//tr/th[normalize-space(descendant-or-self::text())='%s']/preceding-sibling::th)+1", columnName);
}
protected WebElement getElement(String place) {
return getSeleniumHelper().getElement(place);
}
public String textByXPath(String xPath) {
return getTextByXPath(xPath);
}
protected String getTextByXPath(String xpathPattern, String... params) {
WebElement element = findByXPath(xpathPattern, params);
return getElementText(element);
}
public String textByClassName(String className) {
return getTextByClassName(className);
}
protected String getTextByClassName(String className) {
WebElement element = findByClassName(className);
return getElementText(element);
}
protected WebElement findByClassName(String className) {
By by = By.className(className);
return getSeleniumHelper().findElement(by);
}
protected WebElement findByXPath(String xpathPattern, String... params) {
By by = getSeleniumHelper().byXpath(xpathPattern, params);
return getSeleniumHelper().findElement(by);
}
protected List<WebElement> findAllByXPath(String xpathPattern, String... params) {
By by = getSeleniumHelper().byXpath(xpathPattern, params);
return getSeleniumHelper().driver().findElements(by);
}
protected List<WebElement> findAllByCss(String cssPattern, String... params) {
By by = getSeleniumHelper().byCss(cssPattern, params);
return getSeleniumHelper().driver().findElements(by);
}
public void waitMilliSecondAfterScroll(int msToWait) {
waitAfterScroll = msToWait;
}
protected String getElementText(WebElement element) {
String result = null;
if (element != null) {
scrollIfNotOnScreen(element);
result = element.getText();
}
return result;
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
*/
public void scrollTo(String place) {
WebElement element = getElement(place);
if (place != null) {
scrollTo(element);
}
}
/**
* Scrolls browser window so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollTo(WebElement element) {
getSeleniumHelper().executeJavascript("arguments[0].scrollIntoView(true);", element);
if (waitAfterScroll > 0) {
waitMilliSeconds(waitAfterScroll);
}
}
/**
* Scrolls browser window if element is not currently visible so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollIfNotOnScreen(WebElement element) {
if (element.isDisplayed() && !isElementOnScreen(element)) {
scrollTo(element);
}
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @return true if element is displayed and in viewport.
*/
public boolean isVisible(String place) {
boolean result = false;
WebElement element = getElement(place);
if (element != null) {
result = element.isDisplayed() && isElementOnScreen(element);
}
return result;
}
/**
* Checks whether element is in browser's viewport.
* @param element element to check
* @return true if element is in browser's viewport.
*/
protected boolean isElementOnScreen(WebElement element) {
return (Boolean)getSeleniumHelper().executeJavascript(ELEMENT_ON_SCREEN_JS, element);
}
/**
* @param timeout number of seconds before waitUntil() throws TimeOutException.
*/
public void secondsBeforeTimeout(int timeout) {
secondsBeforeTimeout = timeout;
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setPageLoadWait(timeoutInMs);
}
/**
* @return number of seconds waitUntil() will wait at most.
*/
public int secondsBeforeTimeout() {
return secondsBeforeTimeout;
}
/**
* Clears HTML5's localStorage.
*/
public void clearLocalStorage() {
getSeleniumHelper().executeJavascript("localStorage.clear();");
}
/**
* @param directory sets base directory where screenshots will be stored.
*/
public void screenshotBaseDirectory(String directory) {
if (directory.equals("")
|| directory.endsWith("/")
|| directory.endsWith("\\")) {
screenshotBase = directory;
} else {
screenshotBase = directory + "/";
}
}
/**
* @param height height to use to display screenshot images
*/
public void screenshotShowHeight(String height) {
screenshotHeight = height;
}
/**
* Takes screenshot from current page
* @param basename filename (below screenshot base directory).
* @return location of screenshot.
*/
public String takeScreenshot(String basename) {
String screenshotFile = createScreenshot(basename);
if (screenshotFile == null) {
throw new RuntimeException("Unable to take screenshot: does the webdriver support it?");
} else {
if (screenshotFile.startsWith(filesDir)) {
// make href to screenshot
String relativeFile = screenshotFile.substring(filesDir.length());
relativeFile = relativeFile.replace('\\', '/');
String wikiUrl = "files" + relativeFile;
if ("".equals(screenshotHeight)) {
wikiUrl = String.format("<a href=\"%s\">%s</a>",
wikiUrl, screenshotFile);
} else {
wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"></a>",
wikiUrl, screenshotFile, screenshotHeight);
}
screenshotFile = wikiUrl;
}
}
return screenshotFile;
}
private String createScreenshot(String basename) {
String name = screenshotBase + basename;
return getSeleniumHelper().takeScreenshot(name);
}
/**
* Implementations should wait until the condition evaluates to a value that is neither null nor
* false. Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws org.openqa.selenium.TimeoutException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntil(ExpectedCondition<T> condition) {
try {
FluentWait<WebDriver> wait = waitDriver().withTimeout(secondsBeforeTimeout(), TimeUnit.SECONDS);
return wait.until(condition);
} catch (TimeoutException e) {
// take a screenshot of what was on screen
String screenShotFile = null;
try {
screenShotFile = createScreenshot("timeouts/" + getClass().getSimpleName() + "/timeout");
} catch (Exception sse) {
// unable to take screenshot
sse.printStackTrace();
}
if (screenShotFile == null) {
throw new TimeoutStopTestException(e);
} else {
throw new TimeoutStopTestException("Screenshot available at: " + screenShotFile, e);
}
}
}
private WebDriverWait waitDriver() {
return getSeleniumHelper().waitDriver();
}
/**
* @return helper to use.
*/
protected final SeleniumHelper getSeleniumHelper() {
return seleniumHelper;
}
/**
* Sets SeleniumHelper to use, for testing purposes.
* @param helper helper to use.
*/
void setSeleniumHelper(SeleniumHelper helper) {
seleniumHelper = helper;
}
public int currentBrowserWidth() {
WebDriver.Window window = getSeleniumHelper().driver().manage().window();
window.setPosition(new Point(0, 0));
return window.getSize().getWidth();
}
public void setBrowserWidth(int newWidth) {
WebDriver.Window window = getSeleniumHelper().driver().manage().window();
window.setPosition(new Point(0, 0));
int currentBrowserHeight = window.getSize().getHeight();
window.setSize(new Dimension(newWidth, currentBrowserHeight));
}
}
|
package org.folio.rest;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import io.restassured.response.Response;
import io.restassured.RestAssured;
import io.restassured.filter.log.ErrorLoggingFilter;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import org.folio.rest.jaxrs.model.Parameter;
import org.folio.rest.jaxrs.model.TenantAttributes;
import org.folio.rest.tools.utils.VertxUtils;
import org.junit.jupiter.api.BeforeAll;
public class ApiTestBase {
static Vertx vertx;
/** default request header with "x-okapi-tenant: testlib" and "Content-type: application/json"
* and ErrorLoggingFilter (logs to System.out).
*/
static RequestSpecification r;
private static final CompletableFuture<String> deploymentFuture = new CompletableFuture<String>();
@BeforeAll
static void beforeAll() {
RestAssured.port = 9230;
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
vertx = VertxUtils.getVertxWithExceptionHandler();
// once for all test classes: starting and tenant initialization
if (deploymentFuture.isDone()) {
return;
}
DeploymentOptions deploymentOptions = new DeploymentOptions()
.setConfig(new JsonObject().put("http.port", RestAssured.port));
vertx.deployVerticle(RestVerticle.class, deploymentOptions, deploy -> {
if (deploy.failed()) {
deploymentFuture.completeExceptionally(deploy.cause());
return;
}
deploymentFuture.complete(deploy.result());
});
try {
deploymentFuture.get(10, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new RuntimeException(e);
}
r = given().
filter(new ErrorLoggingFilter()).
header("x-okapi-tenant", "testlib").
contentType(ContentType.JSON);
// delete tenant (schema, tables, ...) if it exists from previous tests
TenantAttributes delete = new TenantAttributes()
.withModuleFrom("mod-api-0.0.0")
.withParameters(Collections.singletonList(
new Parameter().withKey("purge").withValue("true")));
given(r)
.body(Json.encode(delete))
.when().post("/_/tenant")
.then(); // ignore errors
List<Parameter> list = new LinkedList<>();
list.add(new Parameter().withKey("loadReference").withValue("true"));
TenantAttributes ta = new TenantAttributes().withModuleTo("mod-api-1.0.0").withParameters(list);
// create tenant (schema, tables, ...)
Response response = given(r).header("x-okapi-url-to", "http://localhost:" + port).
contentType(ContentType.JSON)
.body(Json.encode(ta))
.when().post("/_/tenant")
.then().statusCode(201).extract().response();
String location = response.header("Location");
given(r).
when().get(location + "?wait=5000").
then().statusCode(200);
}
/**
* @param path API path, for example <code>/bees</code>
* @param arrayName property name of the result array, for example <code>bees</code>
*/
static void deleteAll(String path, String arrayName) {
List<Map<String,String>> array =
given(r).
when().get(path + "?limit=100").
then().
statusCode(200).
body("total_records", lessThan(100)).
extract().path(arrayName);
for (Map<String,String> item : array) {
given(r).
when().delete(path + "/" + item.get("id")).
then().statusCode(204);
}
given(r).
when().get(path).
then().
statusCode(200).
body("total_records", equalTo(0));
}
static String randomUuid() {
return UUID.randomUUID().toString();
}
}
|
package nl.hsac.fitnesse.fixture.slim.web;
import fitnesse.slim.fixtureInteraction.FixtureInteraction;
import nl.hsac.fitnesse.fixture.slim.SlimFixture;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.StopTestException;
import nl.hsac.fitnesse.fixture.slim.web.annotation.TimeoutPolicy;
import nl.hsac.fitnesse.fixture.slim.web.annotation.WaitUntil;
import nl.hsac.fitnesse.fixture.util.BinaryHttpResponse;
import nl.hsac.fitnesse.fixture.util.FileUtil;
import nl.hsac.fitnesse.fixture.util.HttpResponse;
import nl.hsac.fitnesse.fixture.util.ReflectionHelper;
import nl.hsac.fitnesse.fixture.util.selenium.PageSourceSaver;
import nl.hsac.fitnesse.fixture.util.selenium.SeleniumHelper;
import nl.hsac.fitnesse.slim.interaction.ExceptionHelper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class BrowserTest extends SlimFixture {
private SeleniumHelper seleniumHelper = getEnvironment().getSeleniumHelper();
private ReflectionHelper reflectionHelper = getEnvironment().getReflectionHelper();
private NgBrowserTest ngBrowserTest;
private boolean implicitWaitForAngular = false;
private boolean implicitFindInFrames = true;
private int secondsBeforeTimeout;
private int secondsBeforePageLoadTimeout;
private int waitAfterScroll = 150;
private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/";
private String screenshotHeight = "200";
private String downloadBase = new File(filesDir, "downloads").getPath() + "/";
private String pageSourceBase = new File(filesDir, "pagesources").getPath() + "/";
@Override
protected void beforeInvoke(Method method, Object[] arguments) {
super.beforeInvoke(method, arguments);
waitForAngularIfNeeded(method);
}
@Override
protected Object invoke(final FixtureInteraction interaction, final Method method, final Object[] arguments)
throws Throwable {
Object result;
WaitUntil waitUntil = reflectionHelper.getAnnotation(WaitUntil.class, method);
if (waitUntil == null) {
result = superInvoke(interaction, method, arguments);
} else {
result = invokedWrappedInWaitUntil(waitUntil, interaction, method, arguments);
}
return result;
}
protected Object invokedWrappedInWaitUntil(WaitUntil waitUntil, final FixtureInteraction interaction, final Method method, final Object[] arguments) {
ExpectedCondition<Object> condition = new ExpectedCondition<Object>() {
@Override
public Object apply(WebDriver webDriver) {
try {
return superInvoke(interaction, method, arguments);
} catch (Throwable e) {
Throwable realEx = ExceptionHelper.stripReflectionException(e);
if (realEx instanceof RuntimeException) {
throw (RuntimeException) realEx;
} else if (realEx instanceof Error) {
throw (Error) realEx;
} else {
throw new RuntimeException(realEx);
}
}
}
};
if (implicitFindInFrames) {
condition = getSeleniumHelper().conditionForAllFrames(condition);
}
Object result;
switch (waitUntil.value()) {
case STOP_TEST:
result = waitUntilOrStop(condition);
break;
case RETURN_NULL:
result = waitUntilOrNull(condition);
break;
case RETURN_FALSE:
result = waitUntilOrNull(condition) != null;
break;
case THROW:
default:
result = waitUntil(condition);
break;
}
return result;
}
protected Object superInvoke(FixtureInteraction interaction, Method method, Object[] arguments) throws Throwable {
return super.invoke(interaction, method, arguments);
}
/**
* Determines whether the current method might require waiting for angular given the currently open site,
* and ensure it does if needed.
* @param method
*/
protected void waitForAngularIfNeeded(Method method) {
if (isImplicitWaitForAngularEnabled()) {
try {
if (ngBrowserTest == null) {
ngBrowserTest = new NgBrowserTest();
}
if (ngBrowserTest.requiresWaitForAngular(method) && currentSiteUsesAngular()) {
try {
ngBrowserTest.waitForAngularRequestsToFinish();
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Found Angular, but encountered an error while waiting for it to be ready. ");
e.printStackTrace();
}
}
} catch (UnhandledAlertException e) {
System.err.println("Cannot determine whether Angular is present while alert is active.");
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Error while determining whether Angular is present. ");
e.printStackTrace();
}
}
}
protected boolean currentSiteUsesAngular() {
Object windowHasAngular = getSeleniumHelper().executeJavascript("return window.angular?1:0;");
return Long.valueOf(1).equals(windowHasAngular);
}
@Override
protected Throwable handleException(Method method, Object[] arguments, Throwable t) {
Throwable result;
if (t instanceof UnhandledAlertException) {
UnhandledAlertException e = (UnhandledAlertException) t;
String alertText = e.getAlertText();
if (alertText == null) {
alertText = alertText();
}
String msgBase = "Unhandled alert: alert must be confirmed or dismissed before test can continue. Alert text: " + alertText;
String msg = getSlimFixtureExceptionMessage("alertException", msgBase, e);
result = new StopTestException(false, msg, t);
} else if (t instanceof SlimFixtureException) {
result = super.handleException(method, arguments, t);
} else {
String msg = getSlimFixtureExceptionMessage("exception", null, t);
result = new SlimFixtureException(false, msg, t);
}
return result;
}
public BrowserTest() {
secondsBeforeTimeout(seleniumHelper.getDefaultTimeoutSeconds());
ensureActiveTabIsNotClosed();
}
public BrowserTest(int secondsBeforeTimeout) {
secondsBeforeTimeout(secondsBeforeTimeout);
ensureActiveTabIsNotClosed();
}
public boolean open(String address) {
final String url = getUrl(address);
try {
getNavigation().to(url);
} catch (TimeoutException e) {
handleTimeoutException(e);
} finally {
switchToDefaultContent();
}
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
String readyState = getSeleniumHelper().executeJavascript("return document.readyState").toString();
// IE 7 is reported to return "loaded"
boolean done = "complete".equalsIgnoreCase(readyState) || "loaded".equalsIgnoreCase(readyState);
if (!done) {
System.err.printf("Open of %s returned while document.readyState was %s", url, readyState);
System.err.println();
}
return done;
}
});
return true;
}
public String location() {
return driver().getCurrentUrl();
}
public boolean back() {
getNavigation().back();
switchToDefaultContent();
// firefox sometimes prevents immediate back, if previous page was reached via POST
waitMilliseconds(500);
WebElement element = findElement(By.id("errorTryAgain"));
if (element != null) {
element.click();
// don't use confirmAlert as this may be overridden in subclass and to get rid of the
// firefox pop-up we need the basic behavior
getSeleniumHelper().getAlert().accept();
}
return true;
}
public boolean forward() {
getNavigation().forward();
switchToDefaultContent();
return true;
}
public boolean refresh() {
getNavigation().refresh();
switchToDefaultContent();
return true;
}
private WebDriver.Navigation getNavigation() {
return getSeleniumHelper().navigate();
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String alertText() {
Alert alert = getAlert();
String text = null;
if (alert != null) {
text = alert.getText();
}
return text;
}
@WaitUntil
public boolean confirmAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.accept();
onAlertHandled(true);
result = true;
}
return result;
}
@WaitUntil
public boolean dismissAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.dismiss();
onAlertHandled(false);
result = true;
}
return result;
}
/**
* Called when an alert is either dismissed or accepted.
* @param accepted true if the alert was accepted, false if dismissed.
*/
protected void onAlertHandled(boolean accepted) {
// if we were looking in nested frames, we could not go back to original frame
// because of the alert. Ensure we do so now the alert is handled.
getSeleniumHelper().resetFrameDepthOnAlertError();
}
protected Alert getAlert() {
return getSeleniumHelper().getAlert();
}
public boolean openInNewTab(String url) {
String cleanUrl = getUrl(url);
final int tabCount = tabCount();
getSeleniumHelper().executeJavascript("window.open('%s', '_blank')", cleanUrl);
// ensure new window is open
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return tabCount() > tabCount;
}
});
return switchToNextTab();
}
@WaitUntil
public boolean switchToNextTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab + 1;
if (nextTab == tabs.size()) {
nextTab = 0;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
@WaitUntil
public boolean switchToPreviousTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab - 1;
if (nextTab < 0) {
nextTab = tabs.size() - 1;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
public boolean closeTab() {
boolean result = false;
List<String> tabs = getTabHandles();
int currentTab = getCurrentTabIndex(tabs);
int tabToGoTo = -1;
if (currentTab > 0) {
tabToGoTo = currentTab - 1;
} else {
if (tabs.size() > 1) {
tabToGoTo = 1;
}
}
if (tabToGoTo > -1) {
WebDriver driver = driver();
driver.close();
goToTab(tabs, tabToGoTo);
result = true;
}
return result;
}
public void ensureOnlyOneTab() {
ensureActiveTabIsNotClosed();
int tabCount = tabCount();
for (int i = 1; i < tabCount; i++) {
closeTab();
}
}
public boolean ensureActiveTabIsNotClosed() {
boolean result = false;
List<String> tabHandles = getTabHandles();
int currentTab = getCurrentTabIndex(tabHandles);
if (currentTab < 0) {
result = true;
goToTab(tabHandles, 0);
}
return result;
}
public int tabCount() {
return getTabHandles().size();
}
public int currentTabIndex() {
return getCurrentTabIndex(getTabHandles()) + 1;
}
protected int getCurrentTabIndex(List<String> tabHandles) {
return getSeleniumHelper().getCurrentTabIndex(tabHandles);
}
protected void goToTab(List<String> tabHandles, int indexToGoTo) {
getSeleniumHelper().goToTab(tabHandles, indexToGoTo);
}
protected List<String> getTabHandles() {
return getSeleniumHelper().getTabHandles();
}
/**
* Activates main/top-level iframe (i.e. makes it the current frame).
*/
public void switchToDefaultContent() {
getSeleniumHelper().switchToDefaultContent();
clearSearchContext();
}
/**
* Activates specified child frame of current iframe.
* @param technicalSelector selector to find iframe.
* @return true if iframe was found.
*/
public boolean switchToFrame(String technicalSelector) {
boolean result = false;
WebElement iframe = getElement(technicalSelector);
if (iframe != null) {
getSeleniumHelper().switchToFrame(iframe);
result = true;
}
return result;
}
/**
* Activates parent frame of current iframe.
* Does nothing if when current frame is the main/top-level one.
*/
public void switchToParentFrame() {
getSeleniumHelper().switchToParentFrame();
}
public String pageTitle() {
return getSeleniumHelper().getPageTitle();
}
/**
* @return current page's content type.
*/
public String pageContentType() {
String result = null;
Object ct = getSeleniumHelper().executeJavascript("return document.contentType;");
if (ct != null) {
result = ct.toString();
}
return result;
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAs(String value, String place) {
return enterAsIn(value, place, null);
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAsIn(String value, String place, String container) {
return enter(value, place, container, true);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterFor(String value, String place) {
return enterForIn(value, place, null);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterForIn(String value, String place, String container) {
return enter(value, place, container, false);
}
protected boolean enter(String value, String place, boolean shouldClear) {
return enter(value, place, null, shouldClear);
}
protected boolean enter(String value, String place, String container, boolean shouldClear) {
WebElement element = getElementToSendValue(place, container);
boolean result = element != null && isInteractable(element);
if (result) {
if (shouldClear) {
element.clear();
}
sendValue(element, value);
}
return result;
}
protected WebElement getElementToSendValue(String place) {
return getElementToSendValue(place, null);
}
protected WebElement getElementToSendValue(String place, String container) {
return getElement(place, container);
}
/**
* Simulates pressing the 'Tab' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressTab() {
return sendKeysToActiveElement(Keys.TAB);
}
/**
* Simulates pressing the 'Enter' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEnter() {
return sendKeysToActiveElement(Keys.ENTER);
}
/**
* Simulates pressing the 'Esc' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEsc() {
return sendKeysToActiveElement(Keys.ESCAPE);
}
/**
* Simulates typing a text to the current active element.
* @param text text to type.
* @return true, if an element was active the text could be sent to.
*/
public boolean type(String text) {
String value = cleanupValue(text);
return sendKeysToActiveElement(value);
}
public boolean press(String key) {
CharSequence s;
String[] parts = key.split("\\s*\\+\\s*");
if (parts.length > 1
&& !"".equals(parts[0]) && !"".equals(parts[1])) {
CharSequence[] sequence = new CharSequence[parts.length];
for (int i = 0; i < parts.length; i++) {
sequence[i] = parseKey(parts[i]);
}
s = Keys.chord(sequence);
} else {
s = parseKey(key);
}
return sendKeysToActiveElement(s);
}
protected CharSequence parseKey(String key) {
CharSequence s;
try {
s = Keys.valueOf(key.toUpperCase());
} catch (IllegalArgumentException e) {
s = key;
}
return s;
}
/**
* Simulates pressing keys.
* @param keys keys to press.
* @return true, if an element was active the keys could be sent to.
*/
protected boolean sendKeysToActiveElement(CharSequence keys) {
boolean result = false;
WebElement element = getSeleniumHelper().getActiveElement();
if (element != null) {
element.sendKeys(keys);
result = true;
}
return result;
}
/**
* Sends Fitnesse cell content to element.
* @param element element to call sendKeys() on.
* @param value cell content.
*/
protected void sendValue(WebElement element, String value) {
if (StringUtils.isNotEmpty(value)) {
String keys = cleanupValue(value);
element.sendKeys(keys);
}
}
@WaitUntil
public boolean selectAs(String value, String place) {
return selectFor(value, place);
}
@WaitUntil
public boolean selectFor(String value, String place) {
return selectForIn(value, place, null);
}
@WaitUntil
public boolean selectForIn(String value, String place, String container) {
SearchContext searchContext = setSearchContextToContainer(container);
try {
// choose option for select, if possible
boolean result = clickSelectOption(place, value);
if (!result) {
// try to click the first element with right value
result = click(value);
}
return result;
} finally {
resetSearchContext(searchContext);
}
}
@WaitUntil
public boolean enterForHidden(final String value, final String idOrName) {
return getSeleniumHelper().setHiddenInputValue(idOrName, value);
}
private boolean clickSelectOption(String selectPlace, String optionValue) {
WebElement element = getElementToSelectFor(selectPlace);
return clickSelectOption(element, optionValue);
}
protected WebElement getElementToSelectFor(String selectPlace) {
return getElement(selectPlace);
}
protected boolean clickSelectOption(WebElement element, String optionValue) {
boolean result = false;
if (element != null) {
if (isSelect(element)) {
optionValue = cleanupValue(optionValue);
By xpath = getSeleniumHelper().byXpath(".//option[normalized(text()) = '%s']", optionValue);
WebElement option = getSeleniumHelper().findElement(element, false, xpath);
if (option == null) {
xpath = getSeleniumHelper().byXpath(".//option[contains(normalized(text()), '%s')]", optionValue);
option = getSeleniumHelper().findElement(element, false, xpath);
}
if (option != null) {
result = clickElement(option);
}
}
}
return result;
}
@WaitUntil
public boolean click(final String place) {
return clickImp(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailable(String place) {
return clickIfAvailableIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailableIn(String place, String container) {
return clickImp(place, container);
}
@WaitUntil
public boolean clickIn(String place, String container) {
return clickImp(place, container);
}
protected boolean clickImp(String place, String container) {
boolean result = false;
place = cleanupValue(place);
try {
WebElement element = getElementToClick(place, container);
result = clickElement(element);
} catch (WebDriverException e) {
// if other element hides the element (in Chrome) an exception is thrown
String msg = e.getMessage();
if (msg == null || !msg.contains("Other element would receive the click")) {
throw e;
}
}
return result;
}
@WaitUntil
public boolean doubleClick(final String place) {
WebElement element = getElementToClick(place);
return doubleClick(element);
}
protected boolean doubleClick(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
Actions actions = getActions();
actions.doubleClick(element).perform();
result = true;
}
}
return result;
}
protected Actions getActions() {
WebDriver driver = driver();
return new Actions(driver);
}
protected WebElement getElementToClick(String place) {
return getElementToClick(place, null);
}
protected WebElement getElementToClick(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
return getSeleniumHelper().getElementToClick(place);
} finally {
resetSearchContext(currentSearchContext);
}
}
@WaitUntil
public boolean setSearchContextTo(String container) {
boolean result = false;
WebElement containerElement = getContainerElement(container);
if (containerElement != null) {
getSeleniumHelper().setCurrentContext(containerElement);
result = true;
}
return result;
}
protected SearchContext setSearchContextToContainer(String container) {
SearchContext result = null;
if (container != null) {
SearchContext currentSearchContext = getSeleniumHelper().getCurrentContext();
if (setSearchContextTo(container)) {
result = currentSearchContext;
}
}
return result;
}
public void clearSearchContext() {
getSeleniumHelper().setCurrentContext(null);
}
protected void resetSearchContext(SearchContext currentSearchContext) {
if (currentSearchContext != null) {
getSeleniumHelper().setCurrentContext(currentSearchContext);
}
}
protected WebElement getContainerElement(String container) {
WebElement containerElement = null;
By by = getSeleniumHelper().placeToBy(container);
if (by != null) {
containerElement = findElement(by);
} else {
containerElement = findByXPath(".//fieldset[.//legend/text()[normalized(.) = '%s']]", container);
if (containerElement == null) {
containerElement = getSeleniumHelper().getElementByAriaLabel(container, -1);
if (containerElement == null) {
containerElement = findByXPath(".//fieldset[.//legend/text()[contains(normalized(.), '%s')]]", container);
if (containerElement == null) {
containerElement = getSeleniumHelper().getElementByPartialAriaLabel(container, -1);
}
}
}
}
return containerElement;
}
protected boolean clickElement(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
element.click();
result = true;
}
}
return result;
}
protected boolean isInteractable(WebElement element) {
return getSeleniumHelper().isInteractable(element);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForPage(String pageName) {
return pageTitle().equals(pageName);
}
public boolean waitForTagWithText(String tagName, String expectedText) {
return waitForElementWithText(By.tagName(tagName), expectedText);
}
public boolean waitForClassWithText(String cssClassName, String expectedText) {
return waitForElementWithText(By.className(cssClassName), expectedText);
}
protected boolean waitForElementWithText(final By by, String expectedText) {
final String textToLookFor = cleanExpectedValue(expectedText);
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
boolean ok = false;
List<WebElement> elements = webDriver.findElements(by);
if (elements != null) {
for (WebElement element : elements) {
// we don't want stale elements to make single
// element false, but instead we stop processing
// current list and do a new findElements
ok = hasText(element, textToLookFor);
if (ok) {
// no need to continue to check other elements
break;
}
}
}
return ok;
}
});
}
protected String cleanExpectedValue(String expectedText) {
return cleanupValue(expectedText);
}
protected boolean hasText(WebElement element, String textToLookFor) {
boolean ok;
String actual = getElementText(element);
if (textToLookFor == null) {
ok = actual == null;
} else {
if (StringUtils.isEmpty(actual)) {
String value = element.getAttribute("value");
if (!StringUtils.isEmpty(value)) {
actual = value;
}
}
if (actual != null) {
actual = actual.trim();
}
ok = textToLookFor.equals(actual);
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForClass(String cssClassName) {
boolean ok = false;
WebElement element = findElement(By.className(cssClassName));
if (element != null) {
ok = true;
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisible(String place) {
return waitForVisibleIn(place, null);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisibleIn(String place, String container) {
Boolean result = Boolean.FALSE;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
/**
* @deprecated use #waitForVisible(xpath=) instead
*/
@Deprecated
public boolean waitForXPathVisible(String xPath) {
By by = By.xpath(xPath);
return waitForVisible(by);
}
@Deprecated
protected boolean waitForVisible(final By by) {
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
Boolean result = Boolean.FALSE;
WebElement element = findElement(by);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
});
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOf(String place) {
return valueFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueFor(String place) {
return valueForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfIn(String place, String container) {
return valueForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueForIn(String place, String container) {
WebElement element = getElementToRetrieveValue(place, container);
return valueFor(element);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfAttributeOn(String attribute, String place) {
return valueOfAttributeOnIn(attribute, place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfAttributeOnIn(String attribute, String place, String container) {
String result = null;
WebElement element = getElementToRetrieveValue(place, container);
if(element != null) {
result = element.getAttribute(attribute);
}
return result;
}
protected WebElement getElementToRetrieveValue(String place, String container) {
return getElement(place, container);
}
protected String valueFor(WebElement element) {
String result = null;
if (element != null) {
if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
if (options.size() > 0) {
result = getElementText(options.get(0));
}
} else {
String elementType = element.getAttribute("type");
if ("checkbox".equals(elementType)
|| "radio".equals(elementType)) {
result = String.valueOf(element.isSelected());
} else if ("li".equalsIgnoreCase(element.getTagName())) {
result = getElementText(element);
} else {
result = element.getAttribute("value");
if (result == null) {
result = getElementText(element);
}
}
}
}
return result;
}
private boolean isSelect(WebElement element) {
return "select".equalsIgnoreCase(element.getTagName());
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOf(String place) {
return valuesFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOfIn(String place, String container) {
return valuesForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesFor(String place) {
return valuesForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesForIn(String place, String container) {
ArrayList<String> values = null;
WebElement element = getElementToRetrieveValue(place, container);
if (element != null) {
values = new ArrayList<String>();
String tagName = element.getTagName();
if ("ul".equalsIgnoreCase(tagName)
|| "ol".equalsIgnoreCase(tagName)) {
List<WebElement> items = element.findElements(By.tagName("li"));
for (WebElement item : items) {
if (item.isDisplayed()) {
values.add(getElementText(item));
}
}
} else if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
for (WebElement item : options) {
values.add(getElementText(item));
}
} else {
values.add(valueFor(element));
}
}
return values;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberFor(String place) {
return numberForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberForIn(String place, String container) {
SearchContext searchContext = setSearchContextToContainer(container);
try {
Integer number = null;
WebElement element = findByXPath(".//ol/li/descendant-or-self::text()[normalized(.)='%s']/ancestor-or-self::li", place);
if (element == null) {
element = findByXPath(".//ol/li/descendant-or-self::text()[contains(normalized(.),'%s')]/ancestor-or-self::li", place);
}
if (element != null) {
scrollIfNotOnScreen(element);
number = getSeleniumHelper().getNumberFor(element);
}
return number;
} finally {
resetSearchContext(searchContext);
}
}
public ArrayList<String> availableOptionsFor(String place) {
ArrayList<String> result = null;
WebElement element = getElementToSelectFor(place);
if (element != null) {
scrollIfNotOnScreen(element);
result = getSeleniumHelper().getAvailableOptions(element);
}
return result;
}
@WaitUntil
public boolean clear(String place) {
return clearIn(place, null);
}
@WaitUntil
public boolean clearIn(String place, String container) {
boolean result = false;
WebElement element = getElementToClear(place, container);
if (element != null) {
element.clear();
result = true;
}
return result;
}
protected WebElement getElementToClear(String place, String container) {
return getElementToSendValue(place, container);
}
@WaitUntil
public boolean enterAsInRowWhereIs(String value, String requestedColumnName, String selectOnColumn, String selectOnValue) {
boolean result = false;
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
String requestedIndex = getXPathForColumnIndex(requestedColumnName);
WebElement cell = findByXPath("%s[%s]", columnXPath, requestedIndex);
if (cell != null) {
WebElement element = getSeleniumHelper().getNestedElementForValue(cell);
if (isSelect(element)) {
result = clickSelectOption(element, value);
} else {
if (isInteractable(element)) {
result = true;
element.clear();
sendValue(element, value);
}
}
}
return result;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfColumnNumberInRowNumber(int columnIndex, int rowIndex) {
return getValueByXPath("(.//tr[boolean(td)])[%s]/td[%s]", Integer.toString(rowIndex), Integer.toString(columnIndex));
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowNumber(String requestedColumnName, int rowIndex) {
String columnXPath = String.format("(.//tr[boolean(td)])[%s]/td", rowIndex);
return valueInRow(columnXPath, requestedColumnName);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowWhereIs(String requestedColumnName, String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return valueInRow(columnXPath, requestedColumnName);
}
protected String valueInRow(String columnXPath, String requestedColumnName) {
String requestedIndex = getXPathForColumnIndex(requestedColumnName);
return getValueByXPath("%s[%s]", columnXPath, requestedIndex);
}
protected String getValueByXPath(String xpathPattern, String... params) {
WebElement element = findByXPath(xpathPattern, params);
if (element != null) {
WebElement nested = getSeleniumHelper().getNestedElementForValue(element);
if (isInteractable(nested)) {
element = nested;
}
}
return valueFor(element);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean rowExistsWhereIs(String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return findByXPath(columnXPath) != null;
}
@WaitUntil
public boolean clickInRowNumber(String place, int rowIndex) {
String columnXPath = String.format("(.//tr[boolean(td)])[%s]/td", rowIndex);
return clickInRow(columnXPath, place);
}
@WaitUntil
public boolean clickInRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return clickInRow(columnXPath, place);
}
protected boolean clickInRow(String columnXPath, String place) {
// find an input to click in the row
/**
* Downloads the target of a link in a grid's row.
* @param place which link to download.
* @param rowNumber (1-based) row number to retrieve link from.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowNumber(String place, int rowNumber) {
String columnXPath = String.format("(.//tr[boolean(td)])[%s]/td", rowNumber);
return downloadFromRow(columnXPath, place);
}
/**
* Downloads the target of a link in a grid, finding the row based on one of the other columns' value.
* @param place which link to download.
* @param selectOnColumn column header of cell whose value must be selectOnValue.
* @param selectOnValue value to be present in selectOnColumn to find correct row.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue);
return downloadFromRow(columnXPath, place);
}
protected String downloadFromRow(String columnXPath, String place) {
String result = null;
// find an a to download from based on its text()
WebElement element = findByXPath("%s//a[contains(normalized(text()),'%s')]", columnXPath, place);
if (element == null) {
// find an a to download based on its column header
String requestedIndex = getXPathForColumnIndex(place);
element = findByXPath("%s[%s]//a", columnXPath, requestedIndex);
if (element == null) {
// find an a to download in the row by its title (aka tooltip)
element = findByXPath("%s//a[contains(@title, '%s')]", columnXPath, place);
}
}
if (element != null) {
result = downloadLinkTarget(element);
}
return result;
}
/**
* Creates an XPath expression that will find a cell in a row, selecting the row based on the
* text in a specific column (identified by its header text).
* @param columnName header text of the column to find value in.
* @param value text to find in column with the supplied header.
* @return XPath expression selecting a td in the row
*/
protected String getXPathForColumnInRowByValueInOtherColumn(String columnName, String value) {
String selectIndex = getXPathForColumnIndex(columnName);
return String.format(".//tr[td[%s]/descendant-or-self::text()[normalized(.)='%s']]/td", selectIndex, value);
}
/**
* Creates an XPath expression that will determine, for a row, which index to use to select the cell in the column
* with the supplied header text value.
* @param columnName name of column in header (th)
* @return XPath expression which can be used to select a td in a row
*/
protected String getXPathForColumnIndex(String columnName) {
// determine how many columns are before the column with the requested name
// the column with the requested name will have an index of the value +1 (since XPath indexes are 1 based)
return String.format("count(ancestor::table[1]//tr/th/descendant-or-self::text()[normalized(.)='%s']/ancestor-or-self::th[1]/preceding-sibling::th)+1", columnName);
}
protected WebElement getElement(String place) {
return getElement(place, null);
}
protected WebElement getElement(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
return getSeleniumHelper().getElement(place);
} finally {
resetSearchContext(currentSearchContext);
}
}
/**
* @deprecated use #click(xpath=) instead.
*/
@WaitUntil
@Deprecated
public boolean clickByXPath(String xPath) {
WebElement element = findByXPath(xPath);
return clickElement(element);
}
/**
* @deprecated use #valueOf(xpath=) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByXPath(String xPath) {
return getTextByXPath(xPath);
}
protected String getTextByXPath(String xpathPattern, String... params) {
WebElement element = findByXPath(xpathPattern, params);
return getElementText(element);
}
/**
* @deprecated use #valueOf(css=.) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByClassName(String className) {
return getTextByClassName(className);
}
protected String getTextByClassName(String className) {
WebElement element = findByClassName(className);
return getElementText(element);
}
protected WebElement findByClassName(String className) {
By by = By.className(className);
return findElement(by);
}
protected WebElement findByXPath(String xpathPattern, String... params) {
return getSeleniumHelper().findByXPath(xpathPattern, params);
}
protected WebElement findByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElement(by);
}
protected List<WebElement> findAllByXPath(String xpathPattern, String... params) {
By by = getSeleniumHelper().byXpath(xpathPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByCss(String cssPattern, String... params) {
By by = getSeleniumHelper().byCss(cssPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElements(by);
}
protected List<WebElement> findElements(By by) {
return driver().findElements(by);
}
public void waitMilliSecondAfterScroll(int msToWait) {
waitAfterScroll = msToWait;
}
protected String getElementText(WebElement element) {
String result = null;
if (element != null) {
scrollIfNotOnScreen(element);
result = element.getText();
}
return result;
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
*/
@WaitUntil
public boolean scrollTo(String place) {
return scrollToIn(place, null);
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
* @param container parent of place.
*/
@WaitUntil
public boolean scrollToIn(String place, String container) {
boolean result = false;
WebElement element = getElementToScrollTo(place, container);
if (element != null) {
scrollTo(element);
result = true;
}
return result;
}
protected WebElement getElementToScrollTo(String place, String container) {
return getElementToCheckVisibility(place, container);
}
/**
* Scrolls browser window so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollTo(WebElement element) {
getSeleniumHelper().scrollTo(element);
if (waitAfterScroll > 0) {
waitMilliseconds(waitAfterScroll);
}
}
/**
* Scrolls browser window if element is not currently visible so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollIfNotOnScreen(WebElement element) {
if (!element.isDisplayed() || !isElementOnScreen(element)) {
scrollTo(element);
}
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabled(String place) {
return isEnabledIn(place, null);
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @param container parent of place.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabledIn(String place, String container) {
boolean result = false;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
if ("label".equalsIgnoreCase(element.getTagName())) {
// for labels we want to know whether their target is enabled, not the label itself
WebElement labelTarget = getSeleniumHelper().getLabelledElement(element);
if (labelTarget != null) {
element = labelTarget;
}
}
result = element.isEnabled();
}
return result;
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisible(String place) {
return isVisibleIn(place, null);
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleIn(String place, String container) {
return isVisibleImpl(place, container, true);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPage(String place) {
return isVisibleOnPageIn(place, null);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPageIn(String place, String container) {
return isVisibleImpl(place, container, false);
}
protected boolean isVisibleImpl(String place, String container, boolean checkOnScreen) {
boolean result = false;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null && element.isDisplayed()) {
if (checkOnScreen) {
result = isElementOnScreen(element);
} else {
result = true;
}
}
return result;
}
protected WebElement getElementToCheckVisibility(String place) {
return getElementToCheckVisibility(place, null);
}
protected WebElement getElementToCheckVisibility(String place, String container) {
return getElementToClick(place, container);
}
/**
* Checks whether element is in browser's viewport.
* @param element element to check
* @return true if element is in browser's viewport.
*/
protected boolean isElementOnScreen(WebElement element) {
Boolean onScreen = getSeleniumHelper().isElementOnScreen(element);
return onScreen == null || onScreen.booleanValue();
}
@WaitUntil
public boolean hoverOver(String place) {
return hoverOverIn(place, null);
}
@WaitUntil
public boolean hoverOverIn(String place, String container) {
WebElement element = getElementToClick(place, container);
return hoverOver(element);
}
protected boolean hoverOver(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (element.isDisplayed()) {
getSeleniumHelper().hoverOver(element);
result = true;
}
}
return result;
}
/**
* @param timeout number of seconds before waitUntil() and waitForJavascriptCallback() throw TimeOutException.
*/
public void secondsBeforeTimeout(int timeout) {
secondsBeforeTimeout = timeout;
secondsBeforePageLoadTimeout(timeout);
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setScriptWait(timeoutInMs);
}
/**
* @return number of seconds waitUntil() will wait at most.
*/
public int secondsBeforeTimeout() {
return secondsBeforeTimeout;
}
/**
* @param timeout number of seconds before waiting for a new page to load will throw a TimeOutException.
*/
public void secondsBeforePageLoadTimeout(int timeout) {
secondsBeforePageLoadTimeout = timeout;
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setPageLoadWait(timeoutInMs);
}
/**
* @return number of seconds Selenium will wait at most for a request to load a page.
*/
public int secondsBeforePageLoadTimeout() {
return secondsBeforePageLoadTimeout;
}
/**
* Clears HTML5's localStorage (for the domain of the current open page in the browser).
*/
public void clearLocalStorage() {
getSeleniumHelper().executeJavascript("localStorage.clear();");
}
/**
* Deletes all cookies(for the domain of the current open page in the browser).
*/
public void deleteAllCookies() {
getSeleniumHelper().deleteAllCookies();
}
/**
* @param directory sets base directory where screenshots will be stored.
*/
public void screenshotBaseDirectory(String directory) {
if (directory.equals("")
|| directory.endsWith("/")
|| directory.endsWith("\\")) {
screenshotBase = directory;
} else {
screenshotBase = directory + "/";
}
}
/**
* @param height height to use to display screenshot images
*/
public void screenshotShowHeight(String height) {
screenshotHeight = height;
}
/**
* @return (escaped) HTML content of current page.
*/
public String pageSource() {
String result = null;
String html = getSeleniumHelper().getHtml();
if (html != null) {
result = "<pre>" + StringEscapeUtils.escapeHtml4(html) + "</pre>";
}
return result;
}
/**
* Saves current page's source to the wiki'f files section and returns a link to the
* created file.
* @return hyperlink to the file containing the page source.
*/
public String savePageSource() {
String fileName = getSeleniumHelper().getResourceNameFromLocation();
return savePageSource(fileName, fileName + ".html");
}
protected String savePageSource(String fileName, String linkText) {
PageSourceSaver saver = getSeleniumHelper().getPageSourceSaver(pageSourceBase);
// make href to file
String url = saver.savePageSource(fileName);
return String.format("<a href=\"%s\">%s</a>", url, linkText);
}
/**
* Takes screenshot from current page
* @param basename filename (below screenshot base directory).
* @return location of screenshot.
*/
public String takeScreenshot(String basename) {
try {
String screenshotFile = createScreenshot(basename);
if (screenshotFile == null) {
throw new SlimFixtureException(false, "Unable to take screenshot: does the webdriver support it?");
} else {
screenshotFile = getScreenshotLink(screenshotFile);
}
return screenshotFile;
} catch (UnhandledAlertException e) {
// standard behavior will stop test, this breaks storyboard that will attempt to take screenshot
// after triggering alert, but before the alert can be handled.
// so we output a message but no exception. We rely on a next line to actually handle alert
// (which may mean either really handle or stop test).
return String.format(
"<div><strong>Unable to take screenshot</strong>, alert is active. Alert text:<br/>" +
"'<span>%s</span>'</div>",
StringEscapeUtils.escapeHtml4(alertText()));
}
}
private String getScreenshotLink(String screenshotFile) {
String wikiUrl = getWikiUrl(screenshotFile);
if (wikiUrl != null) {
// make href to screenshot
if ("".equals(screenshotHeight)) {
wikiUrl = String.format("<a href=\"%s\">%s</a>",
wikiUrl, screenshotFile);
} else {
wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"/></a>",
wikiUrl, screenshotFile, screenshotHeight);
}
screenshotFile = wikiUrl;
}
return screenshotFile;
}
private String createScreenshot(String basename) {
String name = getScreenshotBasename(basename);
return getSeleniumHelper().takeScreenshot(name);
}
private String createScreenshot(String basename, Throwable t) {
String screenshotFile;
byte[] screenshotInException = getSeleniumHelper().findScreenshot(t);
if (screenshotInException == null || screenshotInException.length == 0) {
screenshotFile = createScreenshot(basename);
} else {
String name = getScreenshotBasename(basename);
screenshotFile = getSeleniumHelper().writeScreenshot(name, screenshotInException);
}
return screenshotFile;
}
private String getScreenshotBasename(String basename) {
return screenshotBase + basename;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws SlimFixtureException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntil(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
String message = getTimeoutMessage(e);
return lastAttemptBeforeThrow(condition, new SlimFixtureException(false, message, e));
}
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur the whole test is stopped.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws TimeoutStopTestException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntilOrStop(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
try {
return handleTimeoutException(e);
} catch (TimeoutStopTestException tste) {
return lastAttemptBeforeThrow(condition, tste);
}
}
}
/**
* Tries the condition one last time before throwing an exception.
* This to prevent exception messages in the wiki that show no problem, which could happen if the browser's
* window content has changed between last (failing) try at condition and generation of the exception.
* @param <T> the return type of the method, which must not be Void
* @param condition condition that caused exception.
* @param e exception that will be thrown if condition does not return a result.
* @return last attempt results, if not null.
* @throws SlimFixtureException throws e if last attempt returns null.
*/
protected <T> T lastAttemptBeforeThrow(ExpectedCondition<T> condition, SlimFixtureException e) {
T lastAttemptResult = null;
try {
// last attempt to ensure condition has not been met
// this to prevent messages that show no problem
lastAttemptResult = condition.apply(getSeleniumHelper().driver());
} catch (Throwable t) {
// ignore
}
if (lastAttemptResult != null) {
return lastAttemptResult;
}
throw e;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur null is returned.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @return result of condition.
*/
protected <T> T waitUntilOrNull(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
return null;
}
}
protected <T> T waitUntilImpl(ExpectedCondition<T> condition) {
return getSeleniumHelper().waitUntil(secondsBeforeTimeout(), condition);
}
protected <T> T handleTimeoutException(TimeoutException e) {
String message = getTimeoutMessage(e);
throw new TimeoutStopTestException(false, message, e);
}
private String getTimeoutMessage(TimeoutException e) {
String messageBase = String.format("Timed-out waiting (after %ss)", secondsBeforeTimeout());
return getSlimFixtureExceptionMessage("timeouts", "timeout", messageBase, e);
}
protected void handleRequiredElementNotFound(String toFind) {
handleRequiredElementNotFound(toFind, null);
}
protected void handleRequiredElementNotFound(String toFind, Throwable t) {
String messageBase = String.format("Unable to find: %s", toFind);
String message = getSlimFixtureExceptionMessage("notFound", toFind, messageBase, t);
throw new SlimFixtureException(false, message, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotFolder, String screenshotFile, String messageBase, Throwable t) {
String screenshotBaseName = String.format("%s/%s/%s", screenshotFolder, getClass().getSimpleName(), screenshotFile);
return getSlimFixtureExceptionMessage(screenshotBaseName, messageBase, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotBaseName, String messageBase, Throwable t) {
// take a screenshot of what was on screen
String screenShotFile = null;
try {
screenShotFile = createScreenshot(screenshotBaseName, t);
} catch (UnhandledAlertException e) {
System.err.println("Unable to take screenshot while alert is present for exception: " + messageBase);
} catch (Exception sse) {
System.err.println("Unable to take screenshot for exception: " + messageBase);
sse.printStackTrace();
}
String message = messageBase;
if (message == null) {
if (t == null) {
message = "";
} else {
message = ExceptionUtils.getStackTrace(t);
}
}
if (screenShotFile != null) {
String label = "Page content";
try {
String fileName;
if (t != null) {
fileName = t.getClass().getName();
} else if (screenshotBaseName != null) {
fileName = screenshotBaseName;
} else {
fileName = "exception";
}
label = savePageSource(fileName, label);
} catch (UnhandledAlertException e) {
System.err.println("Unable to capture page source while alert is present for exception: " + messageBase);
} catch (Exception e) {
System.err.println("Unable to capture page source for exception: " + messageBase);
e.printStackTrace();
}
String exceptionMsg = formatExceptionMsg(message);
message = String.format("<div><div>%s.</div><div>%s:%s</div></div>",
exceptionMsg, label, getScreenshotLink(screenShotFile));
}
return message;
}
protected String formatExceptionMsg(String value) {
return StringEscapeUtils.escapeHtml4(value);
}
private WebDriver driver() {
return getSeleniumHelper().driver();
}
private WebDriverWait waitDriver() {
return getSeleniumHelper().waitDriver();
}
/**
* @return helper to use.
*/
protected final SeleniumHelper getSeleniumHelper() {
return seleniumHelper;
}
/**
* Sets SeleniumHelper to use, for testing purposes.
* @param helper helper to use.
*/
void setSeleniumHelper(SeleniumHelper helper) {
seleniumHelper = helper;
}
public int currentBrowserWidth() {
return getWindowSize().getWidth();
}
public int currentBrowserHeight() {
return getWindowSize().getHeight();
}
public void setBrowserWidth(int newWidth) {
int currentHeight = currentBrowserHeight();
setBrowserSizeToBy(newWidth, currentHeight);
}
public void setBrowserHeight(int newHeight) {
int currentWidth = currentBrowserWidth();
setBrowserSizeToBy(currentWidth, newHeight);
}
public void setBrowserSizeToBy(int newWidth, int newHeight) {
getSeleniumHelper().setWindowSize(newWidth, newHeight);
Dimension actualSize = getWindowSize();
if (actualSize.getHeight() != newHeight || actualSize.getWidth() != newWidth) {
String message = String.format("Unable to change size to: %s x %s; size is: %s x %s",
newWidth, newHeight, actualSize.getWidth(), actualSize.getHeight());
throw new SlimFixtureException(false, message);
}
}
protected Dimension getWindowSize() {
return getSeleniumHelper().getWindowSize();
}
public void setBrowserSizeToMaximum() {
getSeleniumHelper().setWindowSizeToMaximum();
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String download(String place) {
return downloadIn(place, null);
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @param container part of screen containing link.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadIn(String place, String container) {
SearchContext currentSearchContext = setSearchContextToContainer(container);
try {
By selector = By.linkText(place);
WebElement element = findElement(selector);
if (element == null) {
selector = By.partialLinkText(place);
element = findElement(selector);
if (element == null) {
selector = By.id(place);
element = findElement(selector);
if (element == null) {
selector = By.name(place);
element = findElement(selector);
}
}
}
return downloadLinkTarget(element);
} finally {
resetSearchContext(currentSearchContext);
}
}
protected WebElement findElement(By selector) {
return getSeleniumHelper().findElement(selector);
}
/**
* Downloads the target of the supplied link.
* @param element link to follow.
* @return downloaded file if any, null otherwise.
*/
protected String downloadLinkTarget(WebElement element) {
String result = null;
if (element != null) {
String href = element.getAttribute("href");
if (href != null) {
result = downloadContentFrom(href);
} else {
throw new SlimFixtureException(false, "Could not determine url to download from");
}
}
return result;
}
/**
* Downloads binary content from specified url (using the browser's cookies).
* @param urlOrLink url to download from
* @return link to downloaded file
*/
public String downloadContentFrom(String urlOrLink) {
String result = null;
if (urlOrLink != null) {
String url = getUrl(urlOrLink);
BinaryHttpResponse resp = new BinaryHttpResponse();
getUrlContent(url, resp);
byte[] content = resp.getResponseContent();
if (content == null) {
result = resp.getResponse();
} else {
String fileName = resp.getFileName();
String baseName = FilenameUtils.getBaseName(fileName);
String ext = FilenameUtils.getExtension(fileName);
String downloadedFile = FileUtil.saveToFile(getDownloadName(baseName), ext, content);
String wikiUrl = getWikiUrl(downloadedFile);
if (wikiUrl != null) {
// make href to file
result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName);
} else {
result = downloadedFile;
}
}
}
return result;
}
/**
* Selects a file using the first file upload control.
* @param fileName file to upload
* @return true, if a file input was found and file existed.
*/
@WaitUntil
public boolean selectFile(String fileName) {
return selectFileFor(fileName, "css=input[type='file']");
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileFor(String fileName, String place) {
return selectFileForIn(fileName, place, null);
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @param container part of screen containing place
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileForIn(String fileName, String place, String container) {
boolean result = false;
if (fileName != null) {
String fullPath = getFilePathFromWikiUrl(fileName);
if (new File(fullPath).exists()) {
WebElement element = getElementToSelectFile(place, container);
if (element != null) {
element.sendKeys(fullPath);
result = true;
}
} else {
throw new SlimFixtureException(false, "Unable to find file: " + fullPath);
}
}
return result;
}
protected WebElement getElementToSelectFile(String place, String container) {
WebElement result = null;
WebElement element = getElement(place, container);
if (element != null
&& "input".equalsIgnoreCase(element.getTagName())
&& "file".equalsIgnoreCase(element.getAttribute("type"))) {
result = element;
}
return result;
}
private String getDownloadName(String baseName) {
return downloadBase + baseName;
}
/**
* GETs content of specified URL, using the browsers cookies.
* @param url url to retrieve content from
* @param resp response to store content in
*/
protected void getUrlContent(String url, HttpResponse resp) {
getEnvironment().addSeleniumCookies(resp);
getEnvironment().doGet(url, resp);
}
/**
* Gets the value of the cookie with the supplied name.
* @param cookieName name of cookie to get value from.
* @return cookie's value if any.
*/
public String cookieValue(String cookieName) {
String result = null;
Cookie cookie = getSeleniumHelper().getCookie(cookieName);
if (cookie != null) {
result = cookie.getValue();
}
return result;
}
protected Object waitForJavascriptCallback(String statement, Object... parameters) {
try {
return getSeleniumHelper().waitForJavascriptCallback(statement, parameters);
} catch (TimeoutException e) {
return handleTimeoutException(e);
}
}
public NgBrowserTest getNgBrowserTest() {
return ngBrowserTest;
}
public void setNgBrowserTest(NgBrowserTest ngBrowserTest) {
this.ngBrowserTest = ngBrowserTest;
}
public boolean isImplicitWaitForAngularEnabled() {
return implicitWaitForAngular;
}
public void setImplicitWaitForAngularTo(boolean implicitWaitForAngular) {
this.implicitWaitForAngular = implicitWaitForAngular;
}
public void setImplicitFindInFramesTo(boolean implicitFindInFrames) {
this.implicitFindInFrames = implicitFindInFrames;
}
}
|
package nl.hsac.fitnesse.fixture.slim.web;
import fitnesse.slim.fixtureInteraction.FixtureInteraction;
import nl.hsac.fitnesse.fixture.slim.SlimFixture;
import nl.hsac.fitnesse.fixture.slim.SlimFixtureException;
import nl.hsac.fitnesse.fixture.slim.StopTestException;
import nl.hsac.fitnesse.fixture.slim.web.annotation.TimeoutPolicy;
import nl.hsac.fitnesse.fixture.slim.web.annotation.WaitUntil;
import nl.hsac.fitnesse.fixture.util.BinaryHttpResponse;
import nl.hsac.fitnesse.fixture.util.FileUtil;
import nl.hsac.fitnesse.fixture.util.HttpResponse;
import nl.hsac.fitnesse.fixture.util.ReflectionHelper;
import nl.hsac.fitnesse.fixture.util.selenium.PageSourceSaver;
import nl.hsac.fitnesse.fixture.util.selenium.SeleniumHelper;
import nl.hsac.fitnesse.fixture.util.selenium.by.ContainerBy;
import nl.hsac.fitnesse.fixture.util.selenium.by.GridBy;
import nl.hsac.fitnesse.fixture.util.selenium.by.TextBy;
import nl.hsac.fitnesse.fixture.util.selenium.by.XPathBy;
import nl.hsac.fitnesse.slim.interaction.ExceptionHelper;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class BrowserTest extends SlimFixture {
private SeleniumHelper seleniumHelper = getEnvironment().getSeleniumHelper();
private ReflectionHelper reflectionHelper = getEnvironment().getReflectionHelper();
private NgBrowserTest ngBrowserTest;
private boolean implicitWaitForAngular = false;
private boolean implicitFindInFrames = true;
private int secondsBeforeTimeout;
private int secondsBeforePageLoadTimeout;
private int waitAfterScroll = 150;
private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/";
private String screenshotHeight = "200";
private String downloadBase = new File(filesDir, "downloads").getPath() + "/";
private String pageSourceBase = new File(filesDir, "pagesources").getPath() + "/";
@Override
protected void beforeInvoke(Method method, Object[] arguments) {
super.beforeInvoke(method, arguments);
waitForAngularIfNeeded(method);
}
@Override
protected Object invoke(final FixtureInteraction interaction, final Method method, final Object[] arguments)
throws Throwable {
Object result;
WaitUntil waitUntil = reflectionHelper.getAnnotation(WaitUntil.class, method);
if (waitUntil == null) {
result = superInvoke(interaction, method, arguments);
} else {
result = invokedWrappedInWaitUntil(waitUntil, interaction, method, arguments);
}
return result;
}
protected Object invokedWrappedInWaitUntil(WaitUntil waitUntil, final FixtureInteraction interaction, final Method method, final Object[] arguments) {
ExpectedCondition<Object> condition = new ExpectedCondition<Object>() {
@Override
public Object apply(WebDriver webDriver) {
try {
return superInvoke(interaction, method, arguments);
} catch (Throwable e) {
Throwable realEx = ExceptionHelper.stripReflectionException(e);
if (realEx instanceof RuntimeException) {
throw (RuntimeException) realEx;
} else if (realEx instanceof Error) {
throw (Error) realEx;
} else {
throw new RuntimeException(realEx);
}
}
}
};
condition = wrapConditionForFramesIfNeeded(condition);
Object result;
switch (waitUntil.value()) {
case STOP_TEST:
result = waitUntilOrStop(condition);
break;
case RETURN_NULL:
result = waitUntilOrNull(condition);
break;
case RETURN_FALSE:
result = waitUntilOrNull(condition) != null;
break;
case THROW:
default:
result = waitUntil(condition);
break;
}
return result;
}
protected Object superInvoke(FixtureInteraction interaction, Method method, Object[] arguments) throws Throwable {
return super.invoke(interaction, method, arguments);
}
/**
* Determines whether the current method might require waiting for angular given the currently open site,
* and ensure it does if needed.
* @param method
*/
protected void waitForAngularIfNeeded(Method method) {
if (isImplicitWaitForAngularEnabled()) {
try {
if (ngBrowserTest == null) {
ngBrowserTest = new NgBrowserTest();
}
if (ngBrowserTest.requiresWaitForAngular(method) && currentSiteUsesAngular()) {
try {
ngBrowserTest.waitForAngularRequestsToFinish();
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Found Angular, but encountered an error while waiting for it to be ready. ");
e.printStackTrace();
}
}
} catch (UnhandledAlertException e) {
System.err.println("Cannot determine whether Angular is present while alert is active.");
} catch (Exception e) {
// if something goes wrong, just use normal behavior: continue to invoke()
System.err.print("Error while determining whether Angular is present. ");
e.printStackTrace();
}
}
}
protected boolean currentSiteUsesAngular() {
Object windowHasAngular = getSeleniumHelper().executeJavascript("return window.angular?1:0;");
return Long.valueOf(1).equals(windowHasAngular);
}
@Override
protected Throwable handleException(Method method, Object[] arguments, Throwable t) {
Throwable result;
if (t instanceof UnhandledAlertException) {
UnhandledAlertException e = (UnhandledAlertException) t;
String alertText = e.getAlertText();
if (alertText == null) {
alertText = alertText();
}
String msgBase = "Unhandled alert: alert must be confirmed or dismissed before test can continue. Alert text: " + alertText;
String msg = getSlimFixtureExceptionMessage("alertException", msgBase, e);
result = new StopTestException(false, msg, t);
} else if (t instanceof SlimFixtureException) {
result = super.handleException(method, arguments, t);
} else {
String msg = getSlimFixtureExceptionMessage("exception", null, t);
result = new SlimFixtureException(false, msg, t);
}
return result;
}
public BrowserTest() {
secondsBeforeTimeout(seleniumHelper.getDefaultTimeoutSeconds());
ensureActiveTabIsNotClosed();
}
public BrowserTest(int secondsBeforeTimeout) {
secondsBeforeTimeout(secondsBeforeTimeout);
ensureActiveTabIsNotClosed();
}
public boolean open(String address) {
final String url = getUrl(address);
try {
getNavigation().to(url);
} catch (TimeoutException e) {
handleTimeoutException(e);
} finally {
switchToDefaultContent();
}
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
String readyState = getSeleniumHelper().executeJavascript("return document.readyState").toString();
// IE 7 is reported to return "loaded"
boolean done = "complete".equalsIgnoreCase(readyState) || "loaded".equalsIgnoreCase(readyState);
if (!done) {
System.err.printf("Open of %s returned while document.readyState was %s", url, readyState);
System.err.println();
}
return done;
}
});
return true;
}
public String location() {
return driver().getCurrentUrl();
}
public boolean back() {
getNavigation().back();
switchToDefaultContent();
// firefox sometimes prevents immediate back, if previous page was reached via POST
waitMilliseconds(500);
WebElement element = findElement(By.id("errorTryAgain"));
if (element != null) {
element.click();
// don't use confirmAlert as this may be overridden in subclass and to get rid of the
// firefox pop-up we need the basic behavior
getSeleniumHelper().getAlert().accept();
}
return true;
}
public boolean forward() {
getNavigation().forward();
switchToDefaultContent();
return true;
}
public boolean refresh() {
getNavigation().refresh();
switchToDefaultContent();
return true;
}
private WebDriver.Navigation getNavigation() {
return getSeleniumHelper().navigate();
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String alertText() {
Alert alert = getAlert();
String text = null;
if (alert != null) {
text = alert.getText();
}
return text;
}
@WaitUntil
public boolean confirmAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.accept();
onAlertHandled(true);
result = true;
}
return result;
}
@WaitUntil
public boolean dismissAlert() {
Alert alert = getAlert();
boolean result = false;
if (alert != null) {
alert.dismiss();
onAlertHandled(false);
result = true;
}
return result;
}
/**
* Called when an alert is either dismissed or accepted.
* @param accepted true if the alert was accepted, false if dismissed.
*/
protected void onAlertHandled(boolean accepted) {
// if we were looking in nested frames, we could not go back to original frame
// because of the alert. Ensure we do so now the alert is handled.
getSeleniumHelper().resetFrameDepthOnAlertError();
}
protected Alert getAlert() {
return getSeleniumHelper().getAlert();
}
public boolean openInNewTab(String url) {
String cleanUrl = getUrl(url);
final int tabCount = tabCount();
getSeleniumHelper().executeJavascript("window.open('%s', '_blank')", cleanUrl);
// ensure new window is open
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return tabCount() > tabCount;
}
});
return switchToNextTab();
}
@WaitUntil
public boolean switchToNextTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab + 1;
if (nextTab == tabs.size()) {
nextTab = 0;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
@WaitUntil
public boolean switchToPreviousTab() {
boolean result = false;
List<String> tabs = getTabHandles();
if (tabs.size() > 1) {
int currentTab = getCurrentTabIndex(tabs);
int nextTab = currentTab - 1;
if (nextTab < 0) {
nextTab = tabs.size() - 1;
}
goToTab(tabs, nextTab);
result = true;
}
return result;
}
public boolean closeTab() {
boolean result = false;
List<String> tabs = getTabHandles();
int currentTab = getCurrentTabIndex(tabs);
int tabToGoTo = -1;
if (currentTab > 0) {
tabToGoTo = currentTab - 1;
} else {
if (tabs.size() > 1) {
tabToGoTo = 1;
}
}
if (tabToGoTo > -1) {
WebDriver driver = driver();
driver.close();
goToTab(tabs, tabToGoTo);
result = true;
}
return result;
}
public void ensureOnlyOneTab() {
ensureActiveTabIsNotClosed();
int tabCount = tabCount();
for (int i = 1; i < tabCount; i++) {
closeTab();
}
}
public boolean ensureActiveTabIsNotClosed() {
boolean result = false;
List<String> tabHandles = getTabHandles();
int currentTab = getCurrentTabIndex(tabHandles);
if (currentTab < 0) {
result = true;
goToTab(tabHandles, 0);
}
return result;
}
public int tabCount() {
return getTabHandles().size();
}
public int currentTabIndex() {
return getCurrentTabIndex(getTabHandles()) + 1;
}
protected int getCurrentTabIndex(List<String> tabHandles) {
return getSeleniumHelper().getCurrentTabIndex(tabHandles);
}
protected void goToTab(List<String> tabHandles, int indexToGoTo) {
getSeleniumHelper().goToTab(tabHandles, indexToGoTo);
}
protected List<String> getTabHandles() {
return getSeleniumHelper().getTabHandles();
}
/**
* Activates main/top-level iframe (i.e. makes it the current frame).
*/
public void switchToDefaultContent() {
getSeleniumHelper().switchToDefaultContent();
clearSearchContext();
}
/**
* Activates specified child frame of current iframe.
* @param technicalSelector selector to find iframe.
* @return true if iframe was found.
*/
public boolean switchToFrame(String technicalSelector) {
boolean result = false;
WebElement iframe = getElement(technicalSelector);
if (iframe != null) {
getSeleniumHelper().switchToFrame(iframe);
result = true;
}
return result;
}
/**
* Activates parent frame of current iframe.
* Does nothing if when current frame is the main/top-level one.
*/
public void switchToParentFrame() {
getSeleniumHelper().switchToParentFrame();
}
public String pageTitle() {
return getSeleniumHelper().getPageTitle();
}
/**
* @return current page's content type.
*/
public String pageContentType() {
String result = null;
Object ct = getSeleniumHelper().executeJavascript("return document.contentType;");
if (ct != null) {
result = ct.toString();
}
return result;
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAs(String value, String place) {
return enterAsIn(value, place, null);
}
/**
* Replaces content at place by value.
* @param value value to set.
* @param place element to set value on.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterAsIn(String value, String place, String container) {
return enter(value, place, container, true);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterFor(String value, String place) {
return enterForIn(value, place, null);
}
/**
* Adds content to place.
* @param value value to add.
* @param place element to add value to.
* @param container element containing place.
* @return true, if element was found.
*/
@WaitUntil
public boolean enterForIn(String value, String place, String container) {
return enter(value, place, container, false);
}
protected boolean enter(String value, String place, boolean shouldClear) {
return enter(value, place, null, shouldClear);
}
protected boolean enter(String value, String place, String container, boolean shouldClear) {
WebElement element = getElementToSendValue(place, container);
boolean result = element != null && isInteractable(element);
if (result) {
if (shouldClear) {
element.clear();
}
sendValue(element, value);
}
return result;
}
@WaitUntil
public boolean enterDateAs(String date, String place) {
WebElement element = getElementToSendValue(place);
boolean result = element != null && isInteractable(element);
if (result) {
getSeleniumHelper().fillDateInput(element, date);
}
return result;
}
protected WebElement getElementToSendValue(String place) {
return getElementToSendValue(place, null);
}
protected WebElement getElementToSendValue(String place, String container) {
return getElement(place, container);
}
/**
* Simulates pressing the 'Tab' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressTab() {
return sendKeysToActiveElement(Keys.TAB);
}
/**
* Simulates pressing the 'Enter' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEnter() {
return sendKeysToActiveElement(Keys.ENTER);
}
/**
* Simulates pressing the 'Esc' key.
* @return true, if an element was active the key could be sent to.
*/
public boolean pressEsc() {
return sendKeysToActiveElement(Keys.ESCAPE);
}
/**
* Simulates typing a text to the current active element.
* @param text text to type.
* @return true, if an element was active the text could be sent to.
*/
public boolean type(String text) {
String value = cleanupValue(text);
return sendKeysToActiveElement(value);
}
public boolean press(String key) {
CharSequence s;
String[] parts = key.split("\\s*\\+\\s*");
if (parts.length > 1
&& !"".equals(parts[0]) && !"".equals(parts[1])) {
CharSequence[] sequence = new CharSequence[parts.length];
for (int i = 0; i < parts.length; i++) {
sequence[i] = parseKey(parts[i]);
}
s = Keys.chord(sequence);
} else {
s = parseKey(key);
}
return sendKeysToActiveElement(s);
}
protected CharSequence parseKey(String key) {
CharSequence s;
try {
s = Keys.valueOf(key.toUpperCase());
} catch (IllegalArgumentException e) {
s = key;
}
return s;
}
/**
* Simulates pressing keys.
* @param keys keys to press.
* @return true, if an element was active the keys could be sent to.
*/
protected boolean sendKeysToActiveElement(CharSequence keys) {
boolean result = false;
WebElement element = getSeleniumHelper().getActiveElement();
if (element != null) {
element.sendKeys(keys);
result = true;
}
return result;
}
/**
* Sends Fitnesse cell content to element.
* @param element element to call sendKeys() on.
* @param value cell content.
*/
protected void sendValue(WebElement element, String value) {
if (StringUtils.isNotEmpty(value)) {
String keys = cleanupValue(value);
element.sendKeys(keys);
}
}
@WaitUntil
public boolean selectAs(String value, String place) {
return selectFor(value, place);
}
@WaitUntil
public boolean selectFor(String value, String place) {
WebElement element = getElementToSelectFor(place);
return clickSelectOption(element, value);
}
@WaitUntil
public boolean selectForIn(String value, String place, String container) {
return doInContainer(container, () -> selectFor(value, place));
}
@WaitUntil
public boolean enterForHidden(final String value, final String idOrName) {
return getSeleniumHelper().setHiddenInputValue(idOrName, value);
}
protected WebElement getElementToSelectFor(String selectPlace) {
return getElement(selectPlace);
}
protected boolean clickSelectOption(WebElement element, String optionValue) {
boolean result = false;
if (element != null) {
if (isSelect(element)) {
optionValue = cleanupValue(optionValue);
By xpath = getSeleniumHelper().byXpath(".//option[normalized(text()) = '%s']", optionValue);
WebElement option = getSeleniumHelper().findElement(element, xpath);
if (option == null) {
xpath = getSeleniumHelper().byXpath(".//option[contains(normalized(text()), '%s')]", optionValue);
option = getSeleniumHelper().findElement(element, xpath);
}
if (option != null) {
result = clickElement(option);
}
}
}
return result;
}
@WaitUntil
public boolean click(final String place) {
return clickImp(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailable(String place) {
return clickIfAvailableIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean clickIfAvailableIn(String place, String container) {
return clickImp(place, container);
}
@WaitUntil
public boolean clickIn(String place, String container) {
return clickImp(place, container);
}
protected boolean clickImp(String place, String container) {
boolean result = false;
place = cleanupValue(place);
try {
WebElement element = getElementToClick(place, container);
result = clickElement(element);
} catch (WebDriverException e) {
// if other element hides the element (in Chrome) an exception is thrown
String msg = e.getMessage();
if (msg == null || !msg.contains("Other element would receive the click")) {
throw e;
}
}
return result;
}
@WaitUntil
public boolean doubleClick(String place) {
return doubleClickIn(place, null);
}
@WaitUntil
public boolean doubleClickIn(String place, String container) {
WebElement element = getElementToClick(place, container);
return doubleClick(element);
}
protected boolean doubleClick(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
getSeleniumHelper().doubleClick(element);
result = true;
}
}
return result;
}
@WaitUntil
public boolean rightClick(String place) {
return rightClickIn(place, null);
}
@WaitUntil
public boolean rightClickIn(String place, String container) {
WebElement element = getElementToClick(place, container);
return rightClick(element);
}
protected boolean rightClick(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
getSeleniumHelper().rightClick(element);
result = true;
}
}
return result;
}
@WaitUntil
public boolean dragAndDropTo(String source, String destination) {
WebElement sourceElement = getElementToClick(source);
WebElement destinationElement = getElementToClick(destination);
return dragAndDropTo(sourceElement, destinationElement);
}
protected boolean dragAndDropTo(WebElement sourceElement, WebElement destinationElement) {
boolean result = false;
if ((sourceElement != null) && (destinationElement != null)) {
scrollIfNotOnScreen(sourceElement);
if (isInteractable(sourceElement) && destinationElement.isDisplayed()) {
getSeleniumHelper().dragAndDrop(sourceElement, destinationElement);
result = true;
}
}
return result;
}
protected WebElement getElementToClick(String place) {
return getSeleniumHelper().getElementToClick(place);
}
protected WebElement getElementToClick(String place, String container) {
return doInContainer(container, () -> getElementToClick(place));
}
protected <T> T doInContainer(String container, Supplier<T> action) {
T result = null;
if (container == null) {
result = action.get();
} else {
WebElement containerElement = getContainerElement(container);
if (containerElement != null) {
result = doInContainer(containerElement, action);
}
}
return result;
}
protected <T> T doInContainer(WebElement container, Supplier<T> action) {
return getSeleniumHelper().doInContext(container, action);
}
@WaitUntil
public boolean setSearchContextTo(String container) {
boolean result = false;
WebElement containerElement = getContainerElement(container);
if (containerElement != null) {
setSearchContextTo(containerElement);
result = true;
}
return result;
}
protected void setSearchContextTo(SearchContext containerElement) {
getSeleniumHelper().setCurrentContext(containerElement);
}
public void clearSearchContext() {
getSeleniumHelper().setCurrentContext(null);
}
protected WebElement getContainerElement(String container) {
return findByTechnicalSelectorOr(container, this::getContainerImpl);
}
protected WebElement getContainerImpl(String container) {
return findElement(ContainerBy.heuristic(container));
}
protected boolean clickElement(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (isInteractable(element)) {
element.click();
result = true;
}
}
return result;
}
protected boolean isInteractable(WebElement element) {
return getSeleniumHelper().isInteractable(element);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForPage(String pageName) {
return pageTitle().equals(pageName);
}
public boolean waitForTagWithText(String tagName, String expectedText) {
return waitForElementWithText(By.tagName(tagName), expectedText);
}
public boolean waitForClassWithText(String cssClassName, String expectedText) {
return waitForElementWithText(By.className(cssClassName), expectedText);
}
protected boolean waitForElementWithText(final By by, String expectedText) {
final String textToLookFor = cleanExpectedValue(expectedText);
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
boolean ok = false;
List<WebElement> elements = webDriver.findElements(by);
if (elements != null) {
for (WebElement element : elements) {
// we don't want stale elements to make single
// element false, but instead we stop processing
// current list and do a new findElements
ok = hasText(element, textToLookFor);
if (ok) {
// no need to continue to check other elements
break;
}
}
}
return ok;
}
});
}
protected String cleanExpectedValue(String expectedText) {
return cleanupValue(expectedText);
}
protected boolean hasText(WebElement element, String textToLookFor) {
boolean ok;
String actual = getElementText(element);
if (textToLookFor == null) {
ok = actual == null;
} else {
if (StringUtils.isEmpty(actual)) {
String value = element.getAttribute("value");
if (!StringUtils.isEmpty(value)) {
actual = value;
}
}
if (actual != null) {
actual = actual.trim();
}
ok = textToLookFor.equals(actual);
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForClass(String cssClassName) {
boolean ok = false;
WebElement element = findElement(By.className(cssClassName));
if (element != null) {
ok = true;
}
return ok;
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisible(String place) {
return waitForVisibleIn(place, null);
}
@WaitUntil(TimeoutPolicy.STOP_TEST)
public boolean waitForVisibleIn(String place, String container) {
Boolean result = Boolean.FALSE;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
/**
* @deprecated use #waitForVisible(xpath=) instead
*/
@Deprecated
public boolean waitForXPathVisible(String xPath) {
By by = By.xpath(xPath);
return waitForVisible(by);
}
@Deprecated
protected boolean waitForVisible(final By by) {
return waitUntilOrStop(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
Boolean result = Boolean.FALSE;
WebElement element = findElement(by);
if (element != null) {
scrollIfNotOnScreen(element);
result = element.isDisplayed();
}
return result;
}
});
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOf(String place) {
return valueFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueFor(String place) {
return valueForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfIn(String place, String container) {
return valueForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueForIn(String place, String container) {
WebElement element = getElementToRetrieveValue(place, container);
return valueFor(element);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String normalizedValueOf(String place) {
return normalizedValueFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String normalizedValueFor(String place) {
return normalizedValueForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String normalizedValueOfIn(String place, String container) {
return normalizedValueForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String normalizedValueForIn(String place, String container) {
String value = valueForIn(place, container);
return XPathBy.getNormalizedText(value);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String tooltipFor(String place) {
return tooltipForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String tooltipForIn(String place, String container) {
return valueOfAttributeOnIn("title", place, container);
}
@WaitUntil
public String targetOfLink(String place) {
WebElement linkElement = getSeleniumHelper().getLink(place);
return getLinkTarget(linkElement);
}
protected String getLinkTarget(WebElement linkElement) {
String target = null;
if (linkElement != null) {
target = linkElement.getAttribute("href");
}
return target;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfAttributeOn(String attribute, String place) {
return valueOfAttributeOnIn(attribute, place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfAttributeOnIn(String attribute, String place, String container) {
String result = null;
WebElement element = getElementToRetrieveValue(place, container);
if (element != null) {
result = element.getAttribute(attribute);
}
return result;
}
protected WebElement getElementToRetrieveValue(String place, String container) {
return getElement(place, container);
}
protected String valueFor(By by) {
WebElement element = getSeleniumHelper().findElement(by);
return valueFor(element);
}
protected String valueFor(WebElement element) {
String result = null;
if (element != null) {
if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
if (options.size() > 0) {
result = getElementText(options.get(0));
}
} else {
String elementType = element.getAttribute("type");
if ("checkbox".equals(elementType)
|| "radio".equals(elementType)) {
result = String.valueOf(element.isSelected());
} else if ("li".equalsIgnoreCase(element.getTagName())) {
result = getElementText(element);
} else {
result = element.getAttribute("value");
if (result == null) {
result = getElementText(element);
}
}
}
}
return result;
}
private boolean isSelect(WebElement element) {
return "select".equalsIgnoreCase(element.getTagName());
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOf(String place) {
return valuesFor(place);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesOfIn(String place, String container) {
return valuesForIn(place, container);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesFor(String place) {
return valuesForIn(place, null);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public ArrayList<String> valuesForIn(String place, String container) {
ArrayList<String> values = null;
WebElement element = getElementToRetrieveValue(place, container);
if (element != null) {
values = new ArrayList<String>();
String tagName = element.getTagName();
if ("ul".equalsIgnoreCase(tagName)
|| "ol".equalsIgnoreCase(tagName)) {
List<WebElement> items = element.findElements(By.tagName("li"));
for (WebElement item : items) {
if (item.isDisplayed()) {
values.add(getElementText(item));
}
}
} else if (isSelect(element)) {
Select s = new Select(element);
List<WebElement> options = s.getAllSelectedOptions();
for (WebElement item : options) {
values.add(getElementText(item));
}
} else {
values.add(valueFor(element));
}
}
return values;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberFor(String place) {
Integer number = null;
WebElement element = findByXPath(".//ol/li/descendant-or-self::text()[normalized(.)='%s']/ancestor-or-self::li", place);
if (element == null) {
element = findByXPath(".//ol/li/descendant-or-self::text()[contains(normalized(.),'%s')]/ancestor-or-self::li", place);
}
if (element != null) {
scrollIfNotOnScreen(element);
number = getSeleniumHelper().getNumberFor(element);
}
return number;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public Integer numberForIn(String place, String container) {
return doInContainer(container, () -> numberFor(place));
}
public ArrayList<String> availableOptionsFor(String place) {
ArrayList<String> result = null;
WebElement element = getElementToSelectFor(place);
if (element != null) {
scrollIfNotOnScreen(element);
result = getSeleniumHelper().getAvailableOptions(element);
}
return result;
}
@WaitUntil
public boolean clear(String place) {
return clearIn(place, null);
}
@WaitUntil
public boolean clearIn(String place, String container) {
boolean result = false;
WebElement element = getElementToClear(place, container);
if (element != null) {
element.clear();
result = true;
}
return result;
}
protected WebElement getElementToClear(String place, String container) {
return getElementToSendValue(place, container);
}
@WaitUntil
public boolean enterAsInRowWhereIs(String value, String requestedColumnName, String selectOnColumn, String selectOnValue) {
boolean result = false;
By cellBy = GridBy.columnInRowWhereIs(requestedColumnName, selectOnColumn, selectOnValue);
WebElement element = findElement(cellBy);
if (element != null) {
if (isSelect(element)) {
result = clickSelectOption(element, value);
} else {
if (isInteractable(element)) {
result = true;
element.clear();
sendValue(element, value);
}
}
}
return result;
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfColumnNumberInRowNumber(int columnIndex, int rowIndex) {
By by = GridBy.coordinates(columnIndex, rowIndex);
return valueFor(by);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowNumber(String requestedColumnName, int rowIndex) {
By by = GridBy.columnInRow(requestedColumnName, rowIndex);
return valueFor(by);
}
@WaitUntil(TimeoutPolicy.RETURN_NULL)
public String valueOfInRowWhereIs(String requestedColumnName, String selectOnColumn, String selectOnValue) {
By by = GridBy.columnInRowWhereIs(requestedColumnName, selectOnColumn, selectOnValue);
return valueFor(by);
}
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean rowExistsWhereIs(String selectOnColumn, String selectOnValue) {
return findElement(GridBy.rowWhereIs(selectOnColumn, selectOnValue)) != null;
}
@WaitUntil
public boolean clickInRowNumber(String place, int rowIndex) {
By rowBy = GridBy.rowNumber(rowIndex);
return clickInRow(rowBy, place);
}
@WaitUntil
public boolean clickInRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
By rowBy = GridBy.rowWhereIs(selectOnColumn, selectOnValue);
return clickInRow(rowBy, place);
}
protected boolean clickInRow(By rowBy, String place) {
boolean result = false;
WebElement row = findElement(rowBy);
if (row != null) {
result = doInContainer(row, () -> click(place));
}
return result;
}
/**
* Downloads the target of a link in a grid's row.
* @param place which link to download.
* @param rowNumber (1-based) row number to retrieve link from.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowNumber(String place, int rowNumber) {
return downloadFromRow(GridBy.linkInRow(place, rowNumber));
}
/**
* Downloads the target of a link in a grid, finding the row based on one of the other columns' value.
* @param place which link to download.
* @param selectOnColumn column header of cell whose value must be selectOnValue.
* @param selectOnValue value to be present in selectOnColumn to find correct row.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadFromRowWhereIs(String place, String selectOnColumn, String selectOnValue) {
return downloadFromRow(GridBy.linkInRowWhereIs(place, selectOnColumn, selectOnValue));
}
protected String downloadFromRow(By linkBy) {
String result = null;
WebElement element = findElement(linkBy);
if (element != null) {
result = downloadLinkTarget(element);
}
return result;
}
/**
* Creates an XPath expression that will determine, for a row, which index to use to select the cell in the column
* with the supplied header text value.
* @param columnName name of column in header (th)
* @return XPath expression which can be used to select a td in a row
*/
protected String getXPathForColumnIndex(String columnName) {
return GridBy.getXPathForColumnIndex(columnName);
}
protected WebElement getElement(String place) {
return getSeleniumHelper().getElement(place);
}
protected WebElement getElement(String place, String container) {
return doInContainer(container, () -> getElement(place));
}
/**
* @deprecated use #click(xpath=) instead.
*/
@WaitUntil
@Deprecated
public boolean clickByXPath(String xPath) {
WebElement element = findByXPath(xPath);
return clickElement(element);
}
/**
* @deprecated use #valueOf(xpath=) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByXPath(String xPath) {
return getTextByXPath(xPath);
}
protected String getTextByXPath(String xpathPattern, String... params) {
WebElement element = findByXPath(xpathPattern, params);
return getElementText(element);
}
/**
* @deprecated use #valueOf(css=.) instead.
*/
@WaitUntil(TimeoutPolicy.RETURN_NULL)
@Deprecated
public String textByClassName(String className) {
return getTextByClassName(className);
}
protected String getTextByClassName(String className) {
WebElement element = findByClassName(className);
return getElementText(element);
}
protected WebElement findByClassName(String className) {
By by = By.className(className);
return findElement(by);
}
protected WebElement findByXPath(String xpathPattern, String... params) {
return getSeleniumHelper().findByXPath(xpathPattern, params);
}
protected WebElement findByCss(String cssPattern, String... params) {
By by = getSeleniumHelper().byCss(cssPattern, params);
return findElement(by);
}
protected WebElement findByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElement(by);
}
protected List<WebElement> findAllByXPath(String xpathPattern, String... params) {
By by = getSeleniumHelper().byXpath(xpathPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByCss(String cssPattern, String... params) {
By by = getSeleniumHelper().byCss(cssPattern, params);
return findElements(by);
}
protected List<WebElement> findAllByJavascript(String script, Object... parameters) {
By by = getSeleniumHelper().byJavascript(script, parameters);
return findElements(by);
}
protected List<WebElement> findElements(By by) {
return driver().findElements(by);
}
public void waitMilliSecondAfterScroll(int msToWait) {
waitAfterScroll = msToWait;
}
protected int getWaitAfterScroll() {
return waitAfterScroll;
}
protected String getElementText(WebElement element) {
String result = null;
if (element != null) {
scrollIfNotOnScreen(element);
result = getSeleniumHelper().getText(element);
}
return result;
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
*/
@WaitUntil
public boolean scrollTo(String place) {
return scrollToIn(place, null);
}
/**
* Scrolls browser window so top of place becomes visible.
* @param place element to scroll to.
* @param container parent of place.
*/
@WaitUntil
public boolean scrollToIn(String place, String container) {
boolean result = false;
WebElement element = getElementToScrollTo(place, container);
if (element != null) {
scrollTo(element);
result = true;
}
return result;
}
protected WebElement getElementToScrollTo(String place, String container) {
return getElementToCheckVisibility(place, container);
}
/**
* Scrolls browser window so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollTo(WebElement element) {
getSeleniumHelper().scrollTo(element);
waitAfterScroll(waitAfterScroll);
}
/**
* Wait after the scroll if needed
* @param msToWait amount of ms to wait after the scroll
*/
protected void waitAfterScroll(int msToWait) {
if (msToWait > 0) {
waitMilliseconds(msToWait);
}
}
/**
* Scrolls browser window if element is not currently visible so top of element becomes visible.
* @param element element to scroll to.
*/
protected void scrollIfNotOnScreen(WebElement element) {
if (!element.isDisplayed() || !isElementOnScreen(element)) {
scrollTo(element);
}
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabled(String place) {
return isEnabledIn(place, null);
}
/**
* Determines whether element is enabled (i.e. can be clicked).
* @param place element to check.
* @param container parent of place.
* @return true if element is enabled.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isEnabledIn(String place, String container) {
boolean result = false;
WebElement element = getElementToCheckVisibility(place, container);
if (element != null) {
if ("label".equalsIgnoreCase(element.getTagName())) {
// for labels we want to know whether their target is enabled, not the label itself
WebElement labelTarget = getSeleniumHelper().getLabelledElement(element);
if (labelTarget != null) {
element = labelTarget;
}
}
result = element.isEnabled();
}
return result;
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisible(String place) {
return isVisibleIn(place, null);
}
/**
* Determines whether element can be see in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed and in viewport.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleIn(String place, String container) {
return isVisibleImpl(place, container, true);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPage(String place) {
return isVisibleOnPageIn(place, null);
}
/**
* Determines whether element is somewhere in browser's window.
* @param place element to check.
* @param container parent of place.
* @return true if element is displayed.
*/
@WaitUntil(TimeoutPolicy.RETURN_FALSE)
public boolean isVisibleOnPageIn(String place, String container) {
return isVisibleImpl(place, container, false);
}
protected boolean isVisibleImpl(String place, String container, boolean checkOnScreen) {
WebElement element = getElementToCheckVisibility(place, container);
return getSeleniumHelper().checkVisible(element, checkOnScreen);
}
public int numberOfTimesIsVisible(String text) {
return numberOfTimesIsVisibleInImpl(text, true);
}
public int numberOfTimesIsVisibleOnPage(String text) {
return numberOfTimesIsVisibleInImpl(text, false);
}
public int numberOfTimesIsVisibleIn(String text, String container) {
return doInContainer(container, () -> numberOfTimesIsVisible(text));
}
public int numberOfTimesIsVisibleOnPageIn(String text, String container) {
return doInContainer(container, () -> numberOfTimesIsVisibleOnPage(text));
}
protected int numberOfTimesIsVisibleInImpl(String text, boolean checkOnScreen) {
return getSeleniumHelper().countVisibleOccurrences(text, checkOnScreen);
}
protected WebElement getElementToCheckVisibility(String place) {
WebElement result = findElement(TextBy.partial(place));
if (result == null || !result.isDisplayed()) {
result = getElementToClick(place);
}
return result;
}
protected WebElement getElementToCheckVisibility(String place, String container) {
return doInContainer(container, () -> findByTechnicalSelectorOr(place, this::getElementToCheckVisibility));
}
/**
* Checks whether element is in browser's viewport.
* @param element element to check
* @return true if element is in browser's viewport.
*/
protected boolean isElementOnScreen(WebElement element) {
Boolean onScreen = getSeleniumHelper().isElementOnScreen(element);
return onScreen == null || onScreen.booleanValue();
}
@WaitUntil
public boolean hoverOver(String place) {
return hoverOverIn(place, null);
}
@WaitUntil
public boolean hoverOverIn(String place, String container) {
WebElement element = getElementToClick(place, container);
return hoverOver(element);
}
protected boolean hoverOver(WebElement element) {
boolean result = false;
if (element != null) {
scrollIfNotOnScreen(element);
if (element.isDisplayed()) {
getSeleniumHelper().hoverOver(element);
result = true;
}
}
return result;
}
/**
* @param timeout number of seconds before waitUntil() and waitForJavascriptCallback() throw TimeOutException.
*/
public void secondsBeforeTimeout(int timeout) {
secondsBeforeTimeout = timeout;
secondsBeforePageLoadTimeout(timeout);
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setScriptWait(timeoutInMs);
}
/**
* @return number of seconds waitUntil() will wait at most.
*/
public int secondsBeforeTimeout() {
return secondsBeforeTimeout;
}
/**
* @param timeout number of seconds before waiting for a new page to load will throw a TimeOutException.
*/
public void secondsBeforePageLoadTimeout(int timeout) {
secondsBeforePageLoadTimeout = timeout;
int timeoutInMs = timeout * 1000;
getSeleniumHelper().setPageLoadWait(timeoutInMs);
}
/**
* @return number of seconds Selenium will wait at most for a request to load a page.
*/
public int secondsBeforePageLoadTimeout() {
return secondsBeforePageLoadTimeout;
}
/**
* Clears HTML5's localStorage (for the domain of the current open page in the browser).
*/
public void clearLocalStorage() {
getSeleniumHelper().executeJavascript("localStorage.clear();");
}
/**
* Deletes all cookies(for the domain of the current open page in the browser).
*/
public void deleteAllCookies() {
getSeleniumHelper().deleteAllCookies();
}
/**
* @param directory sets base directory where screenshots will be stored.
*/
public void screenshotBaseDirectory(String directory) {
if (directory.equals("")
|| directory.endsWith("/")
|| directory.endsWith("\\")) {
screenshotBase = directory;
} else {
screenshotBase = directory + "/";
}
}
/**
* @param height height to use to display screenshot images
*/
public void screenshotShowHeight(String height) {
screenshotHeight = height;
}
/**
* @return (escaped) HTML content of current page.
*/
public String pageSource() {
String result = null;
String html = getSeleniumHelper().getHtml();
if (html != null) {
result = "<pre>" + StringEscapeUtils.escapeHtml4(html) + "</pre>";
}
return result;
}
/**
* Saves current page's source to the wiki'f files section and returns a link to the
* created file.
* @return hyperlink to the file containing the page source.
*/
public String savePageSource() {
String fileName = getSeleniumHelper().getResourceNameFromLocation();
return savePageSource(fileName, fileName + ".html");
}
protected String savePageSource(String fileName, String linkText) {
PageSourceSaver saver = getSeleniumHelper().getPageSourceSaver(pageSourceBase);
// make href to file
String url = saver.savePageSource(fileName);
return String.format("<a href=\"%s\">%s</a>", url, linkText);
}
/**
* Takes screenshot from current page
* @param basename filename (below screenshot base directory).
* @return location of screenshot.
*/
public String takeScreenshot(String basename) {
try {
String screenshotFile = createScreenshot(basename);
if (screenshotFile == null) {
throw new SlimFixtureException(false, "Unable to take screenshot: does the webdriver support it?");
} else {
screenshotFile = getScreenshotLink(screenshotFile);
}
return screenshotFile;
} catch (UnhandledAlertException e) {
// standard behavior will stop test, this breaks storyboard that will attempt to take screenshot
// after triggering alert, but before the alert can be handled.
// so we output a message but no exception. We rely on a next line to actually handle alert
// (which may mean either really handle or stop test).
return String.format(
"<div><strong>Unable to take screenshot</strong>, alert is active. Alert text:<br/>" +
"'<span>%s</span>'</div>",
StringEscapeUtils.escapeHtml4(alertText()));
}
}
private String getScreenshotLink(String screenshotFile) {
String wikiUrl = getWikiUrl(screenshotFile);
if (wikiUrl != null) {
// make href to screenshot
if ("".equals(screenshotHeight)) {
wikiUrl = String.format("<a href=\"%s\">%s</a>",
wikiUrl, screenshotFile);
} else {
wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"/></a>",
wikiUrl, screenshotFile, screenshotHeight);
}
screenshotFile = wikiUrl;
}
return screenshotFile;
}
private String createScreenshot(String basename) {
String name = getScreenshotBasename(basename);
return getSeleniumHelper().takeScreenshot(name);
}
private String createScreenshot(String basename, Throwable t) {
String screenshotFile;
byte[] screenshotInException = getSeleniumHelper().findScreenshot(t);
if (screenshotInException == null || screenshotInException.length == 0) {
screenshotFile = createScreenshot(basename);
} else {
String name = getScreenshotBasename(basename);
screenshotFile = getSeleniumHelper().writeScreenshot(name, screenshotInException);
}
return screenshotFile;
}
private String getScreenshotBasename(String basename) {
return screenshotBase + basename;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws SlimFixtureException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntil(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
String message = getTimeoutMessage(e);
return lastAttemptBeforeThrow(condition, new SlimFixtureException(false, message, e));
}
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur the whole test is stopped.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @throws TimeoutStopTestException if condition was not met before secondsBeforeTimeout.
* @return result of condition.
*/
protected <T> T waitUntilOrStop(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
try {
return handleTimeoutException(e);
} catch (TimeoutStopTestException tste) {
return lastAttemptBeforeThrow(condition, tste);
}
}
}
/**
* Tries the condition one last time before throwing an exception.
* This to prevent exception messages in the wiki that show no problem, which could happen if the browser's
* window content has changed between last (failing) try at condition and generation of the exception.
* @param <T> the return type of the method, which must not be Void
* @param condition condition that caused exception.
* @param e exception that will be thrown if condition does not return a result.
* @return last attempt results, if not null.
* @throws SlimFixtureException throws e if last attempt returns null.
*/
protected <T> T lastAttemptBeforeThrow(ExpectedCondition<T> condition, SlimFixtureException e) {
T lastAttemptResult = null;
try {
// last attempt to ensure condition has not been met
// this to prevent messages that show no problem
lastAttemptResult = condition.apply(getSeleniumHelper().driver());
} catch (Throwable t) {
// ignore
}
if (lastAttemptResult != null) {
return lastAttemptResult;
}
throw e;
}
/**
* Waits until the condition evaluates to a value that is neither null nor
* false. If that does not occur null is returned.
* Because of this contract, the return type must not be Void.
* @param <T> the return type of the method, which must not be Void
* @param condition condition to evaluate to determine whether waiting can be stopped.
* @return result of condition.
*/
protected <T> T waitUntilOrNull(ExpectedCondition<T> condition) {
try {
return waitUntilImpl(condition);
} catch (TimeoutException e) {
return null;
}
}
protected <T> T waitUntilImpl(ExpectedCondition<T> condition) {
return getSeleniumHelper().waitUntil(secondsBeforeTimeout(), condition);
}
protected <T> T handleTimeoutException(TimeoutException e) {
String message = getTimeoutMessage(e);
throw new TimeoutStopTestException(false, message, e);
}
private String getTimeoutMessage(TimeoutException e) {
String messageBase = String.format("Timed-out waiting (after %ss)", secondsBeforeTimeout());
return getSlimFixtureExceptionMessage("timeouts", "timeout", messageBase, e);
}
protected void handleRequiredElementNotFound(String toFind) {
handleRequiredElementNotFound(toFind, null);
}
protected void handleRequiredElementNotFound(String toFind, Throwable t) {
String messageBase = String.format("Unable to find: %s", toFind);
String message = getSlimFixtureExceptionMessage("notFound", toFind, messageBase, t);
throw new SlimFixtureException(false, message, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotFolder, String screenshotFile, String messageBase, Throwable t) {
String screenshotBaseName = String.format("%s/%s/%s", screenshotFolder, getClass().getSimpleName(), screenshotFile);
return getSlimFixtureExceptionMessage(screenshotBaseName, messageBase, t);
}
protected String getSlimFixtureExceptionMessage(String screenshotBaseName, String messageBase, Throwable t) {
// take a screenshot of what was on screen
String screenShotFile = null;
try {
screenShotFile = createScreenshot(screenshotBaseName, t);
} catch (UnhandledAlertException e) {
System.err.println("Unable to take screenshot while alert is present for exception: " + messageBase);
} catch (Exception sse) {
System.err.println("Unable to take screenshot for exception: " + messageBase);
sse.printStackTrace();
}
String message = messageBase;
if (message == null) {
if (t == null) {
message = "";
} else {
message = ExceptionUtils.getStackTrace(t);
}
}
if (screenShotFile != null) {
String label = "Page content";
try {
String fileName;
if (t != null) {
fileName = t.getClass().getName();
} else if (screenshotBaseName != null) {
fileName = screenshotBaseName;
} else {
fileName = "exception";
}
label = savePageSource(fileName, label);
} catch (UnhandledAlertException e) {
System.err.println("Unable to capture page source while alert is present for exception: " + messageBase);
} catch (Exception e) {
System.err.println("Unable to capture page source for exception: " + messageBase);
e.printStackTrace();
}
String exceptionMsg = formatExceptionMsg(message);
message = String.format("<div><div>%s.</div><div>%s:%s</div></div>",
exceptionMsg, label, getScreenshotLink(screenShotFile));
}
return message;
}
protected String formatExceptionMsg(String value) {
return StringEscapeUtils.escapeHtml4(value);
}
private WebDriver driver() {
return getSeleniumHelper().driver();
}
private WebDriverWait waitDriver() {
return getSeleniumHelper().waitDriver();
}
/**
* @return helper to use.
*/
protected final SeleniumHelper getSeleniumHelper() {
return seleniumHelper;
}
/**
* Sets SeleniumHelper to use, for testing purposes.
* @param helper helper to use.
*/
void setSeleniumHelper(SeleniumHelper helper) {
seleniumHelper = helper;
}
public int currentBrowserWidth() {
return getWindowSize().getWidth();
}
public int currentBrowserHeight() {
return getWindowSize().getHeight();
}
public void setBrowserWidth(int newWidth) {
int currentHeight = currentBrowserHeight();
setBrowserSizeToBy(newWidth, currentHeight);
}
public void setBrowserHeight(int newHeight) {
int currentWidth = currentBrowserWidth();
setBrowserSizeToBy(currentWidth, newHeight);
}
public void setBrowserSizeToBy(int newWidth, int newHeight) {
getSeleniumHelper().setWindowSize(newWidth, newHeight);
Dimension actualSize = getWindowSize();
if (actualSize.getHeight() != newHeight || actualSize.getWidth() != newWidth) {
String message = String.format("Unable to change size to: %s x %s; size is: %s x %s",
newWidth, newHeight, actualSize.getWidth(), actualSize.getHeight());
throw new SlimFixtureException(false, message);
}
}
protected Dimension getWindowSize() {
return getSeleniumHelper().getWindowSize();
}
public void setBrowserSizeToMaximum() {
getSeleniumHelper().setWindowSizeToMaximum();
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String download(String place) {
WebElement element = getSeleniumHelper().getLink(place);
return downloadLinkTarget(element);
}
/**
* Downloads the target of the supplied link.
* @param place link to follow.
* @param container part of screen containing link.
* @return downloaded file if any, null otherwise.
*/
@WaitUntil
public String downloadIn(String place, String container) {
return doInContainer(container, () -> download(place));
}
protected WebElement findElement(By selector) {
return getSeleniumHelper().findElement(selector);
}
public WebElement findByTechnicalSelectorOr(String place, Function<String, WebElement> supplierF) {
return getSeleniumHelper().findByTechnicalSelectorOr(place, () -> supplierF.apply(place));
}
/**
* Downloads the target of the supplied link.
* @param element link to follow.
* @return downloaded file if any, null otherwise.
*/
protected String downloadLinkTarget(WebElement element) {
String result;
String href = getLinkTarget(element);
if (href != null) {
result = downloadContentFrom(href);
} else {
throw new SlimFixtureException(false, "Could not determine url to download from");
}
return result;
}
/**
* Downloads binary content from specified url (using the browser's cookies).
* @param urlOrLink url to download from
* @return link to downloaded file
*/
public String downloadContentFrom(String urlOrLink) {
String result = null;
if (urlOrLink != null) {
String url = getUrl(urlOrLink);
BinaryHttpResponse resp = new BinaryHttpResponse();
getUrlContent(url, resp);
byte[] content = resp.getResponseContent();
if (content == null) {
result = resp.getResponse();
} else {
String fileName = resp.getFileName();
if (StringUtils.isEmpty(fileName)) {
fileName = "download";
}
String baseName = FilenameUtils.getBaseName(fileName);
String ext = FilenameUtils.getExtension(fileName);
String downloadedFile = FileUtil.saveToFile(getDownloadName(baseName), ext, content);
String wikiUrl = getWikiUrl(downloadedFile);
if (wikiUrl != null) {
// make href to file
result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName);
} else {
result = downloadedFile;
}
}
}
return result;
}
/**
* Selects a file using the first file upload control.
* @param fileName file to upload
* @return true, if a file input was found and file existed.
*/
@WaitUntil
public boolean selectFile(String fileName) {
return selectFileFor(fileName, "css=input[type='file']");
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileFor(String fileName, String place) {
return selectFileForIn(fileName, place, null);
}
/**
* Selects a file using a file upload control.
* @param fileName file to upload
* @param place file input to select the file for
* @param container part of screen containing place
* @return true, if place was a file input and file existed.
*/
@WaitUntil
public boolean selectFileForIn(String fileName, String place, String container) {
boolean result = false;
if (fileName != null) {
String fullPath = getFilePathFromWikiUrl(fileName);
if (new File(fullPath).exists()) {
WebElement element = getElementToSelectFile(place, container);
if (element != null) {
element.sendKeys(fullPath);
result = true;
}
} else {
throw new SlimFixtureException(false, "Unable to find file: " + fullPath);
}
}
return result;
}
protected WebElement getElementToSelectFile(String place, String container) {
WebElement result = null;
WebElement element = getElement(place, container);
if (element != null
&& "input".equalsIgnoreCase(element.getTagName())
&& "file".equalsIgnoreCase(element.getAttribute("type"))) {
result = element;
}
return result;
}
private String getDownloadName(String baseName) {
return downloadBase + baseName;
}
/**
* GETs content of specified URL, using the browsers cookies.
* @param url url to retrieve content from
* @param resp response to store content in
*/
protected void getUrlContent(String url, HttpResponse resp) {
getEnvironment().addSeleniumCookies(resp);
getEnvironment().doGet(url, resp);
}
/**
* Gets the value of the cookie with the supplied name.
* @param cookieName name of cookie to get value from.
* @return cookie's value if any.
*/
public String cookieValue(String cookieName) {
String result = null;
Cookie cookie = getSeleniumHelper().getCookie(cookieName);
if (cookie != null) {
result = cookie.getValue();
}
return result;
}
public boolean refreshUntilValueOfIs(String place, String expectedValue) {
return repeatUntil(getRefreshUntilValueIs(place, expectedValue));
}
public boolean refreshUntilValueOfIsNot(String place, String expectedValue) {
return repeatUntilNot(getRefreshUntilValueIs(place, expectedValue));
}
protected RepeatUntilValueIsCompletion getRefreshUntilValueIs(String place, String expectedValue) {
return new RepeatUntilValueIsCompletion(place, expectedValue) {
@Override
public void repeat() {
refresh();
}
};
}
public boolean clickUntilValueOfIs(String clickPlace, String checkPlace, String expectedValue) {
return repeatUntil(getClickUntilValueIs(clickPlace, checkPlace, expectedValue));
}
public boolean clickUntilValueOfIsNot(String clickPlace, String checkPlace, String expectedValue) {
return repeatUntilNot(getClickUntilValueIs(clickPlace, checkPlace, expectedValue));
}
protected RepeatUntilValueIsCompletion getClickUntilValueIs(String clickPlace, String checkPlace, String expectedValue) {
String place = cleanupValue(clickPlace);
return getClickUntilCompletion(place, checkPlace, expectedValue);
}
protected RepeatUntilValueIsCompletion getClickUntilCompletion(String place, String checkPlace, String expectedValue) {
ExpectedCondition<Object> condition = wrapConditionForFramesIfNeeded(webDriver -> click(place));
return new RepeatUntilValueIsCompletion(checkPlace, expectedValue) {
@Override
public void repeat() {
waitUntil(condition);
}
};
}
protected <T> ExpectedCondition<T> wrapConditionForFramesIfNeeded(ExpectedCondition<T> condition) {
if (implicitFindInFrames) {
condition = getSeleniumHelper().conditionForAllFrames(condition);
}
return condition;
}
@Override
protected boolean repeatUntil(RepeatCompletion repeat) {
// During repeating we reduce the timeout used for finding elements,
// but the page load timeout is kept as-is (which takes extra work because secondsBeforeTimeout(int)
// also changes that.
int previousTimeout = secondsBeforeTimeout();
int pageLoadTimeout = secondsBeforePageLoadTimeout();
try {
int timeoutDuringRepeat = Math.max((Math.toIntExact(repeatInterval() / 1000)), 1);
secondsBeforeTimeout(timeoutDuringRepeat);
secondsBeforePageLoadTimeout(pageLoadTimeout);
return super.repeatUntil(repeat);
} finally {
secondsBeforeTimeout(previousTimeout);
secondsBeforePageLoadTimeout(pageLoadTimeout);
}
}
protected abstract class RepeatUntilValueIsCompletion implements RepeatCompletion {
private final String place;
private final String expectedValue;
protected RepeatUntilValueIsCompletion(String place, String expectedValue) {
this.place = place;
this.expectedValue = cleanExpectedValue(expectedValue);
}
@Override
public boolean isFinished() {
ExpectedCondition<Boolean> condition = wrapConditionForFramesIfNeeded(webDriver -> checkValueImpl());
Boolean valueFound = waitUntilOrNull(condition);
return valueFound != null && valueFound;
}
protected boolean checkValueImpl() {
boolean match;
String actual = valueOf(place);
if (expectedValue == null) {
match = actual == null;
} else {
match = expectedValue.equals(actual);
}
return match;
}
}
protected Object waitForJavascriptCallback(String statement, Object... parameters) {
try {
return getSeleniumHelper().waitForJavascriptCallback(statement, parameters);
} catch (TimeoutException e) {
return handleTimeoutException(e);
}
}
public NgBrowserTest getNgBrowserTest() {
return ngBrowserTest;
}
public void setNgBrowserTest(NgBrowserTest ngBrowserTest) {
this.ngBrowserTest = ngBrowserTest;
}
public boolean isImplicitWaitForAngularEnabled() {
return implicitWaitForAngular;
}
public void setImplicitWaitForAngularTo(boolean implicitWaitForAngular) {
this.implicitWaitForAngular = implicitWaitForAngular;
}
public void setImplicitFindInFramesTo(boolean implicitFindInFrames) {
this.implicitFindInFrames = implicitFindInFrames;
}
/**
* Executes javascript in the browser.
* @param script you want to execute
* @return result from script
*/
public Object executeScript(String script) {
String statement = cleanupValue(script);
return getSeleniumHelper().executeJavascript(statement);
}
}
|
package online.zhaopei.myproject.tool.common;
import java.io.Serializable;
import com.alibaba.druid.util.StringUtils;
import online.zhaopei.myproject.constant.CommonConstant;
import online.zhaopei.myproject.domain.para.Para;
import online.zhaopei.myproject.service.para.CountryService;
import online.zhaopei.myproject.service.para.CurrService;
import online.zhaopei.myproject.service.para.CustomsService;
import online.zhaopei.myproject.service.para.TradeService;
import online.zhaopei.myproject.service.para.TransfService;
import online.zhaopei.myproject.service.para.UnitService;
import online.zhaopei.myproject.service.para.WrapService;
public class ParaTool implements Serializable {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 6915465654456254940L;
public String getCountryDesc(String countryCode, CountryService countryService) {
String result = "";
Para para = null;
if (StringUtils.isEmpty(CommonConstant.getCOUNTRY_MAP().get(countryCode))) {
para = countryService.getCountryByCode(countryCode);
if (null != para) {
CommonConstant.getCOUNTRY_MAP().put(countryCode, para.getName());
result = para.getName();
}
} else {
result = CommonConstant.getCOUNTRY_MAP().get(countryCode);
}
return result;
}
public String getCurrDesc(String currCode, CurrService currService) {
String result = "";
Para para = null;
if (StringUtils.isEmpty(CommonConstant.getCURRENCY_MAP().get(currCode))) {
para = currService.getCurrByCode(currCode);
if (null != para) {
CommonConstant.getCURRENCY_MAP().put(currCode, para.getName());
result = para.getName();
}
} else {
result = CommonConstant.getCURRENCY_MAP().get(currCode);
}
return result;
}
public String getTradeModeDesc(String tradeMode, TradeService tradeService) {
String result = "";
Para para = null;
if (StringUtils.isEmpty(CommonConstant.getTRADE_MODE_MAP().get(tradeMode))) {
para = tradeService.getTradeByCode(tradeMode);
if (null != para) {
CommonConstant.getTRADE_MODE_MAP().put(tradeMode, para.getName());
result = para.getName();
}
} else {
result = CommonConstant.getTRADE_MODE_MAP().get(tradeMode);
}
return result;
}
public String getCustomsDesc(String customsCode, CustomsService customsService) {
String result = "";
Para para = null;
if (StringUtils.isEmpty(CommonConstant.getCUSTOMS_MAP().get(customsCode))) {
para = customsService.getCustomsByCode(customsCode);
if (null != para) {
CommonConstant.getCUSTOMS_MAP().put(customsCode, para.getName());
result = para.getName();
}
} else {
result = CommonConstant.getCUSTOMS_MAP().get(customsCode);
}
return result;
}
public String getWrapDesc(String wrapCode, WrapService wrapService) {
String result = "";
Para para = null;
if (StringUtils.isEmpty(CommonConstant.getWRAP_TYPE_MAP().get(wrapCode))) {
para = wrapService.getWrapByCode(wrapCode);
if (null != para) {
CommonConstant.getWRAP_TYPE_MAP().put(wrapCode, para.getName());
result = para.getName();
}
} else {
result = CommonConstant.getWRAP_TYPE_MAP().get(wrapCode);
}
return result;
}
public String getUnitDesc(String unitCode, UnitService unitService) {
String result = "";
Para para = null;
if (StringUtils.isEmpty(CommonConstant.getUNIT_MAP().get(unitCode))) {
para = unitService.getUnitByCode(unitCode);
if (null != para) {
CommonConstant.getUNIT_MAP().put(unitCode, para.getName());
result = para.getName();
}
} else {
result = CommonConstant.getUNIT_MAP().get(unitCode);
}
return result;
}
public String getTransfDesc(String transfCode, TransfService transfService) {
String result = "";
Para para = null;
if (StringUtils.isEmpty(CommonConstant.getTRAF_MODE_MAP().get(transfCode))) {
para = transfService.getTransfByCode(transfCode);
if (null != para) {
CommonConstant.getTRAF_MODE_MAP().put(transfCode, para.getName());
result = para.getName();
}
} else {
result = CommonConstant.getTRAF_MODE_MAP().get(transfCode);
}
return result;
}
}
|
package org.glassfish.grizzly.bm;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.http.util.Header;
/**
* Json usecase
*/
public class JsonHttpHandler extends HttpHandler {
// Response message class.
public static class HelloMessage {
public final String message = "Hello, World!";
}
@Override
public void service(final Request request, final Response response)
throws Exception {
response.setContentType("application/json");
response.setHeader(Header.Server, Server.SERVER_VERSION);
ObjectMapper MAPPER = new ObjectMapper();
// Write JSON encoded message to the response.
try
{
MAPPER.writeValue(response.getOutputStream(), new HelloMessage());
}
catch (IOException ioe)
{
// do nothing
}
}
@Override
protected ExecutorService getThreadPool(Request request) {
return null;
}
}
|
package org.oss.jshuntingyard.lexer;
import java.util.regex.Pattern;
public enum TokenType {
BOOLEANVALUE("(?i)false|(?i)true"),
NULL("(?i)null"),
NAN("NaN"),
FUNCTIONNAME("[A-Za-z]+([0-9])?"),
DIGIT("([-])?([0-9]+(\\.\\d+)?)"),
SINGLEQUOTED("\'[^\']*+\'"),
COMMA(","),
OPENBRACE("\\("),
CLOSEBRACE("\\)"),
OPERATOR("\\+|-|\\*|/|==|!=|\\^|\\%|\\|\\||<=|>=|<|>|&&|!"),
VARIABLE("\\$([a-zA-Z0-9])+([_])?([a-zA-Z0-9])*");
private final Pattern pattern;
TokenType(String regularExpression) {
this.pattern = Pattern.compile(regularExpression);
}
public Pattern pattern() {
return pattern;
}
}
|
package edu.isi.karma.rdf;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.io.IOUtils;
import org.apache.tika.detect.DefaultDetector;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.mime.MediaTypeRegistry;
import org.apache.tika.mime.MimeTypes;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import edu.isi.karma.controller.command.selection.SuperSelection;
import edu.isi.karma.controller.command.selection.SuperSelectionManager;
import edu.isi.karma.imp.Import;
import edu.isi.karma.imp.avro.AvroImport;
import edu.isi.karma.imp.csv.CSVImport;
import edu.isi.karma.imp.json.JsonImport;
import edu.isi.karma.kr2rml.ContextIdentifier;
import edu.isi.karma.kr2rml.ErrorReport;
import edu.isi.karma.kr2rml.KR2RMLWorksheetRDFGenerator;
import edu.isi.karma.kr2rml.mapping.KR2RMLMapping;
import edu.isi.karma.kr2rml.mapping.R2RMLMappingIdentifier;
import edu.isi.karma.kr2rml.mapping.WorksheetR2RMLJenaModelParser;
import edu.isi.karma.kr2rml.planning.RootStrategy;
import edu.isi.karma.kr2rml.planning.SteinerTreeRootStrategy;
import edu.isi.karma.kr2rml.planning.WorksheetDepthRootStrategy;
import edu.isi.karma.kr2rml.writer.BloomFilterKR2RMLRDFWriter;
import edu.isi.karma.kr2rml.writer.JSONKR2RMLRDFWriter;
import edu.isi.karma.kr2rml.writer.KR2RMLRDFWriter;
import edu.isi.karma.rep.Worksheet;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.util.EncodingDetector;
import edu.isi.karma.util.JSONUtil;
import edu.isi.karma.webserver.KarmaException;
public class GenericRDFGenerator extends RdfGenerator {
private static Logger logger = LoggerFactory.getLogger(GenericRDFGenerator.class);
protected ConcurrentHashMap<String, R2RMLMappingIdentifier> modelIdentifiers;
protected ConcurrentHashMap<String, WorksheetR2RMLJenaModelParser> readModelParsers;
protected HashMap<String, ContextIdentifier> contextIdentifiers;
protected HashMap<String, JSONObject> contextCache;
public enum InputType {
CSV,
JSON,
XML,
AVRO
};
public GenericRDFGenerator() {
this(null);
}
public GenericRDFGenerator(String selectionName) {
super(selectionName);
this.modelIdentifiers = new ConcurrentHashMap<String, R2RMLMappingIdentifier>();
this.readModelParsers = new ConcurrentHashMap<String, WorksheetR2RMLJenaModelParser>();
this.contextCache = new HashMap<String, JSONObject>();
this.contextIdentifiers = new HashMap<String, ContextIdentifier>();
}
public void addModel(R2RMLMappingIdentifier modelIdentifier) {
this.modelIdentifiers.put(modelIdentifier.getName(), modelIdentifier);
}
public void addContext(ContextIdentifier id) {
this.contextIdentifiers.put(id.getName(), id);
}
public WorksheetR2RMLJenaModelParser getModelParser(String modelName) throws JSONException, KarmaException {
WorksheetR2RMLJenaModelParser modelParser = readModelParsers.get(modelName);
R2RMLMappingIdentifier id = this.modelIdentifiers.get(modelName);
if(modelParser == null) {
modelParser = loadModel(id);
}
return modelParser;
}
private void generateRDF(String modelName, String sourceName,String contextName, InputStream data, InputType dataType, int maxNumLines,
boolean addProvenance, List<KR2RMLRDFWriter> writers, RootStrategy rootStrategy,
List<String> tripleMapToKill, List<String> tripleMapToStop, List<String> POMToKill)
throws KarmaException, IOException {
R2RMLMappingIdentifier id = this.modelIdentifiers.get(modelName);
ContextIdentifier contextId = this.contextIdentifiers.get(contextName);
if(id == null) {
throw new KarmaException("Cannot generate RDF. Model named " + modelName + " does not exist");
}
JSONObject context;
if (contextId == null) {
context = new JSONObject();
}
else {
context = this.contextCache.get(contextName);
}
if (context == null) {
try {
context = loadContext(contextId);
}catch(Exception e) {
context = new JSONObject();
}
}
for (KR2RMLRDFWriter writer : writers) {
if (writer instanceof JSONKR2RMLRDFWriter) {
JSONKR2RMLRDFWriter t = (JSONKR2RMLRDFWriter)writer;
t.setGlobalContext(context, contextId);
}
if (writer instanceof BloomFilterKR2RMLRDFWriter) {
BloomFilterKR2RMLRDFWriter t = (BloomFilterKR2RMLRDFWriter)writer;
t.setR2RMLMappingIdentifier(id);
}
}
//Check if the parser for this model exists, else create one
WorksheetR2RMLJenaModelParser modelParser = getModelParser(modelName);
generateRDF(modelParser, sourceName, data, dataType, maxNumLines, addProvenance, writers, rootStrategy, tripleMapToKill, tripleMapToStop, POMToKill);
}
private void generateRDF(WorksheetR2RMLJenaModelParser modelParser, String sourceName, InputStream data, InputType dataType, int maxNumLines,
boolean addProvenance, List<KR2RMLRDFWriter> writers, RootStrategy rootStrategy,
List<String> tripleMapToKill, List<String> tripleMapToStop, List<String> POMToKill) throws KarmaException, IOException {
logger.debug("Generating rdf for " + sourceName);
logger.debug("Initializing workspace for {}", sourceName);
Workspace workspace = initializeWorkspace();
logger.debug("Initialized workspace for {}", sourceName);
try
{
logger.debug("Generating worksheet for {}", sourceName);
Worksheet worksheet = generateWorksheet(sourceName, new BufferedInputStream(data), dataType,
workspace, maxNumLines);
logger.debug("Generated worksheet for {}", sourceName);
logger.debug("Parsing mapping for {}", sourceName);
//Generate mappping data for the worksheet using the model parser
KR2RMLMapping mapping = modelParser.parse();
logger.debug("Parsed mapping for {}", sourceName);
applyHistoryToWorksheet(workspace, worksheet, mapping);
SuperSelection selection = SuperSelectionManager.DEFAULT_SELECTION;
if (selectionName != null && !selectionName.trim().isEmpty())
selection = worksheet.getSuperSelectionManager().getSuperSelection(selectionName);
if (selection == null)
return;
//Generate RDF using the mapping data
ErrorReport errorReport = new ErrorReport();
if(rootStrategy == null)
{
rootStrategy = new SteinerTreeRootStrategy(new WorksheetDepthRootStrategy());
}
logger.debug("Generating output for {}", sourceName);
KR2RMLWorksheetRDFGenerator rdfGen = new KR2RMLWorksheetRDFGenerator(worksheet,
workspace.getFactory(), writers,
addProvenance, rootStrategy, tripleMapToKill, tripleMapToStop, POMToKill,
mapping, errorReport, selection);
rdfGen.generateRDF(true);
logger.debug("Generated output for {}", sourceName);
}
catch( Exception e)
{
throw new KarmaException(e.getMessage());
}
finally
{
removeWorkspace(workspace);
}
logger.debug("Generated rdf for {}", sourceName);
}
public void generateRDF(RDFGeneratorRequest request) throws KarmaException, IOException
{
InputStream inputStream = null;
if(request.getInputFile() != null)
{
inputStream = new FileInputStream(request.getInputFile());
}
else if(request.getInputData() != null)
{
inputStream = IOUtils.toInputStream(request.getInputData());
}
else if(request.getInputStream() != null)
{
inputStream = request.getInputStream();
}
generateRDF(request.getModelName(), request.getSourceName(), request.getContextName(),
inputStream,request.getDataType(), request.getMaxNumLines(), request.isAddProvenance(),
request.getWriters(), request.getStrategy(),
request.getTripleMapToKill(), request.getTripleMapToStop(), request.getPOMToKill());
}
private InputType getInputType(Metadata metadata) {
String[] contentType = metadata.get(Metadata.CONTENT_TYPE).split(";");
switch (contentType[0]) {
case "application/json" : {
return InputType.JSON;
}
case "application/xml": {
return InputType.XML;
}
case "text/csv": {
return InputType.CSV;
}
}
return null;
}
protected Worksheet generateWorksheet(String sourceName, BufferedInputStream is, InputType inputType,
Workspace workspace, int maxNumLines) throws IOException, KarmaException {
Worksheet worksheet = null;
try{
is.mark(Integer.MAX_VALUE);
String encoding = null;
if(inputType == null) {
Metadata metadata = new Metadata();
metadata.set(Metadata.RESOURCE_NAME_KEY, sourceName);
DefaultDetector detector = new DefaultDetector();
MediaType type = detector.detect(is, metadata);
ContentHandler contenthandler = new BodyContentHandler();
AutoDetectParser parser = new AutoDetectParser();
try {
parser.parse(is, contenthandler, metadata);
} catch (SAXException | TikaException e) {
logger.error("Unable to parse stream: " + e.getMessage());
throw new KarmaException("Unable to parse stream: "
+ e.getMessage());
}
MediaTypeRegistry registry = MimeTypes.getDefaultMimeTypes()
.getMediaTypeRegistry();
registry.addSuperType(new MediaType("text", "csv"), new MediaType(
"text", "plain"));
MediaType parsedType = MediaType.parse(metadata
.get(Metadata.CONTENT_TYPE));
if (registry.isSpecializationOf(registry.normalize(type), registry
.normalize(parsedType).getBaseType())) {
metadata.set(Metadata.CONTENT_TYPE, type.toString());
}
logger.info("Detected " + metadata.get(Metadata.CONTENT_TYPE));
inputType = getInputType(metadata);
encoding = metadata.get(Metadata.CONTENT_ENCODING);
} else {
encoding = EncodingDetector.detect(is);
}
is.reset();
if(inputType == null) {
throw new KarmaException("Content type unrecognized");
}
switch (inputType) {
case JSON : {
worksheet = generateWorksheetFromJSONStream(sourceName, is,
workspace, encoding, maxNumLines);
break;
}
case XML : {
worksheet = generateWorksheetFromXMLStream(sourceName, is,
workspace, encoding, maxNumLines);
break;
}
case CSV : {
worksheet = generateWorksheetFromDelimitedStream(sourceName,
is, workspace, encoding, maxNumLines);
break;
}
case AVRO : {
worksheet = generateWorksheetFromAvroStream(sourceName, is, workspace, encoding, maxNumLines);
}
}
} catch (Exception e ) {
logger.error("Error generating worksheet", e);
throw new KarmaException("Unable to generate worksheet: " + e.getMessage());
}
if(worksheet == null) {
throw new KarmaException("Content type unrecognized");
}
return worksheet;
}
private synchronized WorksheetR2RMLJenaModelParser loadModel(R2RMLMappingIdentifier modelIdentifier) throws JSONException, KarmaException {
if(readModelParsers.containsKey(modelIdentifier.getName()))
{
return readModelParsers.get(modelIdentifier.getName());
}
WorksheetR2RMLJenaModelParser parser = new WorksheetR2RMLJenaModelParser(modelIdentifier);
this.readModelParsers.put(modelIdentifier.getName(), parser);
return parser;
}
public JSONObject loadContext(ContextIdentifier id) throws IOException {
if (contextCache.containsKey(id.getName())) {
return contextCache.get(id.getName());
}
JSONTokener token = new JSONTokener(id.getLocation().openStream());
JSONObject obj = new JSONObject(token);
this.contextCache.put(id.getName(), obj);
return obj;
}
public Map<String, R2RMLMappingIdentifier> getModels()
{
return Collections.unmodifiableMap(modelIdentifiers);
}
private Worksheet generateWorksheetFromDelimitedStream(String sourceName, InputStream is,
Workspace workspace, String encoding, int maxNumLines) throws IOException,
KarmaException, ClassNotFoundException {
Worksheet worksheet;
Import fileImport = new CSVImport(1, 2, ',', '\"', encoding, maxNumLines,
sourceName, is, workspace, null);
worksheet = fileImport.generateWorksheet();
return worksheet;
}
private Worksheet generateWorksheetFromXMLStream(String sourceName, InputStream is,
Workspace workspace, String encoding, int maxNumLines)
throws IOException {
Worksheet worksheet;
String contents = IOUtils.toString(is, encoding);
JSONObject json = XML.toJSONObject(contents);
JsonImport imp = new JsonImport(json, sourceName, workspace, encoding, maxNumLines);
worksheet = imp.generateWorksheet();
return worksheet;
}
private Worksheet generateWorksheetFromJSONStream(String sourceName, InputStream is,
Workspace workspace, String encoding, int maxNumLines)
throws IOException {
Worksheet worksheet;
Reader reader = EncodingDetector.getInputStreamReader(is, encoding);
Object json = JSONUtil.createJson(reader);
JsonImport imp = new JsonImport(json, sourceName, workspace, encoding, maxNumLines);
worksheet = imp.generateWorksheet();
return worksheet;
}
private Worksheet generateWorksheetFromAvroStream(String sourceName, InputStream is,
Workspace workspace, String encoding, int maxNumLines)
throws IOException, JSONException, KarmaException {
Worksheet worksheet;
AvroImport imp = new AvroImport(is, sourceName, workspace, encoding, maxNumLines);
worksheet = imp.generateWorksheet();
return worksheet;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.