answer
stringlengths 17
10.2M
|
|---|
package org.opencms.ade.sitemap;
import org.opencms.ade.configuration.CmsADEConfigData;
import org.opencms.ade.configuration.CmsADEManager;
import org.opencms.ade.configuration.CmsFunctionReference;
import org.opencms.ade.configuration.CmsModelPageConfig;
import org.opencms.ade.configuration.CmsResourceTypeConfig;
import org.opencms.ade.detailpage.CmsDetailPageConfigurationWriter;
import org.opencms.ade.detailpage.CmsDetailPageInfo;
import org.opencms.ade.sitemap.shared.CmsClientSitemapEntry;
import org.opencms.ade.sitemap.shared.CmsClientSitemapEntry.EntryType;
import org.opencms.ade.sitemap.shared.CmsDetailPageTable;
import org.opencms.ade.sitemap.shared.CmsGalleryFolderEntry;
import org.opencms.ade.sitemap.shared.CmsGalleryType;
import org.opencms.ade.sitemap.shared.CmsModelPageEntry;
import org.opencms.ade.sitemap.shared.CmsNewResourceInfo;
import org.opencms.ade.sitemap.shared.CmsSitemapCategoryData;
import org.opencms.ade.sitemap.shared.CmsSitemapChange;
import org.opencms.ade.sitemap.shared.CmsSitemapChange.ChangeType;
import org.opencms.ade.sitemap.shared.CmsSitemapClipboardData;
import org.opencms.ade.sitemap.shared.CmsSitemapData;
import org.opencms.ade.sitemap.shared.CmsSitemapData.EditorMode;
import org.opencms.ade.sitemap.shared.CmsSitemapInfo;
import org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService;
import org.opencms.configuration.CmsDefaultUserSettings;
import org.opencms.db.CmsAlias;
import org.opencms.db.CmsAliasManager;
import org.opencms.db.CmsRewriteAlias;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.CmsUser;
import org.opencms.file.CmsVfsResourceNotFoundException;
import org.opencms.file.history.CmsHistoryResourceHandler;
import org.opencms.file.types.CmsResourceTypeFolder;
import org.opencms.file.types.CmsResourceTypeFolderExtended;
import org.opencms.file.types.CmsResourceTypeFolderSubSitemap;
import org.opencms.file.types.CmsResourceTypeUnknownFolder;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.flex.CmsFlexController;
import org.opencms.gwt.CmsCoreService;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.CmsRpcException;
import org.opencms.gwt.CmsTemplateFinder;
import org.opencms.gwt.shared.CmsBrokenLinkBean;
import org.opencms.gwt.shared.CmsCategoryTreeEntry;
import org.opencms.gwt.shared.CmsClientLock;
import org.opencms.gwt.shared.CmsCoreData;
import org.opencms.gwt.shared.CmsCoreData.AdeContext;
import org.opencms.gwt.shared.CmsListInfoBean;
import org.opencms.gwt.shared.alias.CmsAliasEditValidationReply;
import org.opencms.gwt.shared.alias.CmsAliasEditValidationRequest;
import org.opencms.gwt.shared.alias.CmsAliasImportResult;
import org.opencms.gwt.shared.alias.CmsAliasInitialFetchResult;
import org.opencms.gwt.shared.alias.CmsAliasSaveValidationRequest;
import org.opencms.gwt.shared.alias.CmsAliasTableRow;
import org.opencms.gwt.shared.alias.CmsRewriteAliasTableRow;
import org.opencms.gwt.shared.alias.CmsRewriteAliasValidationReply;
import org.opencms.gwt.shared.alias.CmsRewriteAliasValidationRequest;
import org.opencms.gwt.shared.property.CmsClientProperty;
import org.opencms.gwt.shared.property.CmsPropertyModification;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.json.JSONArray;
import org.opencms.jsp.CmsJspNavBuilder;
import org.opencms.jsp.CmsJspNavBuilder.Visibility;
import org.opencms.jsp.CmsJspNavElement;
import org.opencms.loader.CmsLoaderException;
import org.opencms.lock.CmsLock;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.relations.CmsCategory;
import org.opencms.relations.CmsCategoryService;
import org.opencms.search.galleries.CmsGallerySearch;
import org.opencms.search.galleries.CmsGallerySearchResult;
import org.opencms.security.CmsPermissionSet;
import org.opencms.security.CmsRole;
import org.opencms.security.CmsRoleViolationException;
import org.opencms.security.CmsSecurityException;
import org.opencms.site.CmsSite;
import org.opencms.util.CmsDateUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.workplace.CmsWorkplaceManager;
import org.opencms.workplace.CmsWorkplaceMessages;
import org.opencms.workplace.explorer.CmsExplorerTypeAccess;
import org.opencms.workplace.explorer.CmsExplorerTypeSettings;
import org.opencms.workplace.galleries.A_CmsAjaxGallery;
import org.opencms.xml.CmsXmlException;
import org.opencms.xml.I_CmsXmlDocument;
import org.opencms.xml.containerpage.CmsContainerBean;
import org.opencms.xml.containerpage.CmsContainerElementBean;
import org.opencms.xml.containerpage.CmsContainerPageBean;
import org.opencms.xml.containerpage.CmsXmlContainerPage;
import org.opencms.xml.containerpage.CmsXmlContainerPageFactory;
import org.opencms.xml.containerpage.CmsXmlDynamicFunctionHandler;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.content.CmsXmlContentProperty;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Ordering;
/**
* Handles all RPC services related to the vfs sitemap.<p>
*
* @since 8.0.0
*
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapServiceAsync
*/
public class CmsVfsSitemapService extends CmsGwtService implements I_CmsSitemapService {
/** Helper class for representing information about a lock. */
protected class LockInfo {
/** The lock state. */
private CmsLock m_lock;
/** True if the lock was just locked. */
private boolean m_wasJustLocked;
/**
* Creates a new LockInfo object.<p>
*
* @param lock the lock state
* @param wasJustLocked true if the lock was just locked
*/
public LockInfo(CmsLock lock, boolean wasJustLocked) {
m_lock = lock;
m_wasJustLocked = wasJustLocked;
}
/**
* Returns the lock state.<p>
*
* @return the lock state
*/
public CmsLock getLock() {
return m_lock;
}
/**
* Returns true if the lock was just locked.<p>
*
* @return true if the lock was just locked
*/
public boolean wasJustLocked() {
return m_wasJustLocked;
}
}
/** The path of the JSP used to download aliases. */
public static final String ALIAS_DOWNLOAD_PATH = "/system/modules/org.opencms.ade.sitemap/pages/download-aliases.jsp";
/** The path to the JSP used to upload aliases. */
public static final String ALIAS_IMPORT_PATH = "/system/modules/org.opencms.ade.sitemap/pages/import-aliases.jsp";
/** The galleries folder name. */
public static final String GALLERIES_FOLDER_NAME = ".galleries";
/** The configuration key for the functionDetail attribute in the container.info property. */
public static final String KEY_FUNCTION_DETAIL = "functionDetail";
/** The additional user info key for deleted list. */
private static final String ADDINFO_ADE_DELETED_LIST = "ADE_DELETED_LIST";
/** The additional user info key for modified list. */
private static final String ADDINFO_ADE_MODIFIED_LIST = "ADE_MODIFIED_LIST";
/** The lock table to prevent multiple users from editing the alias table concurrently. */
private static CmsAliasEditorLockTable aliasEditorLockTable = new CmsAliasEditorLockTable();
/** The table containing the alias import results. */
private static CmsAliasImportResponseTable aliasImportResponseTable = new CmsAliasImportResponseTable();
/** The static log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsVfsSitemapService.class);
/** The redirect recource type name. */
private static final String RECOURCE_TYPE_NAME_REDIRECT = "htmlredirect";
/** The redirect target XPath. */
private static final String REDIRECT_LINK_TARGET_XPATH = "Link";
/** Serialization uid. */
private static final long serialVersionUID = -7236544324371767330L;
/** The VFS path of the redirect copy page for navigation level entries. */
private static final String SUB_LEVEL_REDIRECT_COPY_PAGE = "/system/modules/org.opencms.ade.sitemap/pages/sub-level-redirect.html";
/** The navigation builder. */
private CmsJspNavBuilder m_navBuilder;
/**
* Adds an alias import result.<p>
*
* @param results the list of alias import results to add
*
* @return the key to retrieve the alias import results
*/
public static String addAliasImportResult(List<CmsAliasImportResult> results) {
return aliasImportResponseTable.addImportResult(results);
}
/**
* Creates a client property bean from a server-side property.<p>
*
* @param prop the property from which to create the client property
* @param preserveOrigin if true, the origin will be copied into the new object
*
* @return the new client property
*/
public static CmsClientProperty createClientProperty(CmsProperty prop, boolean preserveOrigin) {
CmsClientProperty result = new CmsClientProperty(
prop.getName(),
prop.getStructureValue(),
prop.getResourceValue());
if (preserveOrigin) {
result.setOrigin(prop.getOrigin());
}
return result;
}
/**
* Fetches the sitemap data.<p>
*
* @param request the current request
* @param sitemapUri the site relative path
*
* @return the sitemap data
*
* @throws CmsRpcException if something goes wrong
*/
public static CmsSitemapData prefetch(HttpServletRequest request, String sitemapUri) throws CmsRpcException {
CmsVfsSitemapService service = new CmsVfsSitemapService();
service.setCms(CmsFlexController.getCmsObject(request));
service.setRequest(request);
CmsSitemapData result = null;
try {
result = service.prefetch(sitemapUri);
} finally {
service.clearThreadStorage();
}
return result;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#changeCategory(java.lang.String, org.opencms.util.CmsUUID, java.lang.String, java.lang.String)
*/
public void changeCategory(String entryPoint, CmsUUID id, String title, String name) throws CmsRpcException {
try {
name = OpenCms.getResourceManager().getFileTranslator().translateResource(name.trim().replace('/', '-'));
CmsObject cms = getCmsObject();
CmsResource categoryResource = cms.readResource(id);
ensureLock(categoryResource);
String sitePath = cms.getSitePath(categoryResource);
String newPath = CmsStringUtil.joinPaths(CmsResource.getParentFolder(sitePath), name);
cms.writePropertyObject(sitePath, new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, title, null));
if (!CmsStringUtil.joinPaths("/", newPath, "/").equals(CmsStringUtil.joinPaths("/", sitePath, "/"))) {
cms.moveResource(sitePath, newPath);
}
} catch (Exception e) {
error(e);
}
}
@Override
public void checkPermissions(CmsObject cms) throws CmsRoleViolationException {
OpenCms.getRoleManager().checkRole(cms, CmsRole.EDITOR);
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#createCategory(java.lang.String, org.opencms.util.CmsUUID, java.lang.String, java.lang.String)
*/
public void createCategory(String entryPoint, CmsUUID id, String title, String name) throws CmsRpcException {
try {
name = OpenCms.getResourceManager().getFileTranslator().translateResource(name.trim().replace('/', '-'));
CmsObject cms = getCmsObject();
CmsCategoryService catService = CmsCategoryService.getInstance();
CmsCategory createdCategory = null;
if (id.isNullUUID()) {
String localRepositoryPath = CmsStringUtil.joinPaths(
entryPoint,
OpenCms.getWorkplaceManager().getCategoryFolder());
// ensure category repository exists
if (!cms.existsResource(localRepositoryPath)) {
tryUnlock(cms.createResource(
localRepositoryPath,
OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolder.getStaticTypeName()).getTypeId()));
}
createdCategory = catService.createCategory(cms, null, name, title, "", localRepositoryPath);
} else {
CmsResource parentResource = cms.readResource(id);
CmsCategory parent = catService.getCategory(cms, parentResource);
createdCategory = catService.createCategory(
cms,
parent,
name,
title,
"",
cms.getRequestContext().removeSiteRoot(parentResource.getRootPath()));
}
tryUnlock(cms.readResource(createdCategory.getId()));
} catch (Exception e) {
error(e);
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#createNewGalleryFolder(java.lang.String, java.lang.String, int)
*/
public CmsGalleryFolderEntry createNewGalleryFolder(String parentFolder, String title, int folderTypeId)
throws CmsRpcException {
CmsObject cms = getCmsObject();
CmsGalleryFolderEntry folderEntry = null;
try {
if (!cms.existsResource(parentFolder, CmsResourceFilter.IGNORE_EXPIRATION)) {
CmsResource parent = cms.createResource(parentFolder, CmsResourceTypeFolder.getStaticTypeId());
tryUnlock(parent);
}
String folderName = OpenCms.getResourceManager().getFileTranslator().translateResource(title);
folderName = OpenCms.getResourceManager().getNameGenerator().getUniqueFileName(
cms,
parentFolder,
folderName);
String folderPath = CmsStringUtil.joinPaths(parentFolder, folderName);
CmsResource galleryFolder = cms.createResource(
folderPath,
folderTypeId,
null,
Collections.singletonList(new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, title, null)));
folderEntry = readGalleryFolderEntry(
galleryFolder,
OpenCms.getResourceManager().getResourceType(galleryFolder).getTypeName());
tryUnlock(galleryFolder);
} catch (CmsException e) {
error(e);
}
return folderEntry;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#createNewModelPage(java.lang.String, java.lang.String, java.lang.String, org.opencms.util.CmsUUID)
*/
public CmsModelPageEntry createNewModelPage(String entryPointUri, String title, String description, CmsUUID copyId)
throws CmsRpcException {
try {
CmsObject cms = getCmsObject();
CmsResource rootResource = cms.readResource(entryPointUri);
CmsModelPageHelper helper = new CmsModelPageHelper(getCmsObject(), rootResource);
CmsResource page = helper.createPageInModelFolder(title, description, copyId);
String configPath = CmsStringUtil.joinPaths(entryPointUri, ".content/.config");
CmsResource configResource = cms.readResource(configPath);
helper.addModelPageToSitemapConfiguration(configResource, page, false);
CmsModelPageEntry result = helper.createModelPageEntry(page);
OpenCms.getADEManager().waitForCacheUpdate(false);
return result;
} catch (Throwable e) {
error(e);
return null;
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#createSubSitemap(org.opencms.util.CmsUUID)
*/
public CmsSitemapChange createSubSitemap(CmsUUID entryId) throws CmsRpcException {
CmsObject cms = getCmsObject();
try {
ensureSession();
CmsResource subSitemapFolder = cms.readResource(entryId);
ensureLock(subSitemapFolder);
String sitePath = cms.getSitePath(subSitemapFolder);
createSitemapContentFolder(cms, subSitemapFolder);
subSitemapFolder.setType(getSubsitemapType());
cms.writeResource(subSitemapFolder);
tryUnlock(subSitemapFolder);
CmsSitemapClipboardData clipboard = getClipboardData();
CmsClientSitemapEntry entry = toClientEntry(
getNavBuilder().getNavigationForResource(sitePath, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED),
false);
clipboard.addModified(entry);
setClipboardData(clipboard);
CmsSitemapChange result = new CmsSitemapChange(entry.getId(), entry.getSitePath(), ChangeType.modify);
result.setUpdatedEntry(entry);
return result;
} catch (Exception e) {
error(e);
}
return null;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getAliasImportResult(java.lang.String)
*/
public List<CmsAliasImportResult> getAliasImportResult(String resultKey) {
return aliasImportResponseTable.getAndRemove(resultKey);
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getAliasTable()
*/
public CmsAliasInitialFetchResult getAliasTable() throws CmsRpcException {
try {
CmsObject cms = getCmsObject();
CmsAliasManager aliasManager = OpenCms.getAliasManager();
List<CmsAlias> aliases = aliasManager.getAliasesForSite(cms, cms.getRequestContext().getSiteRoot());
List<CmsAliasTableRow> rows = new ArrayList<CmsAliasTableRow>();
CmsAliasInitialFetchResult result = new CmsAliasInitialFetchResult();
for (CmsAlias alias : aliases) {
CmsAliasTableRow row = createAliasTableEntry(cms, alias);
rows.add(row);
}
result.setRows(rows);
List<CmsRewriteAlias> rewriteAliases = aliasManager.getRewriteAliases(
cms,
cms.getRequestContext().getSiteRoot());
List<CmsRewriteAliasTableRow> rewriteRows = new ArrayList<CmsRewriteAliasTableRow>();
for (CmsRewriteAlias rewriteAlias : rewriteAliases) {
CmsRewriteAliasTableRow rewriteRow = new CmsRewriteAliasTableRow(
rewriteAlias.getId(),
rewriteAlias.getPatternString(),
rewriteAlias.getReplacementString(),
rewriteAlias.getMode());
rewriteRows.add(rewriteRow);
}
result.setRewriteRows(rewriteRows);
CmsUser otherLockOwner = aliasEditorLockTable.update(cms, cms.getRequestContext().getSiteRoot());
if (otherLockOwner != null) {
result.setAliasLockOwner(otherLockOwner.getName());
}
result.setDownloadUrl(OpenCms.getLinkManager().substituteLinkForRootPath(cms, ALIAS_DOWNLOAD_PATH));
return result;
} catch (Throwable e) {
error(e);
return null;
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getCategoryData(java.lang.String)
*/
public CmsSitemapCategoryData getCategoryData(String entryPoint) throws CmsRpcException {
CmsObject cms = getCmsObject();
try {
List<CmsCategoryTreeEntry> entries = CmsCoreService.getCategoriesForSitePathStatic(cms, entryPoint);
CmsSitemapCategoryData categoryData = new CmsSitemapCategoryData();
for (CmsCategoryTreeEntry entry : entries) {
categoryData.add(entry);
}
CmsResource entryPointResource = cms.readResource(entryPoint);
String basePath = CmsStringUtil.joinPaths(
entryPointResource.getRootPath(),
OpenCms.getWorkplaceManager().getCategoryFolder());
categoryData.setBasePath(basePath);
return categoryData;
} catch (Exception e) {
error(e);
return null;
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getChildren(java.lang.String, org.opencms.util.CmsUUID, int)
*/
public CmsClientSitemapEntry getChildren(String entryPointUri, CmsUUID entryId, int levels) throws CmsRpcException {
CmsClientSitemapEntry entry = null;
try {
CmsObject cms = getCmsObject();
//ensure that root ends with a '/' if it's a folder
CmsResource rootRes = cms.readResource(entryId, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
String root = cms.getSitePath(rootRes);
CmsJspNavElement navElement = getNavBuilder().getNavigationForResource(
root,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
boolean isRoot = root.equals(entryPointUri);
entry = toClientEntry(navElement, isRoot);
if ((levels > 0) && (isRoot || (rootRes.isFolder()))) {
entry.setSubEntries(getChildren(root, levels, null), null);
}
} catch (Throwable e) {
error(e);
}
return entry;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getGalleryData(java.lang.String)
*/
public Map<CmsGalleryType, List<CmsGalleryFolderEntry>> getGalleryData(String entryPointUri) {
List<String> subSitePaths = OpenCms.getADEManager().getSubSitePaths(
getCmsObject(),
getCmsObject().getRequestContext().addSiteRoot(entryPointUri));
List<CmsGalleryType> galleryTypes = collectGalleryTypes();
Map<CmsGalleryType, List<CmsGalleryFolderEntry>> result = new HashMap<CmsGalleryType, List<CmsGalleryFolderEntry>>();
for (CmsGalleryType type : galleryTypes) {
List<CmsGalleryFolderEntry> galleries = null;
try {
galleries = getGalleriesForType(entryPointUri, type, subSitePaths);
} catch (CmsException e) {
log(e.getLocalizedMessage(), e);
}
result.put(type, galleries);
}
return result;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getModelPages(org.opencms.util.CmsUUID)
*/
public List<CmsModelPageEntry> getModelPages(CmsUUID rootId) throws CmsRpcException {
try {
CmsObject cms = getCmsObject();
CmsResource rootResource = cms.readResource(rootId);
CmsModelPageHelper modelPageHelper = new CmsModelPageHelper(getCmsObject(), rootResource);
List<CmsModelPageEntry> entries = modelPageHelper.getModelPages();
return entries;
} catch (Throwable e) {
error(e);
return null; // will never be reached
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#getNewElementInfo(java.lang.String)
*/
public List<CmsNewResourceInfo> getNewElementInfo(String entryPointUri) throws CmsRpcException {
try {
CmsObject cms = getCmsObject();
String rootPath = cms.getRequestContext().addSiteRoot(entryPointUri);
CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration(cms, rootPath);
Locale locale = getLocaleForNewResourceInfos(cms, config);
List<CmsNewResourceInfo> result = getNewResourceInfos(cms, config, locale);
return result;
} catch (Throwable e) {
error(e);
return null;
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#mergeSubSitemap(java.lang.String, org.opencms.util.CmsUUID)
*/
public CmsSitemapChange mergeSubSitemap(String entryPoint, CmsUUID subSitemapId) throws CmsRpcException {
CmsObject cms = getCmsObject();
try {
ensureSession();
CmsResource subSitemapFolder = cms.readResource(subSitemapId, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(subSitemapFolder);
subSitemapFolder.setType(OpenCms.getResourceManager().getResourceType(
CmsResourceTypeFolder.RESOURCE_TYPE_NAME).getTypeId());
cms.writeResource(subSitemapFolder);
String sitePath = cms.getSitePath(subSitemapFolder);
String sitemapConfigName = CmsStringUtil.joinPaths(
sitePath,
CmsADEManager.CONTENT_FOLDER_NAME,
CmsADEManager.CONFIG_FILE_NAME);
if (cms.existsResource(sitemapConfigName)) {
cms.deleteResource(sitemapConfigName, CmsResource.DELETE_PRESERVE_SIBLINGS);
}
tryUnlock(subSitemapFolder);
CmsSitemapClipboardData clipboard = getClipboardData();
CmsClientSitemapEntry entry = toClientEntry(
getNavBuilder().getNavigationForResource(
cms.getSitePath(subSitemapFolder),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED),
false);
clipboard.addModified(entry);
setClipboardData(clipboard);
entry = getChildren(entryPoint, subSitemapId, 1);
CmsSitemapChange result = new CmsSitemapChange(entry.getId(), entry.getSitePath(), ChangeType.modify);
result.setUpdatedEntry(entry);
return result;
} catch (Exception e) {
error(e);
}
return null;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#prefetch(java.lang.String)
*/
public CmsSitemapData prefetch(String sitemapUri) throws CmsRpcException {
CmsSitemapData result = null;
CmsObject cms = getCmsObject();
try {
OpenCms.getRoleManager().checkRole(cms, CmsRole.EDITOR);
String openPath = getRequest().getParameter(CmsCoreData.PARAM_PATH);
if (!isValidOpenPath(cms, openPath)) {
// if no path is supplied, start from root
openPath = "/";
}
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.getRequestContext().addSiteRoot(openPath));
Map<String, CmsXmlContentProperty> propertyConfig = new LinkedHashMap<String, CmsXmlContentProperty>(
configData.getPropertyConfigurationAsMap());
Map<String, CmsClientProperty> parentProperties = generateParentProperties(configData.getBasePath());
String siteRoot = cms.getRequestContext().getSiteRoot();
String exportRfsPrefix = OpenCms.getStaticExportManager().getDefaultRfsPrefix();
CmsSite site = OpenCms.getSiteManager().getSiteForSiteRoot(siteRoot);
boolean isSecure = site.hasSecureServer();
String parentSitemap = null;
if (configData.getBasePath() != null) {
CmsADEConfigData parentConfigData = OpenCms.getADEManager().lookupConfiguration(
cms,
CmsResource.getParentFolder(configData.getBasePath()));
parentSitemap = parentConfigData.getBasePath();
if (parentSitemap != null) {
parentSitemap = cms.getRequestContext().removeSiteRoot(parentSitemap);
}
}
String noEdit = "";
CmsNewResourceInfo defaultNewInfo = null;
List<CmsNewResourceInfo> newResourceInfos = null;
CmsDetailPageTable detailPages = null;
List<CmsNewResourceInfo> resourceTypeInfos = null;
boolean canEditDetailPages = false;
boolean isOnlineProject = CmsProject.isOnlineProject(cms.getRequestContext().getCurrentProject().getUuid());
String defaultGalleryFolder = GALLERIES_FOLDER_NAME;
Locale locale = getLocaleForNewResourceInfos(cms, configData);
try {
String basePath = configData.getBasePath();
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
CmsResource baseDir = rootCms.readResource(basePath, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
CmsProperty galleryFolderProp = cms.readPropertyObject(
baseDir,
CmsPropertyDefinition.PROPERTY_GALLERIES_FOLDER,
true);
if (!galleryFolderProp.isNullProperty()
&& CmsStringUtil.isNotEmptyOrWhitespaceOnly(galleryFolderProp.getValue())) {
defaultGalleryFolder = galleryFolderProp.getValue();
}
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
detailPages = new CmsDetailPageTable(configData.getAllDetailPages());
if (!isOnlineProject) {
newResourceInfos = getNewResourceInfos(cms, configData, locale);
CmsResource modelResource = null;
if (configData.getDefaultModelPage() != null) {
if (cms.existsResource(configData.getDefaultModelPage().getResource().getStructureId())) {
modelResource = configData.getDefaultModelPage().getResource();
} else {
try {
modelResource = cms.readResource(
cms.getSitePath(configData.getDefaultModelPage().getResource()),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
}
if ((modelResource == null) && !newResourceInfos.isEmpty()) {
try {
modelResource = cms.readResource(newResourceInfos.get(0).getCopyResourceId());
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
if (modelResource != null) {
resourceTypeInfos = getResourceTypeInfos(
getCmsObject(),
configData.getResourceTypes(),
configData.getFunctionReferences(),
modelResource,
locale);
try {
defaultNewInfo = createNewResourceInfo(cms, modelResource, locale);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
}
canEditDetailPages = !(configData.isModuleConfiguration());
}
if (isOnlineProject) {
noEdit = Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_SITEMAP_NO_EDIT_ONLINE_0);
}
List<String> allPropNames = getPropertyNames(cms);
String returnCode = getRequest().getParameter(CmsCoreData.PARAM_RETURNCODE);
if (!isValidReturnCode(returnCode)) {
returnCode = null;
}
cms.getRequestContext().getSiteRoot();
String aliasImportUrl = OpenCms.getLinkManager().substituteLinkForRootPath(cms, ALIAS_IMPORT_PATH);
boolean canEditAliases = OpenCms.getAliasManager().hasPermissionsForMassEdit(cms, siteRoot);
List<CmsListInfoBean> subsitemapFolderTypeInfos = collectSitemapTypeInfos(cms, configData);
// evaluate the editor mode
EditorMode editorMode = EditorMode.navigation;
String modeParam = getRequest().getParameter(CmsSitemapData.PARAM_EDITOR_MODE);
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(modeParam)) {
try {
editorMode = EditorMode.valueOf(modeParam);
} catch (Exception e) {
// ignore
}
}
result = new CmsSitemapData(
(new CmsTemplateFinder(cms)).getTemplates(),
propertyConfig,
getClipboardData(),
CmsCoreService.getContextMenuEntries(cms, configData.getResource().getStructureId(), AdeContext.sitemap),
parentProperties,
allPropNames,
exportRfsPrefix,
isSecure,
noEdit,
isDisplayToolbar(getRequest()),
defaultNewInfo,
newResourceInfos,
createResourceTypeInfo(OpenCms.getResourceManager().getResourceType(RECOURCE_TYPE_NAME_REDIRECT), null),
createNavigationLevelTypeInfo(),
getSitemapInfo(configData.getBasePath()),
parentSitemap,
getRootEntry(configData.getBasePath(), CmsResource.getFolderPath(openPath)),
openPath,
30,
detailPages,
resourceTypeInfos,
returnCode,
canEditDetailPages,
aliasImportUrl,
canEditAliases,
OpenCms.getWorkplaceManager().getDefaultUserSettings().getSubsitemapCreationMode() == CmsDefaultUserSettings.SubsitemapCreationMode.createfolder,
OpenCms.getRoleManager().hasRole(cms, CmsRole.GALLERY_EDITOR),
OpenCms.getRoleManager().hasRole(cms, CmsRole.CATEGORY_EDITOR),
subsitemapFolderTypeInfos,
editorMode,
defaultGalleryFolder);
CmsUUID rootId = cms.readResource("/", CmsResourceFilter.ALL).getStructureId();
result.setSiteRootId(rootId);
} catch (Throwable e) {
error(e);
}
return result;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#removeModelPage(java.lang.String, org.opencms.util.CmsUUID)
*/
public void removeModelPage(String entryPointUri, CmsUUID id) throws CmsRpcException {
try {
CmsObject cms = getCmsObject();
CmsResource rootResource = cms.readResource(entryPointUri);
CmsModelPageHelper helper = new CmsModelPageHelper(getCmsObject(), rootResource);
String configPath = CmsStringUtil.joinPaths(entryPointUri, ".content/.config");
CmsResource configResource = cms.readResource(configPath);
helper.removeModelPage(configResource, id);
OpenCms.getADEManager().waitForCacheUpdate(false);
} catch (Throwable e) {
error(e);
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#save(java.lang.String, org.opencms.ade.sitemap.shared.CmsSitemapChange)
*/
public CmsSitemapChange save(String entryPoint, CmsSitemapChange change) throws CmsRpcException {
CmsSitemapChange result = null;
try {
result = saveInternal(entryPoint, change);
} catch (Exception e) {
error(e);
}
return result;
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#saveAliases(org.opencms.gwt.shared.alias.CmsAliasSaveValidationRequest)
*/
public CmsAliasEditValidationReply saveAliases(CmsAliasSaveValidationRequest saveRequest) throws CmsRpcException {
CmsObject cms = getCmsObject();
CmsAliasBulkEditHelper helper = new CmsAliasBulkEditHelper(cms);
try {
return helper.saveAliases(saveRequest);
} catch (Exception e) {
error(e);
return null;
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#saveSync(java.lang.String, org.opencms.ade.sitemap.shared.CmsSitemapChange)
*/
public CmsSitemapChange saveSync(String entryPoint, CmsSitemapChange change) throws CmsRpcException {
return save(entryPoint, change);
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#updateAliasEditorStatus(boolean)
*/
public void updateAliasEditorStatus(boolean editing) {
CmsObject cms = getCmsObject();
if (editing) {
aliasEditorLockTable.update(cms, cms.getRequestContext().getSiteRoot());
} else {
aliasEditorLockTable.clear(cms, cms.getRequestContext().getSiteRoot());
}
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#validateAliases(org.opencms.gwt.shared.alias.CmsAliasEditValidationRequest)
*/
public CmsAliasEditValidationReply validateAliases(CmsAliasEditValidationRequest validationRequest) {
CmsObject cms = getCmsObject();
CmsAliasBulkEditHelper helper = new CmsAliasBulkEditHelper(cms);
return helper.validateAliases(validationRequest);
}
/**
* @see org.opencms.ade.sitemap.shared.rpc.I_CmsSitemapService#validateRewriteAliases(org.opencms.gwt.shared.alias.CmsRewriteAliasValidationRequest)
*/
public CmsRewriteAliasValidationReply validateRewriteAliases(CmsRewriteAliasValidationRequest validationRequest) {
CmsRewriteAliasValidationReply result = new CmsRewriteAliasValidationReply();
for (CmsRewriteAliasTableRow editedRow : validationRequest.getEditedRewriteAliases()) {
try {
String patternString = editedRow.getPatternString();
Pattern.compile(patternString);
} catch (PatternSyntaxException e) {
result.addError(editedRow.getId(), "Syntax error in regular expression: " + e.getMessage());
}
}
return result;
}
/**
* Creates a "broken link" bean based on a resource.<p>
*
* @param resource the resource
*
* @return the "broken link" bean with the data from the resource
*
* @throws CmsException if something goes wrong
*/
protected CmsBrokenLinkBean createSitemapBrokenLinkBean(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
CmsProperty titleProp = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, true);
String defaultTitle = "";
String title = titleProp.getValue(defaultTitle);
String path = cms.getSitePath(resource);
String subtitle = path;
return new CmsBrokenLinkBean(resource.getStructureId(), title, subtitle);
}
/**
* Locks the given resource with a temporary, if not already locked by the current user.
* Will throw an exception if the resource could not be locked for the current user.<p>
*
* @param resource the resource to lock
*
* @return the assigned lock
*
* @throws CmsException if the resource could not be locked
*/
protected LockInfo ensureLockAndGetInfo(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
boolean justLocked = false;
List<CmsResource> blockingResources = cms.getBlockingLockedResources(resource);
if ((blockingResources != null) && !blockingResources.isEmpty()) {
throw new CmsException(org.opencms.gwt.Messages.get().container(
org.opencms.gwt.Messages.ERR_RESOURCE_HAS_BLOCKING_LOCKED_CHILDREN_1,
cms.getSitePath(resource)));
}
CmsUser user = cms.getRequestContext().getCurrentUser();
CmsLock lock = cms.getLock(resource);
if (!lock.isOwnedBy(user)) {
cms.lockResourceTemporary(resource);
lock = cms.getLock(resource);
justLocked = true;
} else if (!lock.isOwnedInProjectBy(user, cms.getRequestContext().getCurrentProject())) {
cms.changeLock(resource);
lock = cms.getLock(resource);
justLocked = true;
}
return new LockInfo(lock, justLocked);
}
/**
* Internal method for saving a sitemap.<p>
*
* @param entryPoint the URI of the sitemap to save
* @param change the change to save
*
* @return list of changed sitemap entries
*
* @throws CmsException if something goes wrong
*/
protected CmsSitemapChange saveInternal(String entryPoint, CmsSitemapChange change) throws CmsException {
ensureSession();
switch (change.getChangeType()) {
case clipboardOnly:
// do nothing
break;
case remove:
change = removeEntryFromNavigation(change);
break;
case undelete:
change = undelete(change);
break;
default:
change = applyChange(entryPoint, change);
}
setClipboardData(change.getClipBoardData());
return change;
}
/**
* Converts a sequence of properties to a map of client-side property beans.<p>
*
* @param props the sequence of properties
* @param preserveOrigin if true, the origin of the properties should be copied to the client properties
*
* @return the map of client properties
*
*/
Map<String, CmsClientProperty> createClientProperties(Iterable<CmsProperty> props, boolean preserveOrigin) {
Map<String, CmsClientProperty> result = new HashMap<String, CmsClientProperty>();
for (CmsProperty prop : props) {
CmsClientProperty clientProp = createClientProperty(prop, preserveOrigin);
result.put(prop.getName(), clientProp);
}
return result;
}
/**
* Removes unnecessary locales from a container page.<p>
*
* @param containerPage the container page which should be changed
* @param localeRes the resource used to determine the locale
*
* @throws CmsException if something goes wrong
*/
void ensureSingleLocale(CmsXmlContainerPage containerPage, CmsResource localeRes) throws CmsException {
CmsObject cms = getCmsObject();
Locale mainLocale = CmsLocaleManager.getMainLocale(cms, localeRes);
OpenCms.getLocaleManager();
Locale defaultLocale = CmsLocaleManager.getDefaultLocale();
if (containerPage.hasLocale(mainLocale)) {
removeAllLocalesExcept(containerPage, mainLocale);
// remove other locales
} else if (containerPage.hasLocale(defaultLocale)) {
containerPage.copyLocale(defaultLocale, mainLocale);
removeAllLocalesExcept(containerPage, mainLocale);
} else if (containerPage.getLocales().size() > 0) {
containerPage.copyLocale(containerPage.getLocales().get(0), mainLocale);
removeAllLocalesExcept(containerPage, mainLocale);
} else {
containerPage.addLocale(cms, mainLocale);
}
}
/**
* Gets the properties of a resource as a map of client properties.<p>
*
* @param cms the CMS context to use
* @param res the resource whose properties to read
* @param search true if the inherited properties should be read
*
* @return the client properties as a map
*
* @throws CmsException if something goes wrong
*/
Map<String, CmsClientProperty> getClientProperties(CmsObject cms, CmsResource res, boolean search)
throws CmsException {
List<CmsProperty> props = cms.readPropertyObjects(res, search);
Map<String, CmsClientProperty> result = createClientProperties(props, false);
return result;
}
/**
* Adds a function detail element to a container page.<p>
*
* @param cms the current CMS context
* @param page the container page which should be changed
* @param containerName the name of the container which should be used for function detail elements
* @param elementId the structure id of the element to add
* @param formatterId the structure id of the formatter for the element
*
* @throws CmsException if something goes wrong
*/
private void addFunctionDetailElement(
CmsObject cms,
CmsXmlContainerPage page,
String containerName,
CmsUUID elementId,
CmsUUID formatterId) throws CmsException {
CmsContainerPageBean bean = page.getContainerPage(cms);
List<CmsContainerBean> containerBeans = new ArrayList<CmsContainerBean>();
Collection<CmsContainerBean> originalContainers = bean.getContainers().values();
if ((containerName == null) && !originalContainers.isEmpty()) {
CmsContainerBean firstContainer = originalContainers.iterator().next();
containerName = firstContainer.getName();
}
boolean foundContainer = false;
for (CmsContainerBean cntBean : originalContainers) {
boolean isDetailTarget = cntBean.getName().equals(containerName);
if (isDetailTarget && !foundContainer) {
foundContainer = true;
List<CmsContainerElementBean> newElems = new ArrayList<CmsContainerElementBean>();
newElems.addAll(cntBean.getElements());
CmsContainerElementBean newElement = new CmsContainerElementBean(
elementId,
formatterId,
new HashMap<String, String>(),
false);
newElems.add(0, newElement);
CmsContainerBean newCntBean = new CmsContainerBean(
cntBean.getName(),
cntBean.getType(),
cntBean.getParentInstanceId(),
newElems);
containerBeans.add(newCntBean);
} else {
containerBeans.add(cntBean);
}
}
if (!foundContainer) {
throw new CmsException(Messages.get().container(
Messages.ERR_NO_FUNCTION_DETAIL_CONTAINER_1,
page.getFile().getRootPath()));
}
CmsContainerPageBean bean2 = new CmsContainerPageBean(new ArrayList<CmsContainerBean>(containerBeans));
page.writeContainerPage(cms, bean2);
}
/**
* Applys the given change to the VFS.<p>
*
* @param entryPoint the sitemap entry-point
* @param change the change
*
* @return the updated entry
*
* @throws CmsException if something goes wrong
*/
private CmsSitemapChange applyChange(String entryPoint, CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource configFile = null;
// lock the config file first, to avoid half done changes
if (change.hasDetailPageInfos()) {
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(
cms,
cms.getRequestContext().addSiteRoot(entryPoint));
if (!configData.isModuleConfiguration() && (configData.getResource() != null)) {
configFile = configData.getResource();
}
if (configFile != null) {
ensureLock(configFile);
}
}
if (change.isNew()) {
CmsClientSitemapEntry newEntry = createNewEntry(entryPoint, change);
change.setUpdatedEntry(newEntry);
change.setEntryId(newEntry.getId());
} else if (change.getChangeType() == ChangeType.delete) {
delete(change);
} else if (change.getEntryId() != null) {
modifyEntry(change);
}
if (change.hasDetailPageInfos() && (configFile != null)) {
saveDetailPages(change.getDetailPageInfos(), configFile, change.getEntryId(), change.getUpdatedEntry());
tryUnlock(configFile);
}
return change;
}
/**
* Changes the navigation for a moved entry and its neighbors.<p>
*
* @param change the sitemap change
* @param entryFolder the moved entry
*
* @throws CmsException if something goes wrong
*/
private void applyNavigationChanges(CmsSitemapChange change, CmsResource entryFolder) throws CmsException {
CmsObject cms = getCmsObject();
String parentPath = null;
if (change.hasNewParent()) {
CmsResource parent = cms.readResource(change.getParentId());
parentPath = cms.getSitePath(parent);
} else {
parentPath = CmsResource.getParentFolder(cms.getSitePath(entryFolder));
}
List<CmsJspNavElement> navElements = getNavBuilder().getNavigationForFolder(
parentPath,
Visibility.all,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
CmsSitemapNavPosCalculator npc = new CmsSitemapNavPosCalculator(navElements, entryFolder, change.getPosition());
List<CmsJspNavElement> navs = npc.getNavigationChanges();
List<CmsResource> needToUnlock = new ArrayList<CmsResource>();
try {
for (CmsJspNavElement nav : navs) {
LockInfo lockInfo = ensureLockAndGetInfo(nav.getResource());
if (!nav.getResource().equals(entryFolder) && lockInfo.wasJustLocked()) {
needToUnlock.add(nav.getResource());
}
}
for (CmsJspNavElement nav : navs) {
CmsProperty property = new CmsProperty(
CmsPropertyDefinition.PROPERTY_NAVPOS,
"" + nav.getNavPosition(),
null);
cms.writePropertyObject(cms.getSitePath(nav.getResource()), property);
}
} finally {
for (CmsResource lockedRes : needToUnlock) {
try {
cms.unlockResource(lockedRes);
} catch (CmsException e) {
// we catch this because we still want to unlock the other resources
LOG.error(e.getLocalizedMessage(), e);
}
}
}
}
/**
* Builds the list info bean for a resource type which can be used as a sub-sitemap folder.<p>
*
* @param sitemapType the sitemap folder type
*
* @return the list info bean for the given type
*/
private CmsListInfoBean buildSitemapTypeInfo(I_CmsResourceType sitemapType) {
CmsListInfoBean result = new CmsListInfoBean();
CmsWorkplaceManager wm = OpenCms.getWorkplaceManager();
String typeName = sitemapType.getTypeName();
Locale wpLocale = wm.getWorkplaceLocale(getCmsObject());
String title = typeName;
String description = "";
try {
title = CmsWorkplaceMessages.getResourceTypeName(wpLocale, typeName);
} catch (Throwable e) {
LOG.warn(e.getLocalizedMessage(), e);
}
try {
description = CmsWorkplaceMessages.getResourceTypeDescription(wpLocale, typeName);
} catch (Throwable e) {
LOG.warn(e.getLocalizedMessage(), e);
}
result.setResourceType(typeName);
result.setTitle(title);
result.setSubTitle(description);
return result;
}
/**
* Returns all available gallery folder resource types.<p>
*
* @return the gallery folder resource types
*/
private List<CmsGalleryType> collectGalleryTypes() {
Locale wpLocale = OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject());
Map<String, List<String>> galleryContentTypes = new HashMap<String, List<String>>();
List<CmsGalleryType> result = new ArrayList<CmsGalleryType>();
for (I_CmsResourceType resourceType : OpenCms.getResourceManager().getResourceTypes()) {
if (resourceType instanceof CmsResourceTypeFolderExtended) {
// found a configured extended folder resource type
CmsResourceTypeFolderExtended galleryType = (CmsResourceTypeFolderExtended)resourceType;
String folderClassName = galleryType.getFolderClassName();
if (CmsStringUtil.isNotEmpty(folderClassName)) {
// only process this as a gallery if the folder name is not empty
try {
// check, if the folder class is a subclass of A_CmsGallery
if (A_CmsAjaxGallery.class.isAssignableFrom(Class.forName(folderClassName))) {
CmsGalleryType gallery = new CmsGalleryType();
gallery.setTypeId(resourceType.getTypeId());
gallery.setTypeName(resourceType.getTypeName());
gallery.setNiceName(CmsWorkplaceMessages.getResourceTypeName(
wpLocale,
resourceType.getTypeName()));
gallery.setDescription(CmsWorkplaceMessages.getResourceTypeDescription(
wpLocale,
resourceType.getTypeName()));
result.add(gallery);
}
} catch (Exception e) {
this.log(e.getLocalizedMessage(), e);
}
}
} else {
List<I_CmsResourceType> galleryTypes = resourceType.getGalleryTypes();
if ((galleryTypes != null) && !galleryTypes.isEmpty()) {
for (I_CmsResourceType galleryType : galleryTypes) {
List<String> typeList = galleryContentTypes.get(galleryType.getTypeName());
if (typeList == null) {
typeList = new ArrayList<String>();
galleryContentTypes.put(galleryType.getTypeName(), typeList);
}
typeList.add(resourceType.getTypeName());
}
}
}
}
for (CmsGalleryType galleryType : result) {
galleryType.setContentTypeNames(galleryContentTypes.get(galleryType.getTypeName()));
}
return result;
}
/**
* Gets the information for the available sitemap folder types.<p>
*
* @param cms the current CMS context
* @param configData the configuration data for the current subsitemap
* @return the list info beans corresponding to available sitemap folder types
*/
private List<CmsListInfoBean> collectSitemapTypeInfos(CmsObject cms, CmsADEConfigData configData) {
List<CmsListInfoBean> subsitemapFolderTypeInfos = new ArrayList<CmsListInfoBean>();
List<Integer> sitemapTypeIds = CmsResourceTypeFolderSubSitemap.getSubSitemapResourceTypeIds();
String checkPath = configData.getBasePath();
if (checkPath != null) {
checkPath = cms.getRequestContext().removeSiteRoot(checkPath);
} else {
checkPath = "/";
}
CmsResource checkResource = null;
try {
checkResource = cms.readResource(checkPath);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
for (Integer typeId : sitemapTypeIds) {
try {
I_CmsResourceType sitemapType = OpenCms.getResourceManager().getResourceType(typeId.intValue());
String typeName = sitemapType.getTypeName();
CmsExplorerTypeSettings explorerType = OpenCms.getWorkplaceManager().getExplorerTypeSetting(typeName);
if ((explorerType != null) && (checkResource != null)) {
try {
CmsExplorerTypeAccess access = explorerType.getAccess();
if (!access.getPermissions(cms, checkResource).requiresControlPermission()) {
continue;
}
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
CmsListInfoBean infoBean = buildSitemapTypeInfo(sitemapType);
subsitemapFolderTypeInfos.add(infoBean);
} catch (CmsLoaderException e) {
LOG.warn("Could not read sitemap folder type " + typeId + ": " + e.getLocalizedMessage(), e);
}
}
return subsitemapFolderTypeInfos;
}
/**
* Creates a client alias bean from a server-side alias.<p>
*
* @param cms the current CMS context
* @param alias the alias to convert
*
* @return the alias table row
*
* @throws CmsException if something goes wrong
*/
private CmsAliasTableRow createAliasTableEntry(CmsObject cms, CmsAlias alias) throws CmsException {
CmsResource resource = cms.readResource(alias.getStructureId(), CmsResourceFilter.ALL);
CmsAliasTableRow result = new CmsAliasTableRow();
result.setStructureId(alias.getStructureId());
result.setOriginalStructureId(alias.getStructureId());
result.setAliasPath(alias.getAliasPath());
result.setResourcePath(cms.getSitePath(resource));
result.setKey((new CmsUUID()).toString());
result.setMode(alias.getMode());
result.setChanged(false);
return result;
}
/**
* Creates a navigation level type info.<p>
*
* @return the navigation level type info bean
*
* @throws CmsException if reading the sub level redirect copy page fails
*/
private CmsNewResourceInfo createNavigationLevelTypeInfo() throws CmsException {
String name = CmsResourceTypeFolder.getStaticTypeName();
Locale locale = getWorkplaceLocale();
String subtitle = Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_NAVIGATION_LEVEL_SUBTITLE_0);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(subtitle)) {
subtitle = CmsWorkplaceMessages.getResourceTypeName(locale, name);
}
CmsNewResourceInfo result = new CmsNewResourceInfo(
CmsResourceTypeFolder.getStaticTypeId(),
name,
Messages.get().getBundle(getWorkplaceLocale()).key(Messages.GUI_NAVIGATION_LEVEL_TITLE_0),
subtitle,
getCmsObject().readResource(SUB_LEVEL_REDIRECT_COPY_PAGE).getStructureId(),
false,
subtitle);
result.setCreateParameter(CmsJspNavBuilder.NAVIGATION_LEVEL_FOLDER);
return result;
}
/**
* Creates new content elements if required by the model page.<p>
*
* @param cms the cms context
* @param page the page
* @param sitePath the resource site path
*
* @throws CmsException when unable to create the content elements
*/
private void createNewContainerElements(CmsObject cms, CmsXmlContainerPage page, String sitePath)
throws CmsException {
CmsADEConfigData configData = OpenCms.getADEManager().lookupConfiguration(cms, cms.addSiteRoot(sitePath));
Locale contentLocale = page.getLocales().get(0);
CmsObject cloneCms = OpenCms.initCmsObject(cms);
cloneCms.getRequestContext().setLocale(contentLocale);
CmsContainerPageBean pageBean = page.getContainerPage(cms);
boolean needsChanges = false;
List<CmsContainerBean> updatedContainers = new ArrayList<CmsContainerBean>();
for (CmsContainerBean container : pageBean.getContainers().values()) {
List<CmsContainerElementBean> updatedElements = new ArrayList<CmsContainerElementBean>();
for (CmsContainerElementBean element : container.getElements()) {
if (element.isCreateNew() && !element.isGroupContainer(cms) && !element.isInheritedContainer(cms)) {
needsChanges = true;
String typeName = OpenCms.getResourceManager().getResourceType(element.getResource()).getTypeName();
CmsResourceTypeConfig typeConfig = configData.getResourceType(typeName);
if (typeConfig == null) {
throw new IllegalArgumentException("Can not copy template model element '"
+ element.getResource().getRootPath()
+ "' because the resource type '"
+ typeName
+ "' is not available in this sitemap.");
}
CmsResource newResource = typeConfig.createNewElement(cloneCms, element.getResource());
CmsContainerElementBean newBean = new CmsContainerElementBean(
newResource.getStructureId(),
element.getFormatterId(),
element.getIndividualSettings(),
false);
updatedElements.add(newBean);
} else {
updatedElements.add(element);
}
}
CmsContainerBean updatedContainer = new CmsContainerBean(
container.getName(),
container.getType(),
container.getParentInstanceId(),
container.getMaxElements(),
updatedElements);
updatedContainers.add(updatedContainer);
}
if (needsChanges) {
CmsContainerPageBean updatedPage = new CmsContainerPageBean(updatedContainers);
page.writeContainerPage(cms, updatedPage);
}
}
/**
* Creates a new page in navigation.<p>
*
* @param entryPoint the site-map entry-point
* @param change the new change
*
* @return the updated entry
*
* @throws CmsException if something goes wrong
*/
private CmsClientSitemapEntry createNewEntry(String entryPoint, CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsClientSitemapEntry newEntry = null;
if (change.getParentId() != null) {
CmsResource parentFolder = cms.readResource(change.getParentId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
String entryPath = "";
CmsResource entryFolder = null;
CmsResource newRes = null;
byte[] content = null;
List<CmsProperty> properties = Collections.emptyList();
CmsResource copyPage = null;
if (change.getNewCopyResourceId() != null) {
copyPage = cms.readResource(change.getNewCopyResourceId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
content = cms.readFile(copyPage).getContents();
properties = cms.readPropertyObjects(copyPage, false);
}
List<CmsProperty> filteredProperties = new ArrayList<CmsProperty>();
for (CmsProperty property : properties) {
if (!property.getName().equals(CmsPropertyDefinition.PROPERTY_DESCRIPTION)) {
filteredProperties.add(property);
}
}
properties = filteredProperties;
if (isRedirectType(change.getNewResourceTypeId())) {
entryPath = CmsStringUtil.joinPaths(cms.getSitePath(parentFolder), change.getName());
newRes = cms.createResource(
entryPath,
change.getNewResourceTypeId(),
null,
Collections.singletonList(new CmsProperty(
CmsPropertyDefinition.PROPERTY_TITLE,
change.getName(),
null)));
cms.writePropertyObjects(newRes, generateInheritProperties(change, newRes));
applyNavigationChanges(change, newRes);
} else {
String entryFolderPath = CmsStringUtil.joinPaths(cms.getSitePath(parentFolder), change.getName() + "/");
boolean idWasNull = change.getEntryId() == null;
// we don't really need to create a folder object here anymore.
if (idWasNull) {
// need this for calculateNavPosition, even though the id will get overwritten
change.setEntryId(new CmsUUID());
}
boolean isFunctionDetail = false;
boolean isNavigationLevel = false;
if (change.getCreateParameter() != null) {
if (CmsUUID.isValidUUID(change.getCreateParameter())) {
isFunctionDetail = true;
} else if (CmsJspNavBuilder.NAVIGATION_LEVEL_FOLDER.equals(change.getCreateParameter())) {
isNavigationLevel = true;
}
}
String folderType = CmsResourceTypeFolder.getStaticTypeName();
String createSitemapFolderType = change.getCreateSitemapFolderType();
if (createSitemapFolderType != null) {
folderType = createSitemapFolderType;
}
int folderTypeId = OpenCms.getResourceManager().getResourceType(folderType).getTypeId();
entryFolder = new CmsResource(
change.getEntryId(),
new CmsUUID(),
entryFolderPath,
folderTypeId,
true,
0,
cms.getRequestContext().getCurrentProject().getUuid(),
CmsResource.STATE_NEW,
System.currentTimeMillis(),
cms.getRequestContext().getCurrentUser().getId(),
System.currentTimeMillis(),
cms.getRequestContext().getCurrentUser().getId(),
CmsResource.DATE_RELEASED_DEFAULT,
CmsResource.DATE_EXPIRED_DEFAULT,
1,
0,
System.currentTimeMillis(),
0);
List<CmsProperty> folderProperties = generateInheritProperties(change, entryFolder);
if (isNavigationLevel) {
folderProperties.add(new CmsProperty(
CmsPropertyDefinition.PROPERTY_DEFAULT_FILE,
CmsJspNavBuilder.NAVIGATION_LEVEL_FOLDER,
null));
}
entryFolder = cms.createResource(entryFolderPath, folderTypeId, null, folderProperties);
if (createSitemapFolderType != null) {
createSitemapContentFolder(cms, entryFolder);
}
if (idWasNull) {
change.setEntryId(entryFolder.getStructureId());
}
applyNavigationChanges(change, entryFolder);
entryPath = CmsStringUtil.joinPaths(entryFolderPath, "index.html");
boolean isContainerPage = change.getNewResourceTypeId() == CmsResourceTypeXmlContainerPage.getContainerPageTypeIdSafely();
if (isContainerPage && (copyPage != null)) {
// do *NOT* get this from the cache, because we perform some destructive operation on the XML content
CmsXmlContainerPage page = CmsXmlContainerPageFactory.unmarshal(
cms,
cms.readFile(copyPage),
true,
true);
ensureSingleLocale(page, entryFolder);
if (isFunctionDetail) {
String functionDetailContainer = getFunctionDetailContainerName(parentFolder);
CmsUUID functionStructureId = new CmsUUID(change.getCreateParameter());
CmsResource functionFormatter = cms.readResource(
CmsXmlDynamicFunctionHandler.FORMATTER_PATH,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
addFunctionDetailElement(
cms,
page,
functionDetailContainer,
functionStructureId,
functionFormatter.getStructureId());
}
createNewContainerElements(cms, page, entryPath);
content = page.marshal();
}
newRes = cms.createResource(
entryPath,
copyPage != null ? copyPage.getTypeId() : change.getNewResourceTypeId(),
content,
properties);
cms.writePropertyObjects(newRes, generateOwnProperties(change));
}
if (entryFolder != null) {
tryUnlock(entryFolder);
String sitePath = cms.getSitePath(entryFolder);
newEntry = toClientEntry(
getNavBuilder().getNavigationForResource(sitePath, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED),
false);
newEntry.setSubEntries(getChildren(sitePath, 1, null), null);
newEntry.setChildrenLoadedInitially(true);
}
if (newRes != null) {
tryUnlock(newRes);
}
if (newEntry == null) {
newEntry = toClientEntry(
getNavBuilder().getNavigationForResource(
cms.getSitePath(newRes),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED),
false);
}
// mark position as not set
newEntry.setPosition(-1);
newEntry.setNew(true);
change.getClipBoardData().getModifications().remove(null);
change.getClipBoardData().getModifications().put(newEntry.getId(), newEntry);
}
return newEntry;
}
/**
* Creates a new resource info to a given model page resource.<p>
*
* @param cms the current CMS context
* @param modelResource the model page resource
* @param locale the locale used for retrieving descriptions/titles
*
* @return the new resource info
*
* @throws CmsException if something goes wrong
*/
private CmsNewResourceInfo createNewResourceInfo(CmsObject cms, CmsResource modelResource, Locale locale)
throws CmsException {
// if model page got overwritten by another resource, reread from site path
if (!cms.existsResource(modelResource.getStructureId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
modelResource = cms.readResource(cms.getSitePath(modelResource), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
}
int typeId = modelResource.getTypeId();
String name = OpenCms.getResourceManager().getResourceType(typeId).getTypeName();
String title = cms.readPropertyObject(modelResource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
String description = cms.readPropertyObject(modelResource, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
try {
CmsGallerySearchResult result = CmsGallerySearch.searchById(cms, modelResource.getStructureId(), locale);
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(result.getTitle())) {
title = result.getTitle();
}
if (!CmsStringUtil.isEmptyOrWhitespaceOnly(result.getDescription())) {
description = result.getDescription();
}
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
boolean editable = false;
try {
CmsResource freshModelResource = cms.readResource(
modelResource.getStructureId(),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
editable = cms.hasPermissions(
freshModelResource,
CmsPermissionSet.ACCESS_WRITE,
false,
CmsResourceFilter.DEFAULT);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
CmsNewResourceInfo info = new CmsNewResourceInfo(
typeId,
name,
title,
description,
modelResource.getStructureId(),
editable,
description);
Float navpos = null;
try {
CmsProperty navposProp = cms.readPropertyObject(modelResource, CmsPropertyDefinition.PROPERTY_NAVPOS, true);
String navposStr = navposProp.getValue();
if (navposStr != null) {
try {
navpos = Float.valueOf(navposStr);
} catch (NumberFormatException e) {
// noop
}
}
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
info.setNavPos(navpos);
info.setDate(CmsDateUtil.getDate(
new Date(modelResource.getDateLastModified()),
DateFormat.LONG,
getWorkplaceLocale()));
info.setVfsPath(modelResource.getRootPath());
return info;
}
/**
* Creates a resource type info bean for a given resource type.<p>
*
* @param resType the resource type
* @param copyResource the structure id of the copy resource
*
* @return the resource type info bean
*/
private CmsNewResourceInfo createResourceTypeInfo(I_CmsResourceType resType, CmsResource copyResource) {
String name = resType.getTypeName();
Locale locale = getWorkplaceLocale();
String subtitle = CmsWorkplaceMessages.getResourceTypeDescription(locale, name);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(subtitle)) {
subtitle = CmsWorkplaceMessages.getResourceTypeName(locale, name);
}
if (copyResource != null) {
return new CmsNewResourceInfo(
copyResource.getTypeId(),
name,
CmsWorkplaceMessages.getResourceTypeName(locale, name),
CmsWorkplaceMessages.getResourceTypeDescription(locale, name),
copyResource.getStructureId(),
false,
subtitle);
} else {
return new CmsNewResourceInfo(resType.getTypeId(), name, CmsWorkplaceMessages.getResourceTypeName(
locale,
name), CmsWorkplaceMessages.getResourceTypeDescription(locale, name), null, false, subtitle);
}
}
/**
* Helper method for creating the .content folder of a sub-sitemap.<p>
*
* @param cms the current CMS context
* @param subSitemapFolder the sub-sitemap folder in which the .content folder should be created
*
* @throws CmsException if something goes wrong
*/
private void createSitemapContentFolder(CmsObject cms, CmsResource subSitemapFolder) throws CmsException {
String sitePath = cms.getSitePath(subSitemapFolder);
String folderName = CmsStringUtil.joinPaths(sitePath, CmsADEManager.CONTENT_FOLDER_NAME + "/");
String sitemapConfigName = CmsStringUtil.joinPaths(folderName, CmsADEManager.CONFIG_FILE_NAME);
if (!cms.existsResource(folderName)) {
cms.createResource(
folderName,
OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_FOLDER_TYPE).getTypeId());
}
I_CmsResourceType configType = OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_TYPE);
if (cms.existsResource(sitemapConfigName)) {
CmsResource configFile = cms.readResource(sitemapConfigName);
if (configFile.getTypeId() != configType.getTypeId()) {
throw new CmsException(Messages.get().container(
Messages.ERR_CREATING_SUB_SITEMAP_WRONG_CONFIG_FILE_TYPE_2,
sitemapConfigName,
CmsADEManager.CONFIG_TYPE));
}
} else {
cms.createResource(
sitemapConfigName,
OpenCms.getResourceManager().getResourceType(CmsADEManager.CONFIG_TYPE).getTypeId());
}
}
/**
* Deletes a resource according to the change data.<p>
*
* @param change the change data
*
* @return CmsClientSitemapEntry always null
*
*
* @throws CmsException if something goes wrong
*/
private CmsClientSitemapEntry delete(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource resource = cms.readResource(change.getEntryId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(resource);
cms.deleteResource(cms.getSitePath(resource), CmsResource.DELETE_PRESERVE_SIBLINGS);
tryUnlock(resource);
return null;
}
/**
* Generates a client side lock info object representing the current lock state of the given resource.<p>
*
* @param resource the resource
*
* @return the client lock
*
* @throws CmsException if something goes wrong
*/
private CmsClientLock generateClientLock(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
CmsLock lock = cms.getLock(resource);
CmsClientLock clientLock = new CmsClientLock();
clientLock.setLockType(CmsClientLock.LockType.valueOf(lock.getType().getMode()));
CmsUUID ownerId = lock.getUserId();
if (!lock.isUnlocked() && (ownerId != null)) {
clientLock.setLockOwner(cms.readUser(ownerId).getDisplayName(cms, cms.getRequestContext().getLocale()));
clientLock.setOwnedByUser(cms.getRequestContext().getCurrentUser().getId().equals(ownerId));
}
return clientLock;
}
/**
* Generates a list of property object to save to the sitemap entry folder to apply the given change.<p>
*
* @param change the change
* @param entryFolder the entry folder
*
* @return the property objects
*/
private List<CmsProperty> generateInheritProperties(CmsSitemapChange change, CmsResource entryFolder) {
List<CmsProperty> result = new ArrayList<CmsProperty>();
Map<String, CmsClientProperty> clientProps = change.getOwnInternalProperties();
if (clientProps != null) {
for (CmsClientProperty clientProp : clientProps.values()) {
CmsProperty prop = new CmsProperty(
clientProp.getName(),
clientProp.getStructureValue(),
clientProp.getResourceValue());
result.add(prop);
}
}
result.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, change.getName(), null));
return result;
}
/**
* Generates a list of property object to save to the sitemap entry resource to apply the given change.<p>
*
* @param change the change
*
* @return the property objects
*/
private List<CmsProperty> generateOwnProperties(CmsSitemapChange change) {
List<CmsProperty> result = new ArrayList<CmsProperty>();
Map<String, CmsClientProperty> clientProps = change.getDefaultFileProperties();
if (clientProps != null) {
for (CmsClientProperty clientProp : clientProps.values()) {
CmsProperty prop = new CmsProperty(
clientProp.getName(),
clientProp.getStructureValue(),
clientProp.getResourceValue());
result.add(prop);
}
}
result.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, change.getName(), null));
return result;
}
/**
* Generates a list of property values inherited to the site-map root entry.<p>
*
* @param rootPath the root entry name
*
* @return the list of property values inherited to the site-map root entry
*
* @throws CmsException if something goes wrong reading the properties
*/
private Map<String, CmsClientProperty> generateParentProperties(String rootPath) throws CmsException {
CmsObject cms = getCmsObject();
if (rootPath == null) {
rootPath = cms.getRequestContext().addSiteRoot("/");
}
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
String parentRootPath = CmsResource.getParentFolder(rootPath);
Map<String, CmsClientProperty> result = new HashMap<String, CmsClientProperty>();
if (parentRootPath != null) {
List<CmsProperty> props = rootCms.readPropertyObjects(parentRootPath, true);
for (CmsProperty prop : props) {
CmsClientProperty clientProp = createClientProperty(prop, true);
result.put(clientProp.getName(), clientProp);
}
}
return result;
}
/**
* Returns the sitemap children for the given path with all descendants up to the given level or to the given target path, ie.
* <dl><dt>levels=1 <dd>only children<dt>levels=2<dd>children and great children</dl>
* and so on.<p>
*
* @param root the site relative root
* @param levels the levels to recurse
* @param targetPath the target path
*
* @return the sitemap children
*
* @throws CmsException if something goes wrong
*/
private List<CmsClientSitemapEntry> getChildren(String root, int levels, String targetPath) throws CmsException {
List<CmsClientSitemapEntry> children = new ArrayList<CmsClientSitemapEntry>();
int i = 0;
for (CmsJspNavElement navElement : getNavBuilder().getNavigationForFolder(
root,
Visibility.all,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
CmsClientSitemapEntry child = toClientEntry(navElement, false);
if (child != null) {
child.setPosition(i);
children.add(child);
int nextLevels = levels;
if ((nextLevels == 2) && (targetPath != null) && targetPath.startsWith(child.getSitePath())) {
nextLevels = 3;
}
if (child.isFolderType() && ((nextLevels > 1) || (nextLevels == -1)) && !isSubSitemap(navElement)) {
child.setSubEntries(getChildren(child.getSitePath(), nextLevels - 1, targetPath), null);
child.setChildrenLoadedInitially(true);
}
i++;
}
}
return children;
}
/**
* Returns the clipboard data from the current user.<p>
*
* @return the clipboard data
*/
private CmsSitemapClipboardData getClipboardData() {
CmsSitemapClipboardData result = new CmsSitemapClipboardData();
result.setModifications(getModifiedList());
result.setDeletions(getDeletedList());
return result;
}
/**
* Returns the deleted list from the current user.<p>
*
* @return the deleted list
*/
private LinkedHashMap<CmsUUID, CmsClientSitemapEntry> getDeletedList() {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
Object obj = user.getAdditionalInfo(ADDINFO_ADE_DELETED_LIST);
LinkedHashMap<CmsUUID, CmsClientSitemapEntry> result = new LinkedHashMap<CmsUUID, CmsClientSitemapEntry>();
if (obj instanceof String) {
try {
JSONArray array = new JSONArray((String)obj);
for (int i = 0; i < array.length(); i++) {
try {
CmsUUID delId = new CmsUUID(array.getString(i));
CmsResource res = cms.readResource(delId, CmsResourceFilter.ALL);
if (res.getState().isDeleted()) {
// make sure resource is still deleted
CmsClientSitemapEntry delEntry = new CmsClientSitemapEntry();
delEntry.setSitePath(cms.getSitePath(res));
delEntry.setOwnProperties(getClientProperties(cms, res, false));
delEntry.setName(res.getName());
delEntry.setVfsPath(cms.getSitePath(res));
delEntry.setResourceTypeName(OpenCms.getResourceManager().getResourceType(res).getTypeName());
delEntry.setEntryType(res.isFolder() ? EntryType.folder : isRedirectType(res.getTypeId())
? EntryType.redirect
: EntryType.leaf);
delEntry.setId(delId);
result.put(delId, delEntry);
}
} catch (Throwable e) {
// should never happen, catches wrong or no longer existing values
LOG.warn(e.getLocalizedMessage());
}
}
} catch (Throwable e) {
// should never happen, catches json parsing
LOG.warn(e.getLocalizedMessage());
}
}
return result;
}
/**
* Gets the container name for function detail elements depending on the parent folder.<p>
*
* @param parent the parent folder
* @return the name of the function detail container
*/
private String getFunctionDetailContainerName(CmsResource parent) {
CmsObject cms = getCmsObject();
String notFound = null;
String containerInfo = OpenCms.getTemplateContextManager().readPropertyFromTemplate(
cms,
parent,
CmsPropertyDefinition.PROPERTY_CONTAINER_INFO,
notFound);
if (containerInfo == notFound) {
return null;
}
Map<String, String> attrs = CmsStringUtil.splitAsMap(containerInfo, "|", "="); //$NON-NLS-2$
String functionDetailContainerName = attrs.get(KEY_FUNCTION_DETAIL);
return functionDetailContainerName;
}
/**
* Returns the galleries of the given sub site for the requested gallery type.<p>
*
* @param entryPointUri the sub site entry point
* @param galleryType the gallery type
* @param subSitePaths the sub site paths
*
* @return the gallery folder entries
*
* @throws CmsException if reading the resources fails
*/
private List<CmsGalleryFolderEntry> getGalleriesForType(
String entryPointUri,
CmsGalleryType galleryType,
List<String> subSitePaths) throws CmsException {
List<CmsGalleryFolderEntry> galleries = new ArrayList<CmsGalleryFolderEntry>();
List<CmsResource> galleryFolders = getCmsObject().readResources(
entryPointUri,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireType(galleryType.getTypeId()));
for (CmsResource folder : galleryFolders) {
try {
if (!isInSubsite(subSitePaths, folder.getRootPath())) {
galleries.add(readGalleryFolderEntry(folder, galleryType.getTypeName()));
}
} catch (CmsException ex) {
log(ex.getLocalizedMessage(), ex);
}
}
// create a tree structure
Collections.sort(galleries, new Comparator<CmsGalleryFolderEntry>() {
public int compare(CmsGalleryFolderEntry o1, CmsGalleryFolderEntry o2) {
return o1.getSitePath().compareTo(o2.getSitePath());
}
});
List<CmsGalleryFolderEntry> galleryTree = new ArrayList<CmsGalleryFolderEntry>();
for (int i = 0; i < galleries.size(); i++) {
boolean isSubGallery = false;
if (i > 0) {
for (int j = i - 1; j >= 0; j
if (galleries.get(i).getSitePath().startsWith(galleries.get(j).getSitePath())) {
galleries.get(j).addSubGallery(galleries.get(i));
isSubGallery = true;
break;
}
}
}
if (!isSubGallery) {
galleryTree.add(galleries.get(i));
}
}
return galleryTree;
}
/**
* Gets the locale to use for creating the new resource info beans.<p>
*
* @param cms the CMS context
* @param configData the sitemap configuration
*
* @return the locale to use
*/
private Locale getLocaleForNewResourceInfos(CmsObject cms, CmsADEConfigData configData) {
Locale locale = CmsLocaleManager.getDefaultLocale();
try {
String basePath = configData.getBasePath();
CmsObject rootCms = OpenCms.initCmsObject(cms);
rootCms.getRequestContext().setSiteRoot("");
CmsResource baseDir = rootCms.readResource(basePath, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
locale = CmsLocaleManager.getMainLocale(cms, baseDir);
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
return locale;
}
/**
* Returns the modified list from the current user.<p>
*
* @return the modified list
*/
private LinkedHashMap<CmsUUID, CmsClientSitemapEntry> getModifiedList() {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
Object obj = user.getAdditionalInfo(ADDINFO_ADE_MODIFIED_LIST);
LinkedHashMap<CmsUUID, CmsClientSitemapEntry> result = new LinkedHashMap<CmsUUID, CmsClientSitemapEntry>();
if (obj instanceof String) {
try {
JSONArray array = new JSONArray((String)obj);
for (int i = 0; i < array.length(); i++) {
try {
CmsUUID modId = new CmsUUID(array.getString(i));
CmsResource res = cms.readResource(modId, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
String sitePath = cms.getSitePath(res);
CmsJspNavElement navEntry = getNavBuilder().getNavigationForResource(
sitePath,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
if (navEntry.isInNavigation()) {
CmsClientSitemapEntry modEntry = toClientEntry(navEntry, false);
result.put(modId, modEntry);
}
} catch (Throwable e) {
// should never happen, catches wrong or no longer existing values
LOG.warn(e.getLocalizedMessage());
}
}
} catch (Throwable e) {
// should never happen, catches json parsing
LOG.warn(e.getLocalizedMessage());
}
}
return result;
}
/**
* Returns a navigation builder reference.<p>
*
* @return the navigation builder
*/
private CmsJspNavBuilder getNavBuilder() {
if (m_navBuilder == null) {
m_navBuilder = new CmsJspNavBuilder(getCmsObject());
}
return m_navBuilder;
}
/**
* Returns the new resource infos.<p>
*
* @param cms the current CMS context
* @param configData the configuration data from which the new resource infos should be read
* @param locale locale used for retrieving descriptions/titles
*
* @return the new resource infos
*/
private List<CmsNewResourceInfo> getNewResourceInfos(CmsObject cms, CmsADEConfigData configData, Locale locale) {
List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>();
for (CmsModelPageConfig modelConfig : configData.getModelPages()) {
try {
result.add(createNewResourceInfo(cms, modelConfig.getResource(), locale));
} catch (CmsException e) {
LOG.debug(e.getLocalizedMessage(), e);
}
}
Collections.sort(result, new Comparator<CmsNewResourceInfo>() {
public int compare(CmsNewResourceInfo a, CmsNewResourceInfo b) {
return ComparisonChain.start().compare(a.getNavPos(), b.getNavPos(), Ordering.natural().nullsLast()).result();
}
});
return result;
}
/**
* Gets the names of all available properties.<p>
*
* @param cms the CMS context
*
* @return the list of all property names
*
* @throws CmsException if something goes wrong
*/
private List<String> getPropertyNames(CmsObject cms) throws CmsException {
List<CmsPropertyDefinition> propDefs = cms.readAllPropertyDefinitions();
List<String> result = new ArrayList<String>();
for (CmsPropertyDefinition propDef : propDefs) {
result.add(propDef.getName());
}
return result;
}
/**
* Gets the resource type info beans for types for which new detail pages can be created.<p>
*
* @param cms the current CMS context
* @param resourceTypeConfigs the resource type configurations
* @param functionReferences the function references
* @param modelResource the model resource
* @param locale the locale used for retrieving descriptions/titles
*
* @return the resource type info beans for types for which new detail pages can be created
*/
private List<CmsNewResourceInfo> getResourceTypeInfos(
CmsObject cms,
List<CmsResourceTypeConfig> resourceTypeConfigs,
List<CmsFunctionReference> functionReferences,
CmsResource modelResource,
Locale locale) {
List<CmsNewResourceInfo> result = new ArrayList<CmsNewResourceInfo>();
for (CmsResourceTypeConfig typeConfig : resourceTypeConfigs) {
if (typeConfig.isDetailPagesDisabled()) {
continue;
}
String typeName = typeConfig.getTypeName();
try {
I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(typeName);
result.add(createResourceTypeInfo(resourceType, modelResource));
} catch (CmsLoaderException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
for (CmsFunctionReference functionRef : functionReferences) {
try {
CmsResource functionRes = cms.readResource(functionRef.getStructureId());
String description = cms.readPropertyObject(
functionRes,
CmsPropertyDefinition.PROPERTY_DESCRIPTION,
false).getValue();
String subtitle = description;
try {
CmsGallerySearchResult searchResult = CmsGallerySearch.searchById(
cms,
functionRef.getStructureId(),
getWorkplaceLocale());
subtitle = searchResult.getDescription();
} catch (CmsException e) {
LOG.warn(e.getLocalizedMessage(), e);
}
CmsNewResourceInfo info = new CmsNewResourceInfo(
modelResource.getTypeId(),
CmsDetailPageInfo.FUNCTION_PREFIX + functionRef.getName(),
functionRef.getName(),
description,
modelResource.getStructureId(),
false,
subtitle);
info.setCreateParameter(functionRef.getStructureId().toString());
info.setIsFunction(true);
result.add(info);
} catch (CmsVfsResourceNotFoundException e) {
LOG.warn(e.getLocalizedMessage(), e);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
return result;
}
private CmsClientSitemapEntry getRootEntry(String rootPath, String targetPath)
throws CmsSecurityException, CmsException {
String sitePath = "/";
if (rootPath != null) {
sitePath = getCmsObject().getRequestContext().removeSiteRoot(rootPath);
}
CmsJspNavElement navElement = getNavBuilder().getNavigationForResource(
sitePath,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
CmsClientSitemapEntry result = toClientEntry(navElement, true);
if (result != null) {
result.setPosition(0);
result.setChildrenLoadedInitially(true);
result.setSubEntries(getChildren(sitePath, 2, targetPath), null);
}
return result;
}
/**
* Returns the sitemap info for the given base path.<p>
*
* @param basePath the base path
*
* @return the sitemap info
*
* @throws CmsException if something goes wrong reading the resources
*/
private CmsSitemapInfo getSitemapInfo(String basePath) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource baseFolder = null;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(basePath)) {
baseFolder = cms.readResource(
cms.getRequestContext().removeSiteRoot(basePath),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
} else {
// in case of an empty base path, use base folder of the current site
basePath = "/";
baseFolder = cms.readResource("/");
}
CmsResource defaultFile = cms.readDefaultFile(baseFolder, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
String title = cms.readPropertyObject(baseFolder, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(title) && (defaultFile != null)) {
title = cms.readPropertyObject(defaultFile, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();
}
String description = cms.readPropertyObject(baseFolder, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
if (CmsStringUtil.isEmptyOrWhitespaceOnly(description) && (defaultFile != null)) {
description = cms.readPropertyObject(defaultFile, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
}
return new CmsSitemapInfo(
cms.getRequestContext().getCurrentProject().getName(),
description,
OpenCms.getLocaleManager().getDefaultLocale(cms, baseFolder).toString(),
OpenCms.getSiteManager().getCurrentSite(cms).getUrl()
+ OpenCms.getLinkManager().substituteLinkForUnknownTarget(cms, basePath),
title);
}
/**
* Gets the default type id for subsitemap folders.<p>
*
* @return the default type id for subsitemap folders
*
* @throws CmsRpcException in case of an error
*/
private int getSubsitemapType() throws CmsRpcException {
try {
return OpenCms.getResourceManager().getResourceType(CmsResourceTypeFolderSubSitemap.TYPE_SUBSITEMAP).getTypeId();
} catch (CmsLoaderException e) {
error(e);
}
return CmsResourceTypeUnknownFolder.getStaticTypeId();
}
/**
* Returns the workplace locale for the current user.<p>
*
* @return the workplace locale
*/
private Locale getWorkplaceLocale() {
Locale result = OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject());
if (result == null) {
result = CmsLocaleManager.getDefaultLocale();
}
if (result == null) {
result = Locale.getDefault();
}
return result;
}
/**
* Checks whether the sitemap change has default file changes.<p>
*
* @param change a sitemap change
* @return true if the change would change the default file
*/
private boolean hasDefaultFileChanges(CmsSitemapChange change) {
return (change.getDefaultFileId() != null) && !change.isNew();
}
/**
* Checks whether the sitemap change has changes for the sitemap entry resource.<p>
*
* @param change the sitemap change
* @return true if the change would change the original sitemap entry resource
*/
private boolean hasOwnChanges(CmsSitemapChange change) {
return !change.isNew();
}
/**
* Checks whether a resource is a default file of a folder.<p>
*
* @param resource the resource to check
*
* @return true if the resource is the default file of a folder
*
* @throws CmsException if something goes wrong
*/
private boolean isDefaultFile(CmsResource resource) throws CmsException {
CmsObject cms = getCmsObject();
if (resource.isFolder()) {
return false;
}
CmsResource parent = cms.readResource(
CmsResource.getParentFolder(cms.getSitePath(resource)),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
CmsResource defaultFile = cms.readDefaultFile(parent, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
return resource.equals(defaultFile);
}
/**
* Checks if the toolbar should be displayed.<p>
*
* @param request the current request to get the default locale from
*
* @return <code>true</code> if the toolbar should be displayed
*/
private boolean isDisplayToolbar(HttpServletRequest request) {
// display the toolbar by default
boolean displayToolbar = true;
if (CmsHistoryResourceHandler.isHistoryRequest(request)) {
// we do not want to display the toolbar in case of an historical request
displayToolbar = false;
}
return displayToolbar;
}
/**
* Returns if the given path is located below one of the given sub site paths.<p>
*
* @param subSitePaths the sub site root paths
* @param path the root path to check
*
* @return <code>true</code> if the given path is located below one of the given sub site paths
*/
private boolean isInSubsite(List<String> subSitePaths, String path) {
boolean result = false;
for (String subSite : subSitePaths) {
if (path.startsWith(subSite)) {
result = true;
break;
}
}
return result;
}
/**
* Returns if the given type id matches the xml-redirect resource type.<p>
*
* @param typeId the resource type id
*
* @return <code>true</code> if the given type id matches the xml-redirect resource type
*/
private boolean isRedirectType(int typeId) {
try {
return typeId == OpenCms.getResourceManager().getResourceType(RECOURCE_TYPE_NAME_REDIRECT).getTypeId();
} catch (Exception e) {
return false;
}
}
/**
* Returns if the given nav-element resembles a sub-sitemap entry-point.<p>
*
* @param navElement the nav-element
*
* @return <code>true</code> if the given nav-element resembles a sub-sitemap entry-point.<p>
*/
private boolean isSubSitemap(CmsJspNavElement navElement) {
return CmsResourceTypeFolderSubSitemap.isSubSitemap(navElement.getResource());
}
/**
* Checks if the given open path is valid.<p>
*
* @param cms the cms context
* @param openPath the open path
*
* @return <code>true</code> if the given open path is valid
*/
private boolean isValidOpenPath(CmsObject cms, String openPath) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(openPath)) {
return false;
}
if (!cms.existsResource(openPath)) {
// in case of a detail-page check the parent folder
String parent = CmsResource.getParentFolder(openPath);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(parent) || !cms.existsResource(parent)) {
return false;
}
}
return true;
}
/**
* Returns if the given return code is valid.<p>
*
* @param returnCode the return code to check
*
* @return <code>true</code> if the return code is valid
*/
private boolean isValidReturnCode(String returnCode) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(returnCode)) {
return false;
}
int pos = returnCode.indexOf(":");
if (pos > 0) {
return CmsUUID.isValidUUID(returnCode.substring(0, pos))
&& CmsUUID.isValidUUID(returnCode.substring(pos + 1));
} else {
return CmsUUID.isValidUUID(returnCode);
}
}
/**
* Applys the given changes to the entry.<p>
*
* @param change the change to apply
*
* @throws CmsException if something goes wrong
*/
private void modifyEntry(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource entryPage = null;
CmsResource entryFolder = null;
CmsResource ownRes = null;
CmsResource defaultFileRes = null;
try {
// lock all resources necessary first to avoid doing changes only half way through
if (hasOwnChanges(change)) {
ownRes = cms.readResource(change.getEntryId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(ownRes);
}
if (hasDefaultFileChanges(change)) {
defaultFileRes = cms.readResource(change.getDefaultFileId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(defaultFileRes);
}
if ((ownRes != null) && ownRes.isFolder()) {
entryFolder = ownRes;
}
if ((ownRes != null) && ownRes.isFile()) {
entryPage = ownRes;
}
if (defaultFileRes != null) {
entryPage = defaultFileRes;
}
if (change.isLeafType()) {
entryFolder = entryPage;
}
updateProperties(cms, ownRes, defaultFileRes, change.getPropertyChanges());
if (change.hasChangedPosition()) {
updateNavPos(ownRes, change);
}
if (entryFolder != null) {
if (change.hasNewParent() || change.hasChangedName()) {
String destinationPath;
if (change.hasNewParent()) {
CmsResource futureParent = cms.readResource(
change.getParentId(),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
destinationPath = CmsStringUtil.joinPaths(cms.getSitePath(futureParent), change.getName());
} else {
destinationPath = CmsStringUtil.joinPaths(
CmsResource.getParentFolder(cms.getSitePath(entryFolder)),
change.getName());
}
if (change.isLeafType() && destinationPath.endsWith("/")) {
destinationPath = destinationPath.substring(0, destinationPath.length() - 1);
}
// only if the site-path has really changed
if (!cms.getSitePath(entryFolder).equals(destinationPath)) {
cms.moveResource(cms.getSitePath(entryFolder), destinationPath);
}
entryFolder = cms.readResource(
entryFolder.getStructureId(),
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
}
}
} finally {
if (entryPage != null) {
tryUnlock(entryPage);
}
if (entryFolder != null) {
tryUnlock(entryFolder);
}
}
}
/**
* Reads the gallery folder properties.<p>
*
* @param folder the folder resource
* @param typeName the resource type name
*
* @return the folder entry data
*
* @throws CmsException if the folder properties can not be read
*/
private CmsGalleryFolderEntry readGalleryFolderEntry(CmsResource folder, String typeName) throws CmsException {
CmsObject cms = getCmsObject();
CmsGalleryFolderEntry folderEntry = new CmsGalleryFolderEntry();
folderEntry.setResourceType(typeName);
folderEntry.setSitePath(cms.getSitePath(folder));
folderEntry.setStructureId(folder.getStructureId());
folderEntry.setOwnProperties(getClientProperties(cms, folder, false));
return folderEntry;
}
/**
* Helper method for removing all locales except one from a container page.<p>
*
* @param page the container page to proces
* @param localeToKeep the locale which should be kept
*
* @throws CmsXmlException if something goes wrong
*/
private void removeAllLocalesExcept(CmsXmlContainerPage page, Locale localeToKeep) throws CmsXmlException {
List<Locale> locales = page.getLocales();
for (Locale locale : locales) {
if (!locale.equals(localeToKeep)) {
page.removeLocale(locale);
}
}
}
/**
* Applys the given remove change.<p>
*
* @param change the change to apply
*
* @return the changed client sitemap entry or <code>null</code>
*
* @throws CmsException if something goes wrong
*/
private CmsSitemapChange removeEntryFromNavigation(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource entryFolder = cms.readResource(change.getEntryId(), CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
ensureLock(entryFolder);
List<CmsProperty> properties = new ArrayList<CmsProperty>();
properties.add(new CmsProperty(
CmsPropertyDefinition.PROPERTY_NAVTEXT,
CmsProperty.DELETE_VALUE,
CmsProperty.DELETE_VALUE));
properties.add(new CmsProperty(
CmsPropertyDefinition.PROPERTY_NAVPOS,
CmsProperty.DELETE_VALUE,
CmsProperty.DELETE_VALUE));
cms.writePropertyObjects(cms.getSitePath(entryFolder), properties);
tryUnlock(entryFolder);
return change;
}
/**
* Saves the detail page information of a sitemap to the sitemap's configuration file.<p>
*
* @param detailPages saves the detailpage configuration
* @param resource the configuration file resource
* @param newId the structure id to use for new detail page entries
* @param updateEntry the new detail page entry
*
* @throws CmsException if something goes wrong
*/
private void saveDetailPages(
List<CmsDetailPageInfo> detailPages,
CmsResource resource,
CmsUUID newId,
CmsClientSitemapEntry updateEntry) throws CmsException {
CmsObject cms = getCmsObject();
if (updateEntry != null) {
for (CmsDetailPageInfo info : detailPages) {
if (info.getId() == null) {
updateEntry.setDetailpageTypeName(info.getType());
break;
}
}
}
CmsDetailPageConfigurationWriter writer = new CmsDetailPageConfigurationWriter(cms, resource);
writer.updateAndSave(detailPages, newId);
}
/**
* Saves the given clipboard data to the session.<p>
*
* @param clipboardData the clipboard data to save
*
* @throws CmsException if something goes wrong writing the user
*/
private void setClipboardData(CmsSitemapClipboardData clipboardData) throws CmsException {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
if (clipboardData != null) {
JSONArray modified = new JSONArray();
if (clipboardData.getModifications() != null) {
for (CmsUUID id : clipboardData.getModifications().keySet()) {
if (id != null) {
modified.put(id.toString());
}
}
}
user.setAdditionalInfo(ADDINFO_ADE_MODIFIED_LIST, modified.toString());
JSONArray deleted = new JSONArray();
if (clipboardData.getDeletions() != null) {
for (CmsUUID id : clipboardData.getDeletions().keySet()) {
if (id != null) {
deleted.put(id.toString());
}
}
}
user.setAdditionalInfo(ADDINFO_ADE_DELETED_LIST, deleted.toString());
cms.writeUser(user);
}
}
/**
* Determines if the title property of the default file should be changed.<p>
*
* @param properties the current default file properties
* @param folderNavtext the 'NavText' property of the folder
*
* @return <code>true</code> if the title property should be changed
*/
private boolean shouldChangeDefaultFileTitle(Map<String, CmsProperty> properties, CmsProperty folderNavtext) {
return (properties == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE) == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue() == null)
|| ((folderNavtext != null) && properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue().equals(
folderNavtext.getValue()));
}
/**
* Determines if the title property should be changed in case of a 'NavText' change.<p>
*
* @param properties the current resource properties
*
* @return <code>true</code> if the title property should be changed in case of a 'NavText' change
*/
private boolean shouldChangeTitle(Map<String, CmsProperty> properties) {
return (properties == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE) == null)
|| (properties.get(CmsPropertyDefinition.PROPERTY_TITLE).getValue() == null)
|| ((properties.get(CmsPropertyDefinition.PROPERTY_NAVTEXT) != null) && properties.get(
CmsPropertyDefinition.PROPERTY_TITLE).getValue().equals(
properties.get(CmsPropertyDefinition.PROPERTY_NAVTEXT).getValue()));
}
/**
* Converts a jsp navigation element into a client sitemap entry.<p>
*
* @param navElement the jsp navigation element
* @param isRoot true if the entry is a root entry
*
* @return the client sitemap entry
*
* @throws CmsException if something goes wrong
*/
private CmsClientSitemapEntry toClientEntry(CmsJspNavElement navElement, boolean isRoot) throws CmsException {
CmsResource entryPage = null;
CmsObject cms = getCmsObject();
CmsClientSitemapEntry clientEntry = new CmsClientSitemapEntry();
CmsResource entryFolder = null;
CmsResource ownResource = navElement.getResource();
clientEntry.setResourceState(ownResource.getState());
CmsResource defaultFileResource = null;
if (ownResource.isFolder() && !navElement.isNavigationLevel()) {
defaultFileResource = cms.readDefaultFile(ownResource, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
}
Map<String, CmsClientProperty> ownProps = getClientProperties(cms, ownResource, false);
Map<String, CmsClientProperty> defaultFileProps = null;
if (defaultFileResource != null) {
defaultFileProps = getClientProperties(cms, defaultFileResource, false);
clientEntry.setDefaultFileId(defaultFileResource.getStructureId());
clientEntry.setDefaultFileType(OpenCms.getResourceManager().getResourceType(defaultFileResource.getTypeId()).getTypeName());
} else {
defaultFileProps = new HashMap<String, CmsClientProperty>();
}
boolean isDefault = isDefaultFile(ownResource);
clientEntry.setId(ownResource.getStructureId());
clientEntry.setResourceTypeId(ownResource.getTypeId());
clientEntry.setFolderDefaultPage(isDefault);
if (navElement.getResource().isFolder()) {
entryFolder = navElement.getResource();
entryPage = defaultFileResource;
clientEntry.setName(entryFolder.getName());
if (entryPage == null) {
entryPage = entryFolder;
}
if (!isRoot && isSubSitemap(navElement)) {
clientEntry.setEntryType(EntryType.subSitemap);
clientEntry.setDefaultFileType(null);
} else if (navElement.isNavigationLevel()) {
clientEntry.setEntryType(EntryType.navigationLevel);
}
CmsLock folderLock = cms.getLock(entryFolder);
clientEntry.setHasForeignFolderLock(!folderLock.isUnlocked()
&& !folderLock.isOwnedBy(cms.getRequestContext().getCurrentUser()));
if (!cms.getRequestContext().getCurrentProject().isOnlineProject()) {
List<CmsResource> blockingChildren = cms.getBlockingLockedResources(entryFolder);
clientEntry.setBlockingLockedChildren((blockingChildren != null) && !blockingChildren.isEmpty());
}
} else {
entryPage = navElement.getResource();
clientEntry.setName(entryPage.getName());
if (isRedirectType(entryPage.getTypeId())) {
clientEntry.setEntryType(EntryType.redirect);
CmsFile file = getCmsObject().readFile(entryPage);
I_CmsXmlDocument content = CmsXmlContentFactory.unmarshal(getCmsObject(), file);
I_CmsXmlContentValue linkValue = content.getValue(
REDIRECT_LINK_TARGET_XPATH,
getCmsObject().getRequestContext().getLocale());
String link = linkValue != null ? linkValue.getStringValue(getCmsObject()) : Messages.get().getBundle(
getWorkplaceLocale()).key(Messages.GUI_REDIRECT_SUB_LEVEL_0);
clientEntry.setRedirectTarget(link);
} else {
clientEntry.setEntryType(EntryType.leaf);
}
}
if (entryPage.isFile()) {
List<CmsAlias> aliases = OpenCms.getAliasManager().getAliasesForStructureId(
getCmsObject(),
entryPage.getStructureId());
if (!aliases.isEmpty()) {
List<String> aliasList = new ArrayList<String>();
for (CmsAlias alias : aliases) {
String aliasPath = alias.getAliasPath();
aliasList.add(aliasPath);
}
clientEntry.setAliases(aliasList);
}
}
long dateExpired = navElement.getResource().getDateExpired();
if (dateExpired != CmsResource.DATE_EXPIRED_DEFAULT) {
clientEntry.setDateExpired(CmsDateUtil.getDate(
new Date(dateExpired),
DateFormat.SHORT,
getWorkplaceLocale()));
}
long dateReleased = navElement.getResource().getDateReleased();
if (dateReleased != CmsResource.DATE_RELEASED_DEFAULT) {
clientEntry.setDateReleased(CmsDateUtil.getDate(
new Date(dateReleased),
DateFormat.SHORT,
getWorkplaceLocale()));
}
clientEntry.setResleasedAndNotExpired(navElement.getResource().isReleasedAndNotExpired(
System.currentTimeMillis()));
String path = cms.getSitePath(entryPage);
clientEntry.setVfsPath(path);
clientEntry.setOwnProperties(ownProps);
clientEntry.setDefaultFileProperties(defaultFileProps);
clientEntry.setSitePath(entryFolder != null ? cms.getSitePath(entryFolder) : path);
clientEntry.setLock(generateClientLock(entryPage));
clientEntry.setInNavigation(isRoot || navElement.isInNavigation());
String type = OpenCms.getResourceManager().getResourceType(ownResource).getTypeName();
clientEntry.setResourceTypeName(type);
clientEntry.setPermissionInfo(OpenCms.getADEManager().getPermissionInfo(cms, ownResource, null));
return clientEntry;
}
/**
* Un-deletes a resource according to the change data.<p>
*
* @param change the change data
*
* @return the changed entry or <code>null</code>
*
* @throws CmsException if something goes wrong
*/
private CmsSitemapChange undelete(CmsSitemapChange change) throws CmsException {
CmsObject cms = getCmsObject();
CmsResource deleted = cms.readResource(change.getEntryId(), CmsResourceFilter.ALL);
if (deleted.getState().isDeleted()) {
ensureLock(deleted);
cms.undeleteResource(getCmsObject().getSitePath(deleted), true);
tryUnlock(deleted);
}
String parentPath = CmsResource.getParentFolder(cms.getSitePath(deleted));
CmsJspNavElement navElement = getNavBuilder().getNavigationForResource(
parentPath,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
CmsClientSitemapEntry entry = toClientEntry(navElement, navElement.isInNavigation());
entry.setSubEntries(getChildren(parentPath, 2, null), null);
change.setUpdatedEntry(entry);
change.setParentId(cms.readParentFolder(deleted.getStructureId()).getStructureId());
return change;
}
/**
* Updates the navigation position for a resource.<p>
*
* @param res the resource for which to update the navigation position
* @param change the sitemap change
*
* @throws CmsException if something goes wrong
*/
private void updateNavPos(CmsResource res, CmsSitemapChange change) throws CmsException {
if (change.hasChangedPosition()) {
applyNavigationChanges(change, res);
}
}
/**
* Updates properties for a resource and possibly its detail page.<p>
*
* @param cms the CMS context
* @param ownRes the resource
* @param defaultFileRes the default file resource (possibly null)
* @param propertyModifications the property modifications
*
* @throws CmsException if something goes wrong
*/
private void updateProperties(
CmsObject cms,
CmsResource ownRes,
CmsResource defaultFileRes,
List<CmsPropertyModification> propertyModifications) throws CmsException {
Map<String, CmsProperty> ownProps = getPropertiesByName(cms.readPropertyObjects(ownRes, false));
// determine if the title property should be changed in case of a 'NavText' change
boolean changeOwnTitle = shouldChangeTitle(ownProps);
boolean changeDefaultFileTitle = false;
Map<String, CmsProperty> defaultFileProps = Collections.emptyMap();
if (defaultFileRes != null) {
defaultFileProps = getPropertiesByName(cms.readPropertyObjects(defaultFileRes, false));
// determine if the title property of the default file should be changed
changeDefaultFileTitle = shouldChangeDefaultFileTitle(
defaultFileProps,
ownProps.get(CmsPropertyDefinition.PROPERTY_NAVTEXT));
}
String hasNavTextChange = null;
List<CmsProperty> ownPropertyChanges = new ArrayList<CmsProperty>();
List<CmsProperty> defaultFilePropertyChanges = new ArrayList<CmsProperty>();
for (CmsPropertyModification propMod : propertyModifications) {
CmsProperty propToModify = null;
if (ownRes.getStructureId().equals(propMod.getId())) {
if (CmsPropertyDefinition.PROPERTY_NAVTEXT.equals(propMod.getName())) {
hasNavTextChange = propMod.getValue();
} else if (CmsPropertyDefinition.PROPERTY_TITLE.equals(propMod.getName())) {
changeOwnTitle = false;
}
propToModify = ownProps.get(propMod.getName());
if (propToModify == null) {
propToModify = new CmsProperty(propMod.getName(), null, null);
}
ownPropertyChanges.add(propToModify);
} else {
if (CmsPropertyDefinition.PROPERTY_TITLE.equals(propMod.getName())) {
changeDefaultFileTitle = false;
}
propToModify = defaultFileProps.get(propMod.getName());
if (propToModify == null) {
propToModify = new CmsProperty(propMod.getName(), null, null);
}
defaultFilePropertyChanges.add(propToModify);
}
String newValue = propMod.getValue();
if (newValue == null) {
newValue = "";
}
if (propMod.isStructureValue()) {
propToModify.setStructureValue(newValue);
} else {
propToModify.setResourceValue(newValue);
}
}
if (hasNavTextChange != null) {
if (changeOwnTitle) {
CmsProperty titleProp = ownProps.get(CmsPropertyDefinition.PROPERTY_TITLE);
if (titleProp == null) {
titleProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, null, null);
}
titleProp.setStructureValue(hasNavTextChange);
ownPropertyChanges.add(titleProp);
}
if (changeDefaultFileTitle) {
CmsProperty titleProp = defaultFileProps.get(CmsPropertyDefinition.PROPERTY_TITLE);
if (titleProp == null) {
titleProp = new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, null, null);
}
titleProp.setStructureValue(hasNavTextChange);
defaultFilePropertyChanges.add(titleProp);
}
}
if (!ownPropertyChanges.isEmpty()) {
cms.writePropertyObjects(ownRes, ownPropertyChanges);
}
if (!defaultFilePropertyChanges.isEmpty() && (defaultFileRes != null)) {
cms.writePropertyObjects(defaultFileRes, defaultFilePropertyChanges);
}
}
}
|
package com.highcharts.export.pool;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.log4j.Logger;
import com.highcharts.export.server.Server;
import com.highcharts.export.server.ServerState;
import com.highcharts.export.util.TempDir;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.TreeMap;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
public class ServerObjectFactory implements ObjectFactory<Server> {
public String exec;
public String script;
private String host;
private int basePort;
private int readTimeout;
private int poolSize;
private int connectTimeout;
private int maxTimeout;
private static TreeMap<Integer, PortStatus> portUsage = new TreeMap<>();
protected static Logger logger = Logger.getLogger("pool");
private enum PortStatus {
BUSY,
FREE;
}
@Override
public Server create() {
logger.debug("in makeObject, " + exec + ", " + script + ", " + host);
Integer port = this.getAvailablePort();
if (script.isEmpty()) {
// use the bundled highcharts-convert.js script
script = TempDir.getPhantomJsDir().toAbsolutePath().toString() + "/highcharts-convert.js";
}
Server server = new Server(exec, script, host, port, connectTimeout, readTimeout, maxTimeout);
portUsage.put(port, PortStatus.BUSY);
return server;
}
@Override
public boolean validate(Server server) {
boolean isValid = false;
try {
if(server.getState() != ServerState.IDLE) {
logger.debug("server didn\'t pass validation");
return false;
}
String result = server.request("{\"status\":\"isok\"}");
if(result.indexOf("OK") > -1) {
isValid = true;
logger.debug("server passed validation");
} else {
logger.debug("server didn\'t pass validation");
}
} catch (Exception e) {
logger.error("Error while validating object in Pool: " + e.getMessage());
}
return isValid;
}
@Override
public void destroy(Server server) {
ServerObjectFactory.releasePort(server.getPort());
server.cleanup();
}
@Override
public void activate(Server server) {
server.setState(ServerState.ACTIVE);
}
@Override
public void passivate(Server server) {
server.setState(ServerState.IDLE);
}
public static void releasePort(Integer port) {
logger.debug("Releasing port " + port);
portUsage.put(port, PortStatus.FREE);
}
public Integer getAvailablePort() {
/* first we check within the defined port range from baseport
* up to baseport + poolsize
*/
int port = basePort;
for (; port < basePort + poolSize; port++) {
if (portUsage.containsKey(port)) {
if (portUsage.get(port) == PortStatus.FREE) {
return port;
}
} else {
// doesn't exist any longer, but is within the valid port range
return port;
}
}
// at this point there is no free port, we have to look outside of the valid port range
logger.debug("Nothing free in Portusage " + portUsage.toString());
return portUsage.lastKey() + 1;
}
/*Getters and Setters*/
public String getExec() {
return exec;
}
public void setExec(String exec) {
this.exec = exec;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getBasePort() {
return basePort;
}
public void setBasePort(int basePort) {
this.basePort = basePort;
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getMaxTimeout() {
return maxTimeout;
}
public void setMaxTimeout(int maxTimeout) {
this.maxTimeout = maxTimeout;
}
public int getPoolSize() {
return poolSize;
}
public void setPoolSize(int poolSize) {
this.poolSize = poolSize;
}
@PostConstruct
public void afterBeanInit() {
URL u = getClass().getProtectionDomain().getCodeSource().getLocation();
URLClassLoader jarLoader = new URLClassLoader(new URL[]{u}, Thread.currentThread().getContextClassLoader());
String filenames[] = new String[] {"highcharts-convert.js","highcharts.js","highstock.js","jquery.1.9.1.min.js","map.js","highcharts-more.js", "data.js", "drilldown.js", "funnel.js", "heatmap.js", "highcharts-3d.js", "no-data-to-display.js", "solid-gauge.js", "broken-axis.js"};
for (String filename : filenames) {
ClassPathResource resource = new ClassPathResource("phantomjs/" + filename, jarLoader);
if (resource.exists()) {
Path path = Paths.get(TempDir.getPhantomJsDir().toString(), filename);
File file;
try {
file = Files.createFile(path).toFile();
file.deleteOnExit();
InputStream in = resource.getInputStream();
IOUtils.copy(in, new FileOutputStream(file));
} catch (IOException ioex) {
logger.error("Error while setting up phantomjs environment: " + ioex.getMessage());
}
} else {
logger.debug("Copy javascript file to temp folder, resource doesn't exist: " + filename);
}
}
}
}
|
package org.phenoscape.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import org.apache.log4j.Logger;
import org.obo.annotation.view.TermRenderer;
import org.obo.app.swing.BugWorkaroundTable;
import org.obo.app.swing.PlaceholderRenderer;
import org.obo.app.swing.SortDisabler;
import org.obo.app.util.EverythingEqualComparator;
import org.phenoscape.controller.PhenexController;
import org.phenoscape.model.Character;
import org.phenoscape.model.DataSet;
import org.phenoscape.model.MultipleState;
import org.phenoscape.model.MultipleState.MODE;
import org.phenoscape.model.State;
import org.phenoscape.model.Taxon;
import ca.odell.glazedlists.CollectionList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.SortedList;
import ca.odell.glazedlists.event.ListEvent;
import ca.odell.glazedlists.event.ListEventListener;
import ca.odell.glazedlists.gui.AdvancedTableFormat;
import ca.odell.glazedlists.gui.WritableTableFormat;
import ca.odell.glazedlists.swing.EventTableModel;
import ca.odell.glazedlists.swing.TableComparatorChooser;
import com.eekboom.utils.Strings;
public class CharacterMatrixComponent extends PhenoscapeGUIComponent {
private EventTableModel<Taxon> headerModel;
private EventTableModel<Taxon> matrixTableModel;
private JTable matrixTable;
private DefaultCellEditor popupEditor;
private DefaultCellEditor quickEditor;
private final SortedList<Taxon> sortedTaxa = new SortedList<Taxon>(this.getController().getDataSet().getTaxa(), new EverythingEqualComparator<Taxon>());
private final EventList<State> allStates;
private static enum TaxonDisplay {
PUBLICATION_NAME { @Override public String toString() { return "Display Publication Name"; }},
VALID_NAME { @Override public String toString() { return "Display Valid Name"; }},
MATRIX_NAME { @Override public String toString() { return "Display Matrix Name"; }}
}
private static enum CharacterDisplay {
CHARACTER_NUMBER { @Override public String toString() { return "Display Character Number"; }},
CHARACTER_DESCRIPTION { @Override public String toString() { return "Display Character Description"; }}
}
private static enum StateDisplay {
STATE_SYMBOL { @Override public String toString() { return "Display State Symbol"; }},
STATE_DESCRIPTION { @Override public String toString() { return "Display State Description"; }}
}
private TaxonDisplay taxonOption = TaxonDisplay.VALID_NAME;
private CharacterDisplay characterOption = CharacterDisplay.CHARACTER_NUMBER;
private StateDisplay stateOption = StateDisplay.STATE_SYMBOL;
public CharacterMatrixComponent(String id, PhenexController controller) {
super(id, controller);
this.allStates = new CollectionList<Character, State>(this.getController().getDataSet().getCharacters(),
new CollectionList.Model<Character, State>() {
@Override
public List<State> getChildren(Character parent) {
return parent.getStates();
}
}
);
}
@Override
public void init() {
super.init();
this.initializeInterface();
}
private void initializeInterface() {
this.setLayout(new BorderLayout());
this.headerModel = new EventTableModel<Taxon>(this.sortedTaxa, new HeaderTableFormat());
final JTable headerTable = new BugWorkaroundTable(this.headerModel);
headerTable.putClientProperty("Quaqua.Table.style", "striped");
headerTable.setDefaultRenderer(Taxon.class, new TaxonRenderer());
headerTable.getColumnModel().getColumn(0).setMaxWidth(40);
final TableComparatorChooser<Taxon> sortChooser = new TableComparatorChooser<Taxon>(headerTable, this.sortedTaxa, false);
sortChooser.addSortActionListener(new SortDisabler());
this.matrixTableModel = new EventTableModel<Taxon>(this.sortedTaxa, new MatrixTableFormat());
this.matrixTable = new BugWorkaroundTable(this.matrixTableModel);
this.matrixTable.setCellSelectionEnabled(true);
this.matrixTable.setDefaultRenderer(Object.class, new PlaceholderRenderer("None"));
this.matrixTable.setDefaultRenderer(State.class, new StateCellRenderer());
final JComboBox statesBox = new JComboBox();
statesBox.setRenderer(new StateListRenderer());
this.popupEditor = new PopupStateCellEditor(statesBox);
this.popupEditor.setClickCountToStart(2);
this.quickEditor = new QuickStateCellEditor(new JTextField());
this.matrixTable.setDefaultEditor(State.class, this.popupEditor);
this.matrixTable.putClientProperty("Quaqua.Table.style", "striped");
this.matrixTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
this.getController().getDataSet().getCharacters().addListEventListener(new ListEventListener<Character>() {
@Override
public void listChanged(ListEvent<Character> listChanges) {
matrixTableModel.fireTableStructureChanged();
}
});
this.allStates.addListEventListener(new ListEventListener<State>() {
@Override
public void listChanged(ListEvent<State> listChanges) {
matrixTableModel.fireTableDataChanged();
}
});
final JScrollPane headerScroller = new JScrollPane(headerTable);
final JScrollPane matrixScroller = new JScrollPane(matrixTable);
headerScroller.getVerticalScrollBar().setModel(matrixScroller.getVerticalScrollBar().getModel());
headerScroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
headerScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
matrixScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, headerScroller, matrixScroller);
splitPane.setDividerLocation(150);
splitPane.setDividerSize(3);
this.add(splitPane, BorderLayout.CENTER);
this.add(this.createToolBar(), BorderLayout.SOUTH);
this.getController().getDataSet().addPropertyChangeListener(DataSet.MATRIX_CELL, new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
matrixTableModel.fireTableDataChanged();
}
});
}
private JToolBar createToolBar() {
final JToolBar toolBar = new JToolBar();
final JComboBox taxonBox = new JComboBox(TaxonDisplay.values());
taxonBox.setSelectedItem(this.taxonOption);
taxonBox.setAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
taxonOption = (TaxonDisplay)(taxonBox.getSelectedItem());
headerModel.fireTableDataChanged();
}
});
final JComboBox characterBox = new JComboBox(CharacterDisplay.values());
characterBox.setSelectedItem(this.characterOption);
characterBox.setAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
characterOption = (CharacterDisplay)(characterBox.getSelectedItem());
matrixTableModel.fireTableStructureChanged();
}
});
final JComboBox stateBox = new JComboBox(StateDisplay.values());
stateBox.setSelectedItem(this.stateOption);
stateBox.setAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
stateOption = (StateDisplay)(stateBox.getSelectedItem());
matrixTableModel.fireTableDataChanged();
}
});
final JCheckBox editorTypeCheckBox = new JCheckBox("Use quick editor");
editorTypeCheckBox.setSelected(false);
editorTypeCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
matrixTable.setDefaultEditor(State.class, quickEditor);
} else {
matrixTable.setDefaultEditor(State.class, popupEditor);
}
}});
toolBar.add(taxonBox);
toolBar.add(characterBox);
toolBar.add(stateBox);
toolBar.add(editorTypeCheckBox);
toolBar.setFloatable(false);
return toolBar;
}
private class HeaderTableFormat implements AdvancedTableFormat<Taxon> {
@Override
public Class<?> getColumnClass(int column) {
switch (column) {
case 0: return Integer.class;
case 1: return Taxon.class;
default: return null;
}
}
@Override
public Comparator<?> getColumnComparator(int column) {
switch (column) {
case 0: return GlazedLists.comparableComparator();
case 1: return new Comparator<Taxon>() {
@Override
public int compare(Taxon o1, Taxon o2) {
if (taxonOption.equals(TaxonDisplay.VALID_NAME)) {
return GlazedLists.comparableComparator().compare(o1.getValidName(), o2.getValidName());
} else if (taxonOption.equals(TaxonDisplay.PUBLICATION_NAME)){
return Strings.getNaturalComparator().compare(o1.getPublicationName(), o2.getPublicationName());
} else { // MATRIX_NAME
return Strings.getNaturalComparator().compare(o1.getMatrixTaxonName(), o2.getMatrixTaxonName());
}
}
};
default: return null;
}
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int column) {
switch(column) {
case 0: return " ";
case 1: return "Taxon";
default: return null;
}
}
@Override
public Object getColumnValue(Taxon taxon, int column) {
switch(column) {
case 0: return getController().getDataSet().getTaxa().indexOf(taxon) + 1;
case 1: return taxon;
default: return null;
}
}
}
private class MatrixTableFormat implements AdvancedTableFormat<Taxon>, WritableTableFormat<Taxon> {
@Override
public int getColumnCount() {
return getController().getDataSet().getCharacters().size();
}
@Override
public Class<?> getColumnClass(int column) {
return State.class;
}
@Override
public Comparator<?> getColumnComparator(int column) {
return null;
}
@Override
public String getColumnName(int column) {
if (characterOption.equals(CharacterDisplay.CHARACTER_DESCRIPTION)) {
return this.getCharacter(column).toString();
} else if (characterOption.equals(CharacterDisplay.CHARACTER_NUMBER)) {
return "" + (column + 1);
}
return null;
}
@Override
public Object getColumnValue(Taxon taxon, int column) {
return getController().getDataSet().getStateForTaxon(taxon, this.getCharacter(column));
}
@Override
public boolean isEditable(Taxon baseObject, int column) {
return true;
}
@Override
public Taxon setColumnValue(Taxon taxon, Object editedValue, int column) {
getController().getDataSet().setStateForTaxon(taxon, this.getCharacter(column), (State)editedValue);
return taxon;
}
private Character getCharacter(int index) {
return getController().getDataSet().getCharacters().get(index);
}
}
private class StateCellRenderer extends PlaceholderRenderer {
public StateCellRenderer() {
super("?");
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
final State state = (State)value;
if (state != null) {
final Object newValue;
if (stateOption.equals(StateDisplay.STATE_SYMBOL)) {
newValue = state.getSymbol() != null ? state.getSymbol() : "
} else {
newValue = state.getLabel() != null ? state.getLabel() : "untitled";
}
return super.getTableCellRendererComponent(table, newValue, isSelected, hasFocus, row, column);
} else {
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
}
}
private class StateListRenderer extends BasicComboBoxRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
final Object newValue = value != null ? value : "?";
return super.getListCellRendererComponent(list, newValue, index, isSelected, cellHasFocus);
}
}
private class PopupStateCellEditor extends DefaultCellEditor {
private final DefaultComboBoxModel model = new DefaultComboBoxModel();
public PopupStateCellEditor(JComboBox comboBox) {
super(comboBox);
comboBox.setModel(model);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
final Character character = getController().getDataSet().getCharacters().get(column);
this.model.removeAllElements();
this.model.addElement(null);
for (State state : character.getStates()) {
this.model.addElement(state);
}
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
private class QuickStateCellEditor extends DefaultCellEditor {
private List<State> states = new ArrayList<State>();
private State originalValue;
private State currentValue;
private final JTextField field;
private boolean invalid = false;
public QuickStateCellEditor(JTextField textField) {
super(textField);
this.field = textField;
this.field.setBorder(BorderFactory.createLineBorder(Color.BLACK));
textField.getDocument().addDocumentListener(new FieldListener());
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
final Character character = getController().getDataSet().getCharacters().get(column);
this.states = character.getStates();
final State state = (State)value;
final Object newValue = state != null ? state.getSymbol() : null;
this.originalValue = state;
this.currentValue = state;
final Component component = super.getTableCellEditorComponent(table, newValue, isSelected, row, column);
this.field.selectAll();
return component;
}
@Override
public void cancelCellEditing() {
this.currentValue = this.originalValue;
super.cancelCellEditing();
}
@Override
public Object getCellEditorValue() {
return this.currentValue;
}
@Override
public boolean stopCellEditing() {
if (this.getInvalid()) {
return false;
}
return super.stopCellEditing();
}
private boolean getInvalid() {
return this.invalid;
}
private void setInvalid(boolean value) {
this.invalid = value;
if (this.invalid) {
field.setForeground(Color.RED);
} else {
field.setForeground(Color.BLACK);
}
}
private class FieldListener implements DocumentListener {
@Override
public void changedUpdate(DocumentEvent e) { this.documentChanged(); }
@Override
public void insertUpdate(DocumentEvent e) { this.documentChanged(); }
@Override
public void removeUpdate(DocumentEvent e) { this.documentChanged(); }
private void documentChanged() {
final String text = field.getText();
if ((text == null) || (text.equals(""))) {
currentValue = null;
setInvalid(false);
} else {
final State foundState = this.interpretEntry(text);
if (foundState != null) {
currentValue = foundState;
setInvalid(false);
} else {
setInvalid(true);
}
}
}
private State interpretEntry(String text) {
log().debug("Interpret entry: " + text);
if (text.contains("&")) {
final Set<State> multipleStates = this.interpretStateSymbols(text.split("&"));
if (multipleStates != null) {
return new MultipleState(multipleStates, MODE.POLYMORPHIC);
} else {
return null;
}
} else if (text.contains("/")) {
final Set<State> multipleStates = this.interpretStateSymbols(text.split("/"));
if (multipleStates != null) {
return new MultipleState(multipleStates, MODE.UNCERTAIN);
} else {
return null;
}
} else {
for (State state : states) {
if (text.equals(state.getSymbol())) {
return state;
}
}
}
return null;
}
private Set<State> interpretStateSymbols(String[] symbols) {
if (symbols.length == 1) {
return null;
}
final Set<State> multipleStates = new HashSet<State>();
for (String symbol : symbols) {
for (State state : states) {
if (symbol.equals(state.getSymbol())) {
multipleStates.add(state);
}
}
}
if (symbols.length == multipleStates.size()) {
return multipleStates;
} else {
return null;
}
}
}
}
private class TaxonRenderer extends TermRenderer {
public TaxonRenderer() {
super("untitled");
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (taxonOption.equals(TaxonDisplay.VALID_NAME)) {
final Object newValue = value != null ? ((Taxon)value).getValidName() : value;
return super.getTableCellRendererComponent(table, newValue, isSelected, hasFocus, row, column);
} else {
final Object newValue;
if (value != null) {
newValue = taxonOption.equals(TaxonDisplay.PUBLICATION_NAME) ? ((Taxon)value).getPublicationName() : ((Taxon)value).getMatrixTaxonName();
} else {
newValue = value;
}
return super.getTableCellRendererComponent(table, newValue, isSelected, hasFocus, row, column);
}
}
}
@Override
protected Logger log() {
return Logger.getLogger(this.getClass());
}
}
|
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
package org.sosy_lab.java_smt.basicimpl;
import com.google.common.base.Preconditions;
import java.util.concurrent.atomic.AtomicBoolean;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.ShutdownNotifier.ShutdownRequestListener;
/**
* A utility class for interrupting a parallel running solver thread.
*
* <p>The hook is active directly after its construction until calling the method {@link
* ShutdownHook#close()} and forwards all shutdown requests to the provided method.
*/
public final class ShutdownHook implements ShutdownRequestListener, AutoCloseable {
private final ShutdownNotifier shutdownNotifier;
private final Runnable interruptCall;
public ShutdownHook(ShutdownNotifier pShutdownNotifier, Runnable pInterruptCall) {
interruptCall = Preconditions.checkNotNull(pInterruptCall);
shutdownNotifier = Preconditions.checkNotNull(pShutdownNotifier);
shutdownNotifier.register(this);
}
final AtomicBoolean isActiveHook = new AtomicBoolean(true);
// Due to a small delay in some solvers, interrupts have no effect when it is called too soon,
// so we repeat cancellation until the solver's method returns and terminates.
// In that case, we should call #close and terminate this hook.
@Override
public void shutdownRequested(@Nullable String reason_unused) {
while (isActiveHook.get()) { // flag is reset in #cancelHook
interruptCall.run();
try {
Thread.sleep(10); // lets wait a few steps
} catch (InterruptedException e) {
// ignore
}
}
}
@Override
public void close() {
isActiveHook.set(false);
shutdownNotifier.unregister(this);
}
}
|
package org.usfirst.frc.team339.Utils;
import org.usfirst.frc.team339.Hardware.Hardware;
import org.usfirst.frc.team339.HardwareInterfaces.IRSensor;
import org.usfirst.frc.team339.HardwareInterfaces.RobotPotentiometer;
import edu.wpi.first.wpilibj.SpeedController;
// TODO fix everything when we have a physical arm
public class ManipulatorArm
{
public ManipulatorArm (SpeedController armMotorController,
SpeedController intakeMotor,
RobotPotentiometer armPot, IRSensor ballIsInArmSensor)
{
this.motor = armMotorController;
this.armPot = armPot;
this.intakeMotor = intakeMotor;
this.hasBallSensor = ballIsInArmSensor;
}
//TODO change so it doens't move beyond soft limit from encoder.
/**
* Moves the arm at its current slow speed.
*
* @param direction
* Positive one for forward and negative one for backwards
*/
public void moveSlow (int direction, boolean override)
{
direction *= -1;
this.move(direction * this.slowSpeed, override);
}
/**
* Moves the arm at its current fast speed.
*
* @param direction
* Positive one for forward and negative one for backwards
*/
public void moveFast (int direction, boolean override)
{
direction *= -1;
this.move(direction * this.MAX_ARM_SPEED, override);
}
/**
* Method used to smoothly raise and lower arm at a humanly managable speed.
* Changes speed after a certain tipping point.
*
* @param direction
* @param override
*/
public void moveReasonably (int direction, boolean override)
{
direction *= -1;
if (direction > 0)
//Going UP!
{
if (armPot.get() < REASONABLE_DECELERATION_ANGLE)
//Starting up, has to work hard.
{
move(REASONABLE_UP_FACTOR, override);
}
else
//We are over the hump, slow down.
{
move(REASONABLE_UP_AND_OVER_FACTOR, override);
}
}
else
//going down.
{
if (armPot.get() > REASONABLE_DECELERATION_ANGLE)
{
move(REASONABLE_DOWN_FACTOR, override);
}
else
//now gravity is on our side. Slow down a bit.
{
move(REASONABLE_DOWN_UNDER_FACTOR, override);
}
}
}
/**
* Moves the arm at the given speed. Positive brings it up, negative down.
*
* @param speed
* The speed at which to move the arm.
*/
public void move (double speed, boolean override)
{
//If we're currently beyond our soft limits, don't do anything that would
//bring up further out of them. Otherwise do what the user wants.
if ((speed > 0 && this.armPot.get() < this.MIN_SOFT_ARM_STOP)
|| (speed < 0
&& this.armPot.get() > this.MAX_SOFT_ARM_STOP))
{
//we have to give a little bit of voltage to stop the motor.
this.stopArmMotor();
}
else
{
this.motor.set(-speed);
}
}
public void move (double speed)
{
this.move(speed, false);
}
public void stopArmMotor ()
{
if (armPot.get() > STOP_DOWN_ANGLE)
{
this.motor.set(0.15);
}
else
{
this.motor.set(0.0);
}
}
/**
* Starts the intake motor to suck in a ball; stopIntakeArms() needs to be
* called to stop them.
*/
public void pullInBall (boolean override)
{
if (ballHasBeenPreviouslyDetected == false && Hardware.armIR.isOn())
{
ballHasBeenPreviouslyDetected = true;
Hardware.kilroyTimer.reset();
Hardware.kilroyTimer.start();
}
if (Hardware.armIR.isOn() == true && override == false
&& armPot.get() <= DEPOSIT_POSITION
&& Hardware.kilroyTimer.get() > DELAY_AFTER_BALL_DETECTION)
{
//If we already have a ball, no need to pull one in.
//TODO check to make sure -1 pulls in and not the reverse.
this.intakeMotor.set(0.0);
Hardware.kilroyTimer.stop();
ballHasBeenPreviouslyDetected = false;
}
else
{
this.intakeMotor.set(-INTAKE_SPEED);
}
}
/**
* Starts the intake motor to push out a ball; stopIntakeArms() needs to be
* called to stop them.
*/
public void pushOutBall ()
{
//TODO check to make sure 1 pushes out and not the reverse.
this.intakeMotor.set(1.0);
}
/**
*
* @return true if ball is not within its clutches.
*/
public boolean ballIsOut ()
{
return !this.hasBallSensor.get();
}
/**
* Stops the intake arms.
*/
public void stopIntakeArms ()
{
this.intakeMotor.set(0.0);
}
public void setIntakeArmsSpeed (double speed)
{
this.intakeMotor.set(speed);
}
/**
*
* @return true if arm is down.
*/
public boolean isDown ()
{
if (this.armPot.get() <= this.MIN_SOFT_ARM_STOP)
{
return true;
}
else
{
return false;
}
}
/**
*
* @return true if arm is up.
*/
public boolean isUp ()
{
if (this.armPot.get() >= MAX_SOFT_ARM_STOP)
{
return true;
}
else
{
return false;
}
}
/**
*
* @return true if arm is out of the way.
*/
public boolean isClearOfArm ()
{
if (armPot.get() <= this.ARM_OUT_OF_WAY_DEGREES)
{
return true;
}
return false;
}
public boolean isInDepositPosition ()
{
if (armPot.get() > DEPOSIT_POSITION - DEPOSIT_POSITION_THRESHOLD
&& armPot.get() < DEPOSIT_POSITION
+ DEPOSIT_POSITION_THRESHOLD)
{
return true;
}
return false;
}
public void holdInHoldingPosition ()
{
if (armPot.get() < HOLDING_POSITION - HOLDING_POSITION_THRESHOLD)
{
move(MAX_ARM_SPEED);
}
else if (armPot.get() > HOLDING_POSITION
+ HOLDING_POSITION_THRESHOLD)
{
move(-MAX_ARM_SPEED);
}
else
{
move(HOLDING_SPEED);
}
}
/**
* Moves the arm at full speed to the desired position.
*
* @param position
* desired.
* @return true when positioning is complete.
*/
public boolean moveToPosition (ArmPosition position)
{
boolean done = false;
switch (position)
{
case FULL_DOWN:
move(-MAX_ARM_SPEED);
if (this.isDown())
{
move(0.0);
done = true;
}
break;
case FULL_UP:
move(MAX_ARM_SPEED);
if (this.isUp())
{
move(0.0);
done = true;
}
break;
case DEPOSIT:
if (armPot.get() < DEPOSIT_POSITION
- DEPOSIT_POSITION_THRESHOLD)
{
move(MAX_ARM_SPEED);
}
else if (armPot.get() > DEPOSIT_POSITION
+ DEPOSIT_POSITION_THRESHOLD)
{
move(-MAX_ARM_SPEED);
}
else
{
move(0.0);
done = true;
}
break;
case CLEAR_OF_FIRING_ARM:
move(-MAX_ARM_SPEED);
if (this.isClearOfArm() == true)
{
move(0.0);
done = true;
}
break;
default:
case HOLD:
holdInHoldingPosition();
break;
}
return done;
}
/**
*
* A set of positions the arm can be in.
*
*/
public static enum ArmPosition
{
/**
* All the way down, as in down-to-the-floor down.
*/
FULL_DOWN,
/**
* Folded up all the way.
*/
FULL_UP,
/**
* Within a rang from which we can pu the ball into the catapult.
*/
DEPOSIT,
/**
* Out of the way of the catapult.
*/
CLEAR_OF_FIRING_ARM,
/**
* Stay off the ground, yet out of the way,.
*/
HOLD
}
private SpeedController intakeMotor = null;
private SpeedController motor = null;
private RobotPotentiometer armPot = null;
private IRSensor hasBallSensor = null;
private boolean ballHasBeenPreviouslyDetected = false;
//default maximum arm turn speed proportion
private final double MAX_ARM_SPEED = -1.0;
//default slow arm turn speed proportion
private double slowSpeed = .2;
private final double MAX_SOFT_ARM_STOP = 170.0;
private final double MIN_SOFT_ARM_STOP = 21.0;
private final double ARM_OUT_OF_WAY_DEGREES = 130.0;//TODO change back to 130
private final double DEPOSIT_POSITION = 145.0;
private final double DEPOSIT_POSITION_THRESHOLD = 5.0;
private final double REASONABLE_UP_FACTOR = -1.0;
private final double REASONABLE_UP_AND_OVER_FACTOR = -0.40;
private final double REASONABLE_DOWN_FACTOR = 0.35;
private final double REASONABLE_DOWN_UNDER_FACTOR = 0.20;
private final double REASONABLE_DECELERATION_ANGLE = 111.1;
private final double INTAKE_SPEED = 0.5;
private static final int HOLDING_POSITION = 70;
private static final int HOLDING_POSITION_THRESHOLD = 5;
private static final double HOLDING_SPEED = 0.1;
private static final int STOP_DOWN_ANGLE = 45;
private static final double DELAY_AFTER_BALL_DETECTION = 0.1;
}
|
package com.yahoo.bard.webservice.data.config.luthier.factories.metricmaker;
import com.yahoo.bard.webservice.application.luthier.LuthierConfigNode;
import com.yahoo.bard.webservice.data.config.luthier.Factory;
import com.yahoo.bard.webservice.data.config.luthier.LuthierIndustrialPark;
import com.yahoo.bard.webservice.data.config.metric.makers.LongMinMaker;
import com.yahoo.bard.webservice.data.config.metric.makers.MetricMaker;
/**
* Factory that supports LongMinMaker.
*/
public class LongMinMakerFactory implements Factory<MetricMaker> {
@Override
public MetricMaker build(String name, LuthierConfigNode configTable, LuthierIndustrialPark resourceFactories) {
return new LongMinMaker(resourceFactories.getMetricDictionary());
}
}
|
package io.subutai.core.peer.impl;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import io.subutai.common.dao.DaoManager;
import io.subutai.common.exception.NetworkException;
import io.subutai.common.host.HeartBeat;
import io.subutai.common.host.HeartbeatListener;
import io.subutai.common.host.ResourceHostInfo;
import io.subutai.common.network.SocketUtil;
import io.subutai.common.peer.Encrypted;
import io.subutai.common.peer.LocalPeer;
import io.subutai.common.peer.Peer;
import io.subutai.common.peer.PeerException;
import io.subutai.common.peer.PeerId;
import io.subutai.common.peer.PeerInfo;
import io.subutai.common.peer.PeerNotRegisteredException;
import io.subutai.common.peer.PeerPolicy;
import io.subutai.common.peer.RegistrationData;
import io.subutai.common.peer.RegistrationStatus;
import io.subutai.common.peer.RemotePeer;
import io.subutai.common.security.crypto.pgp.PGPKeyUtil;
import io.subutai.common.security.objects.SecurityKeyType;
import io.subutai.common.security.objects.TokenType;
import io.subutai.common.security.relation.RelationManager;
import io.subutai.common.security.relation.model.Relation;
import io.subutai.common.security.relation.model.RelationInfoMeta;
import io.subutai.common.security.relation.model.RelationMeta;
import io.subutai.common.security.relation.model.RelationStatus;
import io.subutai.common.settings.Common;
import io.subutai.common.util.SecurityUtilities;
import io.subutai.common.util.ServiceLocator;
import io.subutai.core.hostregistry.api.HostRegistry;
import io.subutai.core.identity.api.IdentityManager;
import io.subutai.core.identity.api.model.User;
import io.subutai.core.identity.api.model.UserToken;
import io.subutai.core.messenger.api.Messenger;
import io.subutai.core.peer.api.PeerAction;
import io.subutai.core.peer.api.PeerActionListener;
import io.subutai.core.peer.api.PeerActionResponse;
import io.subutai.core.peer.api.PeerActionType;
import io.subutai.core.peer.api.PeerManager;
import io.subutai.core.peer.api.RegistrationClient;
import io.subutai.core.peer.impl.command.CommandResponseListener;
import io.subutai.core.peer.impl.dao.PeerDataService;
import io.subutai.core.peer.impl.dao.PeerRegistrationDataService;
import io.subutai.core.peer.impl.entity.PeerData;
import io.subutai.core.peer.impl.entity.PeerRegistrationData;
import io.subutai.core.peer.impl.request.MessageResponseListener;
import io.subutai.core.security.api.SecurityManager;
import io.subutai.hub.share.resource.PeerGroupResources;
import io.subutai.hub.share.resource.PeerResources;
/**
* PeerManager implementation
*/
@PermitAll
public class PeerManagerImpl implements PeerManager, HeartbeatListener
{
private static final Logger LOG = LoggerFactory.getLogger( PeerManagerImpl.class );
private static final int MAX_CONTAINER_LIMIT = 20;
private static final int MAX_ENVIRONMENT_LIMIT = 20;
private PeerDataService peerDataService;
private PeerRegistrationDataService peerRegistrationDataService;
private final LocalPeer localPeer;
protected Messenger messenger;
CommandResponseListener commandResponseListener;
private MessageResponseListener messageResponseListener;
private DaoManager daoManager;
private SecurityManager securityManager;
private Object provider;
private List<PeerActionListener> peerActionListeners = new CopyOnWriteArrayList<>();
private IdentityManager identityManager;
private Map<String, Peer> peers = new ConcurrentHashMap<>();
private ObjectMapper mapper = new ObjectMapper();
private String localPeerId;
private RegistrationClient registrationClient;
private RelationManager relationManager;
private ScheduledExecutorService localIpSetter = Executors.newSingleThreadScheduledExecutor();
public PeerManagerImpl( final Messenger messenger, LocalPeer localPeer, DaoManager daoManager,
MessageResponseListener messageResponseListener, SecurityManager securityManager,
IdentityManager identityManager, Object provider )
{
Preconditions.checkNotNull( messenger );
Preconditions.checkNotNull( localPeer );
Preconditions.checkNotNull( daoManager );
Preconditions.checkNotNull( messageResponseListener );
Preconditions.checkNotNull( securityManager );
Preconditions.checkNotNull( identityManager );
Preconditions.checkNotNull( provider );
this.messenger = messenger;
this.localPeer = localPeer;
this.daoManager = daoManager;
this.messageResponseListener = messageResponseListener;
this.securityManager = securityManager;
this.identityManager = identityManager;
this.provider = provider;
commandResponseListener = new CommandResponseListener();
localPeer.addRequestListener( commandResponseListener );
registrationClient = new RegistrationClientImpl( provider );
}
public void init()
{
try
{
this.peerDataService = new PeerDataService( daoManager.getEntityManagerFactory() );
this.peerRegistrationDataService = new PeerRegistrationDataService( daoManager.getEntityManagerFactory() );
localPeerId = securityManager.getKeyManager().getPeerId();
PeerData localPeerData = peerDataService.find( localPeerId );
if ( localPeerData == null )
{
PeerInfo localPeerInfo = localPeer.getPeerInfo();
PeerPolicy policy = getDefaultPeerPolicy( localPeerId );
PeerData peerData =
new PeerData( localPeerInfo.getId(), toJson( localPeerInfo ), "", toJson( policy ), 1 );
updatePeerData( peerData );
}
for ( PeerData peerData : this.peerDataService.getAll() )
{
Peer peer = constructPeerPojo( peerData );
updatePeerInCache( peer );
}
localIpSetter.scheduleWithFixedDelay( new IpDetectionJob(), 1, 5, TimeUnit.SECONDS );
}
catch ( Exception e )
{
LOG.error( "Could not initialize peer manager", e );
}
}
public void destroy()
{
commandResponseListener.dispose();
}
public void setRelationManager( final RelationManager relationManager )
{
this.relationManager = relationManager;
}
RelationManager getRelationManager()
{
return relationManager;
}
IdentityManager getIdentityManager()
{
return identityManager;
}
private PeerPolicy getDefaultPeerPolicy( String peerId )
{
//TODO: make values configurable
return new PeerPolicy( peerId, 90, 50, 90, 90, 3, 10 );
}
@Override
public void registerPeerActionListener( PeerActionListener peerActionListener )
{
if ( peerActionListener != null )
{
LOG.info( "Registering peer action listener: " + peerActionListener.getName() );
this.peerActionListeners.add( peerActionListener );
}
}
@Override
public void unregisterPeerActionListener( PeerActionListener peerActionListener )
{
if ( peerActionListener != null )
{
LOG.info( "Unregistering peer action listener: " + peerActionListener.getName() );
this.peerActionListeners.remove( peerActionListener );
}
}
private PeerActionResponses notifyPeerActionListeners( PeerAction action )
{
PeerActionResponses result = new PeerActionResponses();
for ( PeerActionListener peerActionListener : peerActionListeners )
{
PeerActionResponse response = peerActionListener.onPeerAction( action );
result.add( response );
}
return result;
}
private void register( final String keyPhrase, final RegistrationData registrationData ) throws PeerException
{
Preconditions.checkNotNull( keyPhrase, "Key phrase could not be null." );
Preconditions.checkArgument( !keyPhrase.isEmpty(), "Key phrase could not be empty" );
if ( !notifyPeerActionListeners( new PeerAction( PeerActionType.REGISTER ) ).succeeded() )
{
throw new PeerException( "Could not register peer." );
}
Encrypted encryptedSslCert = registrationData.getSslCert();
try
{
SocketUtil.check( registrationData.getPeerInfo().getIp(), 3,
registrationData.getPeerInfo().getPublicSecurePort() );
byte[] key = SecurityUtilities.generateKey( keyPhrase.getBytes( "UTF-8" ) );
String decryptedSslCert = encryptedSslCert.decrypt( key, String.class );
securityManager.getKeyStoreManager().importCertAsTrusted( Common.DEFAULT_PUBLIC_SECURE_PORT,
registrationData.getPeerInfo().getId(), decryptedSslCert );
securityManager.getHttpContextManager().reloadKeyStore();
PeerPolicy policy = getDefaultPeerPolicy( registrationData.getPeerInfo().getId() );
final Integer order = getMaxOrder() + 1;
registrationData.getPeerInfo()
.setName( String.format( "Peer on %s", registrationData.getPeerInfo().getIp() ) );
PeerData peerData =
new PeerData( registrationData.getPeerInfo().getId(), toJson( registrationData.getPeerInfo() ),
keyPhrase, toJson( policy ), order );
updatePeerData( peerData );
Peer newPeer = constructPeerPojo( peerData );
updatePeerInCache( newPeer );
Encrypted encryptedPublicKey = registrationData.getPublicKey();
String publicKey = encryptedPublicKey.decrypt( key, String.class );
securityManager.getKeyManager()
.savePublicKeyRing( registrationData.getPeerInfo().getId(), SecurityKeyType.PEER_KEY.getId(),
publicKey );
}
catch ( GeneralSecurityException e )
{
throw new PeerException( "Invalid keyphrase or general security exception." );
}
catch ( NetworkException e )
{
throw new PeerException( e.getMessage() );
}
catch ( Exception e )
{
LOG.warn( e.getMessage(), e );
throw new PeerException( "Could not register peer." );
}
}
//todo review and remove if not needed (when kurjun will be removed)
private String generateActiveUserToken() throws PeerException
{
try
{
User user = identityManager.getActiveUser();
UserToken userToken =
identityManager.createUserToken( user, "", "", "", TokenType.PERMANENT.getId(), null );
return userToken.getFullToken();
}
catch ( Exception e )
{
throw new PeerException( "Failed to generate active user token.", e );
}
}
private <T> T fromJson( String value, Class<T> type ) throws IOException
{
return mapper.readValue( value, type );
}
private String toJson( Object value ) throws IOException
{
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString( value );
}
void updatePeerInCache( final Peer peer )
{
Preconditions.checkNotNull( peer, "Peer could not be null." );
this.peers.put( peer.getId(), peer );
}
private void removePeerFromCache( String id )
{
Peer peer = this.peers.get( id );
if ( peer != null )
{
this.peers.remove( id );
}
}
private PeerData loadPeerData( final String id )
{
return peerDataService.find( id );
}
private void updatePeerData( final PeerData peerData ) throws PeerException
{
Preconditions.checkNotNull( peerData, "Peer data could not be null." );
this.peerDataService.saveOrUpdate( peerData );
}
private void removePeerData( String id )
{
this.peerDataService.remove( id );
}
/**
* Creates the peer instance by provided peer data
*
* @param peerData peer data
*
* @return peer instance
*/
private Peer constructPeerPojo( final PeerData peerData ) throws PeerException
{
Preconditions.checkNotNull( peerData, "Peer info could not be null." );
try
{
PeerInfo peerInfo = fromJson( peerData.getInfo(), PeerInfo.class );
if ( localPeerId.equals( peerData.getId() ) )
{
localPeer.setPeerInfo( peerInfo );
return localPeer;
}
RemotePeerImpl remotePeer =
new RemotePeerImpl( localPeerId, securityManager, peerInfo, messenger, commandResponseListener,
messageResponseListener, provider, this );
RelationInfoMeta relationInfoMeta = new RelationInfoMeta();
Map<String, String> traits = relationInfoMeta.getRelationTraits();
traits.put( "receiveHeartbeats", "allow" );
traits.put( "sendHeartbeats", "allow" );
traits.put( "hostTemplates", "allow" );
User peerOwner = identityManager.getUserByKeyId( identityManager.getPeerOwnerId() );
RelationMeta relationMeta = new RelationMeta( peerOwner, localPeer, remotePeer, localPeer.getKeyId() );
Relation relation = relationManager.buildRelation( relationInfoMeta, relationMeta );
relation.setRelationStatus( RelationStatus.VERIFIED );
relationManager.saveRelation( relation );
return remotePeer;
}
catch ( Exception e )
{
throw new PeerException( "Could not create peer instance.", e );
}
}
private void unregister( final RegistrationData registrationData ) throws PeerException
{
try
{
/**
* Since heartbeat arrives only once per change on system level, and it can arrive when local peer is not init'ed
* yet, we need this additional job to obtain IP of RH-with-MH
*/
private class IpDetectionJob implements Runnable
{
@Override
public void run()
{
try
{
HostRegistry hostRegistry = ServiceLocator.lookup( HostRegistry.class );
String ip =
( ( ResourceHostInfo ) hostRegistry.getHostInfoById( localPeer.getManagementHost().getId() ) )
.getAddress();
if ( setLocalPeerUrl( ip ) )
{
localIpSetter.shutdown();
}
}
catch ( Exception e )
{
LOG.warn( "Error updating local peer public url", e );
}
}
}
}
|
package com.consol.citrus.validation.interceptor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.message.Message;
import com.consol.citrus.message.MessageDirection;
import com.consol.citrus.message.MessageType;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;
/**
* Message construction interceptor automatically converts message payloads to gzipped content. Supports String typed message payloads and
* payload resources.
*
* @author Christoph Deppisch
*/
public class GzipMessageConstructionInterceptor extends AbstractMessageConstructionInterceptor {
@Override
protected Message interceptMessage(Message message, String messageType, TestContext context) {
try {
if (message.getPayload() instanceof String) {
try (ByteArrayOutputStream zipped = new ByteArrayOutputStream()) {
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(zipped)) {
StreamUtils.copy(context.replaceDynamicContentInString(message.getPayload(String.class)).getBytes(), gzipOutputStream);
}
message.setPayload(zipped.toByteArray());
}
} else if (message.getPayload() instanceof Resource) {
try (ByteArrayOutputStream zipped = new ByteArrayOutputStream()) {
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(zipped)) {
StreamUtils.copy(FileCopyUtils.copyToByteArray(message.getPayload(Resource.class).getInputStream()), gzipOutputStream);
}
message.setPayload(zipped.toByteArray());
}
}
} catch (IOException e) {
throw new CitrusRuntimeException("Failed to gzip message payload", e);
}
return message;
}
@Override
public boolean supportsMessageType(String messageType) {
return MessageType.GZIP.name().equalsIgnoreCase(messageType);
}
@Override
public MessageDirection getDirection() {
return MessageDirection.OUTBOUND;
}
}
|
package com.woorea.openstack.connector;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.ContextResolver;
import org.apache.commons.httpclient.HttpStatus;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonRootName;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientRequestFactory;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.plugins.providers.InputStreamProvider;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import com.woorea.openstack.base.client.OpenStackClientConnector;
import com.woorea.openstack.base.client.OpenStackRequest;
import com.woorea.openstack.base.client.OpenStackResponse;
import com.woorea.openstack.base.client.OpenStackResponseException;
public class RESTEasyConnector implements OpenStackClientConnector {
public static ObjectMapper DEFAULT_MAPPER;
public static ObjectMapper WRAPPED_MAPPER;
private static ResteasyProviderFactory providerFactory;
static {
DEFAULT_MAPPER = new ObjectMapper();
DEFAULT_MAPPER.setSerializationInclusion(Inclusion.NON_NULL);
DEFAULT_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT);
DEFAULT_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
WRAPPED_MAPPER = new ObjectMapper();
WRAPPED_MAPPER.setSerializationInclusion(Inclusion.NON_NULL);
WRAPPED_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT);
WRAPPED_MAPPER.enable(SerializationConfig.Feature.WRAP_ROOT_VALUE);
WRAPPED_MAPPER.enable(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE);
WRAPPED_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
providerFactory = new ResteasyProviderFactory();
providerFactory.addContextResolver(new ContextResolver<ObjectMapper>() {
public ObjectMapper getContext(Class<?> type) {
return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER;
}
});
JacksonJsonProvider jsonProvider = new JacksonJsonProvider();
providerFactory.addMessageBodyReader(jsonProvider);
providerFactory.addMessageBodyWriter(jsonProvider);
InputStreamProvider streamProvider = new InputStreamProvider();
providerFactory.addMessageBodyReader(streamProvider);
providerFactory.addMessageBodyWriter(streamProvider);
}
public <T> OpenStackResponse request(OpenStackRequest<T> request) {
ClientRequest client = new ClientRequest(UriBuilder.fromUri(request.endpoint() + "/" + request.path()),
ClientRequest.getDefaultExecutor(), providerFactory);
for(Map.Entry<String, Object> entry : request.queryParams().entrySet()) {
client = client.queryParameter(entry.getKey(), String.valueOf(entry.getValue()));
}
for (Entry<String, List<Object>> h : request.headers().entrySet()) {
StringBuilder sb = new StringBuilder();
for (Object v : h.getValue()) {
sb.append(String.valueOf(v));
}
client.header(h.getKey(), sb);
}
if (request.entity() != null) {
client.body(request.entity().getContentType(), request.entity().getEntity());
}
ClientResponse<T> response;
try {
response = client.httpMethod(request.method().name(), request.returnType());
} catch (Exception e) {
throw new RuntimeException("Unexpected client exception", e);
}
if (response.getStatus() == HttpStatus.SC_OK
|| response.getStatus() == HttpStatus.SC_CREATED
|| response.getStatus() == HttpStatus.SC_NO_CONTENT) {
return new RESTEasyResponse(response);
}
response.releaseConnection();
throw new OpenStackResponseException(response.getResponseStatus()
.getReasonPhrase(), response.getStatus());
}
}
|
package org.jcryptool.visual.secretsharing.views;
import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Path;
import org.eclipse.swt.graphics.PathData;
import org.eclipse.swt.graphics.Transform;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import org.jcryptool.core.util.colors.ColorService;
import org.jcryptool.core.util.fonts.FontService;
import org.jcryptool.visual.secretsharing.algorithm.Point;
import org.jcryptool.visual.secretsharing.algorithm.ShamirsSecretSharing;
import org.jcryptool.visual.secretsharing.views.Constants;
public class ShamirsSecretSharingComposite extends Composite {
private Group groupSecretSharing;
private Button resetButton;
private Label reconstructPxLabel;
private StyledText stValue;
private Group groupShares;
private ScrolledComposite scrolledShares;
private Composite compositeShares;
private Composite sharesButtonComposite;
private Button selectAllButton;
private Button deselectAllButton;
private Group groupParameter;
private Label numberOfConcernedLabel;
private Spinner spnrN;
private Label numberForReconstructionLabel;
private Spinner spnrT;
private Label modulLabel;
private Text modulText;
private VerifyListener numberOnlyVerifyListenerModul;
private Label secretLabel;
private Text secretText;
private VerifyListener numberOnlyVerifyListenerSecret;
private Label coefficentLabel;
private Button selectCoefficientButton;
private Label polynomLabel;
private Label pxLabel;
private StyledText stPolynom;
private Button computeSharesButton;
protected String[] result;
protected BigInteger[] coefficients;
protected BigInteger modul;
protected BigInteger secret;
protected String polynomialString = "";
protected ShamirsSecretSharing shamirsSecretSharing;
protected Point[] shares = new Point[] {};
protected Canvas canvasCurve;
private Text infoText;
private StyledText stInfo;
private Button[] sharesUseCheckButtonSet;
private Button reconstructButton;
private Vector<BigInteger[]> subpolynomial;
private BigInteger[] reconstructedPolynomial;
private Group groupReconstruction;
protected Composite compositeReconstruction;
private ScrolledComposite scrolledReconstruction;
private Text shareYCoordinateModText;
private Text sharesYCoordinateText;
private Group groupCurve;
private Composite sharePointInfo;
private Label shareLabel;
private Label openLabel;
private Text xText;
private Label seperatorLabel;
private Text yText;
private Label closeLabel;
protected int mousePosX;
protected int mousePosY;
private int yAxisGap;
private int xAxisGap;
protected int pointValue;
private int gridSizeY;
private int gridSizeX;
public ShamirsSecretSharingComposite(Composite parent, int style) {
super(parent, style);
setLayout(new GridLayout(2, false));
setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
createCompositeIntro(this);
createGroupSecretSharing(this);
createGroupCurve(this);
}
private void createGroupSecretSharing(Composite parent) {
groupSecretSharing = new Group(parent, SWT.NONE);
groupSecretSharing.setLayout(new GridLayout(2, true));
groupSecretSharing.setText(Messages.ShamirsCompositeGraphical_title);
GridData gd_groupSecretSharing = new GridData(SWT.FILL, SWT.FILL, false, true);
groupSecretSharing.setLayoutData(gd_groupSecretSharing);
createGroupParameter(groupSecretSharing);
createGroupShares(groupSecretSharing);
createGroupInfo(groupSecretSharing);
createGroupReconstruction(groupSecretSharing);
createCompositeReset(groupSecretSharing);
}
private void createCompositeReset(Composite parent) {
Composite resetComposite = new Composite(parent, SWT.NONE);
resetComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
GridLayout gl_resetComposite = new GridLayout(3, false);
resetComposite.setLayout(gl_resetComposite);
resetButton = new Button(resetComposite, SWT.NONE);
resetButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
adjustButtonsForReset();
coefficients = null;
shamirsSecretSharing = null;
shares = null;
result = null;
sharesUseCheckButtonSet = null;
subpolynomial = null;
reconstructedPolynomial = null;
canvasCurve.setBackground(ColorService.WHITE);
canvasCurve.redraw();
}
});
resetButton.setText(Messages.SSSConstants_Reset);
resetButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false));
reconstructPxLabel = new Label(resetComposite, SWT.NONE);
reconstructPxLabel.setEnabled(false);
reconstructPxLabel.setText(Constants.MESSAGE_RECONSTRUCTION);
reconstructPxLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
stValue = new StyledText(resetComposite, SWT.READ_ONLY | SWT.BORDER);
stValue.setEnabled(false);
GridData gd_stValue = new GridData(SWT.FILL, SWT.CENTER, true, false);
stValue.setLayoutData(gd_stValue);
}
/**
* Created the info header. Plugin title + description.
*/
private void createCompositeIntro(Composite parent) {
Composite compositeIntro = new Composite(parent, SWT.NONE);
compositeIntro.setBackground(ColorService.WHITE);
compositeIntro.setLayout(new GridLayout());
GridData gd_compositeIntro = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
gd_compositeIntro.widthHint = 1000;
compositeIntro.setLayoutData(gd_compositeIntro);
Label label = new Label(compositeIntro, SWT.NONE);
label.setFont(FontService.getHeaderFont());
label.setBackground(ColorService.WHITE);
label.setText(Messages.ShamirsCompositeGraphical_title);
Text stDescription = new Text(compositeIntro, SWT.READ_ONLY | SWT.WRAP);
stDescription.setBackground(ColorService.WHITE);
stDescription.setText(Messages.SSSConstants_Title_Info + " "
+ Messages.SSSConstants_Title_Info_Formula + " "
+ Messages.lagrange_formular); //$NON-NLS-1$ //$NON-NLS-2$
stDescription.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
}
/**
* Creates the share group
*/
private void createGroupShares(Composite parent) {
groupShares = new Group(parent, SWT.NONE);
groupShares.setLayout(new GridLayout());
groupShares.setText("Shares");
groupShares.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
scrolledShares = new ScrolledComposite(groupShares, SWT.V_SCROLL | SWT.BORDER);
GridData gd_scrolledShares = new GridData(SWT.FILL, SWT.FILL, true, true);
scrolledShares.setExpandHorizontal(true);
gd_scrolledShares.heightHint = 110;
scrolledShares.setLayoutData(gd_scrolledShares);
compositeShares = new Composite(scrolledShares, SWT.NONE);
compositeShares.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 10;
compositeShares.setLayout(gridLayout);
sharesButtonComposite = new Composite(groupShares, SWT.NONE);
sharesButtonComposite.setLayout(new GridLayout(2, false));
sharesButtonComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
selectAllButton = new Button(sharesButtonComposite, SWT.NONE);
selectAllButton.setEnabled(false);
selectAllButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
for (int i = 0; i < sharesUseCheckButtonSet.length; i++) {
sharesUseCheckButtonSet[i].setSelection(true);
}
reconstructButton.setEnabled(true);
canvasCurve.redraw();
}
});
selectAllButton.setText(Messages.SSSConstants_Select_All_Button);
selectAllButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
deselectAllButton = new Button(sharesButtonComposite, SWT.NONE);
deselectAllButton.setEnabled(false);
deselectAllButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
for (int i = 0; i < sharesUseCheckButtonSet.length; i++) {
sharesUseCheckButtonSet[i].setSelection(false);
}
reconstructButton.setEnabled(false);
canvasCurve.redraw();
}
});
deselectAllButton.setText(Messages.SSSConstants_Deselect_All_Button);
deselectAllButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
scrolledShares.setContent(compositeShares);
compositeShares.pack();
}
/**
* Creates the parameter group
*/
private void createGroupParameter(Composite parent) {
groupParameter = new Group(parent, SWT.NONE);
groupParameter.setLayout(new GridLayout(6, false));
final GridData gd_groupParameter = new GridData(SWT.FILL, SWT.FILL, false, false);
groupParameter.setLayoutData(gd_groupParameter);
groupParameter.setText(Messages.SSSConstants_Select_Parameter);
numberOfConcernedLabel = new Label(groupParameter, SWT.NONE);
numberOfConcernedLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1));
numberOfConcernedLabel.setText(Messages.SSSConstants_Concerned_Persons);
spnrN = new Spinner(groupParameter, SWT.BORDER);
spnrN.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
spnrT.setMaximum(spnrN.getSelection());
spnrT.setSelection(spnrT.getSelection());
}
});
spnrN.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
spnrN.setMinimum(2);
spnrN.setMaximum(500);
spnrN.setSelection(4);
numberForReconstructionLabel = new Label(groupParameter, SWT.NONE);
numberForReconstructionLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1));
numberForReconstructionLabel.setText(Messages.SSSConstants_reconstruct_Person);
spnrT = new Spinner(groupParameter, SWT.BORDER);
spnrT.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
if (spnrT.getSelection() >= spnrN.getSelection()) {
spnrT.setMaximum(spnrT.getSelection() + 1);
spnrN.setSelection(spnrT.getSelection());
}
}
});
spnrT.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
spnrT.setMinimum(2);
spnrT.setMaximum(3);
spnrT.setSelection(3);
modulLabel = new Label(groupParameter, SWT.NONE);
modulLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1));
modulLabel.setText(Messages.SSSConstants_Modul_info);
ModifyListener modulAndSecretEmptyListener = new ModifyListener () {
public void modifyText(ModifyEvent e) {
if (!secretText.getText().isEmpty() && !modulText.getText().isEmpty()) {
selectCoefficientButton.setEnabled(true);
} else {
selectCoefficientButton.setEnabled(false);
}
}
};
modulText = new Text(groupParameter, SWT.BORDER);
modulText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
modulText.setText("23");
numberOnlyVerifyListenerModul = new VerifyListener() {
public void verifyText(VerifyEvent e) {
/*
* keyCode == 8 is BACKSPACE and keyCode == 48 is ZERO and keyCode == 127 is DEL
*/
if (e.text.matches("[0-9]") || e.keyCode == 8 || e.keyCode == 127) { //$NON-NLS-1$
if (modulText.getText().length() == 0 && e.text.compareTo("0") == 0) { //$NON-NLS-1$
e.doit = false;
} else if (modulText.getSelection().x == 0 && e.keyCode == 48) {
e.doit = false;
} else {
e.doit = true;
}
} else {
e.doit = false;
}
}
};
modulText.addVerifyListener(numberOnlyVerifyListenerModul);
modulText.addModifyListener(modulAndSecretEmptyListener);
secretLabel = new Label(groupParameter, SWT.NONE);
secretLabel.setText(Messages.SSSConstants_Secret_Info);
secretLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1));
secretText = new Text(groupParameter, SWT.BORDER);
secretText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
secretText.setText("8");
numberOnlyVerifyListenerSecret = new VerifyListener() {
public void verifyText(VerifyEvent e) {
/*
* keyCode == 8 is BACKSPACE and keyCode == 48 is ZERO and keyCode == 127 is DEL
*/
if (e.text.matches("[0-9]") || e.keyCode == 8 || e.keyCode == 127) { //$NON-NLS-1$
if (secretText.getText().length() == 0 && e.text.compareTo("0") == 0) { //$NON-NLS-1$
e.doit = false;
} else if (secretText.getSelection().x == 0 && e.keyCode == 48) {
e.doit = false;
} else {
e.doit = true;
}
} else {
e.doit = false;
}
}
};
secretText.addVerifyListener(numberOnlyVerifyListenerSecret);
secretText.addModifyListener(modulAndSecretEmptyListener);
coefficentLabel = new Label(groupParameter, SWT.NONE);
coefficentLabel.setText(Messages.SSSConstants_Coefficient);
coefficentLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1));
selectCoefficientButton = new Button(groupParameter, SWT.NONE);
selectCoefficientButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
int statusPrime = 0;
int statusSecret = 0;
result = new String[2];
result[0] = modulText.getText();
result[1] = secretText.getText();
coefficients = new BigInteger[spnrT.getSelection()];
String tmpModul = modulText.getText();
String tmpSecret = secretText.getText();
/*
* check if the input(modul and secret) isEmpty
*/
if (tmpModul.length() > 0 && tmpSecret.length() > 0) {
boolean isPrime = false;
modul = new BigInteger(tmpModul);
secret = new BigInteger(tmpSecret);
isPrime = modul.isProbablePrime(2000000);
if (modul.compareTo(new BigInteger(spnrT.getText())) >= 0) {
/*
* check if the modul is prime
*/
if (!isPrime) {
PrimeDialog primeDialog = new PrimeDialog(getDisplay().getActiveShell(), modul, result);
statusPrime = primeDialog.open();
if (statusPrime == 0) {
modulText.removeVerifyListener(numberOnlyVerifyListenerModul);
modulText.setText(result[0]);
modul = new BigInteger(modulText.getText());
modulText.addVerifyListener(numberOnlyVerifyListenerModul);
}
}
/*
* check if the secret is smaller than the modul
*/
if (secret.compareTo(modul) >= 0 && statusPrime != 1) {
SecretDialog secretDialog = new SecretDialog(getDisplay().getActiveShell(), secret, result);
statusSecret = secretDialog.open();
if (statusSecret == 0) {
secretText.removeVerifyListener(numberOnlyVerifyListenerSecret);
secretText.setText(result[1]);
secret = new BigInteger(secretText.getText());
secretText.addVerifyListener(numberOnlyVerifyListenerSecret);
}
}
/*
* if the precondition is correct and the input is not empty than select the coefficients
*/
if (statusPrime == 0 && statusSecret == 0) {
CoefficientDialog cdialog = new CoefficientDialog(getDisplay().getActiveShell(), spnrT
.getSelection(), secret, coefficients, modul);
int statusCoefficient = cdialog.open();
if (statusCoefficient == 0) {
/*
* make a polynomial string
*/
polynomialString = createPolynomialString(coefficients);
StyleRange stPolynomStyle = new StyleRange();
stPolynomStyle.start = 0;
stPolynomStyle.length = polynomialString.length();
stPolynomStyle.fontStyle = SWT.BOLD;
stPolynomStyle.foreground = Constants.BLUE;
stPolynom.setText(polynomialString);
stPolynom.setStyleRange(stPolynomStyle);
if (polynomialString.isEmpty()) {
computeSharesButton.setEnabled(false);
} else {
computeSharesButton.setEnabled(true);
}
modulText.setEnabled(false);
secretText.setEnabled(false);
spnrN.setEnabled(false);
spnrT.setEnabled(false);
spnrN.setEnabled(false);
spnrT.setEnabled(false);
selectCoefficientButton.setEnabled(false);
}
}
}
}
}
});
selectCoefficientButton.setText(Messages.SSSConstants_Select);
selectCoefficientButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
selectCoefficientButton.setEnabled(true);
polynomLabel = new Label(groupParameter, SWT.NONE);
polynomLabel.setText(Messages.SSSConstants_Polynom_Info);
polynomLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 6, 1));
pxLabel = new Label(groupParameter, SWT.NONE);
pxLabel.setText("P(x):");
pxLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
stPolynom = new StyledText(groupParameter, SWT.READ_ONLY | SWT.BORDER);
stPolynom.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 5, 1));
computeSharesButton = new Button(groupParameter, SWT.NONE);
computeSharesButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
BigInteger n = new BigInteger(String.valueOf(spnrN.getSelection()));
BigInteger t = new BigInteger(String.valueOf(spnrT.getSelection()));
modul = new BigInteger(modulText.getText());
shares = new Point[n.intValue()];
for (int j = 0; j < shares.length; j++) {
shares[j] = new Point(new BigInteger(String.valueOf(j + 1)));
}
shamirsSecretSharing = new ShamirsSecretSharing(t, n, modul);
shamirsSecretSharing.setCoefficient(coefficients);
shares = shamirsSecretSharing.computeShares(shares);
createShares(shares.length);
computeSharesButton.setEnabled(false);
selectAllButton.setEnabled(true);
deselectAllButton.setEnabled(true);
canvasCurve.redraw();
}
});
computeSharesButton.setEnabled(false);
computeSharesButton.setText(Messages.SSSConstants_Compute_Share_Button);
computeSharesButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 6, 1));
}
/**
* creates the shares
*
* @param n number of share rows
*/
private void createShares(int n) {
sharesUseCheckButtonSet = new Button[n];
for (int i = 0; i < n; i++) {
Label sharesPLabel = new Label(compositeShares, SWT.NONE);
sharesPLabel.setText("Share " + (i + 1));
sharesPLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Label sharesEquivalentLabel = new Label(compositeShares, SWT.NONE);
sharesEquivalentLabel.setText("=");
sharesEquivalentLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Label sharesOpenBracetLabel = new Label(compositeShares, SWT.NONE);
sharesOpenBracetLabel.setText("(");
sharesOpenBracetLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Label sharesXCoordinateLabel = new Label(compositeShares, SWT.NONE);
sharesXCoordinateLabel.setText(String.valueOf(i + 1));
sharesXCoordinateLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Label sharesSeperatorLabel = new Label(compositeShares, SWT.NONE);
sharesSeperatorLabel.setText("|");
sharesSeperatorLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
shareYCoordinateModText = new Text(compositeShares, SWT.READ_ONLY | SWT.BORDER);
shareYCoordinateModText.setText(shares[i].getY().mod(modul).toString());
GridData gd_sharesYCoordinateModText = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd_sharesYCoordinateModText.widthHint = 50;
shareYCoordinateModText.setLayoutData(gd_sharesYCoordinateModText);
Label shareCongruenceLabel = new Label(compositeShares, SWT.NONE);
shareCongruenceLabel.setText(Constants.uCongruence);
shareCongruenceLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
sharesYCoordinateText = new Text(compositeShares, SWT.READ_ONLY | SWT.BORDER);
sharesYCoordinateText.setText(shares[i].getY().toString());
GridData gd_sharesYCoordinateText = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd_sharesYCoordinateText.widthHint = 70;
sharesYCoordinateText.setLayoutData(gd_sharesYCoordinateText);
Label sharesCloseBarcetLabel = new Label(compositeShares, SWT.NONE);
sharesCloseBarcetLabel.setText(")");
sharesCloseBarcetLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Button sharesUseCheckButton = new Button(compositeShares, SWT.CHECK);
sharesUseCheckButton.setLayoutData(new GridData(SWT.NONE, SWT.CENTER, false, false));
sharesUseCheckButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
int checkButtonCounter = 0;
for (int j = 0; j < sharesUseCheckButtonSet.length; j++) {
if (sharesUseCheckButtonSet[j].getSelection()) {
checkButtonCounter++;
}
}
if (checkButtonCounter >= 2) {
reconstructButton.setEnabled(true);
} else {
reconstructButton.setEnabled(false);
}
canvasCurve.redraw();
}
});
sharesUseCheckButtonSet[i] = sharesUseCheckButton;
}
compositeShares.pack();
}
/**
* Creates the info group
*/
private void createGroupInfo(Composite parent) {
Group infoGroup = new Group(parent, SWT.NONE);
// infoGroup.setEnabled(false);
infoGroup.setText(Messages.SSSConstants_Info_Group);
final GridData gd_infoGroup = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_infoGroup.widthHint = 250;
infoGroup.setLayoutData(gd_infoGroup);
infoGroup.setLayout(new GridLayout());
infoText = new Text(infoGroup, SWT.WRAP | SWT.READ_ONLY | SWT.MULTI | SWT.BORDER);
infoText.setEnabled(false);
infoText.setEditable(false);
final GridData gd_infoText = new GridData(SWT.FILL, SWT.FILL, true, false);
infoText.setLayoutData(gd_infoText);
infoText.setText(Messages.Reconstruct_Info + "\n" + Constants.LAGRANGE_FORMULAR + "\n" + Constants.LAGRANGE_FORMULAR_RANGE); //$NON-NLS-1$ //$NON-NLS-2$
stInfo = new StyledText(infoGroup, SWT.WRAP | SWT.BORDER);
stInfo.setEditable(false);
// stInfo.setEnabled(false);
final GridData gd_stInfo = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_stInfo.heightHint = 80;
stInfo.setLayoutData(gd_stInfo);
}
/**
* Creates the reconstruction group
*/
private void createGroupReconstruction(Composite parent) {
groupReconstruction = new Group(parent, SWT.NONE);
groupReconstruction.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
groupReconstruction.setLayout(new GridLayout());
groupReconstruction.setText(Messages.SSSConstants_Reconstruction_Group);
reconstructButton = new Button(groupReconstruction, SWT.NONE);
reconstructButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
/*
* clear the composite for the next visualization
*/
Control[] tmpWidgets = compositeReconstruction.getChildren();
for (int i = 0; i < tmpWidgets.length; i++) {
tmpWidgets[i].dispose();
}
compositeReconstruction.pack();
Vector<Point> tmpPointSet = new Vector<Point>();
for (int i = 0; i < sharesUseCheckButtonSet.length; i++) {
if (sharesUseCheckButtonSet[i].getSelection()) {
tmpPointSet.add(shares[i]);
}
}
Point[] pointSet = new Point[tmpPointSet.size()];
for (int i = 0; i < tmpPointSet.size(); i++) {
pointSet[i] = tmpPointSet.get(i);
}
reconstructedPolynomial = shamirsSecretSharing.interpolatePoints(pointSet, modul);
subpolynomial = shamirsSecretSharing.getSubPolynomialNumerical();
createReconstruction(subpolynomial.size());
String tmpPolynomial = createPolynomialString(reconstructedPolynomial);
if (tmpPolynomial.charAt(0) == '0' && tmpPolynomial.length() > 1) {
tmpPolynomial = tmpPolynomial.substring(4);
}
stValue.setText(tmpPolynomial);
StyleRange styleValue = new StyleRange();
StyleRange styleInfo = new StyleRange();
styleValue.start = 0;
styleInfo.start = 0;
styleValue.length = stValue.getText().length();
if (comparePolynomial(reconstructedPolynomial, coefficients)) {
styleValue.foreground = Constants.GREEN;
stInfo.setForeground(Constants.BLACK);
stInfo.setText(MessageFormat.format(Messages.SSSConstants_Polynom_Equal, secretText.getText()));
stInfo.setBackground(Constants.GREEN);
} else {
styleValue.foreground = Constants.RED;
// Count how many checkboxes are selected.
int counterSelectedShares = 0;
for (Button btn : sharesUseCheckButtonSet) {
counterSelectedShares = btn.getSelection() ? counterSelectedShares + 1 : counterSelectedShares;
}
stInfo.setText(MessageFormat.format(Messages.SSSConstants_Polynom_Not_Equal, counterSelectedShares, spnrT.getSelection()));
stInfo.setBackground(Constants.RED);
}
styleInfo.length = stInfo.getText().length();
styleInfo.fontStyle = SWT.BOLD;
styleValue.fontStyle = SWT.BOLD;
stInfo.setStyleRange(styleInfo);
stValue.setStyleRange(styleValue);
reconstructPxLabel.setEnabled(true);
canvasCurve.redraw();
}
});
reconstructButton.setEnabled(false);
reconstructButton.setText(Messages.SSSConstants_Reconstrct);
reconstructButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
scrolledReconstruction = new ScrolledComposite(groupReconstruction, SWT.V_SCROLL | SWT.BORDER);
scrolledReconstruction.setExpandHorizontal(true);
final GridData gd_scrolledReconstruction = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_scrolledReconstruction.heightHint = 109;
scrolledReconstruction.setLayoutData(gd_scrolledReconstruction);
compositeReconstruction = new Composite(scrolledReconstruction, SWT.NONE);
compositeReconstruction.setLocation(0, 0);
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
compositeReconstruction.setLayout(gridLayout);
/*
* BEGIN dummy for design only
*/
// final Label w_1Label = new Label(compositeReconstruction, SWT.NONE);
// w_1Label.setText("w_1");
// final Label label = new Label(compositeReconstruction, SWT.NONE);
// label.setText("=");
// text_1 = new Text(compositeReconstruction, SWT.BORDER);
// text_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
// false));
// compositeReconstruction.setSize(253, 80);
/*
* END dummy
*/
scrolledReconstruction.setContent(compositeReconstruction);
compositeReconstruction.pack();
}
/**
* Creates the subpolynomial
*
* @param n the number of subpolynomial rows
*/
private void createReconstruction(int n) {
for (int i = 0; i < n; i++) {
Label reconstructionLabel = new Label(compositeReconstruction, SWT.NONE);
reconstructionLabel.setText("w" + convertToSubset(i));
Label reconstructEquivalentLabel = new Label(compositeReconstruction, SWT.NONE);
reconstructEquivalentLabel.setText("=");
Text reconstructPolynomial = new Text(compositeReconstruction, SWT.READ_ONLY | SWT.BORDER);
String polynomString = createPolynomialString(subpolynomial.get(i));
if (polynomString.charAt(0) == '0' && polynomString.length() > 1) {
reconstructPolynomial.setText(polynomString.substring(4));
} else {
reconstructPolynomial.setText(polynomString);
}
GridData gd_reconstructPolynomial = new GridData(SWT.FILL, SWT.CENTER, true, false);
reconstructPolynomial.setLayoutData(gd_reconstructPolynomial);
}
compositeReconstruction.pack();
}
/**
* converts an array containing coefficients to a polynomial string
*
* @param coefficients
* @return a string representation of a polynomial
*/
private String createPolynomialString(BigInteger[] coefficients) {
String result = ""; //$NON-NLS-1$
for (int i = 0; i < coefficients.length; i++) {
if (i == 0) {
result = coefficients[i].toString() + " "; //$NON-NLS-1$
} else {
BigInteger bi = coefficients[i];
if (bi.compareTo(BigInteger.ZERO) != 0) {
if (bi.compareTo(BigInteger.ZERO) < 0) {
if (bi.compareTo(Constants.MINUS_ONE) == 0) {
result += "-x" + convertToSuperscript(i) + " "; //$NON-NLS-1$ //$NON-NLS-2$
} else {
result += coefficients[i] + "x" + convertToSuperscript(i) + " "; //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
if (bi.compareTo(BigInteger.ONE) == 0) {
result += "+ " + "x" + convertToSuperscript(i) + " "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else {
result += "+ " + coefficients[i] + "x" + convertToSuperscript(i) + " "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
}
}
result = result.trim();
return result;
}
/**
* compares two BigInterger array equality
*
* @param a a BigInteger array
* @param b a BigInteger array
* @return true if the arrays are equal otherwise false
*/
private boolean comparePolynomial(BigInteger[] a, BigInteger[] b) {
boolean result = true;
int n;
if (a.length < b.length) {
n = a.length;
} else {
n = b.length;
}
for (int i = 0; i < n; i++) {
if (!a[i].mod(modul).equals(b[i].mod(modul))) {
result = false;
}
}
return result;
}
/**
* Convert a number to a superscript index
*
* @param id is the number to be converted
* @return a string which contains only superscript
*/
private String convertToSuperscript(int id) {
char[] data = String.valueOf(id).toCharArray();
StringBuilder result = new StringBuilder();
if (id == 0 || id == 1)
return ""; //$NON-NLS-1$
for (int i = 0; i < data.length; i++) {
if (data[i] == '2')
result.append(Constants.sTwo);
else if (data[i] == '3')
result.append(Constants.sThree);
else if (data[i] == '4')
result.append(Constants.sFour);
else if (data[i] == '5')
result.append(Constants.sFive);
else if (data[i] == '6')
result.append(Constants.sSix);
else if (data[i] == '7')
result.append(Constants.sSeven);
else if (data[i] == '8')
result.append(Constants.sEight);
else if (data[i] == '9')
result.append(Constants.sNine);
}
return result.toString();
}
/**
* Converts the id value to subscript
*
* @param id
* @return a subscript converted string
*/
private String convertToSubset(int id) {
char[] data = String.valueOf(id).toCharArray();
String result = ""; //$NON-NLS-1$
for (int i = 0; i < data.length; i++) {
if (data[i] == '0')
result += Constants.uZero;
if (data[i] == '1')
result += Constants.uOne;
if (data[i] == '2')
result += Constants.uTwo;
if (data[i] == '3')
result += Constants.uThree;
if (data[i] == '4')
result += Constants.uFour;
if (data[i] == '5')
result += Constants.uFive;
if (data[i] == '6')
result += Constants.uSix;
if (data[i] == '7')
result += Constants.uSeven;
if (data[i] == '8')
result += Constants.uEight;
if (data[i] == '9')
result += Constants.uNine;
}
return result;
}
/**
* reset the control elements
*/
public void adjustButtonsForReset() {
spnrN.setEnabled(true);
// spnrN.setSelection(4);
// spnrN.setMinimum(2);
// spnrN.setMaximum(500);
spnrT.setEnabled(true);
// spnrT.setSelection(3);
// spnrT.setMinimum(2);
// spnrT.setMaximum(3);
computeSharesButton.setEnabled(false);
// secret = null;
// modul = null;
// secretText.removeVerifyListener(numberOnlyVerifyListenerSecret);
// secretText.setText("8"); //$NON-NLS-1$
secretText.setEnabled(true);
secretText.addVerifyListener(numberOnlyVerifyListenerSecret);
// modulText.removeVerifyListener(numberOnlyVerifyListenerModul);
// modulText.setText("23"); //$NON-NLS-1$
modulText.setEnabled(true);
modulText.addVerifyListener(numberOnlyVerifyListenerModul);
stPolynom.setText(""); //$NON-NLS-1$
polynomialString = ""; //$NON-NLS-1$
stPolynom.setEnabled(true);
selectCoefficientButton.setEnabled(true);
computeSharesButton.setEnabled(false);
reconstructButton.setEnabled(false);
selectAllButton.setEnabled(false);
deselectAllButton.setEnabled(false);
Control[] tmpWidgets = compositeShares.getChildren();
for (int i = 0; i < tmpWidgets.length; i++) {
tmpWidgets[i].dispose();
}
compositeShares.pack();
tmpWidgets = compositeReconstruction.getChildren();
for (int i = 0; i < tmpWidgets.length; i++) {
tmpWidgets[i].dispose();
}
compositeReconstruction.pack();
stValue.setText(""); //$NON-NLS-1$
stInfo.setText(""); //$NON-NLS-1$
stInfo.setBackground(Constants.WHITE);
reconstructPxLabel.setEnabled(false);
}
private void createGroupCurve(Composite parent) {
groupCurve = new Group(parent, SWT.NONE);
groupCurve.setLayout(new GridLayout(11, false));
groupCurve.setText("Graph");
final GridData gd_groupCurve = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_groupCurve.heightHint = 558;
groupCurve.setLayoutData(gd_groupCurve);
createCanvasCurve();
sharePointInfo = new Composite(groupCurve, SWT.NONE);
sharePointInfo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 11, 1));
sharePointInfo.setLayout(new GridLayout(8, false));
final Label dummyLabel = new Label(sharePointInfo, SWT.NONE);
dummyLabel.setText("dummy"); //$NON-NLS-1$
dummyLabel.setVisible(false);
shareLabel = new Label(sharePointInfo, SWT.NONE);
shareLabel.setText("Share"); //$NON-NLS-1$
shareLabel.setVisible(false);
openLabel = new Label(sharePointInfo, SWT.NONE);
openLabel.setText("("); //$NON-NLS-1$
openLabel.setVisible(false);
xText = new Text(sharePointInfo, SWT.READ_ONLY | SWT.BORDER);
final GridData gd_xText = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd_xText.heightHint = 20;
xText.setLayoutData(gd_xText);
xText.setVisible(false);
seperatorLabel = new Label(sharePointInfo, SWT.NONE);
seperatorLabel.setText("|"); //$NON-NLS-1$
seperatorLabel.setVisible(false);
yText = new Text(sharePointInfo, SWT.READ_ONLY | SWT.BORDER);
final GridData gd_yText = new GridData(SWT.FILL, SWT.CENTER, true, false);
gd_yText.heightHint = 20;
yText.setLayoutData(gd_yText);
yText.setVisible(false);
closeLabel = new Label(sharePointInfo, SWT.NONE);
closeLabel.setText(")"); //$NON-NLS-1$
closeLabel.setVisible(false);
final Label phLabel = new Label(sharePointInfo, SWT.NONE);
phLabel.setText("ph"); //$NON-NLS-1$
phLabel.setVisible(false);
}
/**
* Creates the canvas group
*/
private void createCanvasCurve() {
canvasCurve = new Canvas(groupCurve, SWT.NONE);
canvasCurve.addMouseMoveListener(new MouseMoveListener() {
public void mouseMove(final MouseEvent e) {
mousePosX = e.x;
mousePosY = e.y;
if (shares != null) {
Point point = nearSharePoint(shares, mousePosX, mousePosY);
if (point != null) {
xText.setText(point.getX().toString());
yText.setText(point.getY().toString());
makePointVisible(true);
} else if (pointValue == Integer.MAX_VALUE) {
boolean found = false;
for (int i = 0; i < shares.length; i++) {
int tmpX = shares[i].getX().intValue() * 60 + xAxisGap;
int tmpY = 408 + 1 * 6;
if ((tmpX - 3 == mousePosX || tmpX - 2 == mousePosX || tmpX - 1 == mousePosX
|| tmpX == mousePosX || tmpX + 1 == mousePosX || tmpX + 2 == mousePosX || tmpX + 3 == mousePosX)
&& (tmpY - 3 == mousePosY || tmpY - 2 == mousePosY || tmpY - 1 == mousePosY
|| tmpY == mousePosY || tmpY + 1 == mousePosY || tmpY + 2 == mousePosY || tmpY + 3 == mousePosY)) {
xText.setText(shares[i].getX().toString());
yText.setText(shares[i].getY().toString());
found = true;
}
}
if (found) {
makePointVisible(true);
} else {
makePointVisible(false);
}
} else {
makePointVisible(false);
}
}
}
});
canvasCurve.setBackground(Constants.WHITE);
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 11, 1);
gridData.widthHint = 506;
canvasCurve.setLayoutData(gridData);
canvasCurve.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
if (!polynomialString.isEmpty()) {
drawPolynomial(e);
}
}
});
}
private Point nearSharePoint(Point[] sharePoints, int x, int y) {
Point point = null;
for (int i = 0; i < sharePoints.length; i++) {
int tmpX = sharePoints[i].getX().intValue() * 60 + xAxisGap;
int tmpY = yAxisGap - sharePoints[i].getY().intValue() * 6;
if ((tmpX - 3 == x || tmpX - 2 == x || tmpX - 1 == x || tmpX == x || tmpX + 1 == x || tmpX + 2 == x || tmpX + 3 == x)
&& (tmpY - 3 == y || tmpY - 2 == y || tmpY - 1 == y || tmpY == y || tmpY + 1 == y || tmpY + 2 == y || tmpY + 3 == y)) {
point = sharePoints[i];
return point;
}
}
return point;
}
private void makePointVisible(boolean visible) {
shareLabel.setVisible(visible);
openLabel.setVisible(visible);
xText.setVisible(visible);
seperatorLabel.setVisible(visible);
yText.setVisible(visible);
closeLabel.setVisible(visible);
}
private int getMaxXCoord() {
int tmp = 0;
for (Point p : shares) {
if (p.getY().intValue() > tmp) {
tmp = p.getY().intValue();
}
}
return tmp;
}
/**
* @param e the PaintEvent that represents the graphic context
*/
private void drawPolynomial(PaintEvent e) {
GC gc = e.gc;
gc.setLineWidth(0);
//canvasCurve.setSize(getMaxXCoord(), getMaxYCoord());
org.eclipse.swt.graphics.Point size = canvasCurve.getSize();
int maxX = getMaxXCoord();
gridSizeY = 1;
gridSizeX = 60;
if (maxX <= 50) {
gridSizeY = 7;
gridSizeX = 60;
} else if (maxX <= 100) {
gridSizeY = 6;
gridSizeX = 60;
} else if (maxX <= 150) {
gridSizeY = 4;
gridSizeX = 60;
} else if (maxX <= 220) {
gridSizeY = 2;
gridSizeX = 60;
}
gc.setForeground(Constants.LIGHTGREY);
/*
* draw the grid in x direction
*/
xAxisGap = 0;
for (int i = 0; i < size.x; i += gridSizeX) {
if (xAxisGap + gridSizeX <= size.x / 2) {
xAxisGap += gridSizeX;
}
xAxisGap = gridSizeX;
//x axis lines
gc.drawLine(i, 0, i, size.y);
}
/*
* draw the grid in y direction
*/
yAxisGap = 0;
for (int i = 0; i < size.y; i += gridSizeY) {
if (yAxisGap + gridSizeY <= size.y / 2) {
yAxisGap += gridSizeY;
}
yAxisGap = gridSizeY * ((size.y / gridSizeY)) - 20;
if (maxX <= 150) {
gc.drawLine(0, i, size.x, i);
} else if (i % (gridSizeY * 5) == 0) {
gc.drawLine(0, i, size.x, i);
}
}
int labeljumps = 1;
int gapSmall = 3;
int gapBig = 7;
int textOffset = gapBig + 8;
int fontWidth = 6;
int fontHeight = 10;
int numberLength = 0;
/*
* draw the axis
*/
gc.setForeground(Constants.BLACK);
gc.drawLine(xAxisGap, 0, xAxisGap, size.y);
gc.drawLine(0, yAxisGap, size.x, yAxisGap);
/*
* draw the x marker
*/
int i = 0;
for (int x = xAxisGap; x < size.x; x += gridSizeX) {
i++;
numberLength = String.valueOf(i).length();
/*
* thin lines
*/
gc.drawLine(x, yAxisGap - gapSmall, x, yAxisGap + gapSmall);
gc.drawLine(xAxisGap - i * gridSizeX, yAxisGap - gapSmall, xAxisGap - i * gridSizeX, yAxisGap + gapSmall);
/*
* thick lines
*/
if ((i - 1) % labeljumps == 0) {
gc.drawLine(x, yAxisGap - gapBig, x, yAxisGap + gapBig);
gc.drawLine(xAxisGap - i * labeljumps * gridSizeX, yAxisGap - gapBig, xAxisGap - i * labeljumps
* gridSizeX, yAxisGap + gapBig);
if (i != 1) {
gc.drawText(String.valueOf(i - 1), x - (fontWidth * numberLength) / 2, yAxisGap - gapBig
+ textOffset, true);
gc.drawText(String.valueOf(i - 1), xAxisGap - i * labeljumps * gridSizeX, yAxisGap + gapBig, true);
}
}
}
//determine label jump
if (maxX <= 150){
labeljumps = 10;
} else if (maxX <= 250) {
labeljumps = 20;
} else {
labeljumps = 40;
}
/*
* draw the y markers
*/
i = 0;
for (int y = yAxisGap; y >= 0; y -= gridSizeY) {
i++;
numberLength = String.valueOf(i).length();
/*
* thin lines
*/
if (maxX <= 150) {
gc.drawLine(xAxisGap - gapSmall, y, xAxisGap + gapSmall, y);
gc.drawLine(xAxisGap - gapSmall, yAxisGap + i * gridSizeY, xAxisGap + gapSmall, yAxisGap + i * gridSizeY);
}
/*
* thick lines
*/
if ((i - 1) % labeljumps == 0) {
gc.drawLine(xAxisGap - gapBig, y, xAxisGap + gapBig, y);
gc.drawLine(xAxisGap - gapBig, yAxisGap + i * labeljumps * gridSizeY, xAxisGap + gapBig, yAxisGap + i
* labeljumps * gridSizeY);
if (i != 1) {
gc.drawText(String.valueOf(i - 1), xAxisGap - gapBig - (fontWidth * numberLength) - 3, y
- fontHeight / 2 - 4, true);
}
}
}
gc.drawText(String.valueOf(-5), xAxisGap - gapBig - 2 - (fontWidth * numberLength), yAxisGap + 5 * gridSizeY
- 8, true);
/*
* new GraphicContent for drawing the polynomial curve
*/
GC polynomial = gc;
// GC polynomial = new GC(gc.getDevice());
Path polynomPath = new Path(null);
float dx = 0.1f / gridSizeY;
polynomPath.moveTo(-10, valueAt(-10));
for (float x = -10.0f; x < size.x / 2; x += dx) {
polynomPath.lineTo(x, valueAt(x));
}
polynomial.setForeground(Constants.BLUE);
// Transform polynomTransform = new Transform(gc.getDevice());
// polynomTransform.translate(xAxisGap, yAxisGap);
// polynomTransform.scale(gridSizeX, -gridSizeY);
// polynomial.setTransform(polynomTransform);
this.drawPath(polynomial, polynomPath, gridSizeX, -gridSizeY, xAxisGap, yAxisGap);
/*
* new GraphicContent for drawing the reconstructed polynomial curve
*/
if (stValue.getText().length() > 0) {
GC subPolynomial = gc;
// GC subPolynomial = new GC(gc.getDevice());
Transform subPolynomialTransform = new Transform(gc.getDevice());
subPolynomialTransform.translate(xAxisGap, yAxisGap);
subPolynomialTransform.scale(gridSizeX, -gridSizeY);
Path subPolynomialPath = new Path(null);
subPolynomialPath.moveTo(-10, valueAt(-10));
for (float x = -10.0f; x < size.x / 2; x += dx) {
subPolynomialPath.lineTo(x, valueAtReconstruction(x));
}
if (comparePolynomial(coefficients, reconstructedPolynomial)) {
subPolynomial.setForeground(Constants.GREEN);
} else {
subPolynomial.setForeground(Constants.RED);
}
// subPolynomial.setTransform(polynomTransform);
this.drawPath(subPolynomial, subPolynomialPath, gridSizeX, -gridSizeY, xAxisGap, yAxisGap);
// subPolynomial.dispose();
}
/*
* new GraphicContent for drawing shares points
*/
GC points = gc;
// GC points = new GC(gc.getDevice());
Transform pointTransform = new Transform(gc.getDevice());
pointTransform.translate(xAxisGap, yAxisGap);
// points.setTransform(pointTransform);
pointValue = (int) valueAt(shares.length);
for (int k = 1; k <= shares.length; k++) {
if (sharesUseCheckButtonSet[k - 1].getSelection()) {
points.setBackground(Constants.RED);
} else {
points.setBackground(Constants.DARKPURPLE);
}
if (pointValue == Integer.MAX_VALUE) {
this.fillOval(points, gridSizeX * k - 3, (pointValue) * -gridSizeY - 3, 6, 6, 1.0f, 1.0f, xAxisGap, yAxisGap);
// points.fillOval(gridSizeX * k - 3, (pointValue) * -gridSizeY - 3, 6, 6);
} else {
this.fillOval(points, gridSizeX * k - 3, ((int) valueAt(k)) * -gridSizeY - 3, 6, 6, 1.0f, 1.0f, xAxisGap, yAxisGap);
// points.fillOval(gridSizeX * k - 3, ((int) valueAt(k)) * -gridSizeY - 3, 6, 6);
}
}
// polynomial.dispose();
// points.dispose();
}
private void fillOval(GC gc, int x, int y, int w, int h, float scaleX, float scaleY, float translateX, float translateY) {
Transform prevTf = new Transform(gc.getDevice());
gc.getTransform(prevTf);
// gc.setTransform(tf);
Transform scaleTf= new Transform(gc.getDevice());
scaleTf.scale(scaleX, scaleY);
Transform transTf= new Transform(gc.getDevice());
transTf.translate(translateX, translateY);
Transform fullTf = new Transform(gc.getDevice());
fullTf.multiply(transTf);
fullTf.multiply(scaleTf);
float xTfd = x;
float yTfd = y;
float wTfd = w;
float hTfd = h;
float[] pt = new float[] {xTfd,yTfd};
float[] wh = new float[] {wTfd,hTfd};
fullTf.transform(pt);
scaleTf.transform(wh);
gc.fillOval((int) Math.round(pt[0]), (int) Math.round(pt[1]), (int) Math.round(wh[0]), (int) Math.round(wh[1]));
// gc.setTransform(prevTf);
}
private void drawPath(GC gc, Path path, float scaleX, float scaleY, int translateX, int translateY) {
Path transformed = new Path(gc.getDevice());
PathData pd = path.getPathData();
Transform scaleTf= new Transform(gc.getDevice());
scaleTf.scale(scaleX, scaleY);
Transform transTf= new Transform(gc.getDevice());
transTf.translate(translateX, translateY);
Transform fullTf = new Transform(gc.getDevice());
fullTf.multiply(transTf);
fullTf.multiply(scaleTf);
int i=0;
float xTfd = -1000;
float yTfd = -1000;
for (float el: pd.points) {
if(i % 2 == 1) {
yTfd = el;
float[] point=new float[] {xTfd, yTfd};
fullTf.transform(point);
if (i == 1) {
transformed.moveTo(point[0], point[1]);
}
transformed.lineTo(point[0], point[1]);
} else {
xTfd = el;
}
i++;
}
gc.drawPath(transformed);
//gc.setTransform(prevTf);
}
/**
* compute the y value for a given x value for the original polynomial
*
* @param x is the point to evaluate
* @return the corresponding y value
*/
private float valueAt(float x) {
float value = 0;
for (int i = 0; i < coefficients.length; i++) {
value += coefficients[i].intValue() * Math.pow(x, i);
}
return value;
}
/**
* compute the y value for a given x value for the reconstructed polynomial
*
* @param x is the point to evaluate
* @return the corresponding y value
*/
private float valueAtReconstruction(float x) {
float value = 0;
for (int i = 0; i < reconstructedPolynomial.length; i++) {
value += reconstructedPolynomial[i].intValue() * Math.pow(x, i);
}
return value;
}
}
|
package org.lamport.tla.toolbox.tool.tlc.traceexplorer;
import java.util.Vector;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.lamport.tla.toolbox.Activator;
import org.lamport.tla.toolbox.tool.ToolboxHandle;
import org.lamport.tla.toolbox.tool.tlc.launch.TraceExplorerDelegate;
import org.lamport.tla.toolbox.tool.tlc.model.Formula;
import org.lamport.tla.toolbox.tool.tlc.model.TraceExpressionModelWriter;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.ModelEditor;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.provider.FormulaContentProvider;
import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper;
import org.lamport.tla.toolbox.tool.tlc.ui.view.TLCErrorView;
import org.lamport.tla.toolbox.tool.tlc.ui.wizard.FormulaWizard;
import org.lamport.tla.toolbox.tool.tlc.util.ModelHelper;
/**
* This is somewhat mislabeled as a composite. Its really
* a wrapper class for a section.
*
* This contains a section which contains a table that is populated
* with items that have a checkbox next to them to indicate if they should
* be used in the run of the trace explorer.
*
* There are five buttons to the right of the table: Add, Remove, Edit, Explore, and Restore.
* Explore launches the trace explorer and restore restores the old trace without any expressions
* from the trace explorer section.
*
* {@link TraceExplorerComposite#sectionInitialize(FormToolkit)} is called within the constructor
* to setup the widgets for the section (i.e. table, table viewer, buttons).
*
* {@link TraceExplorerComposite#doAdd()} is called when the user clicks the add button.
*
* {@link TraceExplorerComposite#doEdit()} is called when the user clicks the edit button.
*
* {@link TraceExplorerComposite#doRemove()} is called when the user clicks the remove button.
*
* {@link TraceExplorerComposite#doExplore()} is called when the user clicks the explore button.
*
* {@link TraceExplorerComposite#doRestore()} is called when the user clicks the explore button.
*/
public class TraceExplorerComposite
{
private static final String EXPANDED_STATE = "EXPANDED_STATE";
protected CheckboxTableViewer tableViewer;
private Button buttonAdd;
private Button buttonEdit;
private Button buttonRemove;
private Button buttonExplore;
private Button buttonRestore;
private Section section;
private TLCErrorView view;
// a listener reacting on button clicks
// this calls the appropriate method when a user
// clicks a button next to the table
protected SelectionListener fSelectionListener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e)
{
Object source = e.getSource();
if (source == buttonAdd)
{
doAdd();
} else if (source == buttonRemove)
{
doRemove();
} else if (source == buttonEdit)
{
doEdit();
} else if (source == buttonExplore)
{
doExplore();
} else if (source == buttonRestore)
{
doRestore();
}
}
};
// a listener reacting on selection in the table viewer
// this calls the method that changes button enablement
// depending on whether a formula is selected or not
protected ISelectionChangedListener fSelectionChangedListener = new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event)
{
Object source = event.getSource();
if (source != null && source == tableViewer)
{
changeButtonEnablement();
}
}
};
public TraceExplorerComposite(Composite parent, String title, String description, FormToolkit toolkit,
TLCErrorView errorView)
{
view = errorView;
section = FormHelper.createSectionComposite(parent, title, description, toolkit, Section.DESCRIPTION
| Section.TITLE_BAR | Section.TREE_NODE | Section.EXPANDED, null);
/*
* We want the section to take up the excess horizontal space so that it spans the entire
* error view, but we dont want it to take up the excess vertical space because that
* allows the sash form containing the trace and the variable viewer to expand into
* the space left behind when the trace explorer table section is contracted.
*
* This assumes the trace explorer table section is on top of this sash form.
* I haven't tested to see if it will work when the trace explorer section is on the bottom.
*/
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false);
section.setLayoutData(gd);
sectionInitialize(toolkit);
// Initially, we want the section to be expanded for users to recognize the
// error-trace exploration feature. If a user collapses the section, it will
// remain collapsed.
final IDialogSettings dialogSettings = Activator.getDefault().getDialogSettings();
if (dialogSettings.get(EXPANDED_STATE) != null) {
final boolean expand = dialogSettings.getBoolean(EXPANDED_STATE);
section.setExpanded(expand);
} else {
section.setExpanded(true);
}
section.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
final IDialogSettings dialogSettings = Activator.getDefault().getDialogSettings();
dialogSettings.put(EXPANDED_STATE, section.isExpanded());
}
});
}
/**
* Constructs the section content
*
* This consists of setting the layout for the
* client area of the section, creating the table
* for the section, creating the table viewer, and
* creating the buttons.
*
* @param toolkit
*/
protected void sectionInitialize(FormToolkit toolkit)
{
GridData gd;
// create the composite
Composite sectionArea = (Composite) section.getClient();
sectionArea.setLayout(new GridLayout(2, false));
// create the table
Table table = createTable(sectionArea, toolkit);
// The table grabs the entire space in the section
gd = new GridData(GridData.FILL_BOTH);
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
// span for the buttons
// there are currently 5 buttons, each occupying one
// cell, so the table must span 5 vertical cells
gd.verticalSpan = 5;
table.setLayoutData(gd);
// create the table viewer
tableViewer = createTableViewer(table);
// create buttons
createButtons(sectionArea, toolkit);
// setup the buttons
changeButtonEnablement();
}
/**
* This creates the table viewer. It should be called
* within {@link TraceExplorerComposite#sectionInitialize(FormToolkit)}.
* @param table
* @return
*/
protected CheckboxTableViewer createTableViewer(Table table)
{
// create
CheckboxTableViewer tableViewer = new CheckboxTableViewer(table);
// represent formulas in the view
tableViewer.setContentProvider(new FormulaContentProvider());
// on changed selection change button enablement
tableViewer.addSelectionChangedListener(fSelectionChangedListener);
// edit on double-click on a formula
tableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event)
{
doEdit();
}
});
// save the input when an element is checked or unchecked
tableViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event)
{
view.getModel().save(new NullProgressMonitor());
}
});
tableViewer.setInput(new Vector());
return tableViewer;
}
/**
* Creates the table to be put into the tableviewer. It should be called
* within {@link TraceExplorerComposite#sectionInitialize(FormToolkit)}.
*
* @param sectionArea
* @return
*/
protected Table createTable(Composite sectionArea, FormToolkit toolkit)
{
Table table = toolkit.createTable(sectionArea, SWT.MULTI | SWT.CHECK | SWT.V_SCROLL | SWT.H_SCROLL
| SWT.FULL_SELECTION);
table.setLinesVisible(false);
table.setHeaderVisible(false);
return table;
}
/**
* Creates buttons. Currently, this creates the following buttons:
*
* Add
* Edit
* Remove
* Explore
* Restore
*
*/
protected void createButtons(Composite sectionArea, FormToolkit toolkit)
{
final GridData gd = new GridData();
gd.verticalAlignment = SWT.TOP;
gd.horizontalAlignment = SWT.FILL;
// add button
buttonAdd = toolkit.createButton(sectionArea, "Add", SWT.PUSH);
buttonAdd.addSelectionListener(fSelectionListener);
buttonAdd.setLayoutData(GridDataFactory.copyData(gd));
// edit button
buttonEdit = toolkit.createButton(sectionArea, "Edit", SWT.PUSH);
buttonEdit.addSelectionListener(fSelectionListener);
buttonEdit.setLayoutData(GridDataFactory.copyData(gd));
// remove button
buttonRemove = toolkit.createButton(sectionArea, "Remove", SWT.PUSH);
buttonRemove.addSelectionListener(fSelectionListener);
buttonRemove.setLayoutData(GridDataFactory.copyData(gd));
// explore button
buttonExplore = toolkit.createButton(sectionArea, "Explore", SWT.PUSH);
buttonExplore.addSelectionListener(fSelectionListener);
buttonExplore.setLayoutData(GridDataFactory.copyData(gd));
// restore button
buttonRestore = toolkit.createButton(sectionArea, "Restore", SWT.PUSH);
buttonRestore.addSelectionListener(fSelectionListener);
buttonRestore.setLayoutData(GridDataFactory.copyData(gd));
}
/**
* Retrieves the table viewer
* @return
*/
public TableViewer getTableViewer()
{
return tableViewer;
}
/**
* Remove the selected formulas
*/
protected void doRemove()
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
Vector input = (Vector) tableViewer.getInput();
input.removeAll(selection.toList());
tableViewer.setInput(input);
changeButtonEnablement();
view.getModel().setTraceExplorerExpression(FormHelper.getSerializedInput(tableViewer));
}
/**
* Add a formula to the list
*/
protected void doAdd()
{
Formula formula = doEditFormula(null);
// add a formula
if (formula != null)
{
@SuppressWarnings("unchecked")
Vector<Formula> input = ((Vector<Formula>) tableViewer.getInput());
input.add(formula);
tableViewer.setInput(input);
if (tableViewer instanceof CheckboxTableViewer)
{
((CheckboxTableViewer) tableViewer).setChecked(formula, true);
}
changeButtonEnablement();
view.getModel().setTraceExplorerExpression(FormHelper.getSerializedInput(tableViewer));
}
}
/**
* Edit selected formula
*/
protected void doEdit()
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
Formula formula = (Formula) selection.getFirstElement();
Formula editedFormula = doEditFormula(formula);
if (editedFormula != null)
{
formula.setFormula(editedFormula.getFormula());
if (tableViewer instanceof CheckboxTableViewer)
{
((CheckboxTableViewer) tableViewer).setChecked(formula, true);
}
tableViewer.refresh();
}
changeButtonEnablement();
view.getModel().setTraceExplorerExpression(FormHelper.getSerializedInput(tableViewer));
}
/**
* Runs the trace explorer with the expressions
* that are in the table.
*/
private void doExplore()
{
/*
* Check for module TE in spec.
* Cannot run trace explorer if the spec contains a module named TE.
*/
String rootModuleFileName = ToolboxHandle.getRootModule().getName();
if (ModelHelper.containsTraceExplorerModuleConflict(rootModuleFileName))
{
MessageDialog.openError(view.getSite().getShell(), "Illegal module name",
"Trace exploration is not allowed for a spec that contains a module named "
+ ModelHelper.TE_MODEL_NAME + ".");
return;
}
/*
* Check for validation errors.
*
* If there is a validation error in the model, switch to a page
* with an error, display a message to the user indicating that
* the trace explorer cannot be run with a validation error, and
* do not run the trace explorer.
*
* If a model editor is not open on this model, then it is not
* currently possible to check for validation errors, so the
* trace explorer cannot be run.
*/
final ModelEditor modelEditor = view.getModel().getAdapter(ModelEditor.class);
if (modelEditor == null)
{
// the model editor must be open to run the trace explorer
// in order to detect validation errors
// the model editor is null, so show a message to the user
// and do not run the trace explorer
MessageDialog
.openError(
view.getSite().getShell(),
"Trace exploration not allowed",
"There is no model editor open on this model. The trace explorer cannot be run without opening the model editor on this model.");
return;
} else if (!modelEditor.isComplete())
{
// validation error
MessageDialog.openError(view.getSite().getShell(), "Trace exploration not allowed",
"The model contains errors, which should be corrected before running the trace explorer.");
// do not run trace explorer
return;
}
// Save model without validating.
// Validating would erase MC.out, which we dont want
// the trace explorer to do.
// This could erase a trace that was produced
// after a three week run of TLC.
modelEditor.doSaveWithoutValidating((new NullProgressMonitor()));
// save the launch configuration
// if the trace is empty, then do nothing
if (!view.getTrace().isTraceEmpty())
{
// TraceExplorerHelper.serializeTrace(modelConfig);
// Wrap the launch in a WorkspaceJob to guarantee that the
// operation is executed atomically from the workspace perspective.
// If the runnable would be omitted, the launch can become interleaved with
// workspace (autobuild) jobs triggered by IResourceChange events.
// The Toolbox's IResourceChangeListeners reacting to resource change events
// run the SANY parser and SANY does not support concurrent execution.
final Job job = new WorkspaceJob("Exploring the trace...") {
public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
view.getModel().save(monitor).launch(TraceExplorerDelegate.MODE_TRACE_EXPLORE, monitor, true);
return Status.OK_STATUS;
}
};
job.setRule(ResourcesPlugin.getWorkspace().getRoot());
job.setUser(true);
job.schedule();
tableViewer.getTable().setEnabled(false);
buttonExplore.setEnabled(false);
buttonAdd.setEnabled(false);
buttonEdit.setEnabled(false);
buttonRemove.setEnabled(false);
buttonRestore.setEnabled(true);
}
}
/**
* Restores the original trace produced by the last run of TLC for model checking (not trace exploration).
*/
private void doRestore()
{
// set the model to have the original trace shown
view.setOriginalTraceShown(true);
// update the error view with this provider
view.updateErrorView();
tableViewer.getTable().setEnabled(true);
buttonExplore.setEnabled(true);
buttonAdd.setEnabled(true);
buttonEdit.setEnabled(true);
buttonRemove.setEnabled(true);
buttonRestore.setEnabled(false);
}
/**
* If a formula in the table is selected, then enable the
* Remove and Edit buttons, else disable them.
*/
protected void changeButtonEnablement()
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
if (!tableViewer.getTable().isEnabled()) {
return;
}
if (buttonRemove != null)
{
buttonRemove.setEnabled(!selection.isEmpty());
}
if (buttonEdit != null)
{
buttonEdit.setEnabled(selection.size() == 1);
}
if (buttonExplore != null)
{
buttonExplore.setEnabled(view.getTrace() != null && !view.getTrace().isTraceEmpty()
&& tableViewer.getCheckedElements().length > 0);
}
}
/**
* Sets the explore button enablement status to isTrace.
* @param isTrace
*/
public void changeExploreEnablement(boolean isTrace)
{
buttonExplore.setEnabled(isTrace);
}
/**
* Opens a dialog for formula processing and returns the edited formula
* @param formula initial formula, can be <code>null</code>
* @return result of editing or <code>null</code>, if editing canceled
*/
protected Formula doEditFormula(Formula formula)
{
// Create the wizard
FormulaWizard wizard = new FormulaWizard(section.getText(),
"Enter an expression to be evaluated at each state of the trace.",
String.format(
"The expression may be named and may include the %s and %s operators (click question mark below for details).",
TraceExpressionModelWriter.TRACE, TraceExpressionModelWriter.POSITION),
"ErrorTraceExplorerExpression");
wizard.setFormula(formula);
// Create the wizard dialog
WizardDialog dialog = new WizardDialog(getTableViewer().getTable().getShell(), wizard);
dialog.setHelpAvailable(true);
// Open the wizard dialog
if (Window.OK == dialog.open())
{
return wizard.getFormula();
} else
{
return null;
}
}
}
|
package de.avgl.dmp.persistence.service.schema.test.internalmodel;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.junit.Ignore;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sun.mail.imap.protocol.Namespaces.Namespace;
import de.avgl.dmp.persistence.GuicedTest;
import de.avgl.dmp.persistence.model.schema.Attribute;
import de.avgl.dmp.persistence.model.schema.AttributePath;
import de.avgl.dmp.persistence.model.schema.NameSpacePrefixRegistry;
import de.avgl.dmp.persistence.model.schema.Schema;
import de.avgl.dmp.persistence.model.schema.proxy.ProxySchema;
import de.avgl.dmp.persistence.service.schema.SchemaService;
import de.avgl.dmp.persistence.service.test.IDBasicJPAServiceTest;
public class InternalSchemaBuilderTest extends GuicedTest {
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(InternalSchemaBuilderTest.class);
private final ObjectMapper objectMapper = GuicedTest.injector.getInstance(ObjectMapper.class);
private Map<Long, Attribute> attributes = Maps.newLinkedHashMap();
private static final String NL = System.lineSeparator();
@Ignore
@Test
public void buildInternalSchema() {
InternalSchemaBuilder schemaBuilder = new InternalSchemaBuilder();
Schema internalSchema = schemaBuilder.buildInternalSchema();
printSchemaJSON(internalSchema);
printSchemaText(internalSchema);
printSchemaTextAsPrefixPaths(schemaBuilder);
}
private void printSchemaTextAsPrefixPaths(InternalSchemaBuilder schemaBuilder) {
System.out.println("****************************************************");
System.out.println("Schema as prefix paths");
System.out.println("****************************************************");
System.out.println(schemaBuilder.getPrefixPaths());
System.out.println("****************************************************");
}
public void printSchemaJSON(Schema schema){
String json = null;
try {
json = objectMapper.writeValueAsString(schema);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("****************************************************");
System.out.println("Schema as json: " + json);
System.out.println("****************************************************");
}
public void printSchemaText(Schema schema){
System.out.println("****************************************************");
System.out.println("Schema for " + schema.getRecordClass().getUri() );
System.out.println("****************************************************");
Set<AttributePath> pathSet = schema.getAttributePaths();
for (Iterator<AttributePath> iterator = pathSet.iterator(); iterator.hasNext();) {
AttributePath attributePath = (AttributePath) iterator.next();
printAttributePath(attributePath);
}
System.out.println("****************************************************");
}
public static void printAttributePath(AttributePath path){
System.out.println(path.toAttributePath().replace("", " :: "));
}
}
|
package ua.com.fielden.platform.serialisation.jackson.serialisers;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.meta.MetaProperty;
import ua.com.fielden.platform.reflection.PropertyTypeDeterminator;
import ua.com.fielden.platform.reflection.Reflector;
import ua.com.fielden.platform.serialisation.jackson.EntitySerialiser;
import ua.com.fielden.platform.serialisation.jackson.EntitySerialiser.CachedProperty;
import ua.com.fielden.platform.serialisation.jackson.EntityType;
import ua.com.fielden.platform.serialisation.jackson.JacksonContext;
import ua.com.fielden.platform.serialisation.jackson.References;
import ua.com.fielden.platform.utils.Pair;
import static ua.com.fielden.platform.serialisation.jackson.DefaultValueContract.*;
public class EntityJsonSerialiser<T extends AbstractEntity<?>> extends StdSerializer<T> {
private final Class<T> type;
private final Logger logger = Logger.getLogger(getClass());
private final List<CachedProperty> properties;
private final EntityType entityType;
private final boolean excludeNulls;
public EntityJsonSerialiser(final Class<T> type, final List<CachedProperty> properties, final EntityType entityType, final boolean excludeNulls) {
super(type);
if (entityType.get_number() == null) {
throw new IllegalStateException("The number of the type [" + entityType + "] should be populated to be ready for serialisation.");
}
this.type = type;
this.properties = properties;
this.entityType = entityType;
this.excludeNulls = excludeNulls;
}
@Override
public void serialize(final T entity, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
///////////////// handle references ////////////////
final JacksonContext context = EntitySerialiser.getContext();
References references = (References) context.getTemp(EntitySerialiser.ENTITY_JACKSON_REFERENCES);
if (references == null) {
// Use non-temporary storage to avoid repeated allocation.
references = (References) context.get(EntitySerialiser.ENTITY_JACKSON_REFERENCES);
if (references == null) {
context.put(EntitySerialiser.ENTITY_JACKSON_REFERENCES, references = new References());
} else {
references.reset();
}
context.putTemp(EntitySerialiser.ENTITY_JACKSON_REFERENCES, references);
}
final String reference = references.getReference(entity);
if (reference != null) {
generator.writeStartObject();
generator.writeFieldName("@id_ref");
generator.writeObject(reference);
generator.writeEndObject();
} else {
final String newReference = EntitySerialiser.newSerialisationId(entity, references, entityType.get_number());
references.putReference(entity, newReference);
generator.writeStartObject();
generator.writeFieldName("@id");
generator.writeObject(newReference);
final boolean uninstrumented = !PropertyTypeDeterminator.isInstrumented(entity.getClass());
if (uninstrumented) {
generator.writeFieldName("@uninstrumented");
generator.writeObject(null);
}
// serialise id
generator.writeFieldName(AbstractEntity.ID);
generator.writeObject(entity.getId());
// serialise version -- should never be null
generator.writeFieldName(AbstractEntity.VERSION);
if (Reflector.isPropertyProxied(entity, AbstractEntity.VERSION)) {
generator.writeObject(Long.valueOf(0L));
} else {
generator.writeObject(entity.getVersion());
}
// serialise all the properties relying on the fact that property sequence is consistent with order of fields in the class declaration
for (final CachedProperty prop : properties) {
// non-composite keys should be persisted by identifying their actual type
final String name = prop.field().getName();
if (!Reflector.isPropertyProxied(entity, name)) {
Object value = null;
try {
// at this stage the field should be already accessible
value = prop.field().get(entity);
} catch (final IllegalAccessException e) {
// developer error -- please ensure that all fields are accessible
e.printStackTrace();
logger.error("The field [" + prop.field() + "] is not accessible. Fatal error during serialisation process for entity [" + entity + "].", e);
throw new RuntimeException(e);
} catch (final IllegalArgumentException e) {
e.printStackTrace();
logger.error("The field [" + prop.field() + "] is not declared in entity with type [" + type.getName() + "]. Fatal error during serialisation process for entity [" + entity + "].", e);
throw e;
}
if (value != null || !excludeNulls) {
// write actual property
generator.writeFieldName(name);
generator.writeObject(value);
if (!uninstrumented) {
final MetaProperty<Object> metaProperty = entity.getProperty(name);
if (metaProperty == null) {
throw new IllegalStateException(String.format("Meta property [%s] does not exist for instrumented entity instance with type [%s].", name, entity.getClass().getSimpleName()));
}
final Map<String, Object> existingMetaProps = new LinkedHashMap<>();
if (!isEditableDefault(metaProperty)) {
existingMetaProps.put("_" + MetaProperty.EDITABLE_PROPERTY_NAME, getEditable(metaProperty));
}
if (!isChangedFromOriginalDefault(metaProperty)) {
existingMetaProps.put("_cfo", getChangedFromOriginal(metaProperty));
existingMetaProps.put("_originalVal", getOriginalValue(metaProperty));
}
if (!isRequiredDefault(metaProperty)) {
existingMetaProps.put("_" + MetaProperty.REQUIRED_PROPERTY_NAME, getRequired(metaProperty));
}
if (!isVisibleDefault(metaProperty)) {
existingMetaProps.put("_visible", getVisible(metaProperty));
}
if (!isValidationResultDefault(metaProperty)) {
existingMetaProps.put("_validationResult", getValidationResult(metaProperty));
}
final Pair<Integer, Integer> minMax = Reflector.extractValidationLimits(entity, name);
final Integer min = minMax.getKey();
final Integer max = minMax.getValue();
if (!isMinDefault(min)) {
existingMetaProps.put("_min", min);
}
if (!isMaxDefault(max)) {
existingMetaProps.put("_max", max);
}
// write actual meta-property
if (!existingMetaProps.isEmpty()) {
generator.writeFieldName("@" + name);
generator.writeStartObject();
for (final Map.Entry<String, Object> nameAndVal : existingMetaProps.entrySet()) {
generator.writeFieldName(nameAndVal.getKey());
generator.writeObject(nameAndVal.getValue());
}
generator.writeEndObject();
}
}
}
}
}
generator.writeEndObject();
}
}
}
|
package test.javauno.acquire;
import com.sun.star.bridge.UnoUrlResolver;
import com.sun.star.bridge.XBridgeFactory;
import com.sun.star.bridge.XInstanceProvider;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.connection.Acceptor;
import com.sun.star.connection.XAcceptor;
import com.sun.star.connection.XConnection;
import com.sun.star.lib.uno.helper.UnoUrl;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.XInterface;
import util.WaitUnreachable;
public final class TestAcquire {
public static void main(String[] arguments) throws Exception {
// - arguments[0] must be "client" or "server"
// - arguments[1] must be the UNO URL to connect to (client) or accept
// on (server)
XComponentContext context
= Bootstrap.createInitialComponentContext(null);
if (arguments[0].equals("client")) {
execClient(context, arguments[1]);
} else {
execServer(context, arguments[1]);
}
}
private static void assertNotNull(Object obj) {
if (obj == null) {
throw new RuntimeException("assertNotNull failed");
}
}
private static void receive(Object obj) {
assertNotNull(obj);
WaitUnreachable.ensureFinalization(obj);
}
private static void execClient(XComponentContext context, String url)
throws Exception
{
XTest test = (XTest) UnoRuntime.queryInterface(
XTest.class, UnoUrlResolver.create(context).resolve(url));
WaitUnreachable u;
u = new WaitUnreachable(new XInterface() {});
test.setInterfaceToInterface((XInterface) u.get());
receive(test.getInterfaceFromInterface());
test.clearInterface();
u.waitUnreachable();
u = new WaitUnreachable(new XBase() {});
test.setInterfaceToInterface((XBase) u.get());
receive(test.getInterfaceFromInterface());
test.clearInterface();
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
test.setInterfaceToInterface((XDerived) u.get());
receive(test.getInterfaceFromInterface());
test.clearInterface();
u.waitUnreachable();
u = new WaitUnreachable(new XBase() {});
test.setBaseToInterface((XBase) u.get());
receive(test.getInterfaceFromInterface());
test.clearInterface();
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
test.setBaseToInterface((XDerived) u.get());
receive(test.getInterfaceFromInterface());
test.clearInterface();
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
test.setDerivedToInterface((XDerived) u.get());
receive(test.getInterfaceFromInterface());
test.clearInterface();
u.waitUnreachable();
u = new WaitUnreachable(new XBase() {});
test.setBaseToBase((XBase) u.get());
receive(test.getInterfaceFromBase());
receive(test.getBaseFromBase());
test.clearBase();
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
test.setBaseToBase((XDerived) u.get());
receive(test.getInterfaceFromBase());
receive(test.getBaseFromBase());
test.clearBase();
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
test.setDerivedToBase((XDerived) u.get());
receive(test.getInterfaceFromBase());
receive(test.getBaseFromBase());
test.clearBase();
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
test.setDerivedToDerived((XDerived) u.get());
receive(test.getInterfaceFromDerived());
receive(test.getBaseFromDerived());
receive(test.getDerivedFromDerived());
test.clearDerived();
u.waitUnreachable();
u = new WaitUnreachable(new XInterface() {});
receive(test.roundTripInterfaceToInterface((XInterface) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(new XBase() {});
receive(test.roundTripInterfaceToInterface((XBase) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
receive(test.roundTripInterfaceToInterface((XDerived) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(new XBase() {});
receive(test.roundTripBaseToInterface((XBase) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
receive(test.roundTripBaseToInterface((XDerived) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
receive(test.roundTripDerivedToInterface((XDerived) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(new XBase() {});
receive(test.roundTripBaseToBase((XBase) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
receive(test.roundTripBaseToBase((XDerived) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
receive(test.roundTripDerivedToBase((XDerived) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(new XDerived() {});
receive(test.roundTripDerivedToDerived((XDerived) u.get()));
u.waitUnreachable();
u = new WaitUnreachable(test);
test = null;
u.waitUnreachable();
System.out.println(
"Client and server both cleanly terminate now: Success");
}
private static void execServer(XComponentContext context, String url)
throws Exception
{
XAcceptor acceptor = Acceptor.create(context);
XBridgeFactory factory = (XBridgeFactory) UnoRuntime.queryInterface(
XBridgeFactory.class,
context.getServiceManager().createInstanceWithContext(
"com.sun.star.bridge.BridgeFactory", context));
UnoUrl unoUrl = UnoUrl.parseUnoUrl(url);
System.out.println("Server: Accepting...");
XConnection connection = acceptor.accept(
unoUrl.getConnectionAndParametersAsString());
System.out.println("Server: ...connected...");
factory.createBridge(
"", unoUrl.getProtocolAndParametersAsString(), connection,
new Provider());
System.out.println("Server: ...bridged.");
}
private static final class Provider implements XInstanceProvider {
public Object getInstance(String instanceName) {
return new XTest() {
public void setInterfaceToInterface(Object obj) {
iface = obj;
}
public void setBaseToInterface(XBase obj) {
iface = obj;
}
public void setDerivedToInterface(XDerived obj) {
iface = obj;
}
public Object getInterfaceFromInterface() {
return iface;
}
public void clearInterface() {
WaitUnreachable u = new WaitUnreachable(iface);
iface = null;
u.waitUnreachable();
}
public void setBaseToBase(XBase obj) {
base = obj;
}
public void setDerivedToBase(XDerived obj) {
base = obj;
}
public Object getInterfaceFromBase() {
return base;
}
public XBase getBaseFromBase() {
return base;
}
public void clearBase() {
WaitUnreachable u = new WaitUnreachable(base);
base = null;
u.waitUnreachable();
}
public void setDerivedToDerived(XDerived obj) {
derived = obj;
}
public Object getInterfaceFromDerived() {
return derived;
}
public XBase getBaseFromDerived() {
return derived;
}
public XDerived getDerivedFromDerived() {
return derived;
}
public void clearDerived() {
WaitUnreachable u = new WaitUnreachable(derived);
derived = null;
u.waitUnreachable();
}
public Object roundTripInterfaceToInterface(Object obj) {
WaitUnreachable.ensureFinalization(obj);
return obj;
}
public Object roundTripBaseToInterface(XBase obj) {
WaitUnreachable.ensureFinalization(obj);
return obj;
}
public Object roundTripDerivedToInterface(XDerived obj) {
WaitUnreachable.ensureFinalization(obj);
return obj;
}
public XBase roundTripBaseToBase(XBase obj) {
WaitUnreachable.ensureFinalization(obj);
return obj;
}
public XBase roundTripDerivedToBase(XDerived obj) {
WaitUnreachable.ensureFinalization(obj);
return obj;
}
public XDerived roundTripDerivedToDerived(XDerived obj) {
WaitUnreachable.ensureFinalization(obj);
return obj;
}
private Object iface;
private XBase base;
private XDerived derived;
};
}
}
}
|
package net.sf.cglib;
import java.util.*;
/**
* @version $Id: FactoryCache.java,v 1.7 2003-01-28 11:42:32 nemecec Exp $
*/
/* package */ class FactoryCache {
private final Map cache;
public FactoryCache() {
this(new WeakHashMap());
}
public FactoryCache(Map cache) {
this.cache = cache;
}
public Object get(ClassLoader loader, Object key) {
return getFactoryMap(loader).get(key);
}
public void put(ClassLoader loader, Object key, Object factory) {
getFactoryMap(loader).put(key, factory);
}
private Map getFactoryMap(ClassLoader loader) {
Map factories = (Map)cache.get(loader);
if (factories == null) {
cache.put(loader, factories = new WeakHashMap());
}
return factories;
}
}
|
package net.sf.cglib;
import java.lang.reflect.*;
import java.util.*;
/**
* @author Chris Nokleberg <a href="mailto:chris@nokleberg.com">chris@nokleberg.com</a>
* @version $Id: ReflectUtils.java,v 1.2 2003-01-05 23:55:10 herbyderby Exp $
*/
abstract /* package */ class ReflectUtils {
private static final Map primitives = new HashMap(8);
private static final Map transforms = new HashMap(8);
private static final ClassLoader defaultLoader = MethodConstants.class.getClassLoader();
private static final String[] packages = { "java.lang", "java.lang.reflect", "net.sf.cglib" };
static {
primitives.put("char", Character.TYPE);
primitives.put("double", Double.TYPE);
primitives.put("float", Float.TYPE);
primitives.put("int", Integer.TYPE);
primitives.put("long", Long.TYPE);
primitives.put("short", Short.TYPE);
primitives.put("boolean", Boolean.TYPE);
transforms.put("byte", "B");
transforms.put("char", "C");
transforms.put("double", "D");
transforms.put("float", "F");
transforms.put("int", "I");
transforms.put("long", "J");
transforms.put("short", "S");
transforms.put("boolean", "Z");
}
public static Method findMethod(String desc) {
return findMethod(desc, defaultLoader);
}
public static Method findMethod(String desc, ClassLoader loader) {
try {
int lparen = desc.indexOf('(');
int rparen = desc.indexOf(')', lparen);
int dot = desc.lastIndexOf('.', lparen);
String className = desc.substring(0, dot).trim();
String methodName = desc.substring(dot + 1, lparen).trim();
List params = new ArrayList();
int start = lparen + 1;
for (;;) {
int comma = desc.indexOf(',', start);
if (comma < 0) {
break;
}
params.add(desc.substring(start, comma).trim());
start = comma + 1;
}
if (start < rparen) {
params.add(desc.substring(start, rparen).trim());
}
Class cls = getClass(className, loader);
Class[] types = new Class[params.size()];
for (int i = 0; i < types.length; i++) {
types[i] = getClass((String)params.get(i), loader);
}
return cls.getDeclaredMethod(methodName, types);
} catch (ClassNotFoundException e) {
throw new CodeGenerationException(e);
} catch (NoSuchMethodException e) {
throw new CodeGenerationException(e);
}
}
private static Class getClass(String className, ClassLoader loader) throws ClassNotFoundException {
String save = className;
int dimensions = 0;
int index = 0;
while ((index = className.indexOf("[]", index) + 1) > 0) {
dimensions++;
}
StringBuffer brackets = new StringBuffer(className.length() - dimensions);
for (int i = 0; i < dimensions; i++) {
brackets.append('[');
}
className = className.substring(0, className.length() - 2 * dimensions);
String prefix = (dimensions > 0) ? brackets + "L" : "";
String suffix = (dimensions > 0) ? ";" : "";
try {
return Class.forName(prefix + className + suffix, false, loader);
} catch (ClassNotFoundException ignore) { }
for (int i = 0; i < packages.length; i++) {
try {
return Class.forName(prefix + packages[i] + '.' + className + suffix, false, loader);
} catch (ClassNotFoundException ignore) { }
}
if (dimensions == 0) {
Class c = (Class)primitives.get(className);
if (c != null) {
return c;
}
} else {
String transform = (String)transforms.get(className);
if (transform != null) {
try {
return Class.forName(brackets + transform, false, loader);
} catch (ClassNotFoundException ignore) { }
}
}
throw new ClassNotFoundException(save);
}
public static Class forName(String name, ClassLoader loader) {
try {
return Class.forName(name, false, loader);
} catch (ClassNotFoundException e) {
throw new CodeGenerationException(e);
}
}
public static Object newInstance(Class clazz, Class[] parameterTypes, Object[] args) {
try {
return clazz.getConstructor(parameterTypes).newInstance(args);
} catch (NoSuchMethodException e) {
throw new CodeGenerationException(e);
} catch (InstantiationException e) {
throw new CodeGenerationException(e);
} catch (IllegalAccessException e) {
throw new CodeGenerationException(e);
} catch (InvocationTargetException e) {
throw new CodeGenerationException(e.getTargetException());
}
}
}
|
package com.thoughtworks.xstream;
import java.awt.font.TextAttribute;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.NotActiveException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterLookup;
import com.thoughtworks.xstream.converters.DataHolder;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.SingleValueConverterWrapper;
import com.thoughtworks.xstream.converters.basic.BigDecimalConverter;
import com.thoughtworks.xstream.converters.basic.BigIntegerConverter;
import com.thoughtworks.xstream.converters.basic.BooleanConverter;
import com.thoughtworks.xstream.converters.basic.ByteConverter;
import com.thoughtworks.xstream.converters.basic.CharConverter;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.basic.DoubleConverter;
import com.thoughtworks.xstream.converters.basic.FloatConverter;
import com.thoughtworks.xstream.converters.basic.IntConverter;
import com.thoughtworks.xstream.converters.basic.LongConverter;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.basic.ShortConverter;
import com.thoughtworks.xstream.converters.basic.StringBufferConverter;
import com.thoughtworks.xstream.converters.basic.StringConverter;
import com.thoughtworks.xstream.converters.basic.URLConverter;
import com.thoughtworks.xstream.converters.collections.ArrayConverter;
import com.thoughtworks.xstream.converters.collections.BitSetConverter;
import com.thoughtworks.xstream.converters.collections.CharArrayConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.converters.collections.MapConverter;
import com.thoughtworks.xstream.converters.collections.PropertiesConverter;
import com.thoughtworks.xstream.converters.collections.TreeMapConverter;
import com.thoughtworks.xstream.converters.collections.TreeSetConverter;
import com.thoughtworks.xstream.converters.extended.ColorConverter;
import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.converters.extended.FileConverter;
import com.thoughtworks.xstream.converters.extended.FontConverter;
import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter;
import com.thoughtworks.xstream.converters.extended.JavaClassConverter;
import com.thoughtworks.xstream.converters.extended.JavaMethodConverter;
import com.thoughtworks.xstream.converters.extended.LocaleConverter;
import com.thoughtworks.xstream.converters.extended.SqlDateConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimeConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter;
import com.thoughtworks.xstream.converters.extended.TextAttributeConverter;
import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker;
import com.thoughtworks.xstream.converters.reflection.SerializableConverter;
import com.thoughtworks.xstream.core.BaseException;
import com.thoughtworks.xstream.core.DefaultConverterLookup;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.core.MapBackedDataHolder;
import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy;
import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy;
import com.thoughtworks.xstream.core.TreeMarshallingStrategy;
import com.thoughtworks.xstream.core.util.ClassLoaderReference;
import com.thoughtworks.xstream.core.util.CompositeClassLoader;
import com.thoughtworks.xstream.core.util.CustomObjectInputStream;
import com.thoughtworks.xstream.core.util.CustomObjectOutputStream;
import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.StatefulWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.mapper.ArrayMapper;
import com.thoughtworks.xstream.mapper.AttributeAliasingMapper;
import com.thoughtworks.xstream.mapper.AttributeMapper;
import com.thoughtworks.xstream.mapper.CachingMapper;
import com.thoughtworks.xstream.mapper.ClassAliasingMapper;
import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper;
import com.thoughtworks.xstream.mapper.DefaultMapper;
import com.thoughtworks.xstream.mapper.DynamicProxyMapper;
import com.thoughtworks.xstream.mapper.EnumMapper;
import com.thoughtworks.xstream.mapper.FieldAliasingMapper;
import com.thoughtworks.xstream.mapper.ImmutableTypesMapper;
import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.thoughtworks.xstream.mapper.OuterClassMapper;
import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper;
/**
* Simple facade to XStream library, a Java-XML serialization tool. <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* XStream xstream = new XStream();
* String xml = xstream.toXML(myObject); // serialize to XML
* Object myObject2 = xstream.fromXML(xml); // deserialize from XML
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Aliasing classes</h3>
* <p/>
* <p>
* To create shorter XML, you can specify aliases for classes using the <code>alias()</code>
* method. For example, you can shorten all occurences of element
* <code><com.blah.MyThing></code> to <code><my-thing></code> by registering an
* alias for the class.
* <p>
* <hr>
* <blockquote>
*
* <pre>
* xstream.alias("my-thing", MyThing.class);
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Converters</h3>
* <p/>
* <p>
* XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each
* of which acts as a strategy for converting a particular type of class to XML and back again. Out
* of the box, XStream contains converters for most basic types (String, Date, int, boolean, etc)
* and collections (Map, List, Set, Properties, etc). For other objects reflection is used to
* serialize each field recursively.
* </p>
* <p/>
* <p>
* Extra converters can be registered using the <code>registerConverter()</code> method. Some
* non-standard converters are supplied in the {@link com.thoughtworks.xstream.converters.extended}
* package and you can create your own by implementing the
* {@link com.thoughtworks.xstream.converters.Converter} interface.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.registerConverter(new SqlTimestampConverter());
* xstream.registerConverter(new DynamicProxyConverter());
* </pre>
*
* </blockquote>
* <hr>
* <p>
* The default converter, ie the converter which will be used if no other registered converter is
* suitable, can be configured by either one of the constructors or can be changed using the
* <code>changeDefaultConverter()</code> method. If not set, XStream uses
* {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the initial default
* converter.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.changeDefaultConverter(new ACustomDefaultConverter());
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Object graphs</h3>
* <p/>
* <p>
* XStream has support for object graphs; a deserialized object graph will keep references intact,
* including circular references.
* </p>
* <p/>
* <p>
* XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using
* <code>setMode()</code>:
* </p>
* <p/> <table border="1">
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td>
* <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML
* with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td>
* <td>Uses XPath absolute references to signify duplicate
* references. This produces XML with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td>
* <td>Uses ID references to signify duplicate references. In some scenarios, such as when using
* hand-written XML, this is easier to work with.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td>
* <td>This disables object graph support and treats the object structure like a tree. Duplicate
* references are treated as two seperate objects and circular references cause an exception. This
* is slightly faster and uses less memory than the other two modes.</td>
* </tr>
* </table>
* <h3>Thread safety</h3>
* <p>
* The XStream instance is thread-safe. That is, once the XStream instance has been created and
* configured, it may be shared across multiple threads allowing objects to be
* serialized/deserialized concurrently.
* <h3>Implicit collections</h3>
* <p/>
* <p>
* To avoid the need for special tags for collections, you can define implicit collections using one
* of the <code>addImplicitCollection</code> methods.
* </p>
*
* @author Joe Walnes
* @author Jörg Schaible
* @author Mauro Talevi
* @author Guilherme Silveira
*/
public class XStream {
// CAUTION: The sequence of the fields is intentional for an optimal XML output of a
// self-serializaion!
private ReflectionProvider reflectionProvider;
private HierarchicalStreamDriver hierarchicalStreamDriver;
private ClassLoaderReference classLoaderReference;
private MarshallingStrategy marshallingStrategy;
private Mapper mapper;
private DefaultConverterLookup converterLookup;
private ClassAliasingMapper classAliasingMapper;
private FieldAliasingMapper fieldAliasingMapper;
private AttributeAliasingMapper attributeAliasingMapper;
private AttributeMapper attributeMapper;
private DefaultImplementationsMapper defaultImplementationsMapper;
private ImmutableTypesMapper immutableTypesMapper;
private ImplicitCollectionMapper implicitCollectionMapper;
private transient JVM jvm = new JVM();
public static final int NO_REFERENCES = 1001;
public static final int ID_REFERENCES = 1002;
public static final int XPATH_RELATIVE_REFERENCES = 1003;
public static final int XPATH_ABSOLUTE_REFERENCES = 1004;
/**
* @deprecated since 1.2, use {@link #XPATH_RELATIVE_REFERENCES} or
* {@link #XPATH_ABSOLUTE_REFERENCES} instead.
*/
public static final int XPATH_REFERENCES = XPATH_RELATIVE_REFERENCES;
public static final int PRIORITY_VERY_HIGH = 10000;
public static final int PRIORITY_NORMAL = 0;
public static final int PRIORITY_LOW = -10;
public static final int PRIORITY_VERY_LOW = -20;
/**
* Constructs a default XStream. The instance will use the {@link XppDriver} as default and tries to determin the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream() {
this(null, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link ReflectionProvider}. The instance will use the {@link XppDriver} as default.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(ReflectionProvider reflectionProvider) {
this(reflectionProvider, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver}. The instance will tries to determin the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) {
this(null, (Mapper)null, hierarchicalStreamDriver);
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider}.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(
ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) {
this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)}
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver) {
this(reflectionProvider, (Mapper)classMapper, driver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)} and
* register classAttributeIdentifier as alias
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver, String classAttributeIdentifier) {
this(reflectionProvider, (Mapper)classMapper, driver);
aliasAttribute(classAttributeIdentifier, "class");
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider} and additionally with a prepared {@link Mapper}.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(
ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) {
jvm = new JVM();
if (reflectionProvider == null) {
reflectionProvider = jvm.bestReflectionProvider();
}
this.reflectionProvider = reflectionProvider;
this.hierarchicalStreamDriver = driver;
this.classLoaderReference = new ClassLoaderReference(new CompositeClassLoader());
this.mapper = mapper == null ? buildMapper() : mapper;
this.converterLookup = new DefaultConverterLookup(this.mapper);
setupMappers();
setupAliases();
setupDefaultImplementations();
setupConverters();
setupImmutableTypes();
setMode(XPATH_RELATIVE_REFERENCES);
}
private Mapper buildMapper() {
Mapper mapper = new DefaultMapper(classLoaderReference);
if ( useXStream11XmlFriendlyMapper() ){
mapper = new XStream11XmlFriendlyMapper(mapper);
}
mapper = new ClassAliasingMapper(mapper);
mapper = new FieldAliasingMapper(mapper);
mapper = new AttributeAliasingMapper(mapper);
mapper = new AttributeMapper(mapper);
mapper = new ImplicitCollectionMapper(mapper);
if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) {
mapper = buildMapperDynamically(
"com.thoughtworks.xstream.mapper.CGLIBMapper",
new Class[]{Mapper.class}, new Object[]{mapper});
}
mapper = new DynamicProxyMapper(mapper);
if (JVM.is15()) {
mapper = new EnumMapper(mapper);
}
mapper = new OuterClassMapper(mapper);
mapper = new ArrayMapper(mapper);
mapper = new DefaultImplementationsMapper(mapper);
mapper = new ImmutableTypesMapper(mapper);
mapper = wrapMapper((MapperWrapper)mapper);
mapper = new CachingMapper(mapper);
return mapper;
}
private Mapper buildMapperDynamically(
String className, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
return (Mapper)constructor.newInstance(constructorParamValues);
} catch (Exception e) {
throw new InitializationException("Could not instatiate mapper : " + className, e);
}
}
protected MapperWrapper wrapMapper(MapperWrapper next) {
return next;
}
protected boolean useXStream11XmlFriendlyMapper() {
return false;
}
private void setupMappers() {
classAliasingMapper = (ClassAliasingMapper)this.mapper
.lookupMapperOfType(ClassAliasingMapper.class);
fieldAliasingMapper = (FieldAliasingMapper)this.mapper
.lookupMapperOfType(FieldAliasingMapper.class);
attributeMapper = (AttributeMapper)this.mapper.lookupMapperOfType(AttributeMapper.class);
attributeAliasingMapper = (AttributeAliasingMapper)this.mapper
.lookupMapperOfType(AttributeAliasingMapper.class);
implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper
.lookupMapperOfType(ImplicitCollectionMapper.class);
defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper
.lookupMapperOfType(DefaultImplementationsMapper.class);
immutableTypesMapper = (ImmutableTypesMapper)this.mapper
.lookupMapperOfType(ImmutableTypesMapper.class);
// should use ctor, but converterLookup is not yet initialized instantiating this mapper
if (attributeMapper != null) {
attributeMapper.setConverterLookup(converterLookup);
}
}
protected void setupAliases() {
if (classAliasingMapper == null) {
return;
}
alias("null", Mapper.Null.class);
alias("int", Integer.class);
alias("float", Float.class);
alias("double", Double.class);
alias("long", Long.class);
alias("short", Short.class);
alias("char", Character.class);
alias("byte", Byte.class);
alias("boolean", Boolean.class);
alias("number", Number.class);
alias("object", Object.class);
alias("big-int", BigInteger.class);
alias("big-decimal", BigDecimal.class);
alias("string-buffer", StringBuffer.class);
alias("string", String.class);
alias("java-class", Class.class);
alias("method", Method.class);
alias("constructor", Constructor.class);
alias("date", Date.class);
alias("url", URL.class);
alias("bit-set", BitSet.class);
alias("map", Map.class);
alias("entry", Map.Entry.class);
alias("properties", Properties.class);
alias("list", List.class);
alias("set", Set.class);
alias("linked-list", LinkedList.class);
alias("vector", Vector.class);
alias("tree-map", TreeMap.class);
alias("tree-set", TreeSet.class);
alias("hashtable", Hashtable.class);
if(jvm.supportsAWT()) {
// Instantiating these two classes starts the AWT system, which is undesirable. Calling
// loadClass ensures a reference to the class is found but they are not instantiated.
alias("awt-color", jvm.loadClass("java.awt.Color"));
alias("awt-font", jvm.loadClass("java.awt.Font"));
alias("awt-text-attribute", TextAttribute.class);
}
if(jvm.supportsSQL()) {
alias("sql-timestamp", Timestamp.class);
alias("sql-time", Time.class);
alias("sql-date", java.sql.Date.class);
}
alias("file", File.class);
alias("locale", Locale.class);
alias("gregorian-calendar", Calendar.class);
// since jdk 1.4 included, but previously available as separate package ...
Class type = jvm.loadClass("javax.security.auth.Subject");
if (type != null) {
alias("auth-subject", type);
}
if (JVM.is14()) {
alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap"));
alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet"));
alias("trace", jvm.loadClass("java.lang.StackTraceElement"));
alias("currency", jvm.loadClass("java.util.Currency"));
aliasType("charset", jvm.loadClass("java.nio.charset.Charset"));
}
if (JVM.is15()) {
alias("enum-set", jvm.loadClass("java.util.EnumSet"));
alias("enum-map", jvm.loadClass("java.util.EnumMap"));
}
}
protected void setupDefaultImplementations() {
if (defaultImplementationsMapper == null) {
return;
}
addDefaultImplementation(HashMap.class, Map.class);
addDefaultImplementation(ArrayList.class, List.class);
addDefaultImplementation(HashSet.class, Set.class);
addDefaultImplementation(GregorianCalendar.class, Calendar.class);
}
protected void setupConverters() {
// use different ReflectionProvider depending on JDK
final ReflectionConverter reflectionConverter;
if (JVM.is15()) {
Class annotationProvider = jvm
.loadClass("com.thoughtworks.xstream.annotations.AnnotationProvider");
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.annotations.AnnotationReflectionConverter",
PRIORITY_VERY_LOW, new Class[]{
Mapper.class, ReflectionProvider.class, annotationProvider},
new Object[]{
mapper, reflectionProvider,
reflectionProvider.newInstance(annotationProvider)});
reflectionConverter = (ReflectionConverter)converterLookup
.lookupConverterForType(Object.class);
} else {
reflectionConverter = new ReflectionConverter(mapper, reflectionProvider);
registerConverter(reflectionConverter, PRIORITY_VERY_LOW);
}
registerConverter(new SerializableConverter(mapper, reflectionProvider), PRIORITY_LOW);
registerConverter(new ExternalizableConverter(mapper), PRIORITY_LOW);
registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
registerConverter(new IntConverter(), PRIORITY_NORMAL);
registerConverter(new FloatConverter(), PRIORITY_NORMAL);
registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
registerConverter(new LongConverter(), PRIORITY_NORMAL);
registerConverter(new ShortConverter(), PRIORITY_NORMAL);
registerConverter(new CharConverter(), PRIORITY_NORMAL);
registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
registerConverter(new ByteConverter(), PRIORITY_NORMAL);
registerConverter(new StringConverter(), PRIORITY_NORMAL);
registerConverter(new StringBufferConverter(), PRIORITY_NORMAL);
registerConverter(new DateConverter(), PRIORITY_NORMAL);
registerConverter(new BitSetConverter(), PRIORITY_NORMAL);
registerConverter(new URLConverter(), PRIORITY_NORMAL);
registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL);
registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL);
registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL);
registerConverter(new CharArrayConverter(), PRIORITY_NORMAL);
registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL);
registerConverter(new MapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL);
registerConverter(new PropertiesConverter(), PRIORITY_NORMAL);
registerConverter(new EncodedByteArrayConverter(), PRIORITY_NORMAL);
registerConverter(new FileConverter(), PRIORITY_NORMAL);
if(jvm.supportsSQL()) {
registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL);
registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL);
registerConverter(new SqlDateConverter(), PRIORITY_NORMAL);
}
registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL);
if(jvm.supportsAWT()) {
registerConverter(new FontConverter(), PRIORITY_NORMAL);
registerConverter(new ColorConverter(), PRIORITY_NORMAL);
registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL);
}
registerConverter(new LocaleConverter(), PRIORITY_NORMAL);
registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL);
// since jdk 1.4 included, but previously available as separate package ...
if (jvm.loadClass("javax.security.auth.Subject") != null) {
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.SubjectConverter",
PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper});
}
if (JVM.is14()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.ThrowableConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.StackTraceElementConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CurrencyConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.RegexPatternConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CharsetConverter",
PRIORITY_NORMAL, null, null);
}
if (JVM.is15()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL,
null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
}
if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) {
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.reflection.CGLIBEnhancedConverter",
PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class},
new Object[]{mapper, reflectionProvider});
}
registerConverter(new SelfStreamingInstanceChecker(reflectionConverter, this), PRIORITY_NORMAL);
}
private void dynamicallyRegisterConverter(
String className, int priority, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
Object instance = constructor.newInstance(constructorParamValues);
if (instance instanceof Converter) {
registerConverter((Converter)instance, priority);
} else if (instance instanceof SingleValueConverter) {
registerConverter((SingleValueConverter)instance, priority);
}
} catch (Exception e) {
throw new InitializationException("Could not instatiate converter : " + className, e);
}
}
protected void setupImmutableTypes() {
if (immutableTypesMapper == null) {
return;
}
// primitives are always immutable
addImmutableType(boolean.class);
addImmutableType(Boolean.class);
addImmutableType(byte.class);
addImmutableType(Byte.class);
addImmutableType(char.class);
addImmutableType(Character.class);
addImmutableType(double.class);
addImmutableType(Double.class);
addImmutableType(float.class);
addImmutableType(Float.class);
addImmutableType(int.class);
addImmutableType(Integer.class);
addImmutableType(long.class);
addImmutableType(Long.class);
addImmutableType(short.class);
addImmutableType(Short.class);
// additional types
addImmutableType(Mapper.Null.class);
addImmutableType(BigDecimal.class);
addImmutableType(BigInteger.class);
addImmutableType(String.class);
addImmutableType(URL.class);
addImmutableType(File.class);
addImmutableType(Class.class);
if(jvm.supportsAWT()) {
addImmutableType(TextAttribute.class);
}
if (JVM.is14()) {
// late bound types - allows XStream to be compiled on earlier JDKs
Class type = jvm.loadClass("com.thoughtworks.xstream.converters.extended.CharsetConverter");
addImmutableType(type);
}
}
public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) {
this.marshallingStrategy = marshallingStrategy;
}
/**
* Serialize an object to a pretty-printed XML String.
* @throws BaseException if the object cannot be serialized
*/
public String toXML(Object obj) {
Writer writer = new StringWriter();
toXML(obj, writer);
return writer.toString();
}
/**
* Serialize an object to the given Writer as pretty-printed XML.
* @throws BaseException if the object cannot be serialized
*/
public void toXML(Object obj, Writer out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize an object to the given OutputStream as pretty-printed XML.
* @throws BaseException if the object cannot be serialized
*/
public void toXML(Object obj, OutputStream out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
* @throws BaseException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer) {
marshal(obj, writer, null);
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
*
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws BaseException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) {
marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder);
}
/**
* Deserialize an object from an XML String.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(String xml) {
return fromXML(new StringReader(xml));
}
/**
* Deserialize an object from an XML Reader.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(Reader xml) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), null);
}
/**
* Deserialize an object from an XML InputStream.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(InputStream input) {
return unmarshal(hierarchicalStreamDriver.createReader(input), null);
}
/**
* Deserialize an object from an XML String, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(String xml, Object root) {
return fromXML(new StringReader(xml), root);
}
/**
* Deserialize an object from an XML Reader, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(Reader xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from an XML InputStream, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(InputStream xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader) {
return unmarshal(reader, null, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML), populating the fields
* of the given root object instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root) {
return unmarshal(reader, root, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
*
* @param root If present, the passed in object will have its fields populated, as opposed to
* XStream creating a new instance.
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addClassAlias(name, type);
}
/**
* Alias a type to a shorter name to be used in XML elements.
* Any class that is assignable to this type will be aliased to the same name.
*
* @param name Short name
* @param type Type to be aliased
* @since 1.2
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void aliasType(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addTypeAlias(name, type);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @param defaultImplementation Default implementation of type to use if no other specified.
* @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type, Class defaultImplementation) {
alias(name, type);
addDefaultImplementation(defaultImplementation, type);
}
/**
* Create an alias for a field name.
*
* @param alias the alias itself
* @param type the type that declares the field
* @param fieldName the name of the field
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void aliasField(String alias, Class type, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.addFieldAlias(alias, type, fieldName);
}
/**
* Create an alias for an attribute
*
* @param alias the alias itself
* @param attributeName the name of the attribute
* @throws InitializationException if no {@link AttributeAliasingMapper} is available
*/
public void aliasAttribute(String alias, String attributeName) {
if (attributeAliasingMapper == null) {
throw new InitializationException("No "
+ AttributeAliasingMapper.class.getName()
+ " available");
}
attributeAliasingMapper.addAliasFor(attributeName, alias);
}
/**
* Create an alias for an attribute.
*
* @param configurableClass the type where the attribute is defined
* @param attributeName the name of the attribute
* @param alias the alias itself
* @throws InitializationException if no {@link AttributeAliasingMapper} is available
*/
public void aliasAttribute(Class configurableClass, String attributeName, String alias) {
if (attributeAliasingMapper == null) {
throw new InitializationException("No "
+ AttributeAliasingMapper.class.getName() + " available");
}
attributeAliasingMapper.addAliasFor(configurableClass, attributeName, alias);
}
/**
* Use an XML attribute for a field or a specific type.
*
* @param fieldName the name of the field
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(String fieldName, Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(fieldName, type);
}
/**
* Use an XML attribute for a field of a specific type.
*
* @param fieldName the name of the field
* @param type the Class containing such field
* @throws InitializationException if no {@link AttributeMapper} is available
* @since upcoming
*/
public void useAttributeFor(Class type, String fieldName) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
try {
Field field = type.getDeclaredField(fieldName);
attributeMapper.addAttributeFor(field);
} catch (SecurityException e) {
throw new InitializationException("Unable to access field " + fieldName + "@" + type.getName());
} catch (NoSuchFieldException e) {
throw new InitializationException("Unable to find field " + fieldName + "@" + type.getName());
}
}
/**
* Use an XML attribute for an arbitrary type.
*
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(type);
}
/**
* Associate a default implementation of a class with an object. Whenever XStream encounters an
* instance of this type, it will use the default implementation instead. For example,
* java.util.ArrayList is the default implementation of java.util.List.
*
* @param defaultImplementation
* @param ofType
* @throws InitializationException if no {@link DefaultImplementationsMapper} is available
*/
public void addDefaultImplementation(Class defaultImplementation, Class ofType) {
if (defaultImplementationsMapper == null) {
throw new InitializationException("No "
+ DefaultImplementationsMapper.class.getName()
+ " available");
}
defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType);
}
/**
* Add immutable types. The value of the instances of these types will always be written into
* the stream even if they appear multiple times.
* @throws InitializationException if no {@link ImmutableTypesMapper} is available
*/
public void addImmutableType(Class type) {
if (immutableTypesMapper == null) {
throw new InitializationException("No "
+ ImmutableTypesMapper.class.getName()
+ " available");
}
immutableTypesMapper.addImmutableType(type);
}
public void registerConverter(Converter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(Converter converter, int priority) {
converterLookup.registerConverter(converter, priority);
}
public void registerConverter(SingleValueConverter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(SingleValueConverter converter, int priority) {
converterLookup.registerConverter(new SingleValueConverterWrapper(converter), priority);
}
/**
* @throws ClassCastException if mapper is not really a deprecated {@link ClassMapper} instance
* @deprecated As of 1.2, use {@link #getMapper}
*/
public ClassMapper getClassMapper() {
if (mapper instanceof ClassMapper) {
return (ClassMapper)mapper;
} else {
return (ClassMapper)Proxy.newProxyInstance(getClassLoader(), new Class[]{ClassMapper.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(mapper, args);
}
});
}
}
/**
* Retrieve the {@link Mapper}. This is by default a chain of {@link MapperWrapper MapperWrappers}.
*
* @return the mapper
* @since 1.2
*/
public Mapper getMapper() {
return mapper;
}
/**
* Retrieve the {@link ReflectionProvider} in use.
*
* @return the mapper
* @since 1.2.1
*/
public ReflectionProvider getReflectionProvider() {
return reflectionProvider;
}
public ConverterLookup getConverterLookup() {
return converterLookup;
}
public void setMode(int mode) {
switch (mode) {
case NO_REFERENCES:
setMarshallingStrategy(new TreeMarshallingStrategy());
break;
case ID_REFERENCES:
setMarshallingStrategy(new ReferenceByIdMarshallingStrategy());
break;
case XPATH_RELATIVE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.RELATIVE));
break;
case XPATH_ABSOLUTE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.ABSOLUTE));
break;
default:
throw new IllegalArgumentException("Unknown mode : " + mode);
}
}
/**
* Adds a default implicit collection which is used for any unmapped xml tag.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
*/
public void addImplicitCollection(Class ownerType, String fieldName) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, Object.class);
}
/**
* Adds implicit collection which is used for all items of the given itemType.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
* @param itemType type of the items to be part of this collection.
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, itemType);
}
/**
* Adds implicit collection which is used for all items of the given element name defined by
* itemFieldName.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
* @param itemFieldName element name of the implicit collection
* @param itemType item type to be aliases be the itemFieldName
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(
Class ownerType, String fieldName, String itemFieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType);
}
public DataHolder newDataHolder() {
return new MapBackedDataHolder();
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer)
throws IOException {
return createObjectOutputStream(writer, "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName)
throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), rootNodeName);
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* Because an ObjectOutputStream can contain multiple items and XML only allows a single root
* node, the stream must be written inside an enclosing node.
* </p>
* <p>
* It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be
* incomplete.
* </p>
* <h3>Example</h3>
*
* <pre>
* ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, "things");
* out.writeInt(123);
* out.writeObject("Hello");
* out.writeObject(someObject)
* out.close();
* </pre>
*
* @param writer The writer to serialize the objects to.
* @param rootNodeName The name of the root node enclosing the stream of objects.
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(
final HierarchicalStreamWriter writer, String rootNodeName) throws IOException {
final StatefulWriter statefulWriter = new StatefulWriter(writer);
statefulWriter.startNode(rootNodeName, null);
return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() {
public void writeToStream(Object object) {
marshal(object, statefulWriter);
}
public void writeFieldsToStream(Map fields) throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void defaultWriteObject() throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void flush() {
statefulWriter.flush();
}
public void close() {
if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) {
statefulWriter.endNode();
statefulWriter.close();
}
}
});
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
*
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException {
return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader));
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
* <h3>Example</h3>
*
* <pre>
* ObjectInputStream in = xstream.createObjectOutputStream(aReader);
* int a = out.readInt();
* Object b = out.readObject();
* Object c = out.readObject();
* </pre>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader)
throws IOException {
return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() {
public Object readFromStream() throws EOFException {
if (!reader.hasMoreChildren()) {
throw new EOFException();
}
reader.moveDown();
Object result = unmarshal(reader);
reader.moveUp();
return result;
}
public Map readFieldsFromStream() throws IOException {
throw new NotActiveException("not in call to readObject");
}
public void defaultReadObject() throws NotActiveException {
throw new NotActiveException("not in call to readObject");
}
public void registerValidation(ObjectInputValidation validation, int priority)
throws NotActiveException {
throw new NotActiveException("stream inactive");
}
public void close() {
reader.close();
}
});
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public void setClassLoader(ClassLoader classLoader) {
classLoaderReference.setReference(classLoader);
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public ClassLoader getClassLoader() {
return classLoaderReference.getReference();
}
/**
* Prevents a field from being serialized. To omit a field you must always provide the declaring
* type and not necessarily the type that is converted.
*
* @since 1.1.3
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void omitField(Class type, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.omitField(type, fieldName);
}
public static class InitializationException extends BaseException {
public InitializationException(String message, Throwable cause) {
super(message, cause);
}
public InitializationException(String message) {
super(message);
}
}
private Object readResolve() {
jvm = new JVM();
return this;
}
}
|
package com.thoughtworks.xstream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.NotActiveException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterLookup;
import com.thoughtworks.xstream.converters.DataHolder;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.SingleValueConverterWrapper;
import com.thoughtworks.xstream.converters.basic.BigDecimalConverter;
import com.thoughtworks.xstream.converters.basic.BigIntegerConverter;
import com.thoughtworks.xstream.converters.basic.BooleanConverter;
import com.thoughtworks.xstream.converters.basic.ByteConverter;
import com.thoughtworks.xstream.converters.basic.CharConverter;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.basic.DoubleConverter;
import com.thoughtworks.xstream.converters.basic.FloatConverter;
import com.thoughtworks.xstream.converters.basic.IntConverter;
import com.thoughtworks.xstream.converters.basic.LongConverter;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.basic.ShortConverter;
import com.thoughtworks.xstream.converters.basic.StringBufferConverter;
import com.thoughtworks.xstream.converters.basic.StringConverter;
import com.thoughtworks.xstream.converters.basic.URLConverter;
import com.thoughtworks.xstream.converters.collections.ArrayConverter;
import com.thoughtworks.xstream.converters.collections.BitSetConverter;
import com.thoughtworks.xstream.converters.collections.CharArrayConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.converters.collections.MapConverter;
import com.thoughtworks.xstream.converters.collections.PropertiesConverter;
import com.thoughtworks.xstream.converters.collections.TreeMapConverter;
import com.thoughtworks.xstream.converters.collections.TreeSetConverter;
import com.thoughtworks.xstream.converters.extended.ColorConverter;
import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.converters.extended.FileConverter;
import com.thoughtworks.xstream.converters.extended.FontConverter;
import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter;
import com.thoughtworks.xstream.converters.extended.JavaClassConverter;
import com.thoughtworks.xstream.converters.extended.JavaMethodConverter;
import com.thoughtworks.xstream.converters.extended.LocaleConverter;
import com.thoughtworks.xstream.converters.extended.SqlDateConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimeConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter;
import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.SerializableConverter;
import com.thoughtworks.xstream.core.BaseException;
import com.thoughtworks.xstream.core.DefaultConverterLookup;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.core.MapBackedDataHolder;
import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy;
import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy;
import com.thoughtworks.xstream.core.TreeMarshallingStrategy;
import com.thoughtworks.xstream.core.util.ClassLoaderReference;
import com.thoughtworks.xstream.core.util.CompositeClassLoader;
import com.thoughtworks.xstream.core.util.CustomObjectInputStream;
import com.thoughtworks.xstream.core.util.CustomObjectOutputStream;
import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.mapper.ArrayMapper;
import com.thoughtworks.xstream.mapper.AttributeAliasingMapper;
import com.thoughtworks.xstream.mapper.CachingMapper;
import com.thoughtworks.xstream.mapper.ClassAliasingMapper;
import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper;
import com.thoughtworks.xstream.mapper.DefaultMapper;
import com.thoughtworks.xstream.mapper.DynamicProxyMapper;
import com.thoughtworks.xstream.mapper.EnumMapper;
import com.thoughtworks.xstream.mapper.FieldAliasingMapper;
import com.thoughtworks.xstream.mapper.ImmutableTypesMapper;
import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.thoughtworks.xstream.mapper.OuterClassMapper;
import com.thoughtworks.xstream.mapper.XmlFriendlyMapper;
/**
* Simple facade to XStream library, a Java-XML serialization tool.
* <p/>
* <p><hr><b>Example</b><blockquote><pre>
* XStream xstream = new XStream();
* String xml = xstream.toXML(myObject); // serialize to XML
* Object myObject2 = xstream.fromXML(xml); // deserialize from XML
* </pre></blockquote><hr>
* <p/>
* <h3>Aliasing classes</h3>
* <p/>
* <p>To create shorter XML, you can specify aliases for classes using
* the <code>alias()</code> method.
* For example, you can shorten all occurences of element
* <code><com.blah.MyThing></code> to
* <code><my-thing></code> by registering an alias for the class.
* <p><hr><blockquote><pre>
* xstream.alias("my-thing", MyThing.class);
* </pre></blockquote><hr>
* <p/>
* <h3>Converters</h3>
* <p/>
* <p>XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter}
* instances, each of which acts as a strategy for converting a particular type
* of class to XML and back again. Out of the box, XStream contains converters
* for most basic types (String, Date, int, boolean, etc) and collections (Map, List,
* Set, Properties, etc). For other objects reflection is used to serialize
* each field recursively.</p>
* <p/>
* <p>Extra converters can be registered using the <code>registerConverter()</code>
* method. Some non-standard converters are supplied in the
* {@link com.thoughtworks.xstream.converters.extended} package and you can create
* your own by implementing the {@link com.thoughtworks.xstream.converters.Converter}
* interface.</p>
* <p/>
* <p><hr><b>Example</b><blockquote><pre>
* xstream.registerConverter(new SqlTimestampConverter());
* xstream.registerConverter(new DynamicProxyConverter());
* </pre></blockquote><hr>
* <p>The default converter, ie the converter which will be used if no other registered
* converter is suitable, can be configured by either one of the constructors
* or can be changed using the <code>changeDefaultConverter()</code> method.
* If not set, XStream uses {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter}
* as the initial default converter.
* </p>
* <p/>
* <p><hr><b>Example</b><blockquote><pre>
* xstream.changeDefaultConverter(new ACustomDefaultConverter());
* </pre></blockquote><hr>
* <p/>
* <h3>Object graphs</h3>
* <p/>
* <p>XStream has support for object graphs; a deserialized object graph
* will keep references intact, including circular references.</p>
* <p/>
* <p>XStream can signify references in XML using either XPath or IDs. The
* mode can be changed using <code>setMode()</code>:</p>
* <p/>
* <table border="1">
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_REFERENCES);</code></td>
* <td><i>(Default)</i> Uses XPath references to signify duplicate
* references. This produces XML with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td>
* <td>Uses ID references to signify duplicate references. In some
* scenarios, such as when using hand-written XML, this is
* easier to work with.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td>
* <td>This disables object graph support and treats the object
* structure like a tree. Duplicate references are treated
* as two seperate objects and circular references cause an
* exception. This is slightly faster and uses less memory
* than the other two modes.</td>
* </tr>
* </table>
*
* <h3>Thread safety</h3>
*
* <p>The XStream instance is thread-safe. That is, once the XStream instance
* has been created and configured, it may be shared across multiple threads
* allowing objects to be serialized/deserialized concurrently.
*
* <h3>Implicit collections</h3>
* <p/>
* <p>To avoid the need for special tags for collections, you can define implicit collections using one of the
* <code>addImplicitCollection</code> methods.</p>
*
* @author Joe Walnes
* @author Jörg Schaible
* @author Mauro Talevi
*/
public class XStream {
private ClassAliasingMapper classAliasingMapper;
private FieldAliasingMapper fieldAliasingMapper;
private AttributeAliasingMapper attributeAliasingMapper;
private DefaultImplementationsMapper defaultImplementationsMapper;
private ImmutableTypesMapper immutableTypesMapper;
private ImplicitCollectionMapper implicitCollectionMapper;
private ReflectionProvider reflectionProvider;
private HierarchicalStreamDriver hierarchicalStreamDriver;
private MarshallingStrategy marshallingStrategy;
private ClassLoaderReference classLoaderReference; // TODO: Should be changeable
private Mapper mapper;
private DefaultConverterLookup converterLookup;
private JVM jvm = new JVM();
public static final int NO_REFERENCES = 1001;
public static final int ID_REFERENCES = 1002;
public static final int XPATH_REFERENCES = 1003;
public static final int PRIORITY_VERY_HIGH = 10000;
public static final int PRIORITY_NORMAL = 0;
public static final int PRIORITY_LOW = -10;
public static final int PRIORITY_VERY_LOW = -20;
public XStream() {
this(null, (Mapper)null, new XppDriver());
}
public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) {
this(null, (Mapper)null, hierarchicalStreamDriver);
}
public XStream(ReflectionProvider reflectionProvider) {
this(reflectionProvider, (Mapper)null, new XppDriver());
}
public XStream(ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) {
this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver);
}
/**
* @deprecated As of 1.2, use {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)}
*/
public XStream(ReflectionProvider reflectionProvider, ClassMapper classMapper, HierarchicalStreamDriver driver) {
this(reflectionProvider, classMapper, driver, null);
}
public XStream(ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) {
this(reflectionProvider, mapper, driver, null);
}
/**
* @deprecated As of 1.2, use {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver, String)}
*/
public XStream(ReflectionProvider reflectionProvider, ClassMapper classMapper, HierarchicalStreamDriver driver, String classAttributeIdentifier) {
this(reflectionProvider, (Mapper)classMapper, driver, classAttributeIdentifier);
}
public XStream(ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver, String classAttributeIdentifier) {
jvm = new JVM();
if (reflectionProvider == null) {
reflectionProvider = jvm.bestReflectionProvider();
}
this.reflectionProvider = reflectionProvider;
this.hierarchicalStreamDriver = driver;
this.classLoaderReference = new ClassLoaderReference(new CompositeClassLoader());
this.mapper = mapper == null ? buildMapper(classAttributeIdentifier) : mapper;
converterLookup = new DefaultConverterLookup(this.mapper);
attributeAliasingMapper.setConverterLookup(converterLookup);
setupAliases();
setupDefaultImplementations();
setupConverters();
setupImmutableTypes();
setMode(XPATH_REFERENCES);
}
private Mapper buildMapper(String classAttributeIdentifier) {
Mapper mapper = new DefaultMapper(classLoaderReference, classAttributeIdentifier);
mapper = new XmlFriendlyMapper(mapper);
mapper = new ClassAliasingMapper(mapper);
classAliasingMapper = (ClassAliasingMapper) mapper; // need a reference to that one
mapper = new FieldAliasingMapper(mapper);
fieldAliasingMapper = (FieldAliasingMapper) mapper; // need a reference to that one
mapper = new AttributeAliasingMapper(mapper, converterLookup);
attributeAliasingMapper = (AttributeAliasingMapper) mapper; // need a reference to that one
mapper = new ImplicitCollectionMapper(mapper);
implicitCollectionMapper = (ImplicitCollectionMapper)mapper; // need a reference to this one
mapper = new DynamicProxyMapper(mapper);
if (JVM.is15()) {
mapper = new EnumMapper(mapper);
}
mapper = new OuterClassMapper(mapper);
mapper = new ArrayMapper(mapper);
mapper = new DefaultImplementationsMapper(mapper);
defaultImplementationsMapper = (DefaultImplementationsMapper) mapper; // and that one
mapper = new ImmutableTypesMapper(mapper);
immutableTypesMapper = (ImmutableTypesMapper)mapper; // that one too
mapper = wrapMapper((MapperWrapper)mapper);
mapper = new CachingMapper(mapper);
return mapper;
}
protected MapperWrapper wrapMapper(MapperWrapper next) {
return next;
}
protected void setupAliases() {
alias("null", Mapper.Null.class);
alias("int", Integer.class);
alias("float", Float.class);
alias("double", Double.class);
alias("long", Long.class);
alias("short", Short.class);
alias("char", Character.class);
alias("byte", Byte.class);
alias("boolean", Boolean.class);
alias("number", Number.class);
alias("object", Object.class);
alias("big-int", BigInteger.class);
alias("big-decimal", BigDecimal.class);
alias("string-buffer", StringBuffer.class);
alias("string", String.class);
alias("java-class", Class.class);
alias("method", Method.class);
alias("constructor", Constructor.class);
alias("date", Date.class);
alias("url", URL.class);
alias("bit-set", BitSet.class);
alias("map", Map.class);
alias("entry", Map.Entry.class);
alias("properties", Properties.class);
alias("list", List.class);
alias("set", Set.class);
alias("linked-list", LinkedList.class);
alias("vector", Vector.class);
alias("tree-map", TreeMap.class);
alias("tree-set", TreeSet.class);
alias("hashtable", Hashtable.class);
// Instantiating these two classes starts the AWT system, which is undesirable. Calling loadClass ensures
// a reference to the class is found but they are not instantiated.
alias("awt-color", jvm.loadClass("java.awt.Color"));
alias("awt-font", jvm.loadClass("java.awt.Font"));
alias("sql-timestamp", Timestamp.class);
alias("sql-time", Time.class);
alias("sql-date", java.sql.Date.class);
alias("file", File.class);
alias("locale", Locale.class);
alias("gregorian-calendar", Calendar.class);
if (JVM.is14()) {
alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap"));
alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet"));
alias("trace", jvm.loadClass("java.lang.StackTraceElement"));
alias("currency", jvm.loadClass("java.util.Currency"));
// since jdk 1.4 included, but previously available as separate package ...
alias("auth-subject", jvm.loadClass("javax.security.auth.Subject"));
}
if (JVM.is15()) {
alias("enum-set", jvm.loadClass("java.util.EnumSet"));
alias("enum-map", jvm.loadClass("java.util.EnumMap"));
}
}
protected void setupDefaultImplementations() {
addDefaultImplementation(HashMap.class, Map.class);
addDefaultImplementation(ArrayList.class, List.class);
addDefaultImplementation(HashSet.class, Set.class);
addDefaultImplementation(GregorianCalendar.class, Calendar.class);
}
protected void setupConverters() {
// use different ReflectionProvider depending on JDK
final ReflectionConverter reflectionConverter;
if (JVM.is15()) {
Class annotationProvider = jvm.loadClass("com.thoughtworks.xstream.annotations.AnnotationProvider");
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.annotations.AnnotationReflectionConverter", PRIORITY_VERY_LOW,
new Class[] {Mapper.class, ReflectionProvider.class, annotationProvider},
new Object[] {mapper, reflectionProvider, reflectionProvider.newInstance(annotationProvider)});
reflectionConverter = (ReflectionConverter)converterLookup.lookupConverterForType(Object.class);
} else {
reflectionConverter = new ReflectionConverter(mapper, reflectionProvider);
registerConverter(reflectionConverter, PRIORITY_VERY_LOW);
}
registerConverter(new SerializableConverter(mapper, reflectionProvider), PRIORITY_LOW);
registerConverter(new ExternalizableConverter(mapper), PRIORITY_LOW);
registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
registerConverter(new IntConverter(), PRIORITY_NORMAL);
registerConverter(new FloatConverter(), PRIORITY_NORMAL);
registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
registerConverter(new LongConverter(), PRIORITY_NORMAL);
registerConverter(new ShortConverter(), PRIORITY_NORMAL);
registerConverter(new CharConverter(), PRIORITY_NORMAL);
registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
registerConverter(new ByteConverter(), PRIORITY_NORMAL);
registerConverter(new StringConverter(), PRIORITY_NORMAL);
registerConverter(new StringBufferConverter(), PRIORITY_NORMAL);
registerConverter(new DateConverter(), PRIORITY_NORMAL);
registerConverter(new BitSetConverter(), PRIORITY_NORMAL);
registerConverter(new URLConverter(), PRIORITY_NORMAL);
registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL);
registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL);
registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL);
registerConverter(new CharArrayConverter(), PRIORITY_NORMAL);
registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL);
registerConverter(new MapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL);
registerConverter(new PropertiesConverter(), PRIORITY_NORMAL);
registerConverter(new EncodedByteArrayConverter(), PRIORITY_NORMAL);
registerConverter(new FileConverter(), PRIORITY_NORMAL);
registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL);
registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL);
registerConverter(new SqlDateConverter(), PRIORITY_NORMAL);
registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaMethodConverter(), PRIORITY_NORMAL);
registerConverter(new FontConverter(), PRIORITY_NORMAL);
registerConverter(new ColorConverter(), PRIORITY_NORMAL);
registerConverter(new LocaleConverter(), PRIORITY_NORMAL);
registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL);
if (JVM.is14()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.ThrowableConverter", PRIORITY_NORMAL,
new Class[] {Converter.class} , new Object[] { reflectionConverter} );
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.StackTraceElementConverter", PRIORITY_NORMAL,
null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CurrencyConverter", PRIORITY_NORMAL,
null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.RegexPatternConverter", PRIORITY_NORMAL,
new Class[] {Converter.class} , new Object[] { reflectionConverter} );
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.SubjectConverter", PRIORITY_NORMAL,
new Class[] {Mapper.class}, new Object[] {mapper});
}
if (JVM.is15()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL,
null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL,
new Class[] {Mapper.class}, new Object[] {mapper});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL,
new Class[] {Mapper.class}, new Object[] {mapper});
}
}
private void dynamicallyRegisterConverter(String className, int priority,
Class[] constructorParamTypes, Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
Object instance = constructor.newInstance(constructorParamValues);
//Converter converter = (Converter) constructor.newInstance(constructorParamValues);
if ( instance instanceof Converter ){
registerConverter((Converter)instance, priority);
} else if ( instance instanceof SingleValueConverter ){
registerConverter((SingleValueConverter)instance, priority);
}
} catch (Exception e) {
throw new InitializationException("Could not instatiate converter : " + className, e);
}
}
protected void setupImmutableTypes() {
// primitives are always immutable
addImmutableType(boolean.class);
addImmutableType(Boolean.class);
addImmutableType(byte.class);
addImmutableType(Byte.class);
addImmutableType(char.class);
addImmutableType(Character.class);
addImmutableType(double.class);
addImmutableType(Double.class);
addImmutableType(float.class);
addImmutableType(Float.class);
addImmutableType(int.class);
addImmutableType(Integer.class);
addImmutableType(long.class);
addImmutableType(Long.class);
addImmutableType(short.class);
addImmutableType(Short.class);
// additional types
addImmutableType(Mapper.Null.class);
addImmutableType(BigDecimal.class);
addImmutableType(BigInteger.class);
addImmutableType(String.class);
addImmutableType(URL.class);
addImmutableType(File.class);
addImmutableType(Class.class);
}
public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) {
this.marshallingStrategy = marshallingStrategy;
}
/**
* Serialize an object to a pretty-printed XML String.
*/
public String toXML(Object obj) {
Writer stringWriter = new StringWriter();
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(stringWriter);
marshal(obj, writer);
writer.flush();
writer.close();
return stringWriter.toString();
}
/**
* Serialize an object to the given Writer as pretty-printed XML.
*/
public void toXML(Object obj, Writer out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize an object to the given OutputStream as pretty-printed XML.
*/
public void toXML(Object obj, OutputStream out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
*/
public void marshal(Object obj, HierarchicalStreamWriter writer) {
marshal(obj, writer, null);
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
*
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If not present, XStream
* shall create one lazily as needed.
*/
public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) {
marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder);
}
/**
* Deserialize an object from an XML String.
*/
public Object fromXML(String xml) {
return fromXML(new StringReader(xml));
}
/**
* Deserialize an object from an XML Reader.
*/
public Object fromXML(Reader xml) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), null);
}
/**
* Deserialize an object from an XML InputStream.
*/
public Object fromXML(InputStream input) {
return unmarshal(hierarchicalStreamDriver.createReader(input), null);
}
/**
* Deserialize an object from an XML String,
* populating the fields of the given root object instead of instantiating
* a new one.
*/
public Object fromXML(String xml, Object root) {
return fromXML(new StringReader(xml), root);
}
/**
* Deserialize an object from an XML Reader,
* populating the fields of the given root object instead of instantiating
* a new one.
*/
public Object fromXML(Reader xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from an XML InputStream,
* populating the fields of the given root object instead of instantiating
* a new one.
*/
public Object fromXML(InputStream xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
*/
public Object unmarshal(HierarchicalStreamReader reader) {
return unmarshal(reader, null, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML),
* populating the fields of the given root object instead of instantiating
* a new one.
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root) {
return unmarshal(reader, root, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
*
* @param root If present, the passed in object will have its fields populated, as opposed to XStream creating a
* new instance.
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If not present, XStream
* shall create one lazily as needed.
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
*/
public void alias(String name, Class type) {
classAliasingMapper.addClassAlias(name, type);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @param defaultImplementation Default implementation of type to use if no other specified.
*/
public void alias(String name, Class type, Class defaultImplementation) {
alias(name, type);
addDefaultImplementation(defaultImplementation, type);
}
public void aliasField(String alias, Class type, String fieldName) {
fieldAliasingMapper.addFieldAlias(alias, type, fieldName);
}
/**
* Alias a Class to be used as an XML attribute
*
* @param attributeName the name of the attribute
* @param type the Class of the type to be aliased
* @since 1.2
*/
public void aliasAttribute(String attributeName, Class type) {
attributeAliasingMapper.addAttributeAlias(attributeName, type);
}
/**
* Associate a default implementation of a class with an object. Whenever XStream encounters an instance of this
* type, it will use the default implementation instead.
*
* For example, java.util.ArrayList is the default implementation of java.util.List.
* @param defaultImplementation
* @param ofType
*/
public void addDefaultImplementation(Class defaultImplementation, Class ofType) {
defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType);
}
public void addImmutableType(Class type) {
immutableTypesMapper.addImmutableType(type);
}
public void registerConverter(Converter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(Converter converter, int priority) {
converterLookup.registerConverter(converter, priority);
}
public void registerConverter(SingleValueConverter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(SingleValueConverter converter, int priority) {
converterLookup.registerConverter(new SingleValueConverterWrapper(converter), priority);
}
/**
* @throws ClassCastException if mapper is not really a deprecated {@link ClassMapper} instance
* @deprecated As of 1.2, use {@link #getMapper}
*/
public ClassMapper getClassMapper() {
return (ClassMapper)mapper;
}
/**
* Retrieve the mapper. This is by default a chain of {@link MapperWrapper MapperWrappers}.
*
* @return the mapper
* @since 1.2
*/
public Mapper getMapper() {
return mapper;
}
public ConverterLookup getConverterLookup() {
return converterLookup;
}
/**
* Change mode for dealing with duplicate references.
* Valid valuse are <code>XStream.XPATH_REFERENCES</code>,
* <code>XStream.ID_REFERENCES</code> and <code>XStream.NO_REFERENCES</code>.
*
* @see #XPATH_REFERENCES
* @see #ID_REFERENCES
* @see #NO_REFERENCES
*/
public void setMode(int mode) {
switch (mode) {
case NO_REFERENCES:
setMarshallingStrategy(new TreeMarshallingStrategy());
break;
case ID_REFERENCES:
setMarshallingStrategy(new ReferenceByIdMarshallingStrategy());
break;
case XPATH_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy());
break;
default:
throw new IllegalArgumentException("Unknown mode : " + mode);
}
}
/**
* Adds a default implicit collection which is used for any unmapped xml tag.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an <code>java.util.ArrayList</code>.
*/
public void addImplicitCollection(Class ownerType, String fieldName) {
implicitCollectionMapper.add(ownerType, fieldName, null, Object.class);
}
/**
* Adds implicit collection which is used for all items of the given itemType.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an <code>java.util.ArrayList</code>.
* @param itemType type of the items to be part of this collection.
*/
public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) {
implicitCollectionMapper.add(ownerType, fieldName, null, itemType);
}
/**
* Adds implicit collection which is used for all items of the given element name defined by itemFieldName.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an <code>java.util.ArrayList</code>.
* @param itemFieldName element name of the implicit collection
* @param itemType item type to be aliases be the itemFieldName
*/
public void addImplicitCollection(Class ownerType, String fieldName, String itemFieldName, Class itemType) {
implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType);
}
public DataHolder newDataHolder() {
return new MapBackedDataHolder();
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream.
*
* <p>To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.</p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream.
*
* <p>To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.</p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer) throws IOException {
return createObjectOutputStream(writer, "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream.
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName) throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), rootNodeName);
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream.
*
* <p>Because an ObjectOutputStream can contain multiple items and XML only allows a single root node, the stream
* must be written inside an enclosing node.</p>
*
* <p>It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be incomplete.</p>
*
* <h3>Example</h3>
* <pre>ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, "things");
* out.writeInt(123);
* out.writeObject("Hello");
* out.writeObject(someObject)
* out.close();</pre>
*
* @param writer The writer to serialize the objects to.
* @param rootNodeName The name of the root node enclosing the stream of objects.
*
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, String rootNodeName) throws IOException {
writer.startNode(rootNodeName);
return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() {
public void writeToStream(Object object) {
marshal(object, writer);
}
public void writeFieldsToStream(Map fields) throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void defaultWriteObject() throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void flush() {
writer.flush();
}
public void close() {
writer.endNode();
writer.close();
}
});
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream.
*
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException {
return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader));
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using XStream.
*
* <h3>Example</h3>
* <pre>ObjectInputStream in = xstream.createObjectOutputStream(aReader);
* int a = out.readInt();
* Object b = out.readObject();
* Object c = out.readObject();</pre>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException {
return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() {
public Object readFromStream() throws EOFException {
if (!reader.hasMoreChildren()) {
throw new EOFException();
}
reader.moveDown();
Object result = unmarshal(reader);
reader.moveUp();
return result;
}
public Map readFieldsFromStream() throws IOException {
throw new NotActiveException("not in call to readObject");
}
public void defaultReadObject() throws NotActiveException {
throw new NotActiveException("not in call to readObject");
}
public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException {
throw new NotActiveException("stream inactive");
}
public void close() {
reader.close();
}
});
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public void setClassLoader(ClassLoader classLoader) {
classLoaderReference.setReference(classLoader);
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public ClassLoader getClassLoader() {
return classLoaderReference.getReference();
}
/**
* Prevents a field from being serialized.
*
* @since 1.1.3
*/
public void omitField(Class type, String fieldName) {
fieldAliasingMapper.omitField(type, fieldName);
}
public static class InitializationException extends BaseException {
public InitializationException(String message, Throwable cause) {
super(message, cause);
}
}
}
|
package com.thoughtworks.xstream;
import java.awt.font.TextAttribute;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.NotActiveException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterLookup;
import com.thoughtworks.xstream.converters.DataHolder;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.SingleValueConverterWrapper;
import com.thoughtworks.xstream.converters.basic.BigDecimalConverter;
import com.thoughtworks.xstream.converters.basic.BigIntegerConverter;
import com.thoughtworks.xstream.converters.basic.BooleanConverter;
import com.thoughtworks.xstream.converters.basic.ByteConverter;
import com.thoughtworks.xstream.converters.basic.CharConverter;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.basic.DoubleConverter;
import com.thoughtworks.xstream.converters.basic.FloatConverter;
import com.thoughtworks.xstream.converters.basic.IntConverter;
import com.thoughtworks.xstream.converters.basic.LongConverter;
import com.thoughtworks.xstream.converters.basic.NullConverter;
import com.thoughtworks.xstream.converters.basic.ShortConverter;
import com.thoughtworks.xstream.converters.basic.StringBufferConverter;
import com.thoughtworks.xstream.converters.basic.StringConverter;
import com.thoughtworks.xstream.converters.basic.URLConverter;
import com.thoughtworks.xstream.converters.collections.ArrayConverter;
import com.thoughtworks.xstream.converters.collections.BitSetConverter;
import com.thoughtworks.xstream.converters.collections.CharArrayConverter;
import com.thoughtworks.xstream.converters.collections.CollectionConverter;
import com.thoughtworks.xstream.converters.collections.MapConverter;
import com.thoughtworks.xstream.converters.collections.PropertiesConverter;
import com.thoughtworks.xstream.converters.collections.TreeMapConverter;
import com.thoughtworks.xstream.converters.collections.TreeSetConverter;
import com.thoughtworks.xstream.converters.extended.ColorConverter;
import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter;
import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter;
import com.thoughtworks.xstream.converters.extended.FileConverter;
import com.thoughtworks.xstream.converters.extended.FontConverter;
import com.thoughtworks.xstream.converters.extended.GregorianCalendarConverter;
import com.thoughtworks.xstream.converters.extended.JavaClassConverter;
import com.thoughtworks.xstream.converters.extended.JavaMethodConverter;
import com.thoughtworks.xstream.converters.extended.LocaleConverter;
import com.thoughtworks.xstream.converters.extended.SqlDateConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimeConverter;
import com.thoughtworks.xstream.converters.extended.SqlTimestampConverter;
import com.thoughtworks.xstream.converters.extended.TextAttributeConverter;
import com.thoughtworks.xstream.converters.reflection.ExternalizableConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;
import com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker;
import com.thoughtworks.xstream.converters.reflection.SerializableConverter;
import com.thoughtworks.xstream.core.BaseException;
import com.thoughtworks.xstream.core.DefaultConverterLookup;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.core.MapBackedDataHolder;
import com.thoughtworks.xstream.core.ReferenceByIdMarshallingStrategy;
import com.thoughtworks.xstream.core.ReferenceByXPathMarshallingStrategy;
import com.thoughtworks.xstream.core.TreeMarshallingStrategy;
import com.thoughtworks.xstream.core.util.ClassLoaderReference;
import com.thoughtworks.xstream.core.util.CompositeClassLoader;
import com.thoughtworks.xstream.core.util.CustomObjectInputStream;
import com.thoughtworks.xstream.core.util.CustomObjectOutputStream;
import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.StatefulWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.mapper.ArrayMapper;
import com.thoughtworks.xstream.mapper.AttributeAliasingMapper;
import com.thoughtworks.xstream.mapper.AttributeMapper;
import com.thoughtworks.xstream.mapper.CachingMapper;
import com.thoughtworks.xstream.mapper.ClassAliasingMapper;
import com.thoughtworks.xstream.mapper.DefaultImplementationsMapper;
import com.thoughtworks.xstream.mapper.DefaultMapper;
import com.thoughtworks.xstream.mapper.DynamicProxyMapper;
import com.thoughtworks.xstream.mapper.EnumMapper;
import com.thoughtworks.xstream.mapper.FieldAliasingMapper;
import com.thoughtworks.xstream.mapper.ImmutableTypesMapper;
import com.thoughtworks.xstream.mapper.ImplicitCollectionMapper;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.thoughtworks.xstream.mapper.OuterClassMapper;
import com.thoughtworks.xstream.mapper.XStream11XmlFriendlyMapper;
/**
* Simple facade to XStream library, a Java-XML serialization tool. <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* XStream xstream = new XStream();
* String xml = xstream.toXML(myObject); // serialize to XML
* Object myObject2 = xstream.fromXML(xml); // deserialize from XML
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Aliasing classes</h3>
* <p/>
* <p>
* To create shorter XML, you can specify aliases for classes using the <code>alias()</code>
* method. For example, you can shorten all occurences of element
* <code><com.blah.MyThing></code> to <code><my-thing></code> by registering an
* alias for the class.
* <p>
* <hr>
* <blockquote>
*
* <pre>
* xstream.alias("my-thing", MyThing.class);
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Converters</h3>
* <p/>
* <p>
* XStream contains a map of {@link com.thoughtworks.xstream.converters.Converter} instances, each
* of which acts as a strategy for converting a particular type of class to XML and back again. Out
* of the box, XStream contains converters for most basic types (String, Date, int, boolean, etc)
* and collections (Map, List, Set, Properties, etc). For other objects reflection is used to
* serialize each field recursively.
* </p>
* <p/>
* <p>
* Extra converters can be registered using the <code>registerConverter()</code> method. Some
* non-standard converters are supplied in the {@link com.thoughtworks.xstream.converters.extended}
* package and you can create your own by implementing the
* {@link com.thoughtworks.xstream.converters.Converter} interface.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.registerConverter(new SqlTimestampConverter());
* xstream.registerConverter(new DynamicProxyConverter());
* </pre>
*
* </blockquote>
* <hr>
* <p>
* The default converter, ie the converter which will be used if no other registered converter is
* suitable, can be configured by either one of the constructors or can be changed using the
* <code>changeDefaultConverter()</code> method. If not set, XStream uses
* {@link com.thoughtworks.xstream.converters.reflection.ReflectionConverter} as the initial default
* converter.
* </p>
* <p/>
* <p>
* <hr>
* <b>Example</b><blockquote>
*
* <pre>
* xstream.changeDefaultConverter(new ACustomDefaultConverter());
* </pre>
*
* </blockquote>
* <hr>
* <p/>
* <h3>Object graphs</h3>
* <p/>
* <p>
* XStream has support for object graphs; a deserialized object graph will keep references intact,
* including circular references.
* </p>
* <p/>
* <p>
* XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using
* <code>setMode()</code>:
* </p>
* <p/> <table border="1">
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES);</code></td>
* <td><i>(Default)</i> Uses XPath relative references to signify duplicate references. This produces XML
* with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);</code></td>
* <td>Uses XPath absolute references to signify duplicate
* references. This produces XML with the least clutter.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.ID_REFERENCES);</code></td>
* <td>Uses ID references to signify duplicate references. In some scenarios, such as when using
* hand-written XML, this is easier to work with.</td>
* </tr>
* <tr>
* <td><code>xstream.setMode(XStream.NO_REFERENCES);</code></td>
* <td>This disables object graph support and treats the object structure like a tree. Duplicate
* references are treated as two seperate objects and circular references cause an exception. This
* is slightly faster and uses less memory than the other two modes.</td>
* </tr>
* </table>
* <h3>Thread safety</h3>
* <p>
* The XStream instance is thread-safe. That is, once the XStream instance has been created and
* configured, it may be shared across multiple threads allowing objects to be
* serialized/deserialized concurrently.
* <h3>Implicit collections</h3>
* <p/>
* <p>
* To avoid the need for special tags for collections, you can define implicit collections using one
* of the <code>addImplicitCollection</code> methods.
* </p>
*
* @author Joe Walnes
* @author Jörg Schaible
* @author Mauro Talevi
* @author Guilherme Silveira
*/
public class XStream {
// CAUTION: The sequence of the fields is intentional for an optimal XML output of a
// self-serializaion!
private ReflectionProvider reflectionProvider;
private HierarchicalStreamDriver hierarchicalStreamDriver;
private ClassLoaderReference classLoaderReference;
private MarshallingStrategy marshallingStrategy;
private Mapper mapper;
private DefaultConverterLookup converterLookup;
private ClassAliasingMapper classAliasingMapper;
private FieldAliasingMapper fieldAliasingMapper;
private AttributeAliasingMapper attributeAliasingMapper;
private AttributeMapper attributeMapper;
private DefaultImplementationsMapper defaultImplementationsMapper;
private ImmutableTypesMapper immutableTypesMapper;
private ImplicitCollectionMapper implicitCollectionMapper;
private transient JVM jvm = new JVM();
public static final int NO_REFERENCES = 1001;
public static final int ID_REFERENCES = 1002;
public static final int XPATH_RELATIVE_REFERENCES = 1003;
public static final int XPATH_ABSOLUTE_REFERENCES = 1004;
/**
* @deprecated since 1.2, use {@link #XPATH_RELATIVE_REFERENCES} or
* {@link #XPATH_ABSOLUTE_REFERENCES} instead.
*/
public static final int XPATH_REFERENCES = XPATH_RELATIVE_REFERENCES;
public static final int PRIORITY_VERY_HIGH = 10000;
public static final int PRIORITY_NORMAL = 0;
public static final int PRIORITY_LOW = -10;
public static final int PRIORITY_VERY_LOW = -20;
/**
* Constructs a default XStream. The instance will use the {@link XppDriver} as default and tries to determin the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream() {
this(null, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link ReflectionProvider}. The instance will use the {@link XppDriver} as default.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(ReflectionProvider reflectionProvider) {
this(reflectionProvider, (Mapper)null, new XppDriver());
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver}. The instance will tries to determin the best
* match for the {@link ReflectionProvider} on its own.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) {
this(null, (Mapper)null, hierarchicalStreamDriver);
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider}.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(
ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) {
this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)}
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver) {
this(reflectionProvider, (Mapper)classMapper, driver);
}
/**
* @deprecated As of 1.2, use
* {@link #XStream(ReflectionProvider, Mapper, HierarchicalStreamDriver)} and
* register classAttributeIdentifier as alias
*/
public XStream(
ReflectionProvider reflectionProvider, ClassMapper classMapper,
HierarchicalStreamDriver driver, String classAttributeIdentifier) {
this(reflectionProvider, (Mapper)classMapper, driver);
aliasAttribute(classAttributeIdentifier, "class");
}
/**
* Constructs an XStream with a special {@link HierarchicalStreamDriver} and {@link ReflectionProvider} and additionally with a prepared {@link Mapper}.
*
* @throws InitializationException in case of an initialization problem
*/
public XStream(
ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) {
jvm = new JVM();
if (reflectionProvider == null) {
reflectionProvider = jvm.bestReflectionProvider();
}
this.reflectionProvider = reflectionProvider;
this.hierarchicalStreamDriver = driver;
this.classLoaderReference = new ClassLoaderReference(new CompositeClassLoader());
this.mapper = mapper == null ? buildMapper() : mapper;
this.converterLookup = new DefaultConverterLookup(this.mapper);
setupMappers();
setupAliases();
setupDefaultImplementations();
setupConverters();
setupImmutableTypes();
setMode(XPATH_RELATIVE_REFERENCES);
}
private Mapper buildMapper() {
Mapper mapper = new DefaultMapper(classLoaderReference);
if ( useXStream11XmlFriendlyMapper() ){
mapper = new XStream11XmlFriendlyMapper(mapper);
}
mapper = new ClassAliasingMapper(mapper);
mapper = new FieldAliasingMapper(mapper);
mapper = new AttributeAliasingMapper(mapper);
mapper = new AttributeMapper(mapper);
mapper = new ImplicitCollectionMapper(mapper);
if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) {
mapper = buildMapperDynamically(
"com.thoughtworks.xstream.mapper.CGLIBMapper",
new Class[]{Mapper.class}, new Object[]{mapper});
}
mapper = new DynamicProxyMapper(mapper);
if (JVM.is15()) {
mapper = new EnumMapper(mapper);
}
mapper = new OuterClassMapper(mapper);
mapper = new ArrayMapper(mapper);
mapper = new DefaultImplementationsMapper(mapper);
mapper = new ImmutableTypesMapper(mapper);
mapper = wrapMapper((MapperWrapper)mapper);
mapper = new CachingMapper(mapper);
return mapper;
}
private Mapper buildMapperDynamically(
String className, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
return (Mapper)constructor.newInstance(constructorParamValues);
} catch (Exception e) {
throw new InitializationException("Could not instatiate mapper : " + className, e);
}
}
protected MapperWrapper wrapMapper(MapperWrapper next) {
return next;
}
protected boolean useXStream11XmlFriendlyMapper() {
return false;
}
private void setupMappers() {
classAliasingMapper = (ClassAliasingMapper)this.mapper
.lookupMapperOfType(ClassAliasingMapper.class);
fieldAliasingMapper = (FieldAliasingMapper)this.mapper
.lookupMapperOfType(FieldAliasingMapper.class);
attributeMapper = (AttributeMapper)this.mapper.lookupMapperOfType(AttributeMapper.class);
attributeAliasingMapper = (AttributeAliasingMapper)this.mapper
.lookupMapperOfType(AttributeAliasingMapper.class);
implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper
.lookupMapperOfType(ImplicitCollectionMapper.class);
defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper
.lookupMapperOfType(DefaultImplementationsMapper.class);
immutableTypesMapper = (ImmutableTypesMapper)this.mapper
.lookupMapperOfType(ImmutableTypesMapper.class);
// should use ctor, but converterLookup is not yet initialized instantiating this mapper
if (attributeMapper != null) {
attributeMapper.setConverterLookup(converterLookup);
}
}
protected void setupAliases() {
if (classAliasingMapper == null) {
return;
}
alias("null", Mapper.Null.class);
alias("int", Integer.class);
alias("float", Float.class);
alias("double", Double.class);
alias("long", Long.class);
alias("short", Short.class);
alias("char", Character.class);
alias("byte", Byte.class);
alias("boolean", Boolean.class);
alias("number", Number.class);
alias("object", Object.class);
alias("big-int", BigInteger.class);
alias("big-decimal", BigDecimal.class);
alias("string-buffer", StringBuffer.class);
alias("string", String.class);
alias("java-class", Class.class);
alias("method", Method.class);
alias("constructor", Constructor.class);
alias("date", Date.class);
alias("url", URL.class);
alias("bit-set", BitSet.class);
alias("map", Map.class);
alias("entry", Map.Entry.class);
alias("properties", Properties.class);
alias("list", List.class);
alias("set", Set.class);
alias("linked-list", LinkedList.class);
alias("vector", Vector.class);
alias("tree-map", TreeMap.class);
alias("tree-set", TreeSet.class);
alias("hashtable", Hashtable.class);
if(jvm.supportsAWT()) {
// Instantiating these two classes starts the AWT system, which is undesirable. Calling
// loadClass ensures a reference to the class is found but they are not instantiated.
alias("awt-color", jvm.loadClass("java.awt.Color"));
alias("awt-font", jvm.loadClass("java.awt.Font"));
alias("awt-text-attribute", TextAttribute.class);
}
if(jvm.supportsSQL()) {
alias("sql-timestamp", Timestamp.class);
alias("sql-time", Time.class);
alias("sql-date", java.sql.Date.class);
}
alias("file", File.class);
alias("locale", Locale.class);
alias("gregorian-calendar", Calendar.class);
// since jdk 1.4 included, but previously available as separate package ...
Class type = jvm.loadClass("javax.security.auth.Subject");
if (type != null) {
alias("auth-subject", type);
}
if (JVM.is14()) {
alias("linked-hash-map", jvm.loadClass("java.util.LinkedHashMap"));
alias("linked-hash-set", jvm.loadClass("java.util.LinkedHashSet"));
alias("trace", jvm.loadClass("java.lang.StackTraceElement"));
alias("currency", jvm.loadClass("java.util.Currency"));
aliasType("charset", jvm.loadClass("java.nio.charset.Charset"));
}
if (JVM.is15()) {
alias("enum-set", jvm.loadClass("java.util.EnumSet"));
alias("enum-map", jvm.loadClass("java.util.EnumMap"));
}
}
protected void setupDefaultImplementations() {
if (defaultImplementationsMapper == null) {
return;
}
addDefaultImplementation(HashMap.class, Map.class);
addDefaultImplementation(ArrayList.class, List.class);
addDefaultImplementation(HashSet.class, Set.class);
addDefaultImplementation(GregorianCalendar.class, Calendar.class);
}
protected void setupConverters() {
// use different ReflectionProvider depending on JDK
final ReflectionConverter reflectionConverter;
if (JVM.is15()) {
Class annotationProvider = jvm
.loadClass("com.thoughtworks.xstream.annotations.AnnotationProvider");
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.annotations.AnnotationReflectionConverter",
PRIORITY_VERY_LOW, new Class[]{
Mapper.class, ReflectionProvider.class, annotationProvider},
new Object[]{
mapper, reflectionProvider,
reflectionProvider.newInstance(annotationProvider)});
reflectionConverter = (ReflectionConverter)converterLookup
.lookupConverterForType(Object.class);
} else {
reflectionConverter = new ReflectionConverter(mapper, reflectionProvider);
registerConverter(reflectionConverter, PRIORITY_VERY_LOW);
}
registerConverter(new SerializableConverter(mapper, reflectionProvider), PRIORITY_LOW);
registerConverter(new ExternalizableConverter(mapper), PRIORITY_LOW);
registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
registerConverter(new IntConverter(), PRIORITY_NORMAL);
registerConverter(new FloatConverter(), PRIORITY_NORMAL);
registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
registerConverter(new LongConverter(), PRIORITY_NORMAL);
registerConverter(new ShortConverter(), PRIORITY_NORMAL);
registerConverter(new CharConverter(), PRIORITY_NORMAL);
registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
registerConverter(new ByteConverter(), PRIORITY_NORMAL);
registerConverter(new StringConverter(), PRIORITY_NORMAL);
registerConverter(new StringBufferConverter(), PRIORITY_NORMAL);
registerConverter(new DateConverter(), PRIORITY_NORMAL);
registerConverter(new BitSetConverter(), PRIORITY_NORMAL);
registerConverter(new URLConverter(), PRIORITY_NORMAL);
registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL);
registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL);
registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL);
registerConverter(new CharArrayConverter(), PRIORITY_NORMAL);
registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL);
registerConverter(new MapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL);
registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL);
registerConverter(new PropertiesConverter(), PRIORITY_NORMAL);
registerConverter(new EncodedByteArrayConverter(), PRIORITY_NORMAL);
registerConverter(new FileConverter(), PRIORITY_NORMAL);
if(jvm.supportsSQL()) {
registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL);
registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL);
registerConverter(new SqlDateConverter(), PRIORITY_NORMAL);
}
registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL);
registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL);
if(jvm.supportsAWT()) {
registerConverter(new FontConverter(), PRIORITY_NORMAL);
registerConverter(new ColorConverter(), PRIORITY_NORMAL);
registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL);
}
registerConverter(new LocaleConverter(), PRIORITY_NORMAL);
registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL);
// since jdk 1.4 included, but previously available as separate package ...
if (jvm.loadClass("javax.security.auth.Subject") != null) {
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.SubjectConverter",
PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper});
}
if (JVM.is14()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.ThrowableConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.StackTraceElementConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CurrencyConverter",
PRIORITY_NORMAL, null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.RegexPatternConverter",
PRIORITY_NORMAL, new Class[]{Converter.class},
new Object[]{reflectionConverter});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.extended.CharsetConverter",
PRIORITY_NORMAL, null, null);
}
if (JVM.is15()) {
// late bound converters - allows XStream to be compiled on earlier JDKs
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumConverter", PRIORITY_NORMAL,
null, null);
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumSetConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.enums.EnumMapConverter", PRIORITY_NORMAL,
new Class[]{Mapper.class}, new Object[]{mapper});
}
if (jvm.loadClass("net.sf.cglib.proxy.Enhancer") != null) {
dynamicallyRegisterConverter(
"com.thoughtworks.xstream.converters.reflection.CGLIBEnhancedConverter",
PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class},
new Object[]{mapper, reflectionProvider});
}
registerConverter(new SelfStreamingInstanceChecker(reflectionConverter, this), PRIORITY_NORMAL);
}
private void dynamicallyRegisterConverter(
String className, int priority, Class[] constructorParamTypes,
Object[] constructorParamValues) {
try {
Class type = Class.forName(className, false, classLoaderReference.getReference());
Constructor constructor = type.getConstructor(constructorParamTypes);
Object instance = constructor.newInstance(constructorParamValues);
if (instance instanceof Converter) {
registerConverter((Converter)instance, priority);
} else if (instance instanceof SingleValueConverter) {
registerConverter((SingleValueConverter)instance, priority);
}
} catch (Exception e) {
throw new InitializationException("Could not instatiate converter : " + className, e);
}
}
protected void setupImmutableTypes() {
if (immutableTypesMapper == null) {
return;
}
// primitives are always immutable
addImmutableType(boolean.class);
addImmutableType(Boolean.class);
addImmutableType(byte.class);
addImmutableType(Byte.class);
addImmutableType(char.class);
addImmutableType(Character.class);
addImmutableType(double.class);
addImmutableType(Double.class);
addImmutableType(float.class);
addImmutableType(Float.class);
addImmutableType(int.class);
addImmutableType(Integer.class);
addImmutableType(long.class);
addImmutableType(Long.class);
addImmutableType(short.class);
addImmutableType(Short.class);
// additional types
addImmutableType(Mapper.Null.class);
addImmutableType(BigDecimal.class);
addImmutableType(BigInteger.class);
addImmutableType(String.class);
addImmutableType(URL.class);
addImmutableType(File.class);
addImmutableType(Class.class);
if(jvm.supportsAWT()) {
addImmutableType(TextAttribute.class);
}
if (JVM.is14()) {
// late bound types - allows XStream to be compiled on earlier JDKs
Class type = jvm.loadClass("com.thoughtworks.xstream.converters.extended.CharsetConverter");
addImmutableType(type);
}
}
public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) {
this.marshallingStrategy = marshallingStrategy;
}
/**
* Serialize an object to a pretty-printed XML String.
* @throws BaseException if the object cannot be serialized
*/
public String toXML(Object obj) {
Writer writer = new StringWriter();
toXML(obj, writer);
return writer.toString();
}
/**
* Serialize an object to the given Writer as pretty-printed XML.
* @throws BaseException if the object cannot be serialized
*/
public void toXML(Object obj, Writer out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize an object to the given OutputStream as pretty-printed XML.
* @throws BaseException if the object cannot be serialized
*/
public void toXML(Object obj, OutputStream out) {
HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out);
marshal(obj, writer);
writer.flush();
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
* @throws BaseException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer) {
marshal(obj, writer, null);
}
/**
* Serialize and object to a hierarchical data structure (such as XML).
*
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws BaseException if the object cannot be serialized
*/
public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) {
marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder);
}
/**
* Deserialize an object from an XML String.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(String xml) {
return fromXML(new StringReader(xml));
}
/**
* Deserialize an object from an XML Reader.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(Reader xml) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), null);
}
/**
* Deserialize an object from an XML InputStream.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(InputStream input) {
return unmarshal(hierarchicalStreamDriver.createReader(input), null);
}
/**
* Deserialize an object from an XML String, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(String xml, Object root) {
return fromXML(new StringReader(xml), root);
}
/**
* Deserialize an object from an XML Reader, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(Reader xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from an XML InputStream, populating the fields of the given root object
* instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object fromXML(InputStream xml, Object root) {
return unmarshal(hierarchicalStreamDriver.createReader(xml), root);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader) {
return unmarshal(reader, null, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML), populating the fields
* of the given root object instead of instantiating a new one.
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root) {
return unmarshal(reader, root, null);
}
/**
* Deserialize an object from a hierarchical data structure (such as XML).
*
* @param root If present, the passed in object will have its fields populated, as opposed to
* XStream creating a new instance.
* @param dataHolder Extra data you can use to pass to your converters. Use this as you want. If
* not present, XStream shall create one lazily as needed.
* @throws BaseException if the object cannot be deserialized
*/
public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
return marshallingStrategy.unmarshal(root, reader, dataHolder, converterLookup, mapper);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addClassAlias(name, type);
}
/**
* Alias a type to a shorter name to be used in XML elements.
* Any class that is assignable to this type will be aliased to the same name.
*
* @param name Short name
* @param type Type to be aliased
* @since 1.2
* @throws InitializationException if no {@link ClassAliasingMapper} is available
*/
public void aliasType(String name, Class type) {
if (classAliasingMapper == null) {
throw new InitializationException("No "
+ ClassAliasingMapper.class.getName()
+ " available");
}
classAliasingMapper.addTypeAlias(name, type);
}
/**
* Alias a Class to a shorter name to be used in XML elements.
*
* @param name Short name
* @param type Type to be aliased
* @param defaultImplementation Default implementation of type to use if no other specified.
* @throws InitializationException if no {@link DefaultImplementationsMapper} or no {@link ClassAliasingMapper} is available
*/
public void alias(String name, Class type, Class defaultImplementation) {
alias(name, type);
addDefaultImplementation(defaultImplementation, type);
}
/**
* Create an alias for a field name.
*
* @param alias the alias itself
* @param type the type that declares the field
* @param fieldName the name of the field
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void aliasField(String alias, Class type, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.addFieldAlias(alias, type, fieldName);
}
/**
* Create an alias for an attribute
*
* @param alias the alias itself
* @param attributeName the name of the attribute
* @throws InitializationException if no {@link AttributeAliasingMapper} is available
*/
public void aliasAttribute(String alias, String attributeName) {
if (attributeAliasingMapper == null) {
throw new InitializationException("No "
+ AttributeAliasingMapper.class.getName()
+ " available");
}
attributeAliasingMapper.addAliasFor(attributeName, alias);
}
/**
* Create an alias for an attribute.
*
* @param configurableClass the type where the attribute is defined
* @param attributeName the name of the attribute
* @param alias the alias itself
* @throws InitializationException if no {@link AttributeAliasingMapper} is available
*/
public void aliasAttribute(Class configurableClass, String attributeName, String alias) {
if (attributeAliasingMapper == null) {
throw new InitializationException("No "
+ AttributeAliasingMapper.class.getName() + " available");
}
attributeAliasingMapper.addAliasFor(configurableClass, attributeName, alias);
}
/**
* Use an XML attribute for a field or a specific type.
*
* @param fieldName the name of the field
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(String fieldName, Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(fieldName, type);
}
/**
* Use an XML attribute for a field declared in a specific type.
*
* @param fieldName the name of the field
* @param definedIn the Class containing such field
* @throws InitializationException if no {@link AttributeMapper} is available
* @since upcoming
*/
public void useAttributeFor(Class definedIn, String fieldName) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
try {
final Field field = definedIn.getDeclaredField(fieldName);
attributeMapper.addAttributeFor(field);
} catch (SecurityException e) {
throw new InitializationException("Unable to access field " + fieldName + "@" + definedIn.getName());
} catch (NoSuchFieldException e) {
throw new InitializationException("Unable to find field " + fieldName + "@" + definedIn.getName());
}
}
/**
* Use an XML attribute for an arbitrary type.
*
* @param type the Class of the type to be rendered as XML attribute
* @throws InitializationException if no {@link AttributeMapper} is available
* @since 1.2
*/
public void useAttributeFor(Class type) {
if (attributeMapper == null) {
throw new InitializationException("No " + AttributeMapper.class.getName() + " available");
}
attributeMapper.addAttributeFor(type);
}
/**
* Associate a default implementation of a class with an object. Whenever XStream encounters an
* instance of this type, it will use the default implementation instead. For example,
* java.util.ArrayList is the default implementation of java.util.List.
*
* @param defaultImplementation
* @param ofType
* @throws InitializationException if no {@link DefaultImplementationsMapper} is available
*/
public void addDefaultImplementation(Class defaultImplementation, Class ofType) {
if (defaultImplementationsMapper == null) {
throw new InitializationException("No "
+ DefaultImplementationsMapper.class.getName()
+ " available");
}
defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType);
}
/**
* Add immutable types. The value of the instances of these types will always be written into
* the stream even if they appear multiple times.
* @throws InitializationException if no {@link ImmutableTypesMapper} is available
*/
public void addImmutableType(Class type) {
if (immutableTypesMapper == null) {
throw new InitializationException("No "
+ ImmutableTypesMapper.class.getName()
+ " available");
}
immutableTypesMapper.addImmutableType(type);
}
public void registerConverter(Converter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(Converter converter, int priority) {
converterLookup.registerConverter(converter, priority);
}
public void registerConverter(SingleValueConverter converter) {
registerConverter(converter, PRIORITY_NORMAL);
}
public void registerConverter(SingleValueConverter converter, int priority) {
converterLookup.registerConverter(new SingleValueConverterWrapper(converter), priority);
}
/**
* @throws ClassCastException if mapper is not really a deprecated {@link ClassMapper} instance
* @deprecated As of 1.2, use {@link #getMapper}
*/
public ClassMapper getClassMapper() {
if (mapper instanceof ClassMapper) {
return (ClassMapper)mapper;
} else {
return (ClassMapper)Proxy.newProxyInstance(getClassLoader(), new Class[]{ClassMapper.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(mapper, args);
}
});
}
}
/**
* Retrieve the {@link Mapper}. This is by default a chain of {@link MapperWrapper MapperWrappers}.
*
* @return the mapper
* @since 1.2
*/
public Mapper getMapper() {
return mapper;
}
/**
* Retrieve the {@link ReflectionProvider} in use.
*
* @return the mapper
* @since 1.2.1
*/
public ReflectionProvider getReflectionProvider() {
return reflectionProvider;
}
public ConverterLookup getConverterLookup() {
return converterLookup;
}
public void setMode(int mode) {
switch (mode) {
case NO_REFERENCES:
setMarshallingStrategy(new TreeMarshallingStrategy());
break;
case ID_REFERENCES:
setMarshallingStrategy(new ReferenceByIdMarshallingStrategy());
break;
case XPATH_RELATIVE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.RELATIVE));
break;
case XPATH_ABSOLUTE_REFERENCES:
setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy(
ReferenceByXPathMarshallingStrategy.ABSOLUTE));
break;
default:
throw new IllegalArgumentException("Unknown mode : " + mode);
}
}
/**
* Adds a default implicit collection which is used for any unmapped xml tag.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
*/
public void addImplicitCollection(Class ownerType, String fieldName) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, Object.class);
}
/**
* Adds implicit collection which is used for all items of the given itemType.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
* @param itemType type of the items to be part of this collection.
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, null, itemType);
}
/**
* Adds implicit collection which is used for all items of the given element name defined by
* itemFieldName.
*
* @param ownerType class owning the implicit collection
* @param fieldName name of the field in the ownerType. This field must be an
* <code>java.util.ArrayList</code>.
* @param itemFieldName element name of the implicit collection
* @param itemType item type to be aliases be the itemFieldName
* @throws InitializationException if no {@link ImplicitCollectionMapper} is available
*/
public void addImplicitCollection(
Class ownerType, String fieldName, String itemFieldName, Class itemType) {
if (implicitCollectionMapper == null) {
throw new InitializationException("No "
+ ImplicitCollectionMapper.class.getName()
+ " available");
}
implicitCollectionMapper.add(ownerType, fieldName, itemFieldName, itemType);
}
public DataHolder newDataHolder() {
return new MapBackedDataHolder();
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* To change the name of the root element (from <object-stream>), use
* {@link #createObjectOutputStream(java.io.Writer, String)}.
* </p>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer)
throws IOException {
return createObjectOutputStream(writer, "object-stream");
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName)
throws IOException {
return createObjectOutputStream(new PrettyPrintWriter(writer), rootNodeName);
}
/**
* Creates an ObjectOutputStream that serializes a stream of objects to the writer using
* XStream.
* <p>
* Because an ObjectOutputStream can contain multiple items and XML only allows a single root
* node, the stream must be written inside an enclosing node.
* </p>
* <p>
* It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be
* incomplete.
* </p>
* <h3>Example</h3>
*
* <pre>
* ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, "things");
* out.writeInt(123);
* out.writeObject("Hello");
* out.writeObject(someObject)
* out.close();
* </pre>
*
* @param writer The writer to serialize the objects to.
* @param rootNodeName The name of the root node enclosing the stream of objects.
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @since 1.0.3
*/
public ObjectOutputStream createObjectOutputStream(
final HierarchicalStreamWriter writer, String rootNodeName) throws IOException {
final StatefulWriter statefulWriter = new StatefulWriter(writer);
statefulWriter.startNode(rootNodeName, null);
return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() {
public void writeToStream(Object object) {
marshal(object, statefulWriter);
}
public void writeFieldsToStream(Map fields) throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void defaultWriteObject() throws NotActiveException {
throw new NotActiveException("not in call to writeObject");
}
public void flush() {
statefulWriter.flush();
}
public void close() {
if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) {
statefulWriter.endNode();
statefulWriter.close();
}
}
});
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
*
* @see #createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException {
return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader));
}
/**
* Creates an ObjectInputStream that deserializes a stream of objects from a reader using
* XStream.
* <h3>Example</h3>
*
* <pre>
* ObjectInputStream in = xstream.createObjectOutputStream(aReader);
* int a = out.readInt();
* Object b = out.readObject();
* Object c = out.readObject();
* </pre>
*
* @see #createObjectOutputStream(com.thoughtworks.xstream.io.HierarchicalStreamWriter, String)
* @since 1.0.3
*/
public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader)
throws IOException {
return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() {
public Object readFromStream() throws EOFException {
if (!reader.hasMoreChildren()) {
throw new EOFException();
}
reader.moveDown();
Object result = unmarshal(reader);
reader.moveUp();
return result;
}
public Map readFieldsFromStream() throws IOException {
throw new NotActiveException("not in call to readObject");
}
public void defaultReadObject() throws NotActiveException {
throw new NotActiveException("not in call to readObject");
}
public void registerValidation(ObjectInputValidation validation, int priority)
throws NotActiveException {
throw new NotActiveException("stream inactive");
}
public void close() {
reader.close();
}
});
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public void setClassLoader(ClassLoader classLoader) {
classLoaderReference.setReference(classLoader);
}
/**
* Change the ClassLoader XStream uses to load classes.
*
* @since 1.1.1
*/
public ClassLoader getClassLoader() {
return classLoaderReference.getReference();
}
/**
* Prevents a field from being serialized. To omit a field you must always provide the declaring
* type and not necessarily the type that is converted.
*
* @since 1.1.3
* @throws InitializationException if no {@link FieldAliasingMapper} is available
*/
public void omitField(Class type, String fieldName) {
if (fieldAliasingMapper == null) {
throw new InitializationException("No "
+ FieldAliasingMapper.class.getName()
+ " available");
}
fieldAliasingMapper.omitField(type, fieldName);
}
public static class InitializationException extends BaseException {
public InitializationException(String message, Throwable cause) {
super(message, cause);
}
public InitializationException(String message) {
super(message);
}
}
private Object readResolve() {
jvm = new JVM();
return this;
}
}
|
package fr.utbm.lo43.entities;
import java.util.ArrayList;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Line;
import org.newdawn.slick.geom.Polygon;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.StateBasedGame;
import fr.utbm.lo43.logic.Map;
public class Segment extends EntityDragable implements EntityDrawable {
private Polygon polygon;
private ArrayList<Station> stations;
private ArrayList<Vector2f> ponts;
private String iconPath;
// Line de Slick2D
Line line;
fr.utbm.lo43.logic.Line line_bus;
int lineIndex;
public Segment(Vector2f _start, Vector2f _end, int index) {
super(_start);
polygon = new Polygon();
polygon.setClosed(false);
polygon.addPoint(_start.x, _start.y);
Vector2f angle = calculateAnglePosition(_start, _end);
polygon.addPoint(angle.x, angle.y);
polygon.addPoint(_end.x, _end.y);
lineIndex = index;
dragedEvent = new EventEntityMouseDraged() {
@Override
public void mouseReleased() {
// TODO Auto-generated method stub
boolean notOnStation = true;
for (Station station : Map.getInstance().getStations()) {
if (station.position == getEndSegment()) {
notOnStation = false;
}
}
if (notOnStation) {
Map.getInstance().getLine(lineIndex).removeSegment(Map.getInstance().getLine(lineIndex)
.getSegments().get(Map.getInstance().getLine(lineIndex).getSegments().size() - 1));
}
System.out.println("Segment.Segment(...).new EventEntityMouseDraged() {...}.mouseReleased()");
}
@Override
public void mousePressed() {
// TODO Auto-generated method stub
System.out.println("Segment.MousePresssed()");
}
};
drawable = true;
}
public void setIcon(String imgPath) {
iconPath = imgPath;
}
public Vector2f getPointPolygon(int index) {
return new Vector2f(polygon.getPoint(index)[0], polygon.getPoint(index)[1]);
}
/***
* Get line number of the segment
*
* @return
*/
public int getLineIndex() {
return lineIndex;
}
public Vector2f getStartSegment() {
return getPointPolygon(0);
}
public Vector2f getEndSegment() {
return getPointPolygon(polygon.getPointCount() - 1);
}
/**
* Get all stations
*
* @return
*/
public ArrayList<Station> getStations() {
return stations;
}
public ArrayList<Vector2f> getPositions() {
ArrayList<Vector2f> _positions = new ArrayList<>();
for (int i = 0; i < polygon.getPointCount(); ++i) {
_positions.add(new Vector2f(polygon.getPoint(i)[0], polygon.getPoint(i)[1]));
}
return _positions;
}
/**
* Renvoie le segment inverse (le point de depart deviens le point d'arriv
* et inversement)
*
* @return
*/
public Segment reverse() {
return new Segment(getEndSegment(), getStartSegment(), lineIndex);
}
public boolean isReverse(Segment _segment) {
return hasSameVectors(_segment.reverse());
}
public Vector2f getMid() {
Line tempLine = new Line(getStartSegment(), getEndSegment());
return new Vector2f(tempLine.getCenterX(), tempLine.getCenterY());
}
public Vector2f getAngle() {
return calculateAnglePosition(getStartSegment(), getEndSegment());
}
@Override
public void render(Graphics arg2) {
int offset = 0;
for (int i = lineIndex; i < Map.getInstance().getLines().size(); i++) {
fr.utbm.lo43.logic.Line _line = Map.getInstance().getLine(i);
for (Segment segment : _line.getSegments()) {
if (!isCrossing(segment) && (segment.hasSameVectors(this) || isOnSegment(segment.getAngle())|| segment.isOnSegment(getAngle()))) { // donc
offset++;
}
}
}
// permet de centrer les segments si il y a des offsets
if (offset % 2 == 0) {
offset = -offset;
}
offset = offset / 2;
arg2.setLineWidth(5);
arg2.setColor(Map.getInstance().getLine(lineIndex).getColor());
Polygon _polygonrender = new Polygon();
_polygonrender.setClosed(false);
for (int i = 0; i < polygon.getPointCount(); ++i) {
// if(polygon.getPoint(i)[0] == polygon.getPoint(i+1)[0] ||
// polygon.getPoint(i)[1] == polygon.getPoint(i+1)[1]){
_polygonrender.addPoint(polygon.getPoint(i)[0], polygon.getPoint(i)[1]);
}
try{
Line tempLine = new Line(getPositions().get(0), getPositions().get(1));
int dx = (int) tempLine.getDX();
int dy = (int) tempLine.getDY();
try{
dx = Math.abs(dx)/dx;
}catch(ArithmeticException e)
{
}
try{
dy = Math.abs(dy)/dy;
}catch(ArithmeticException e){
}
if(Math.abs(dx) == 1 && Math.abs(dy) == 0){
_polygonrender.setLocation(_polygonrender.getX(), _polygonrender.getY() +5*offset);
}
if(Math.abs(dx) == 0 && Math.abs(dy) == 1){
_polygonrender.setLocation(_polygonrender.getX()+5*offset, _polygonrender.getY());
}
if(dx == dy){
_polygonrender.setLocation(_polygonrender.getX()+5*offset, _polygonrender.getY()-5*offset);
}
if(dx == -dy){
_polygonrender.setLocation(_polygonrender.getX()+5*offset, _polygonrender.getY()+5*offset);
}
}catch(IndexOutOfBoundsException e){
}
//_polygonrender.setLocation(_polygonrender.getX()+5*offset, _polygonrender.getY() +5*offset);
arg2.draw(_polygonrender);
if (iconPath != null) {
Image icon;
try {
icon = new Image(iconPath);
icon.drawFlash(getMid().x - Map.GRID_SIZE / 2, getMid().y - Map.GRID_SIZE / 2, Map.GRID_SIZE,
Map.GRID_SIZE, Map.getInstance().getLine(lineIndex).getColor());
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public boolean isFirstinLine() {
return Map.getInstance().getLines().get(lineIndex).getSegments().get(0) == this;
}
public boolean isLastinLine() {
return Map.getInstance().getLines().get(lineIndex).getSegments()
.get(Map.getInstance().getLines().get(lineIndex).getSegments().size() - 1) == this;
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) {
super.update(gc, sbg, delta);
Input input = gc.getInput();
if (getRect().contains(input.getMouseX(), input.getMouseY())
&& input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
if (isGrabed == true) {
position.x = input.getMouseX() - (size.x / 2.0f);
position.y = input.getMouseY() - (size.y / 2.0f);
if (dragedEvent != null)
dragedEvent.mousePressed();
} else {
isGrabed = true;
}
} else {
if (isGrabed != false) {
if (dragedEvent != null)
dragedEvent.mouseReleased();
isGrabed = false;
}
}
}
/***
* To know if a segment cross another one
*
* @param _segment
* Segment to compare
* @return true if the segment cross the line false if not
*/
public boolean isCrossing(Segment _segment) {
if (this == _segment) {
return false;
}
Line tempLine1;
Line tempLine2;
Vector2f intersection;
boolean intersect = false;
for (int i = 0; i < polygon.getPointCount() - 1; ++i) {
tempLine1 = new Line(new Vector2f(polygon.getPoint(i)[0], polygon.getPoint(i)[1]),
new Vector2f(polygon.getPoint(i + 1)[0], polygon.getPoint(i + 1)[1]));
for (int j = 0; j < _segment.polygon.getPointCount() - 1; ++j) {
tempLine2 = new Line(new Vector2f(_segment.polygon.getPoint(j)[0], _segment.polygon.getPoint(j)[1]),
new Vector2f(_segment.polygon.getPoint(j + 1)[0], _segment.polygon.getPoint(j + 1)[1]));
intersection = null;
intersection = tempLine1.intersect(tempLine2, true);
if (intersection != null) {
if (intersection.distance(_segment.getStartSegment()) == 0
|| intersection.distance(_segment.getEndSegment()) == 0
|| intersection.distance(_segment.getAngle()) == 0
|| intersection.distance(getAngle()) == 0) {
} else {
intersect = true;
}
}
}
}
return intersect;
// System.out.println(_segment.line.getpo);
}
public boolean hasSameVectors(Segment _seg) {
if ((_seg.getStartSegment().distance(getStartSegment()) == 0
&& _seg.getEndSegment().distance(getEndSegment()) == 0))
return true;
return false;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if (obj.getClass() != getClass())
return false;
Segment _obj = (Segment) obj;
if (obj == this)
return true;
else if (_obj.getLineIndex() == lineIndex)
if ((_obj.getStartSegment().distance(getStartSegment()) == 0
&& _obj.getEndSegment().distance(getEndSegment()) == 0)
|| (_obj.getStartSegment().distance(getEndSegment()) == 0
&& _obj.getEndSegment().distance(getStartSegment()) == 0)) {
return true;
}
return false;
}
public Segment getNextSegment() {
return (line_bus.getSegments().indexOf(this) + 1) <= (line_bus.getSegments().size())
? line_bus.getSegments().get(line_bus.getSegments().indexOf(this) + 1) : null;
}
public Segment getPreviousSegment() {
return (line_bus.getSegments().indexOf(this) - 1) > 0
? line_bus.getSegments().get(line_bus.getSegments().indexOf(this) + 1) : null;
}
/**
* Retourne la longueur d'un segment
*
* @return
*/
public float getLength() {
float length = 0;
for (int i = 0; i < getPositions().size() - 1; ++i) {
length += getPositions().get(i).distance(getPositions().get(i + 1));
}
return length;
}
/**
* Verifie si un point est sur le segment
*
* @param _vector
* @return
*/
public boolean isOnSegment(Vector2f _vector) {
Line _line;
for (int i = 0; i < getPositions().size() - 1; ++i) {
_line = new Line(getPositions().get(i), getPositions().get(i + 1));
if (_line.on(_vector)) {
return true;
}
}
return false;
}
/**
* Calcule la position de l'angle du segment qui relie 2 positions
*
* @param position1
* @param position2
* @return
*/
public static Vector2f calculateAnglePosition(Vector2f position1, Vector2f position2) {
Vector2f anglePosition;
float distancePosition1;
float distancePosition2;
Line lineTemp1 = new Line(position1.x, position1.y, 0, 1, true);
Line lineTemp2 = new Line(position2.x, position2.y, 1, 1, true);
distancePosition1 = position1.distance(lineTemp1.intersect(lineTemp2));
distancePosition2 = position2.distance(lineTemp1.intersect(lineTemp2));
anglePosition = lineTemp1.intersect(lineTemp2);
lineTemp1 = new Line(position1.x, position1.y, 1, 0, true);
lineTemp2 = new Line(position2.x, position2.y, 1, 1, true);
if (distancePosition1 > position1.distance(lineTemp1.intersect(lineTemp2))) {
anglePosition = lineTemp1.intersect(lineTemp2);
distancePosition1 = position1.distance(lineTemp1.intersect(lineTemp2));
distancePosition2 = position2.distance(lineTemp1.intersect(lineTemp2));
} else if (distancePosition1 == position1.distance(lineTemp1.intersect(lineTemp2))) {
if (distancePosition2 > position2.distance(lineTemp1.intersect(lineTemp2))) {
anglePosition = lineTemp1.intersect(lineTemp2);
distancePosition1 = position1.distance(lineTemp1.intersect(lineTemp2));
distancePosition2 = position2.distance(lineTemp1.intersect(lineTemp2));
}
}
lineTemp1 = new Line(position1.x, position1.y, 0, 1, true);
lineTemp2 = new Line(position2.x, position2.y, -1, 1, true);
if (distancePosition1 > position1.distance(lineTemp1.intersect(lineTemp2))) {
anglePosition = lineTemp1.intersect(lineTemp2);
distancePosition1 = position1.distance(lineTemp1.intersect(lineTemp2));
distancePosition2 = position2.distance(lineTemp1.intersect(lineTemp2));
} else if (distancePosition1 == position1.distance(lineTemp1.intersect(lineTemp2))) {
if (distancePosition2 > position2.distance(lineTemp1.intersect(lineTemp2))) {
anglePosition = lineTemp1.intersect(lineTemp2);
distancePosition1 = position1.distance(lineTemp1.intersect(lineTemp2));
distancePosition2 = position2.distance(lineTemp1.intersect(lineTemp2));
}
}
lineTemp1 = new Line(position1.x, position1.y, 1, 0, true);
lineTemp2 = new Line(position2.x, position2.y, -1, 1, true);
if (distancePosition1 > position1.distance(lineTemp1.intersect(lineTemp2))) {
anglePosition = lineTemp1.intersect(lineTemp2);
distancePosition1 = position1.distance(lineTemp1.intersect(lineTemp2));
distancePosition2 = position2.distance(lineTemp1.intersect(lineTemp2));
} else if (distancePosition1 == position1.distance(lineTemp1.intersect(lineTemp2))) {
if (distancePosition2 > position2.distance(lineTemp1.intersect(lineTemp2))) {
anglePosition = lineTemp1.intersect(lineTemp2);
distancePosition1 = position1.distance(lineTemp1.intersect(lineTemp2));
distancePosition2 = position2.distance(lineTemp1.intersect(lineTemp2));
}
}
return anglePosition;
}
}
|
package edu.teco.dnd.module;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import edu.teco.dnd.network.ConnectionManager;
public class ApplicationClassLoader extends ClassLoader {
private static final Logger LOGGER = LogManager.getLogger(ApplicationClassLoader.class);
private Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
private Map<String, byte[]> classBytes = new HashMap<String, byte[]>();
public ApplicationClassLoader(ConnectionManager connMan, UUID associatedAppId) {
}
@Override
protected Class<?> loadClass(String name, boolean resolveIt) throws ClassNotFoundException {
Class<?> clazz = classes.get(name);
if (clazz != null) {
return clazz; // must always return same if requested twice!
}
try {
return super.loadClass(name, resolveIt);
} catch (ClassNotFoundException e) {
// Continuing below. Error is expected behavior.
}
LOGGER.trace("app loading class: " + name);
if (name.startsWith("java.")) {
throw new ClassNotFoundException("a part of the fully classified name \"" + name
+ "\" is not permitted by this classloader.");
}
System.getSecurityManager().checkPackageAccess(name);
byte[] clBytes = classBytes.get(name);
if (clBytes != null) {
clazz = defineClass(name, clBytes, 0, clBytes.length);
if (clazz == null) {
throw new ClassFormatError();
}
if (resolveIt) {
resolveClass(clazz);
}
classes.put(name, clazz);
classBytes.remove(name);
return clazz;
} else {
LOGGER.warn("class " + name + " bytecode was not loaded before it was instantiated.");
throw new ClassNotFoundException();
// TODO This would be a good point to request class bytecode from other modules, if so desired.
}
}
public void appLoadClass(String name, byte[] classData) {
if(name == null || classData == null) {
throw new NullPointerException();
}
if (!classes.containsKey(name) && !classBytes.containsKey(name)) {
classBytes.put(name, classData);
} else {
LOGGER.debug("double loaded bytecode of class: " + name);
}
}
}
|
package org.kohsuke.args4j.spi;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import org.kohsuke.args4j.CmdLineParser;
/**
* Factory of {@link Setter}s.
*
* @author Kohsuke Kawaguchi
*/
public class Setters {
private Setters() {
// no instance allowed
}
public static Setter create(CmdLineParser parser, AccessibleObject fieldOrMethod, Object bean) {
if (fieldOrMethod instanceof Method) {
return new MethodSetter(parser,bean,(Method) fieldOrMethod);
} else {
return create((Field)fieldOrMethod,bean);
}
}
public static Setter create(Field f, Object bean) {
if (Modifier.isFinal(f.getModifiers()))
throw new IllegalStateException(String.format("Cannot set value to a final field '%s'.", f.getName()));
if(f.getType().isArray())
return new ArrayFieldSetter(bean,f);
if(List.class.isAssignableFrom(f.getType()))
return new MultiValueFieldSetter(bean,f);
else
return new FieldSetter(bean,f);
}
}
|
package com.vmware.vim25.mo.samples;
import java.net.URL;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;
public class HelloVM
{
public static void main(String[] args) throws Exception
{
long start = System.currentTimeMillis();
ServiceInstance si = new ServiceInstance(new URL("https://10.115.66.232/sdk"), "root", "password", true);
long end = System.currentTimeMillis();
System.out.println("time taken:" + (end-start));
Folder rootFolder = si.getRootFolder();
String name = rootFolder.getName();
System.out.println("root:" + name);
ManagedEntity[] mes = new InventoryNavigator(rootFolder).searchManagedEntities("VirtualMachine");
if(mes==null || mes.length ==0)
{
return;
}
VirtualMachine vm = (VirtualMachine) mes[0];
VirtualMachineConfigInfo vminfo = vm.getConfig();
VirtualMachineCapability vmc = vm.getCapability();
vm.getResourcePool();
System.out.println("Hello " + vm.getName());
System.out.println("GuestOS: " + vminfo.getGuestFullName());
System.out.println("Multiple snapshot supported: " + vmc.isMultipleSnapshotsSupported());
si.getServerConnection().logout();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.wizzardo.tools.image;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.wizzardo.tools.io.FileTools;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.*;
import java.io.*;
/**
* @author Moxa
*/
public class ImageTools {
private static ICC_Profile CMYK_PROFILE;
public static void setCmykProfile(File iccProfile) throws IOException {
setCmykProfile(new FileInputStream(iccProfile));
}
public static void setCmykProfile(InputStream iccProfile) throws IOException {
CMYK_PROFILE = ICC_Profile.getInstance(iccProfile);
}
public static BufferedImage toGrayScale2(BufferedImage source) {
BufferedImageOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
BufferedImage im = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
op.filter(source, im);
return im;
}
public static BufferedImage toGrayScale(BufferedImage source) {
BufferedImage im = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
im.getGraphics().drawImage(source, 0, 0, null);
return im;
}
public static void saveJPG(BufferedImage im, String file, int quality) throws IOException {
saveJPG(im, new FileOutputStream(file), quality);
}
public static void saveJPG(BufferedImage im, File file, int quality) throws IOException {
saveJPG(im, new FileOutputStream(file), quality);
}
public static byte[] saveJPGtoBytes(BufferedImage im, int quality) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
saveJPG(im, bytes, quality);
return bytes.toByteArray();
}
public static void saveJPG(BufferedImage im, OutputStream out, int quality) throws IOException {
JpegEncoder encoder = new JpegEncoder(im, quality, out);
encoder.Compress();
out.close();
}
public static void savePNG(BufferedImage im, String file) throws IOException {
ImageIO.write(im, "png", new File(file));
}
public static void savePNG(BufferedImage im, File file) throws IOException {
ImageIO.write(im, "png", file);
}
public static void savePNG(BufferedImage im, OutputStream out) throws IOException {
ImageIO.write(im, "png", out);
}
public static byte[] savePNGtoBytes(BufferedImage im) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ImageIO.write(im, "png", bytes);
return bytes.toByteArray();
}
public static BufferedImage crop(BufferedImage src, int x1, int y1, int x2, int y2) {
int x = x1 > x2 ? x2 : x1;
int y = y1 > y2 ? y2 : y1;
return src.getSubimage(x, y, Math.abs(x2 - x1), Math.abs(y2 - y1));
}
public static BufferedImage read(File f) throws IOException {
return read(FileTools.bytes(f));
}
public static BufferedImage read(byte[] bytes) throws IOException {
if (CMYK_PROFILE == null)
return read(new ByteArrayInputStream(bytes));
try {
return ImageIO.read(new ByteArrayInputStream(bytes));
} catch (javax.imageio.IIOException e) {
return readAndConvertFromCMYK(new ByteArrayInputStream(bytes));
}
}
public static BufferedImage read(InputStream in) throws IOException {
return ImageIO.read(in);
}
public static BufferedImage readAndConvertFromCMYK(InputStream in) throws IOException {
if (CMYK_PROFILE == null)
throw new IOException("You need to setup CMYK profile first by method setCmykProfile");
return readAndConvertFromCMYK(in, CMYK_PROFILE);
}
public static BufferedImage readAndConvertFromCMYK(InputStream in, ICC_Profile cmykProfile) throws IOException {
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
BufferedImage src = decoder.decodeAsBufferedImage();
WritableRaster srcRaster = src.getRaster();
//prepare result image
BufferedImage result = new BufferedImage(srcRaster.getWidth(), srcRaster.getHeight(), BufferedImage.TYPE_INT_RGB);
WritableRaster resultRaster = result.getRaster();
//prepare icc profiles
ColorSpace sRGBColorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
//invert k channel
for (int x = srcRaster.getMinX(); x < srcRaster.getWidth(); x++) {
for (int y = srcRaster.getMinY(); y < srcRaster.getHeight(); y++) {
float[] pixel = srcRaster.getPixel(x, y, (float[]) null);
pixel[3] = 255f - pixel[3];
srcRaster.setPixel(x, y, pixel);
}
}
//convert
ColorConvertOp cmykToRgb = new ColorConvertOp(new ICC_ColorSpace(cmykProfile), sRGBColorSpace, null);
cmykToRgb.filter(srcRaster, resultRaster);
return result;
}
public static BufferedImage read(String f) throws IOException {
return read(new File(f));
}
public static BufferedImage trim(BufferedImage src) {
return trim(src, 0);
}
public static BufferedImage trim(BufferedImage src, int diff) {
return trimHorizontal(trimVertical(src, diff), diff);
}
public static BufferedImage trimHorizontal(BufferedImage src) {
return trimHorizontal(src, 0);
}
public static BufferedImage trimVertical(BufferedImage src) {
return trimVertical(src, 0);
}
public static BufferedImage trimHorizontal(BufferedImage src, int diff) {
int color = src.getRGB(0, 0);
boolean clear = true;
int x;
for (x = 0; x < src.getWidth() && clear; x++) {
int y = 0;
while (clear && y < src.getHeight()) {
clear = diff(color, src.getRGB(x, y)) <= diff;
y++;
}
}
x
int left = x > 0 ? x - 1 : 0;
clear = true;
for (x = src.getWidth() - 1; x >= 0 && clear; x
int y = 0;
while (clear && y < src.getHeight()) {
clear = diff(color, src.getRGB(x, y)) <= diff;
y++;
}
}
x++;
int right = x < src.getWidth() ? x + 1 : src.getWidth();
return crop(src, left, 0, right, src.getHeight());
}
public static BufferedImage trimVertical(BufferedImage src, int diff) {
int color = src.getRGB(0, 0);
boolean clear = true;
int y;
for (y = 0; y < src.getHeight() && clear; y++) {
int x = 0;
while (clear && x < src.getWidth()) {
clear = diff(color, src.getRGB(x, y)) <= diff;
x++;
}
}
y
int top = y > 0 ? y - 1 : 0;
clear = true;
for (y = src.getHeight() - 1; y >= 0 && clear; y
int x = 0;
while (clear && x < src.getWidth()) {
clear = diff(color, src.getRGB(x, y)) <= diff;
x++;
}
}
y++;
int bottom = y < src.getHeight() ? y + 1 : src.getHeight();
return crop(src, 0, top, src.getWidth(), bottom);
}
public static int alpha(int rgb) {
return (rgb >> 24) & 0xff;
}
public static int red(int rgb) {
return (rgb >> 16) & 0xFF;
}
public static int green(int rgb) {
return (rgb >> 8) & 0xFF;
}
public static int blue(int rgb) {
return (rgb >> 0) & 0xFF;
}
public static int diff(Color c1, Color c2) {
return diff(c1.getRGB(), c2.getRGB());
}
public static int diff(int c1, int c2) {
return (int) Math.sqrt(Math.pow(alpha(c1) - alpha(c2), 2)
+ Math.pow(red(c1) - red(c2), 2)
+ Math.pow(green(c1) - green(c2), 2)
+ Math.pow(blue(c1) - blue(c2), 2));
}
public static void drawThickLine(Graphics g, int x1, int y1, int x2, int y2, int thickness, Color c) {
// The thick line is in fact a filled polygon
g.setColor(c);
int dX = x2 - x1;
int dY = y2 - y1;
// line length
double lineLength = Math.sqrt(dX * dX + dY * dY);
double scale = (double) (thickness) / (2 * lineLength);
// The x,y increments from an endpoint needed to create a rectangle...
double ddx = -scale * (double) dY;
double ddy = scale * (double) dX;
ddx += (ddx > 0) ? 0.5 : -0.5;
ddy += (ddy > 0) ? 0.5 : -0.5;
int dx = (int) ddx;
int dy = (int) ddy;
// Now we can compute the corner points...
int xPoints[] = new int[4];
int yPoints[] = new int[4];
xPoints[0] = x1 + dx;
yPoints[0] = y1 + dy;
xPoints[1] = x1 - dx;
yPoints[1] = y1 - dy;
xPoints[2] = x2 - dx;
yPoints[2] = y2 - dy;
xPoints[3] = x2 + dx;
yPoints[3] = y2 + dy;
g.fillPolygon(xPoints, yPoints, 4);
}
public static BufferedImage resizeToWidth(BufferedImage im, int width) throws IOException {
double scale = (width * 1.0) / im.getWidth();
return resize(im, scale);
}
public static BufferedImage resizeToHeight(BufferedImage im, int height) throws IOException {
double scale = (height * 1.0) / im.getHeight();
return resize(im, scale);
}
public static BufferedImage resizeToFit(BufferedImage im, int width, int height) throws IOException {
double scale = Math.min((width * 1.0) / im.getWidth(), (height * 1.0) / im.getHeight());
return resize(im, scale);
}
public static BufferedImage resize(BufferedImage im, double scale) {
int width = (int) (im.getWidth() * scale + 0.5f);
int height = (int) (im.getHeight() * scale + 0.5f);
ResampleOp resizeOp = new ResampleOp(new Lanczos3Filter(), width, height);
return resizeOp.filter(im, null);
}
public static BufferedImage applyAlphaMask(BufferedImage src, BufferedImage mask) {
WritableRaster alpha = mask.getAlphaRaster();
int[] data = new int[mask.getWidth() * mask.getHeight()];
alpha.getPixels(0, 0, mask.getWidth(), mask.getHeight(), data);
if (src.getAlphaRaster() == null) {
BufferedImage t = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB);
t.getGraphics().drawImage(src, 0, 0, null);
src = t;
}
src.getAlphaRaster().setPixels(0, 0, mask.getWidth(), mask.getHeight(), data);
return src;
}
public static BufferedImage applyMask(BufferedImage src, BufferedImage mask) {
if (src.getAlphaRaster() == null) {
BufferedImage t = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB);
t.getGraphics().drawImage(src, 0, 0, null);
src = t;
}
int w = Math.min(src.getWidth(), mask.getWidth());
int h = Math.min(src.getHeight(), mask.getHeight());
int[] data = mask.getRGB(0, 0, w, h, null, 0, w);
for (int i = 0; i < data.length; i++) {
data[i] = red(data[i]);
}
src.getAlphaRaster().setPixels(0, 0, w, h, data);
return src;
}
public static BufferedImage drawOver(BufferedImage src, BufferedImage img) {
src.getGraphics().drawImage(img, 0, 0, null);
return src;
}
public static BufferedImage resizeCanvas(BufferedImage src, int width, int height, Color background) {
return resizeCanvas(src, width, height, background, Position.CENTER);
}
public static enum Position {
LEFT, RIGHT, TOP, BOTTOM, CENTER, LEFT_TOP, LEFT_BOTTOM, RIGHT_TOP, RIGHT_BOTTOM;
}
public static BufferedImage resizeCanvas(BufferedImage src, int width, int height, Color background, Position p) {
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
if (background != null) {
g.setColor(background);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
}
int x, y;
switch (p) {
case TOP: {
x = (width - src.getWidth()) / 2;
y = 0;
break;
}
case BOTTOM: {
x = (width - src.getWidth()) / 2;
y = (height - src.getHeight());
break;
}
case LEFT: {
x = 0;
y = (height - src.getHeight()) / 2;
break;
}
case RIGHT: {
x = (width - src.getWidth());
y = (height - src.getHeight()) / 2;
break;
}
case LEFT_TOP: {
x = 0;
y = 0;
break;
}
case LEFT_BOTTOM: {
x = 0;
y = (height - src.getHeight());
break;
}
case RIGHT_TOP: {
x = (width - src.getWidth());
y = 0;
break;
}
case RIGHT_BOTTOM: {
x = (width - src.getWidth());
y = (height - src.getHeight());
break;
}
case CENTER:
default: {
x = (width - src.getWidth()) / 2;
y = (height - src.getHeight()) / 2;
break;
}
}
g.drawImage(src, x, y, null);
return img;
}
public static BufferedImage colorToAlpha(BufferedImage im, Color c) {
BufferedImage img = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
int[] temp = new int[4];
Raster src = im.getRaster();
WritableRaster result = img.getRaster();
boolean hasAlpha = im.getColorModel().hasAlpha();
int r = c.getRed(), g = c.getGreen(), b = c.getBlue();
for (int x = 0; x < im.getWidth(); x++) {
for (int y = 0; y < im.getHeight(); y++) {
colorToAlpha(src.getPixel(x, y, temp), hasAlpha, r, g, b);
result.setPixel(x, y, temp);
}
}
return img;
}
private static void colorToAlpha(int[] c, boolean hasAlpha, int r1, int g1, int b1) {
int r, g, b, a;
if (hasAlpha) {
r = c[0];
g = c[1];
b = c[2];
a = c[3];
} else {
a = 255;
r = c[0];
g = c[1];
b = c[2];
}
float red, green, blue, alpha;
if (r1 == 0) {
red = r;
} else if (r > r1) {
red = (r - r1) / (255.0f - r1);
} else if (r < r1) {
red = (r1 - r) / (r1 * 1f);
} else {
red = 0.0f;
}
if (g1 == 0) {
green = g;
} else if (g > g1) {
green = (g - g1) / (255.0f - g1);
} else if (g < g1) {
green = (g1 - g) / (g1 * 1f);
} else {
green = 0.0f;
}
if (b1 == 0) {
blue = b;
} else if (b > b1) {
blue = (b - b1) / (255.0f - b1);
} else if (b < b1) {
blue = (b1 - b) / (b1 * 1f);
} else {
blue = 0.0f;
}
if (red > green) {
if (red > blue) {
alpha = red;
} else {
alpha = blue;
}
} else {
if (green > blue) {
alpha = green;
} else {
alpha = blue;
}
}
if (alpha < 0.001) {
c[3] = (int) (alpha * 255);
}
r = (int) ((r - r1) / alpha + r1 + 0.5f);
g = (int) ((g - g1) / alpha + g1 + 0.5f);
b = (int) ((b - b1) / alpha + b1 + 0.5f);
a = (int) (a * alpha + 0.5f);
c[0] = r;
c[1] = g;
c[2] = b;
c[3] = a;
}
public static String toString(Color c) {
return "[" + c.getAlpha() + "," + c.getRed() + "," + c.getGreen() + "," + c.getBlue() + "]";
}
public static BufferedImage rotate(BufferedImage img, double angle) {
double angleRadians = Math.toRadians(angle);
int width = img.getWidth();
int height = img.getHeight();
double x = width / 2;
double y = height / 2;
double cos = Math.abs(Math.cos(angleRadians));
double sin = Math.abs(Math.sin(angleRadians));
int w = (int) (width * cos + height * sin + 0.5);
int h = (int) (width * sin + height * cos + 0.5);
BufferedImage result = new BufferedImage(w, h, img.getType());
Graphics2D g = result.createGraphics();
g.translate((w - img.getWidth()) / 2, (h - img.getHeight()) / 2);
g.rotate(angleRadians, x, y);
g.drawRenderedImage(img, null);
g.dispose();
return result;
}
}
|
package dr.evolution.alignment;
import dr.evolution.datatype.Codons;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.GeneralDataType;
import dr.evolution.sequence.Sequence;
import dr.evolution.sequence.Sequences;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import java.util.Collections;
import java.util.List;
/**
* A simple alignment class that implements gaps by characters in the sequences.
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: SimpleAlignment.java,v 1.46 2005/06/21 16:25:15 beth Exp $
*/
public class SimpleAlignment extends Sequences implements Alignment, dr.util.XHTMLable {
// SimpleAlignment METHODS
/**
* parameterless constructor.
*/
public SimpleAlignment() {
}
/**
* Constructs a sub alignment based on the provided taxa.
*
* @param a
* @param taxa
*/
public SimpleAlignment(Alignment a, TaxonList taxa) {
for (int i = 0; i < taxa.getTaxonCount(); i++) {
Taxon taxon = taxa.getTaxon(i);
Sequence sequence = a.getSequence(a.getTaxonIndex(taxon));
addSequence(sequence);
}
}
public List<Sequence> getSequences() {
return Collections.unmodifiableList(sequences);
}
/**
* Calculates the siteCount by finding the longest sequence.
*/
public void updateSiteCount() {
siteCount = 0;
int i, len, n = getSequenceCount();
for (i = 0; i < n; i++) {
len = getSequence(i).getLength();
if (len > siteCount)
siteCount = len;
}
siteCountKnown = true;
}
// Alignment IMPLEMENTATION
/**
* Sets the dataType of this alignment. This should be the same as
* the sequences.
*/
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
/**
* @return number of sites
*/
public int getSiteCount(DataType dataType) {
return getSiteCount();
}
/**
* sequence character at (sequence, site)
*/
public char getChar(int sequenceIndex, int siteIndex) {
return getSequence(sequenceIndex).getChar(siteIndex);
}
/**
* Returns string representation of single sequence in
* alignment with gap characters included.
*/
public String getAlignedSequenceString(int sequenceIndex) {
return getSequence(sequenceIndex).getSequenceString();
}
/**
* Returns string representation of single sequence in
* alignment with gap characters excluded.
*/
public String getUnalignedSequenceString(int sequenceIndex) {
StringBuffer unaligned = new StringBuffer();
for (int i = 0, n = getSiteCount(); i < n; i++) {
int state = getState(sequenceIndex, i);
if (!dataType.isGapState(state)) {
unaligned.append(dataType.getChar(state));
}
}
return unaligned.toString();
}
// Sequences METHODS
/**
* Add a sequence to the sequence list
*/
public void addSequence(Sequence sequence) {
if (dataType == null) {
if (sequence.getDataType() == null) {
dataType = sequence.guessDataType();
sequence.setDataType(dataType);
} else {
setDataType(sequence.getDataType());
}
} else if (sequence.getDataType() == null) {
sequence.setDataType(dataType);
} else if (dataType != sequence.getDataType()) {
throw new IllegalArgumentException("Sequence's dataType does not match the alignment's");
}
int invalidCharAt = getInvalidChar(sequence.getSequenceString(), dataType);
if (invalidCharAt >= 0)
throw new IllegalArgumentException("Sequence of " + sequence.getTaxon().getId()
+ " contains invalid char \'" + sequence.getChar(invalidCharAt) + "\' at index " + invalidCharAt);
super.addSequence(sequence);
updateSiteCount();
}
/**
* Insert a sequence to the sequence list at position
*/
public void insertSequence(int position, Sequence sequence) {
if (dataType == null) {
if (sequence.getDataType() == null) {
dataType = sequence.guessDataType();
sequence.setDataType(dataType);
} else {
setDataType(sequence.getDataType());
}
} else if (sequence.getDataType() == null) {
sequence.setDataType(dataType);
} else if (dataType != sequence.getDataType()) {
throw new IllegalArgumentException("Sequence's dataType does not match the alignment's");
}
int invalidCharAt = getInvalidChar(sequence.getSequenceString(), dataType);
if (invalidCharAt >= 0)
throw new IllegalArgumentException("Sequence of " + sequence.getTaxon().getId()
+ " contains invalid char \'" + sequence.getChar(invalidCharAt) + "\' at index " + invalidCharAt);
super.insertSequence(position, sequence);
}
/**
* search invalid character in the sequence by given data type, and return its index
*/
protected int getInvalidChar(String sequence, DataType dataType) {
final char[] validChars = dataType.getValidChars();
if (validChars != null) {
String validString = new String(validChars);
for (int i = 0; i < sequence.length(); i++) {
char c = sequence.charAt(i);
if (validString.indexOf(c) < 0) return i;
}
}
return -1;
}
// SiteList IMPLEMENTATION
/**
* @return number of sites
*/
public int getSiteCount() {
if (!siteCountKnown)
updateSiteCount();
return siteCount;
}
/**
* Gets the pattern of site as an array of state numbers (one per sequence)
*
* @return the site pattern at siteIndex
*/
public int[] getSitePattern(int siteIndex) {
Sequence seq;
int i, n = getSequenceCount();
int[] pattern = new int[n];
for (i = 0; i < n; i++) {
seq = getSequence(i);
if (siteIndex >= seq.getLength())
pattern[i] = dataType.getGapState();
else
pattern[i] = seq.getState(siteIndex);
}
return pattern;
}
/**
* Gets the pattern index at a particular site
*
* @return the patternIndex
*/
public int getPatternIndex(int siteIndex) {
return siteIndex;
}
/**
* @return the sequence state at (taxon, site)
*/
public int getState(int taxonIndex, int siteIndex) {
Sequence seq = getSequence(taxonIndex);
if (siteIndex >= seq.getLength()) {
return dataType.getGapState();
}
return seq.getState(siteIndex);
}
public void setState(int taxonIndex, int siteIndex, int state) {
Sequence seq = getSequence(taxonIndex);
if (siteIndex >= seq.getLength()) {
throw new IllegalArgumentException();
}
seq.setState(siteIndex, state);
}
// PatternList IMPLEMENTATION
/**
* @return number of patterns
*/
public int getPatternCount() {
return getSiteCount();
}
/**
* @return number of invariant sites
*/
public int getInvariantCount() {
int invariantSites = 0;
for (int i = 0; i < getSiteCount(); i++) {
int[] pattern = getSitePattern(i);
if (Patterns.isInvariant(pattern)) {
invariantSites++;
}
}
return invariantSites;
}
public int getUniquePatternCount() {
Patterns patterns = new Patterns(this);
return patterns.getPatternCount();
}
public int getInformativeCount() {
Patterns patterns = new Patterns(this);
int informativeCount = 0;
for (int i = 0; i < patterns.getPatternCount(); i++) {
int[] pattern = patterns.getPattern(i);
if (isInformative(pattern)) {
informativeCount += patterns.getPatternWeight(i);
}
}
return informativeCount;
}
public int getSingletonCount() {
Patterns patterns = new Patterns(this);
int singletonCount = 0;
for (int i = 0; i < patterns.getPatternCount(); i++) {
int[] pattern = patterns.getPattern(i);
if (!Patterns.isInvariant(pattern) && !isInformative(pattern)) {
singletonCount += patterns.getPatternWeight(i);
}
}
return singletonCount;
}
private boolean isInformative(int[] pattern) {
int[] stateCounts = new int[getStateCount()];
for (int j = 0; j < pattern.length; j++) {
stateCounts[pattern[j]]++;
}
boolean oneStateGreaterThanOne = false;
boolean secondStateGreaterThanOne = false;
for (int j = 0; j < stateCounts.length; j++) {
if (stateCounts[j] > 1) {
if (!oneStateGreaterThanOne) {
oneStateGreaterThanOne = true;
} else {
secondStateGreaterThanOne = true;
}
}
}
return secondStateGreaterThanOne;
}
/**
* @return number of states for this siteList
*/
public int getStateCount() {
return getDataType().getStateCount();
}
/**
* Gets the length of the pattern strings which will usually be the
* same as the number of taxa
*
* @return the length of patterns
*/
public int getPatternLength() {
return getSequenceCount();
}
/**
* Gets the pattern as an array of state numbers (one per sequence)
*
* @return the pattern at patternIndex
*/
public int[] getPattern(int patternIndex) {
return getSitePattern(patternIndex);
}
/**
* @return state at (taxonIndex, patternIndex)
*/
public int getPatternState(int taxonIndex, int patternIndex) {
return getState(taxonIndex, patternIndex);
}
/**
* Gets the weight of a site pattern (always 1.0)
*/
public double getPatternWeight(int patternIndex) {
return 1.0;
}
/**
* @return the array of pattern weights
*/
public double[] getPatternWeights() {
double[] weights = new double[siteCount];
for (int i = 0; i < siteCount; i++)
weights[i] = 1.0;
return weights;
}
/**
* @return the DataType of this siteList
*/
public DataType getDataType() {
return dataType;
}
/**
* @return the frequency of each state
*/
public double[] getStateFrequencies() {
return PatternList.Utils.empiricalStateFrequencies(this);
}
public void setReportCountStatistics(boolean report) {
countStatistics = report;
}
public String toString() {
dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(6);
StringBuffer buffer = new StringBuffer();
// boolean countStatistics = !(dataType instanceof Codons) && !(dataType instanceof GeneralDataType);
if (countStatistics) {
buffer.append("Site count = ").append(getSiteCount()).append("\n");
buffer.append("Invariant sites = ").append(getInvariantCount()).append("\n");
buffer.append("Singleton sites = ").append(getSingletonCount()).append("\n");
buffer.append("Parsimony informative sites = ").append(getInformativeCount()).append("\n");
buffer.append("Unique site patterns = ").append(getUniquePatternCount()).append("\n\n");
}
for (int i = 0; i < getSequenceCount(); i++) {
String name = formatter.formatToFieldWidth(getTaxonId(i), 10);
buffer.append(">" + name + "\n");
buffer.append(getAlignedSequenceString(i) + "\n");
}
return buffer.toString();
}
public String toXHTML() {
String xhtml = "<p><em>Alignment</em> data type = ";
xhtml += getDataType().getDescription();
xhtml += ", no. taxa = ";
xhtml += getTaxonCount();
xhtml += ", no. sites = ";
xhtml += getSiteCount();
xhtml += "</p>";
xhtml += "<pre>";
int length, maxLength = 0;
for (int i = 0; i < getTaxonCount(); i++) {
length = getTaxonId(i).length();
if (length > maxLength)
maxLength = length;
}
for (int i = 0; i < getTaxonCount(); i++) {
length = getTaxonId(i).length();
xhtml += getTaxonId(i);
for (int j = length; j <= maxLength; j++)
xhtml += " ";
xhtml += getAlignedSequenceString(i) + "\n";
}
xhtml += "</pre>";
return xhtml;
}
// INSTANCE VARIABLES
private DataType dataType = null;
private int siteCount = 0;
private boolean siteCountKnown = false;
private boolean countStatistics = true;
}
|
package com.evolveum.midpoint.provisioning.ucf.impl;
import org.identityconnectors.common.logging.Log.Level;
import org.identityconnectors.common.logging.LogSpi;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
/**
* Logger for ICF Connectors.
*
* The ICF connectors will call this class to log messages. It is configured in
* META-INF/services/org.identityconnectors.common.logging
*
* @author Katka Valalikova
*
*/
public class Slf4jConnectorLogger implements LogSpi {
@Override
public void log(Class<?> clazz, String method, Level level, String message, Throwable ex) {
Trace LOGGER = TraceManager.getTrace(clazz);
//Mark all messages from ICF as ICF
Marker m = MarkerFactory.getMarker("ICF");
//Translate ICF logging into slf4j
// OK -> trace
// INFO -> debug
// WARN -> warn
// ERROR -> error
if (Level.OK.equals(level)) {
if (null == ex) {
LOGGER.trace(m, "method: {} msg:{}", method, message);
} else {
LOGGER.trace(m, "method: {} msg:{}", new Object[] { method, message }, ex);
}
} else if (Level.INFO.equals(level)) {
if (null == ex) {
LOGGER.info(m, "method: {} msg:{}", method, message);
} else {
LOGGER.info(m, "method: {} msg:{}", new Object[] { method, message }, ex);
}
} else if (Level.WARN.equals(level)) {
if (null == ex) {
LOGGER.warn(m, "method: {} msg:{}", method, message);
} else {
LOGGER.warn(m, "method: {} msg:{}", new Object[] { method, message }, ex);
}
} else if (Level.ERROR.equals(level)) {
if (null == ex) {
LOGGER.error(m, "method: {} msg:{}", method, message);
} else {
LOGGER.error(m, "method: {} msg:{}", new Object[] { method, message }, ex);
}
}
}
@Override
public boolean isLoggable(Class<?> clazz, Level level) {
return true;
}
}
|
package sqlancer.postgres.gen;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import sqlancer.Randomly;
import sqlancer.common.query.ExpectedErrors;
import sqlancer.common.query.Query;
import sqlancer.common.query.QueryAdapter;
import sqlancer.postgres.PostgresGlobalState;
import sqlancer.postgres.PostgresSchema;
import sqlancer.postgres.PostgresSchema.PostgresColumn;
import sqlancer.postgres.PostgresSchema.PostgresDataType;
import sqlancer.postgres.PostgresSchema.PostgresTable;
import sqlancer.postgres.PostgresVisitor;
import sqlancer.postgres.ast.PostgresExpression;
import sqlancer.sqlite3.gen.SQLite3Common;
public class PostgresTableGenerator {
private final String tableName;
private boolean columnCanHavePrimaryKey;
private boolean columnHasPrimaryKey;
private final StringBuilder sb = new StringBuilder();
private boolean isTemporaryTable;
private final PostgresSchema newSchema;
private final List<PostgresColumn> columnsToBeAdded = new ArrayList<>();
protected final ExpectedErrors errors = new ExpectedErrors();
private final PostgresTable table;
private final boolean generateOnlyKnown;
private final PostgresGlobalState globalState;
public PostgresTableGenerator(String tableName, PostgresSchema newSchema, boolean generateOnlyKnown,
PostgresGlobalState globalState) {
this.tableName = tableName;
this.newSchema = newSchema;
this.generateOnlyKnown = generateOnlyKnown;
this.globalState = globalState;
table = new PostgresTable(tableName, columnsToBeAdded, null, null, null, false, false);
errors.add("invalid input syntax for");
errors.add("is not unique");
errors.add("integer out of range");
errors.add("division by zero");
errors.add("cannot create partitioned table as inheritance child");
errors.add("cannot cast");
errors.add("ERROR: functions in index expression must be marked IMMUTABLE");
errors.add("functions in partition key expression must be marked IMMUTABLE");
errors.add("functions in index predicate must be marked IMMUTABLE");
errors.add("has no default operator class for access method");
errors.add("does not exist for access method");
errors.add("does not accept data type");
errors.add("but default expression is of type text");
errors.add("has pseudo-type unknown");
errors.add("no collation was derived for partition key column");
errors.add("inherits from generated column but specifies identity");
errors.add("inherits from generated column but specifies default");
PostgresCommon.addCommonExpressionErrors(errors);
PostgresCommon.addCommonTableErrors(errors);
}
public static Query generate(String tableName, PostgresSchema newSchema, boolean generateOnlyKnown,
PostgresGlobalState globalState) {
return new PostgresTableGenerator(tableName, newSchema, generateOnlyKnown, globalState).generate();
}
private Query generate() {
columnCanHavePrimaryKey = true;
sb.append("CREATE");
if (Randomly.getBoolean()) {
sb.append(" ");
isTemporaryTable = true;
sb.append(Randomly.fromOptions("TEMPORARY", "TEMP"));
} else if (Randomly.getBoolean()) {
sb.append(" UNLOGGED");
}
sb.append(" TABLE");
if (Randomly.getBoolean()) {
sb.append(" IF NOT EXISTS");
}
sb.append(" ");
sb.append(tableName);
if (Randomly.getBoolean() && !newSchema.getDatabaseTables().isEmpty()) {
createLike();
} else {
createStandard();
}
return new QueryAdapter(sb.toString(), errors, true);
}
private void createStandard() throws AssertionError {
sb.append("(");
for (int i = 0; i < Randomly.smallNumber() + 1; i++) {
if (i != 0) {
sb.append(", ");
}
String name = SQLite3Common.createColumnName(i);
createColumn(name);
}
if (Randomly.getBoolean()) {
errors.add("constraints on temporary tables may reference only temporary tables");
errors.add("constraints on unlogged tables may reference only permanent or unlogged tables");
errors.add("constraints on permanent tables may reference only permanent tables");
errors.add("cannot be implemented");
errors.add("there is no unique constraint matching given keys for referenced table");
errors.add("cannot reference partitioned table");
errors.add("unsupported ON COMMIT and foreign key combination");
errors.add("ERROR: invalid ON DELETE action for foreign key constraint containing generated column");
errors.add("exclusion constraints are not supported on partitioned tables");
PostgresCommon.addTableConstraints(columnHasPrimaryKey, sb, table, globalState, errors);
}
sb.append(")");
generateInherits();
generatePartitionBy();
PostgresCommon.generateWith(sb, globalState, errors);
if (Randomly.getBoolean() && isTemporaryTable) {
sb.append(" ON COMMIT ");
sb.append(Randomly.fromOptions("PRESERVE ROWS", "DELETE ROWS", "DROP"));
sb.append(" ");
}
}
private void createLike() {
sb.append("(");
sb.append("LIKE ");
sb.append(newSchema.getRandomTable().getName());
if (Randomly.getBoolean()) {
for (int i = 0; i < Randomly.smallNumber(); i++) {
String option = Randomly.fromOptions("DEFAULTS", "CONSTRAINTS", "INDEXES", "STORAGE", "COMMENTS",
"GENERATED", "IDENTITY", "STATISTICS", "STORAGE", "ALL");
sb.append(" ");
sb.append(Randomly.fromOptions("INCLUDING", "EXCLUDING"));
sb.append(" ");
sb.append(option);
}
}
sb.append(")");
}
private void createColumn(String name) throws AssertionError {
sb.append(name);
sb.append(" ");
PostgresDataType type = PostgresDataType.getRandomType();
boolean serial = PostgresCommon.appendDataType(type, sb, true, generateOnlyKnown, globalState.getCollates());
PostgresColumn c = new PostgresColumn(name, type);
c.setTable(table);
columnsToBeAdded.add(c);
sb.append(" ");
if (Randomly.getBoolean()) {
createColumnConstraint(type, serial);
}
}
private void generatePartitionBy() {
if (Randomly.getBoolean()) {
return;
}
sb.append(" PARTITION BY ");
// TODO "RANGE",
String partitionOption = Randomly.fromOptions("RANGE", "LIST", "HASH");
sb.append(partitionOption);
sb.append("(");
errors.add("unrecognized parameter");
errors.add("cannot use constant expression");
errors.add("cannot add NO INHERIT constraint to partitioned table");
errors.add("unrecognized parameter");
errors.add("unsupported PRIMARY KEY constraint with partition key definition");
errors.add("which is part of the partition key.");
errors.add("unsupported UNIQUE constraint with partition key definition");
errors.add("does not accept data type");
int n = partitionOption.contentEquals("LIST") ? 1 : Randomly.smallNumber() + 1;
PostgresCommon.addCommonExpressionErrors(errors);
for (int i = 0; i < n; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append("(");
PostgresExpression expr = PostgresExpressionGenerator.generateExpression(globalState, columnsToBeAdded);
sb.append(PostgresVisitor.asString(expr));
sb.append(")");
if (Randomly.getBoolean()) {
sb.append(globalState.getRandomOpclass());
errors.add("does not exist for access method");
}
}
sb.append(")");
}
private void generateInherits() {
if (Randomly.getBoolean() && !newSchema.getDatabaseTables().isEmpty()) {
sb.append(" INHERITS(");
sb.append(newSchema.getDatabaseTablesRandomSubsetNotEmpty().stream().map(t -> t.getName())
.collect(Collectors.joining(", ")));
sb.append(")");
errors.add("has a type conflict");
errors.add("has a generation conflict");
errors.add("cannot create partitioned table as inheritance child");
errors.add("cannot inherit from temporary relation");
errors.add("cannot inherit from partitioned table");
errors.add("has a collation conflict");
}
}
private enum ColumnConstraint {
NULL_OR_NOT_NULL, UNIQUE, PRIMARY_KEY, DEFAULT, CHECK, GENERATED
};
private void createColumnConstraint(PostgresDataType type, boolean serial) {
List<ColumnConstraint> constraintSubset = Randomly.nonEmptySubset(ColumnConstraint.values());
if (Randomly.getBoolean()) {
// make checks constraints less likely
constraintSubset.remove(ColumnConstraint.CHECK);
}
if (!columnCanHavePrimaryKey || columnHasPrimaryKey) {
constraintSubset.remove(ColumnConstraint.PRIMARY_KEY);
}
if (constraintSubset.contains(ColumnConstraint.GENERATED)
&& constraintSubset.contains(ColumnConstraint.DEFAULT)) {
// otherwise: ERROR: both default and identity specified for column
constraintSubset.remove(Randomly.fromOptions(ColumnConstraint.GENERATED, ColumnConstraint.DEFAULT));
}
if (constraintSubset.contains(ColumnConstraint.GENERATED) && type != PostgresDataType.INT) {
// otherwise: ERROR: identity column type must be smallint, integer, or bigint
constraintSubset.remove(ColumnConstraint.GENERATED);
}
if (serial) {
constraintSubset.remove(ColumnConstraint.GENERATED);
constraintSubset.remove(ColumnConstraint.DEFAULT);
constraintSubset.remove(ColumnConstraint.NULL_OR_NOT_NULL);
}
for (ColumnConstraint c : constraintSubset) {
sb.append(" ");
switch (c) {
case NULL_OR_NOT_NULL:
sb.append(Randomly.fromOptions("NOT NULL", "NULL"));
break;
case UNIQUE:
sb.append("UNIQUE");
break;
case PRIMARY_KEY:
sb.append("PRIMARY KEY");
columnHasPrimaryKey = true;
break;
case DEFAULT:
sb.append("DEFAULT");
sb.append(" (");
sb.append(PostgresVisitor.asString(PostgresExpressionGenerator.generateExpression(globalState, type)));
sb.append(")");
// CREATE TEMPORARY TABLE t1(c0 smallint DEFAULT ('566963878'));
errors.add("out of range");
errors.add("is a generated column");
break;
case CHECK:
sb.append("CHECK (");
sb.append(PostgresVisitor.asString(PostgresExpressionGenerator.generateExpression(globalState,
columnsToBeAdded, PostgresDataType.BOOLEAN)));
sb.append(")");
if (Randomly.getBoolean()) {
sb.append(" NO INHERIT");
}
errors.add("out of range");
break;
case GENERATED:
sb.append("GENERATED ");
if (Randomly.getBoolean()) {
sb.append(" ALWAYS AS (");
sb.append(PostgresVisitor.asString(
PostgresExpressionGenerator.generateExpression(globalState, columnsToBeAdded, type)));
sb.append(") STORED");
errors.add("A generated column cannot reference another generated column.");
errors.add("cannot use generated column in partition key");
errors.add("generation expression is not immutable");
errors.add("cannot use column reference in DEFAULT expression");
} else {
sb.append(Randomly.fromOptions("ALWAYS", "BY DEFAULT"));
sb.append(" AS IDENTITY");
}
break;
default:
throw new AssertionError(sb);
}
}
}
}
|
package team1100.season2010.robot;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.AnalogChannel;
public class ChainRotationMotor
{
private AverageController CRM_speed_setpoint;
private double p_coeff;
private double minSpeed;
private double maxSpeed;
private int pot_min = 374;
private int pot_max = 579;
private int pot_center = 483;
private int pot_deadband = 3;
private AdvJaguar chain_rotation_motor;
private AnalogChannel pot;
private AverageController drive_direction_setpoint;
ChainRotationMotor(int CRM_channel, int avgNum, int pot_channel)
{
CRM_speed_setpoint = new AverageController(avgNum);
chain_rotation_motor = new AdvJaguar(CRM_channel);
drive_direction_setpoint = new AverageController(avgNum);
pot = new AnalogChannel(pot_channel);
p_coeff = 1;
minSpeed = .5;
maxSpeed = 1;
}
public void setMinSpeed(double mS)
{
minSpeed = mS;
}
public void setMaxSpeed(double mS)
{
maxSpeed = mS;
}
public void setPCoeff(double pcoeff)
{
p_coeff = pcoeff;
}
public void setInvertedMotor(boolean tf)
{
chain_rotation_motor.setInvertedMotor(tf);
}
public void setPotMin(int potMin)
{
pot_min = potMin;
}
public void setPotMax(int potMax)
{
pot_max = potMax;
}
public void setPotCenter(int potCenter)
{
pot_center = potCenter;
}
public void setPotDeadband(int potDeadband)
{
pot_deadband = potDeadband;
}
public int getPot()
{
return pot.getAverageValue();
}
public void setWheelDirection(double position)
{
drive_direction_setpoint.addNewValue(position);
double avg_dir_setpt = ((pot_max - pot_min) / 2) * (drive_direction_setpoint.getAverageValue() + 1) + pot_min;
double newspeed;
if(avg_dir_setpt > pot.getAverageValue() + pot_deadband)
newspeed = p_coeff * (avg_dir_setpt - pot.getAverageValue())*(maxSpeed - minSpeed)/(pot_max - pot_min) + minSpeed;
else if (avg_dir_setpt < pot.getAverageValue() - pot_deadband)
newspeed = p_coeff * (avg_dir_setpt - pot.getAverageValue())*(maxSpeed - minSpeed)/(pot_max - pot_min) - minSpeed;
else newspeed = 0;
//System.out.println("\t\t\tSpeed: " + p_coeff * (avg_dir_setpt - pot.getAverageValue())*(maxSpeed - minSpeed)/(pot_max - pot_min) + minSpeed);
if(pot.getAverageValue() >= pot_max + pot_deadband)
newspeed = -minSpeed;
else if(pot.getAverageValue() <= pot_min - pot_deadband)
newspeed = minSpeed;
System.out.println("\tSpeed sent: " + newspeed + "\t Potval: " + pot.getAverageValue());
CRM_speed_setpoint.addNewValue(newspeed);
chain_rotation_motor.set(CRM_speed_setpoint.getAverageValue());
}
public void setCenter()
{
setWheelDirection(0);
}
public boolean atCenter()
{
if(pot.getAverageValue() < pot_center + pot_deadband && pot.getAverageValue() > pot_center - pot_deadband)
return true;
else return false;
}
public void resetArray()
{
for(int i=0; i<drive_direction_setpoint.getSize(); i++)
drive_direction_setpoint.addNewValue(0);
}
public void setDirect(double speed)
{
chain_rotation_motor.set(speed);
}
}
|
package com.akiban.server.test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import com.akiban.ais.model.AISBuilder;
import com.akiban.ais.model.AkibanInformationSchema;
import com.akiban.ais.model.Column;
import com.akiban.ais.model.Group;
import com.akiban.ais.model.GroupIndex;
import com.akiban.ais.model.TableIndex;
import com.akiban.ais.model.View;
import com.akiban.qp.operator.QueryContext;
import com.akiban.qp.operator.SimpleQueryContext;
import com.akiban.qp.persistitadapter.PersistitAdapter;
import com.akiban.qp.rowtype.Schema;
import com.akiban.server.AkServerInterface;
import com.akiban.server.AkServerUtil;
import com.akiban.server.api.dml.scan.ScanFlag;
import com.akiban.server.rowdata.SchemaFactory;
import com.akiban.server.service.ServiceManagerImpl;
import com.akiban.server.service.config.ConfigurationService;
import com.akiban.server.rowdata.RowData;
import com.akiban.server.rowdata.RowDefCache;
import com.akiban.server.service.config.TestConfigService;
import com.akiban.server.service.dxl.DXLService;
import com.akiban.server.service.dxl.DXLTestHookRegistry;
import com.akiban.server.service.dxl.DXLTestHooks;
import com.akiban.server.service.servicemanager.GuicedServiceManager;
import com.akiban.server.service.tree.TreeService;
import com.akiban.server.types.extract.ConverterTestUtils;
import com.akiban.server.util.GroupIndexCreator;
import com.akiban.util.AssertUtils;
import com.akiban.util.Strings;
import com.akiban.util.tap.TapReport;
import com.akiban.util.Undef;
import com.persistit.Transaction;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import com.akiban.ais.model.GroupTable;
import com.akiban.ais.model.Index;
import com.akiban.ais.model.IndexColumn;
import com.akiban.server.api.dml.scan.RowDataOutput;
import com.akiban.server.service.config.Property;
import com.akiban.server.store.PersistitStore;
import com.akiban.server.store.Store;
import com.akiban.util.ListUtils;
import com.akiban.ais.model.Table;
import com.akiban.ais.model.TableName;
import com.akiban.ais.model.UserTable;
import com.akiban.server.TableStatistics;
import com.akiban.server.api.DDLFunctions;
import com.akiban.server.api.DMLFunctions;
import com.akiban.server.api.dml.scan.CursorId;
import com.akiban.server.api.dml.scan.NewRow;
import com.akiban.server.api.dml.scan.NiceRow;
import com.akiban.server.api.dml.scan.RowOutput;
import com.akiban.server.api.dml.scan.ScanAllRequest;
import com.akiban.server.api.dml.scan.ScanRequest;
import com.akiban.server.error.InvalidOperationException;
import com.akiban.server.error.NoSuchTableException;
import com.akiban.server.service.ServiceManager;
import com.akiban.server.service.session.Session;
import org.junit.Rule;
import org.junit.rules.MethodRule;
import org.junit.rules.TestName;
import org.junit.rules.TestWatchman;
import org.junit.runners.model.FrameworkMethod;
/**
* <p>Base class for all API tests. Contains a @SetUp that gives you a fresh DDLFunctions and DMLFunctions, plus
* various convenience testing methods.</p>
*/
public class ApiTestBase {
private static final int MIN_FREE_SPACE = 256 * 1024 * 1024;
private static final String TAPS = System.getProperty("it.taps");
protected final static Object UNDEF = Undef.only();
private static final Comparator<? super TapReport> TAP_REPORT_COMPARATOR = new Comparator<TapReport>() {
@Override
public int compare(TapReport o1, TapReport o2) {
return o1.getName().compareTo(o2.getName());
}
};
public static class ListRowOutput implements RowOutput {
private final List<NewRow> rows = new ArrayList<NewRow>();
private final List<NewRow> rowsUnmodifiable = Collections.unmodifiableList(rows);
private int mark = 0;
@Override
public void output(NewRow row) {
rows.add(row);
}
public List<NewRow> getRows() {
return rowsUnmodifiable;
}
public void clear() {
rows.clear();
}
@Override
public void mark() {
mark = rows.size();
}
@Override
public void rewind() {
ListUtils.truncate(rows, mark);
}
}
protected ApiTestBase(String suffix)
{
final String name = this.getClass().getSimpleName();
if (!name.endsWith(suffix)) {
throw new RuntimeException(
String.format("You must rename %s to something like Foo%s", name, suffix)
);
}
}
private static ServiceManager sm;
private Session session;
private int aisGeneration;
private int akibanFKCount;
private final Set<RowUpdater> unfinishedRowUpdaters = new HashSet<RowUpdater>();
private static Map<String,String> lastStartupConfigProperties = null;
private static boolean needServicesRestart = false;
@Rule
public static final TestName testName = new TestName();
protected String testName() {
return testName.getMethodName();
}
@Before
public final void startTestServices() throws Exception {
assertTrue("some row updaters were left over: " + unfinishedRowUpdaters, unfinishedRowUpdaters.isEmpty());
try {
ConverterTestUtils.setGlobalTimezone("UTC");
Collection<Property> startupConfigProperties = startupConfigProperties();
Map<String,String> propertiesForEquality = propertiesForEquality(startupConfigProperties);
if (needServicesRestart || lastStartupConfigProperties == null ||
!lastStartupConfigProperties.equals(propertiesForEquality))
{
// we need a shutdown if we needed a restart, or if the lastStartupConfigProperties are not null,
// which (because of the condition on the "if" above) implies the last startup config properties
// are different from this one's
boolean needShutdown = needServicesRestart || lastStartupConfigProperties != null;
if (needShutdown) {
needServicesRestart = false; // clear the flag if it was set
stopTestServices();
}
int attempt = 1;
while (!AkServerUtil.cleanUpDirectory(TestConfigService.dataDirectory())) {
assertTrue("Too many directory failures", (attempt++ < 10));
TestConfigService.newDataDirectory();
}
assertNull("lastStartupConfigProperties should be null", lastStartupConfigProperties);
sm = createServiceManager(startupConfigProperties);
sm.startServices();
ServiceManagerImpl.setServiceManager(sm);
if (TAPS != null) {
sm.getStatisticsService().reset(TAPS);
sm.getStatisticsService().setEnabled(TAPS, true);
}
lastStartupConfigProperties = propertiesForEquality;
}
session = sm.getSessionService().createSession();
} catch (Exception e) {
handleStartupFailure(e);
}
}
@Rule
public MethodRule exceptionCatchingRule = new TestWatchman() {
@Override
public void failed(Throwable e, FrameworkMethod method) {
needServicesRestart = true;
}
};
/**
* Handle a failure during services startup. The default implementation is to just throw the exception, and
* most tests should <em>not</em> override this. It's designed solely as a testing hook for FailureOnStartupIT.
* @param e the startup exception
* @throws Exception the startup exception
*/
void handleStartupFailure(Exception e) throws Exception {
throw e;
}
protected ServiceManager createServiceManager(Collection<Property> startupConfigProperties) {
TestConfigService.setOverrides(startupConfigProperties);
return new GuicedServiceManager(serviceBindingsProvider());
}
/** Specify special service bindings.
* If you override this, you need to override {@link #startupConfigProperties}
* to return something different so that the special services aren't shared
* with other tests.
*/
protected GuicedServiceManager.BindingsConfigurationProvider serviceBindingsProvider() {
return GuicedServiceManager.testUrls();
}
@After
public final void tearDownAllTables() throws Exception {
if (lastStartupConfigProperties == null)
return; // services never started up
Set<RowUpdater> localUnfinishedUpdaters = new HashSet<RowUpdater>(unfinishedRowUpdaters);
unfinishedRowUpdaters.clear();
dropAllTables();
assertTrue("not all updaters were used: " + localUnfinishedUpdaters, localUnfinishedUpdaters.isEmpty());
String openCursorsMessage = null;
if (sm.serviceIsStarted(DXLService.class)) {
DXLTestHooks dxlTestHooks = DXLTestHookRegistry.get();
// Check for any residual open cursors
if (dxlTestHooks.openCursorsExist()) {
openCursorsMessage = "open cursors remaining:" + dxlTestHooks.describeOpenCursors();
}
}
if (TAPS != null) {
TapReport[] reports = sm.getStatisticsService().getReport(TAPS);
Arrays.sort(reports, TAP_REPORT_COMPARATOR);
for (TapReport report : reports) {
long totalNanos = report.getCumulativeTime();
double totalSecs = ((double) totalNanos) / 1000000000.0d;
double secsPer = totalSecs / report.getOutCount();
System.err.printf("%s:\t in=%d out=%d time=%.2f sec (%d nanos, %.5f sec per out)%n",
report.getName(),
report.getInCount(),
report.getOutCount(),
totalSecs,
totalNanos,
secsPer
);
}
}
session.close();
if (openCursorsMessage != null) {
fail(openCursorsMessage);
}
needServicesRestart |= runningOutOfSpace();
}
private static boolean runningOutOfSpace() {
return TestConfigService.dataDirectory().getFreeSpace() < MIN_FREE_SPACE;
}
private static void beforeStopServices(boolean crash) throws Exception {
com.akiban.sql.pg.PostgresServerITBase.forgetConnection();
}
public final void stopTestServices() throws Exception {
beforeStopServices(false);
ServiceManagerImpl.setServiceManager(null);
if (lastStartupConfigProperties == null) {
return;
}
lastStartupConfigProperties = null;
sm.stopServices();
}
public final void crashTestServices() throws Exception {
beforeStopServices(true);
sm.crashServices();
sm = null;
session = null;
lastStartupConfigProperties = null;
}
public final void restartTestServices(Collection<Property> properties) throws Exception {
ServiceManagerImpl.setServiceManager(null);
sm = createServiceManager( properties );
sm.startServices();
session = sm.getSessionService().createSession();
lastStartupConfigProperties = propertiesForEquality(properties);
ddl(); // loads up the schema manager et al
ServiceManagerImpl.setServiceManager(sm);
}
public final Session createNewSession()
{
return sm.getSessionService().createSession();
}
protected Collection<Property> defaultPropertiesToPreserveOnRestart() {
List<Property> properties = new ArrayList<Property>();
properties.add(new Property(TestConfigService.DATA_PATH_KEY, TestConfigService.dataDirectory().getAbsolutePath()));
return properties;
}
protected boolean defaultDoCleanOnUnload() {
return true;
}
public final void safeRestartTestServices() throws Exception {
safeRestartTestServices(defaultPropertiesToPreserveOnRestart());
}
public final void safeRestartTestServices(Collection<Property> propertiesToPreserve) throws Exception {
/*
* Need this because deleting Trees currently is not transactional. Therefore after
* restart we recover the previous trees and forget about the deleteTree operations.
* TODO: remove when transaction Tree management is done.
*/
treeService().getDb().checkpoint();
final boolean original = TestConfigService.getDoCleanOnUnload();
try {
TestConfigService.setDoCleanOnUnload(defaultDoCleanOnUnload());
crashTestServices(); // TODO: WHY doesn't this work with stop?
} finally {
TestConfigService.setDoCleanOnUnload(original);
}
restartTestServices(propertiesToPreserve);
}
protected final DMLFunctions dml() {
return dxl().dmlFunctions();
}
protected final DDLFunctions ddl() {
return dxl().ddlFunctions();
}
protected final Store store() {
return sm.getStore();
}
protected final PersistitStore persistitStore() {
return store().getPersistitStore();
}
protected final AkServerInterface akServer() {
return sm.getAkSserver();
}
protected String akibanFK(String childCol, String parentTable, String parentCol) {
++akibanFKCount;
return String.format("GROUPING FOREIGN KEY (%s) REFERENCES \"%s\" (%s)",
childCol, parentTable, parentCol
);
}
protected final Session session() {
return session;
}
protected final PersistitAdapter persistitAdapter(Schema schema) {
return new PersistitAdapter(schema, store(), treeService(), session(), configService());
}
protected final QueryContext queryContext(PersistitAdapter adapter) {
return new SimpleQueryContext(adapter);
}
protected final RowDefCache rowDefCache() {
Store store = sm.getStore();
return store.getRowDefCache();
}
protected final ServiceManager serviceManager() {
return sm;
}
protected final ConfigurationService configService() {
return sm.getConfigurationService();
}
protected final DXLService dxl() {
return sm.getDXL();
}
protected final TreeService treeService() {
return sm.getTreeService();
}
protected final int aisGeneration() {
return aisGeneration;
}
protected final void updateAISGeneration() {
aisGeneration = ddl().getGeneration();
}
protected Collection<Property> startupConfigProperties() {
return Collections.emptyList();
}
// Property.equals() does not include the value.
protected Map<String,String> propertiesForEquality(Collection<Property> properties) {
Map<String,String> result = new HashMap<String,String>(properties.size());
for (Property p : properties) {
result.put(p.getKey(), p.getValue());
}
return result;
}
/**
* A simple unique (per class) property that can be returned for tests
* overriding the {@link #startupConfigProperties()} and/or
* {@link #serviceBindingsProvider()} methods.
*/
protected static Collection<Property> uniqueStartupConfigProperties(Class clazz) {
final Collection<Property> properties = new ArrayList<Property>();
properties.add(new Property("test.services", clazz.getName()));
return properties;
}
protected AkibanInformationSchema createFromDDL(String schema, String ddl) {
SchemaFactory schemaFactory = new SchemaFactory(schema);
return schemaFactory.ais(ddl().getAIS(session()), ddl);
}
protected static final class SimpleColumn {
public final String columnName;
public final String typeName;
public final Long param1;
public final Long param2;
public SimpleColumn(String columnName, String typeName) {
this(columnName, typeName, null, null);
}
public SimpleColumn(String columnName, String typeName, Long param1, Long param2) {
this.columnName = columnName;
this.typeName = typeName;
this.param1 = param1;
this.param2 = param2;
}
}
protected final int createTableFromTypes(String schema, String table, boolean firstIsPk, boolean createIndexes,
SimpleColumn... columns) {
AISBuilder builder = new AISBuilder();
builder.userTable(schema, table);
int colPos = 0;
SimpleColumn pk = firstIsPk ? columns[0] : new SimpleColumn("id", "int");
builder.column(schema, table, pk.columnName, colPos++, pk.typeName, null, null, false, false, null, null);
builder.index(schema, table, Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
builder.indexColumn(schema, table, Index.PRIMARY_KEY_CONSTRAINT, pk.columnName, 0, true, null);
for(int i = firstIsPk ? 1 : 0; i < columns.length; ++i) {
SimpleColumn sc = columns[i];
String name = sc.columnName == null ? "c" + (colPos + 1) : sc.columnName;
builder.column(schema, table, name, colPos++, sc.typeName, sc.param1, sc.param2, true, false, null, null);
if(createIndexes) {
builder.index(schema, table, name, false, Index.KEY_CONSTRAINT);
builder.indexColumn(schema, table, name, name, 0, true, null);
}
}
UserTable tempTable = builder.akibanInformationSchema().getUserTable(schema, table);
ddl().createTable(session(), tempTable);
updateAISGeneration();
return tableId(schema, table);
}
protected final int createTableFromTypes(String schema, String table, boolean firstIsPk, boolean createIndexes,
String... typeNames) {
SimpleColumn simpleColumns[] = new SimpleColumn[typeNames.length];
for(int i = 0; i < typeNames.length; ++i) {
simpleColumns[i] = new SimpleColumn(null, typeNames[i]);
}
return createTableFromTypes(schema, table, firstIsPk, createIndexes, simpleColumns);
}
protected final int createTable(String schema, String table, String definition) throws InvalidOperationException {
String ddl = String.format("CREATE TABLE \"%s\" (%s)", table, definition);
AkibanInformationSchema tempAIS = createFromDDL(schema, ddl);
UserTable tempTable = tempAIS.getUserTable(schema, table);
ddl().createTable(session(), tempTable);
updateAISGeneration();
return ddl().getTableId(session(), new TableName(schema, table));
}
protected final int createTable(String schema, String table, String... definitions) throws InvalidOperationException {
assertTrue("must have at least one definition element", definitions.length >= 1);
StringBuilder unifiedDef = new StringBuilder();
for (String definition : definitions) {
unifiedDef.append(definition).append(',');
}
unifiedDef.setLength(unifiedDef.length() - 1);
return createTable(schema, table, unifiedDef.toString());
}
protected final int createTable(TableName tableName, String... definitions) throws InvalidOperationException {
return createTable(tableName.getSchemaName(), tableName.getTableName(), definitions);
}
private AkibanInformationSchema createIndexInternal(String schema, String table, String indexName, String... indexCols) {
String ddl = String.format("CREATE INDEX \"%s\" ON \"%s\".\"%s\"(%s)", indexName, schema, table,
Strings.join(Arrays.asList(indexCols), ","));
return createFromDDL(schema, ddl);
}
protected final TableIndex createIndex(String schema, String table, String indexName, String... indexCols) {
AkibanInformationSchema tempAIS = createIndexInternal(schema, table, indexName, indexCols);
Index tempIndex = tempAIS.getUserTable(schema, table).getIndex(indexName);
ddl().createIndexes(session(), Collections.singleton(tempIndex));
updateAISGeneration();
return ddl().getTable(session(), new TableName(schema, table)).getIndex(indexName);
}
protected final TableIndex createGroupingFKIndex(String schema, String table, String indexName, String... indexCols) {
assertTrue("grouping fk index must start with __akiban", indexName.startsWith("__akiban"));
AkibanInformationSchema tempAIS = createIndexInternal(schema, table, indexName, indexCols);
UserTable userTable = tempAIS.getUserTable(schema, table);
TableIndex tempIndex = userTable.getIndex(indexName);
userTable.removeIndexes(Collections.singleton(tempIndex));
TableIndex fkIndex = TableIndex.create(tempAIS, userTable, indexName, 0, false, "FOREIGN KEY");
for(IndexColumn col : tempIndex.getKeyColumns()) {
fkIndex.addColumn(col);
}
ddl().createIndexes(session(), Collections.singleton(fkIndex));
updateAISGeneration();
return ddl().getTable(session(), new TableName(schema, table)).getIndex(indexName);
}
protected final TableIndex createTableIndex(int tableId, String indexName, boolean unique, String... columns) {
return createTableIndex(getUserTable(tableId), indexName, unique, columns);
}
protected final TableIndex createTableIndex(UserTable table, String indexName, boolean unique, String... columns) {
TableIndex index = new TableIndex(table, indexName, -1, unique, "KEY");
int pos = 0;
for (String columnName : columns) {
Column column = table.getColumn(columnName);
IndexColumn indexColumn = new IndexColumn(index, column, pos++, true, null);
index.addColumn(indexColumn);
}
ddl().createIndexes(session(), Collections.singleton(index));
return getUserTable(table.getTableId()).getIndex(indexName);
}
protected final GroupIndex createGroupIndex(String groupName, String indexName, String tableColumnPairs)
throws InvalidOperationException {
return createGroupIndex(groupName, indexName, tableColumnPairs, Index.JoinType.LEFT);
}
protected final GroupIndex createGroupIndex(String groupName, String indexName, String tableColumnPairs, Index.JoinType joinType)
throws InvalidOperationException {
AkibanInformationSchema ais = ddl().getAIS(session());
final Index index;
index = GroupIndexCreator.createIndex(ais, groupName, indexName, tableColumnPairs, joinType);
ddl().createIndexes(session(), Collections.singleton(index));
return ddl().getAIS(session()).getGroup(groupName).getIndex(indexName);
}
protected int createTablesAndIndexesFromDDL(String schema, String ddl) {
SchemaFactory schemaFactory = new SchemaFactory(schema);
AkibanInformationSchema ais = schemaFactory.ais(ddl);
List<UserTable> tables = new ArrayList<UserTable>(ais.getUserTables().values());
// Need to define from root the leaf; repeating definition order should work.
Collections.sort(tables, new Comparator<UserTable>() {
@Override
public int compare(UserTable t1, UserTable t2) {
return t1.getTableId().compareTo(t2.getTableId());
}
});
for (UserTable table : tables) {
ddl().createTable(session(), table);
}
for (Group group : ais.getGroups().values()) {
Collection<GroupIndex> indexes = group.getIndexes();
if (!indexes.isEmpty())
ddl().createIndexes(session(), indexes);
}
updateAISGeneration();
return ddl().getTableId(session(), tables.get(0).getName());
}
/**
* Expects an exact number of rows. This checks both the countRowExactly and countRowsApproximately
* methods on DMLFunctions.
* @param tableId the table to count
* @param rowsExpected how many rows we expect
* @throws InvalidOperationException for various reasons :)
*/
protected final void expectRowCount(int tableId, long rowsExpected) throws InvalidOperationException {
TableStatistics tableStats = dml().getTableStatistics(session(), tableId, true);
assertEquals("table ID", tableId, tableStats.getRowDefId());
assertEquals("rows by TableStatistics", rowsExpected, tableStats.getRowCount());
}
protected static RuntimeException unexpectedException(Throwable cause) {
return new RuntimeException("unexpected exception", cause);
}
protected final List<RowData> scanFull(ScanRequest request) {
try {
return RowDataOutput.scanFull(session(), aisGeneration(), dml(), request);
} catch (InvalidOperationException e) {
throw new TestException(e);
}
}
protected final List<NewRow> scanAll(ScanRequest request) throws InvalidOperationException {
ListRowOutput output = new ListRowOutput();
CursorId cursorId = dml().openCursor(session(), aisGeneration(), request);
dml().scanSome(session(), cursorId, output);
dml().closeCursor(session(), cursorId);
return output.getRows();
}
protected final List<NewRow> scanAllIndex(TableIndex index) throws InvalidOperationException {
final Set<Integer> columns = new HashSet<Integer>();
for(IndexColumn icol : index.getKeyColumns()) {
columns.add(icol.getColumn().getPosition());
}
return scanAll(new ScanAllRequest(index.getTable().getTableId(), columns, index.getIndexId(), null));
}
protected final void writeRow(int tableId, Object... values) {
dml().writeRow(session(), createNewRow(tableId, values));
}
protected final RowUpdater update(NewRow oldRow) {
RowUpdater updater = new RowUpdaterImpl(oldRow);
unfinishedRowUpdaters.add(updater);
return updater;
}
protected final RowUpdater update(int tableId, Object... values) {
NewRow oldRow = createNewRow(tableId, values);
return update(oldRow);
}
protected final int writeRows(NewRow... rows) throws InvalidOperationException {
for (NewRow row : rows) {
dml().writeRow(session(), row);
}
return rows.length;
}
protected final void deleteRow(int tableId, Object... values) {
dml().deleteRow(session(), createNewRow(tableId, values));
}
protected final void expectRows(ScanRequest request, NewRow... expectedRows) throws InvalidOperationException {
assertEquals("rows scanned", Arrays.asList(expectedRows), scanAll(request));
}
protected final ScanAllRequest scanAllRequest(int tableId) {
Table uTable = ddl().getTable(session(), tableId);
Set<Integer> allCols = new HashSet<Integer>();
for (int i=0, MAX=uTable.getColumns().size(); i < MAX; ++i) {
allCols.add(i);
}
return new ScanAllRequest(tableId, allCols);
}
protected final int indexId(String schema, String table, String index) {
AkibanInformationSchema ais = ddl().getAIS(session());
UserTable userTable = ais.getUserTable(schema, table);
Index aisIndex = userTable.getIndex(index);
if (aisIndex == null) {
throw new RuntimeException("no such index: " + index);
}
return aisIndex.getIndexId();
}
protected final CursorId openFullScan(String schema, String table, String index) throws InvalidOperationException {
AkibanInformationSchema ais = ddl().getAIS(session());
UserTable userTable = ais.getUserTable(schema, table);
Index aisIndex = userTable.getIndex(index);
if (aisIndex == null) {
throw new RuntimeException("no such index: " + index);
}
return openFullScan(
userTable.getTableId(),
aisIndex.getIndexId()
);
}
protected final CursorId openFullScan(int tableId, int indexId) throws InvalidOperationException {
Table uTable = ddl().getTable(session(), tableId);
Set<Integer> allCols = new HashSet<Integer>();
for (int i=0, MAX=uTable.getColumns().size(); i < MAX; ++i) {
allCols.add(i);
}
ScanRequest request = new ScanAllRequest(tableId, allCols, indexId,
EnumSet.of(ScanFlag.START_AT_BEGINNING, ScanFlag.END_AT_END)
);
return dml().openCursor(session(), aisGeneration(), request);
}
protected static <T> Set<T> set(T... items) {
return new HashSet<T>(Arrays.asList(items));
}
protected static <T> T[] array(Class<T> ofClass, T... items) {
if (ofClass == null) {
throw new IllegalArgumentException(
"T[] of null class; you probably meant the array(Object...) overload "
+"with a null for the first element. Use array(Object.class, null, ...) instead"
);
}
return items;
}
protected static Object[] array(Object... items) {
return array(Object.class, items);
}
protected static <T> T get(NewRow row, int field, Class<T> castAs) {
Object obj = row.get(field);
return castAs.cast(obj);
}
protected final void expectFullRows(int tableId, NewRow... expectedRows) throws InvalidOperationException {
ScanRequest all = scanAllRequest(tableId);
expectRows(all, expectedRows);
expectRowCount(tableId, expectedRows.length);
}
protected final List<NewRow> convertRowDatas(List<RowData> rowDatas) {
List<NewRow> ret = new ArrayList<NewRow>(rowDatas.size());
for(RowData rowData : rowDatas) {
NewRow newRow = NiceRow.fromRowData(rowData, ddl().getRowDef(rowData.getRowDefId()));
ret.add(newRow);
}
return ret;
}
protected static Set<CursorId> cursorSet(CursorId... cursorIds) {
Set<CursorId> set = new HashSet<CursorId>();
for (CursorId id : cursorIds) {
if(!set.add(id)) {
fail(String.format("while adding %s to %s", id, set));
}
}
return set;
}
public NewRow createNewRow(int tableId, Object... columns) {
return createNewRow(store(), tableId, columns);
}
public static NewRow createNewRow(Store store, int tableId, Object... columns) {
NewRow row = new NiceRow(tableId, store);
for (int i=0; i < columns.length; ++i) {
if (columns[i] != UNDEF) {
row.put(i, columns[i] );
}
}
return row;
}
protected final void dropAllTables() throws InvalidOperationException {
for(View view : ddl().getAIS(session()).getViews().values()) {
ddl().dropView(session(), view.getName());
}
Set<String> groupNames = new HashSet<String>();
for(UserTable table : ddl().getAIS(session()).getUserTables().values()) {
if(table.getParentJoin() == null && !TableName.INFORMATION_SCHEMA.equals(table.getName().getSchemaName())) {
groupNames.add(table.getGroup().getName());
}
}
for(String groupName : groupNames) {
ddl().dropGroup(session(), groupName);
}
Set<TableName> uTables = new HashSet<TableName>(ddl().getAIS(session()).getUserTables().keySet());
for (Iterator<TableName> iter = uTables.iterator(); iter.hasNext();) {
if (TableName.INFORMATION_SCHEMA.equals(iter.next().getSchemaName())) {
iter.remove();
}
}
Assert.assertEquals("user tables", Collections.<TableName>emptySet(), uTables);
}
protected static <T> void assertEqualLists(String message, List<? extends T> expected, List<? extends T> actual) {
AssertUtils.assertCollectionEquals(message, expected, actual);
}
protected static class TestException extends RuntimeException {
private final InvalidOperationException cause;
public TestException(String message, InvalidOperationException cause) {
super(message, cause);
this.cause = cause;
}
public TestException(InvalidOperationException cause) {
super(cause);
this.cause = cause;
}
@Override
public InvalidOperationException getCause() {
assert super.getCause() == cause;
return cause;
}
}
protected final int tableId(String schema, String table) {
return tableId(new TableName(schema, table));
}
protected final int tableId(TableName tableName) {
try {
return ddl().getTableId(session(), tableName);
} catch (NoSuchTableException e) {
throw new TestException(e);
}
}
protected final TableName tableName(int tableId) {
try {
return ddl().getTableName(session(), tableId);
} catch (NoSuchTableException e) {
throw new TestException(e);
}
}
protected final TableName tableName(String schema, String table) {
return new TableName(schema, table);
}
protected final UserTable getUserTable(String schema, String name) {
return getUserTable(tableName(schema, name));
}
protected final UserTable getUserTable(TableName name) {
return ddl().getUserTable(session(), name);
}
protected final UserTable getUserTable(int tableId) {
final Table table;
try {
table = ddl().getTable(session(), tableId);
} catch (NoSuchTableException e) {
throw new TestException(e);
}
if (table.isUserTable()) {
return (UserTable) table;
}
throw new RuntimeException("not a user table: " + table);
}
protected final Map<TableName,UserTable> getUserTables() {
return stripAISTables(ddl().getAIS(session()).getUserTables());
}
protected final Map<TableName,GroupTable> getGroupTables() {
return stripAISTables(ddl().getAIS(session()).getGroupTables());
}
private static <T extends Table> Map<TableName,T> stripAISTables(Map<TableName,T> map) {
final Map<TableName,T> ret = new HashMap<TableName, T>(map);
for(Iterator<TableName> iter=ret.keySet().iterator(); iter.hasNext(); ) {
if(TableName.INFORMATION_SCHEMA.equals(iter.next().getSchemaName())) {
iter.remove();
}
}
return ret;
}
protected void expectIndexes(int tableId, String... expectedIndexNames) {
UserTable table = getUserTable(tableId);
Set<String> expectedIndexesSet = new TreeSet<String>(Arrays.asList(expectedIndexNames));
Set<String> actualIndexes = new TreeSet<String>();
for (Index index : table.getIndexes()) {
String indexName = index.getIndexName().getName();
boolean added = actualIndexes.add(indexName);
assertTrue("duplicate index name: " + indexName, added);
}
assertEquals("indexes in " + table.getName(), expectedIndexesSet, actualIndexes);
}
protected void expectIndexColumns(int tableId, String indexName, String... expectedColumns) {
UserTable table = getUserTable(tableId);
List<String> expectedColumnsList = Arrays.asList(expectedColumns);
Index index = table.getIndex(indexName);
assertNotNull(indexName + " was null", index);
List<String> actualColumns = new ArrayList<String>();
for (IndexColumn indexColumn : index.getKeyColumns()) {
actualColumns.add(indexColumn.getColumn().getName());
}
assertEquals(indexName + " columns", actualColumns, expectedColumnsList);
}
public interface RowUpdater {
void to(Object... values);
void to(NewRow newRow);
}
private class RowUpdaterImpl implements RowUpdater {
@Override
public void to(Object... values) {
NewRow newRow = createNewRow(oldRow.getTableId(), values);
to(newRow);
}
@Override
public void to(NewRow newRow) {
boolean removed = unfinishedRowUpdaters.remove(this);
dml().updateRow(session(), oldRow, newRow, null);
assertTrue("couldn't remove row updater " + toString(), removed);
}
@Override
public String toString() {
return "RowUpdater for " + oldRow;
}
private RowUpdaterImpl(NewRow oldRow) {
this.oldRow = oldRow;
}
private final NewRow oldRow;
}
protected <T> T transactionally(Callable<T> callable) throws Exception {
Transaction txn = treeService().getTransaction(session());
txn.begin();
try {
T value = callable.call();
txn.commit();
return value;
}
finally {
txn.end();
}
}
protected <T> T transactionallyUnchecked(Callable<T> callable) {
try {
return transactionally(callable);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void transactionallyUnchecked(final Runnable runnable) {
transactionallyUnchecked(new Callable<Void>() {
@Override
public Void call() throws Exception {
runnable.run();
return null;
}
});
}
}
|
package com.github.wovnio.wovnjava;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URLDecoder;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.easymock.EasyMock;
public class ApiTest extends TestCase {
public void testTranslateWithGzipResponse() throws ApiException, IOException, ProtocolException {
byte[] apiServerResponse = gzip("{\"body\": \"<html><body>response html</body></html>\"}".getBytes());
String encoding = "gzip";
String resultingHtml = testTranslate(apiServerResponse, encoding);
String expectedHtml = "<html><body>response html</body></html>";
assertEquals(expectedHtml, resultingHtml);
}
public void testTranslateWithPlainTextResponse() throws ApiException, IOException, ProtocolException {
byte[] apiServerResponse = "{\"body\": \"<html><body>response html</body></html>\"}".getBytes();
String encoding = "";
String resultingHtml = testTranslate(apiServerResponse, encoding);
String expectedHtml = "<html><body>response html</body></html>";
assertEquals(expectedHtml, resultingHtml);
}
private String testTranslate(byte[] apiServerResponse, String encoding) throws ApiException, IOException, ProtocolException {
String html = "<html>much content</html>";
Settings settings = TestUtil.makeSettings(new HashMap<String, String>() {{
put("projectToken", "token0");
put("defaultLang", "en");
put("supportedLangs", "en,ja,fr");
}});
HttpServletRequest request = TestUtil.mockRequestPath("/ja/somepage/");
Headers headers = new Headers(request, settings);
Api api = new Api(settings, headers);
ByteArrayOutputStream requestStream = new ByteArrayOutputStream();
ByteArrayInputStream responseStream = new ByteArrayInputStream(apiServerResponse);
int returnCode = 200;
HttpURLConnection con = mockHttpURLConnection(requestStream, responseStream, returnCode, encoding);
String result = api.translate("ja", html, con);
String encodedApiRequestBody = decompress(requestStream.toByteArray());
String apiRequestBody = URLDecoder.decode(encodedApiRequestBody, "UTF-8");
String expectedRequestBody = "url=https://example.com/somepage/" +
"&token=token0" +
"&lang_code=ja" +
"&url_pattern=path" +
"&body=" + html;
assertEquals(expectedRequestBody, apiRequestBody);
return result;
}
private byte[] gzip(byte[] input) throws IOException, ProtocolException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream(input.length);
GZIPOutputStream gz = new GZIPOutputStream(buffer);
try {
gz.write(input);
} finally {
gz.close();
}
return buffer.toByteArray();
}
private HttpURLConnection mockHttpURLConnection(ByteArrayOutputStream requestStream, ByteArrayInputStream responseStream, int code, String encoding) throws IOException, ProtocolException {
HttpURLConnection mock = EasyMock.createMock(HttpURLConnection.class);
mock.setDoOutput(true);
mock.setRequestProperty(EasyMock.anyString(), EasyMock.anyString());
EasyMock.expectLastCall().atLeastOnce();
mock.setRequestMethod("POST");
EasyMock.expect(mock.getResponseCode()).andReturn(code);
EasyMock.expect(mock.getContentEncoding()).andReturn(encoding);
EasyMock.expect(mock.getOutputStream()).andReturn(requestStream);
EasyMock.expect(mock.getInputStream()).andReturn(responseStream);
EasyMock.replay(mock);
return mock;
}
private static String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
gis.close();
bis.close();
return sb.toString();
}
}
|
package de.bmoth.ltl;
import de.bmoth.TestParser;
import de.bmoth.backend.ltl.transformation.*;
import de.bmoth.parser.ast.nodes.ltl.LTLFormula;
import de.bmoth.parser.ast.nodes.ltl.LTLNode;
import de.bmoth.parser.ast.visitors.AbstractASTTransformation;
import org.junit.Test;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class LTLTransformationTest extends TestParser {
@Test
public void testFinallyFinallyToFinally() {
LTLNode node1 = parseLtlFormula("F( F( { 1 = 1 } ) )").getLTLNode();
LTLNode node2 = parseLtlFormula("F( not( F( { 1 = 1 } ) ) )").getLTLNode();
AbstractASTTransformation transformation = new ConvertFinallyFinallyToFinally();
assertTrue(transformation.canHandleNode(node1));
assertTrue(transformation.canHandleNode(node2));
LTLNode newNode1 = (LTLNode) new ConvertFinallyFinallyToFinally().transformNode(node1);
LTLNode newNode2 = (LTLNode) new ConvertFinallyFinallyToFinally().transformNode(node2);
assertEquals("FINALLY(EQUAL(1,1))", newNode1.toString());
assertEquals("NOT(FINALLY(EQUAL(1,1)))", newNode2.toString());
}
@Test
public void testGloballyGloballyToGlobally() {
LTLNode node1 = parseLtlFormula("G( G( { 1 = 1 } ) )").getLTLNode();
LTLNode node2 = parseLtlFormula("G( not( G( { 1 = 1 } ) ) )").getLTLNode();
AbstractASTTransformation transformation = new ConvertGloballyGloballyToGlobally();
assertTrue(transformation.canHandleNode(node1));
assertTrue(transformation.canHandleNode(node2));
LTLNode newNode1 = (LTLNode) transformation.transformNode(node1);
LTLNode newNode2 = (LTLNode) transformation.transformNode(node2);
assertEquals("GLOBALLY(EQUAL(1,1))", newNode1.toString());
assertEquals("NOT(GLOBALLY(EQUAL(1,1)))", newNode2.toString());
}
@Test
public void testNotGloballyToFinallyNot() {
LTLNode node = parseLtlFormula("not(G { 1=1 })").getLTLNode();
AbstractASTTransformation transformation = new ConvertNotGloballyToFinallyNot();
assertTrue(transformation.canHandleNode(node));
LTLNode newNode = (LTLNode) transformation.transformNode(node);
assertEquals("FINALLY(NOT(EQUAL(1,1)))", newNode.toString());
}
@Test
public void testPhiUntilPhiUntilPsiToPhiUntilPsi() {
LTLNode node1 = parseLtlFormula("{3=3} U ( {3=3} U {2=2} )").getLTLNode();
LTLNode node2 = parseLtlFormula("( {1=1} U {2=2} ) U {2=2}").getLTLNode();
LTLNode node3 = parseLtlFormula("( {1=1} U {2=2} ) U {3=3}").getLTLNode();
LTLNode node4 = parseLtlFormula("{3=3} U ( {5=5} U {2=2} )").getLTLNode();
AbstractASTTransformation transformation = new ConvertPhiUntilPhiUntilPsiToPhiUntilPsi();
assertTrue(transformation.canHandleNode(node1));
assertTrue(transformation.canHandleNode(node2));
assertFalse(transformation.canHandleNode(node3));
assertFalse(transformation.canHandleNode(node4));
LTLNode newNode1 = (LTLNode) transformation.transformNode(node1);
LTLNode newNode2 = (LTLNode) transformation.transformNode(node2);
assertEquals("UNTIL(EQUAL(3,3),EQUAL(2,2))", newNode1.toString());
assertEquals("UNTIL(EQUAL(1,1),EQUAL(2,2))", newNode2.toString());
}
@Test
public void testFinallyPhiOrPsiToFinallyPhiOrFinallyPsi() {
LTLNode node1 = parseLtlFormula("F( ( {3=3} or {2=2} ) )").getLTLNode();
AbstractASTTransformation transformation = new ConvertFinallyPhiOrPsiToFinallyPhiOrFinallyPsi();
assertTrue(transformation.canHandleNode(node1));
LTLNode newNode1 = (LTLNode) transformation.transformNode(node1);
assertEquals("OR(FINALLY(EQUAL(3,3)),FINALLY(EQUAL(2,2)))", newNode1.toString());
}
@Test
public void testGloballyPhiAndPsiToGloballyPhiAndGloballyPsi() {
LTLNode node1 = parseLtlFormula("G( ( {3=3} & {2=2} ) )").getLTLNode();
AbstractASTTransformation transformation = new ConvertGloballyPhiAndPsiToGloballyPhiAndGloballyPsi();
assertTrue(transformation.canHandleNode(node1));
LTLNode newNode1 = (LTLNode) transformation.transformNode(node1);
assertEquals("AND(GLOBALLY(EQUAL(3,3)),GLOBALLY(EQUAL(2,2)))", newNode1.toString());
}
@Test
public void testNotRelease() {
LTLNode node1 = parseLtlFormula("not( {23=23} R {24=24} )").getLTLNode();
LTLNode node2 = parseLtlFormula("not( {23=23} U {24=24} )").getLTLNode();
AbstractASTTransformation transformation = new ConvertNotRelease();
assertTrue(transformation.canHandleNode(node1));
assertFalse(transformation.canHandleNode(node2));
LTLNode newNode1 = (LTLNode) transformation.transformNode(node1);
assertEquals("UNTIL(NOT(EQUAL(23,23)),NOT(EQUAL(24,24)))", newNode1.toString());
}
@Test
public void testWeakToRelease() {
LTLNode node1 = parseLtlFormula("{12=12} W {13=13}").getLTLNode();
LTLNode node2 = parseLtlFormula("{12=12} R {13=13}").getLTLNode();
AbstractASTTransformation transformation = new ConvertWeakToRelease();
assertTrue(transformation.canHandleNode(node1));
assertFalse(transformation.canHandleNode(node2));
LTLNode newNode1 = (LTLNode) transformation.transformNode(node1);
assertEquals("RELEASE(EQUAL(13,13),OR(EQUAL(12,12),EQUAL(13,13)))", newNode1.toString());
}
@Test
public void testTransformationNotFinallyToGloballyNot() {
LTLNode node = parseLtlFormula("not (F {2=1})").getLTLNode();
AbstractASTTransformation transformation = new ConvertNotFinallyToGloballyNot();
assertTrue(transformation.canHandleNode(node));
LTLNode newNode = (LTLNode) transformation.transformNode(node);
assertEquals("GLOBALLY(NOT(EQUAL(2,1)))", newNode.toString());
}
@Test
public void testTransformationNotNextToNextNot() {
LTLFormula ltlFormula = parseLtlFormula("not (X {0=1})");
LTLNode node = (LTLNode) new ConvertNotNextToNextNot().transformNode(ltlFormula.getLTLNode());
assertEquals("NEXT(NOT(EQUAL(0,1)))", node.toString());
}
@Test
public void testTransformationFGFtoGF() {
LTLFormula ltlFormula = parseLtlFormula("F(G (F {0=1}))");
LTLNode node = (LTLNode) new ConvertFinallyGloballyFinallyToGloballyFinally().transformNode(ltlFormula.getLTLNode());
assertEquals("GLOBALLY(FINALLY(EQUAL(0,1)))", node.toString());
}
@Test
public void testTransformationGFGtoFG() {
LTLFormula ltlFormula = parseLtlFormula("G (F (G {0=1}))");
LTLNode node = (LTLNode) new ConvertGloballyFinallyGloballyToFinallyGlobally().transformNode(ltlFormula.getLTLNode());
assertEquals("FINALLY(GLOBALLY(EQUAL(0,1)))", node.toString());
}
}
|
package examples.dustin.commandline.jbock;
import static java.lang.System.out;
import net.jbock.CommandLineArguments;
import net.jbock.Parameter;
import java.util.Optional;
/**
* Demonstrates use of jbock to process command-line
* arguments in a Java application.
*/
public class Main
{
@CommandLineArguments
abstract static class Arguments
{
/**
* Verbosity enabled?
*/
@Parameter(shortName = 'v', longName = "verbose")
abstract boolean verbose();
/**
* File name and path
*/
@Parameter(shortName = 'f', longName = "file")
abstract String file();
}
public static void main(String[] arguments)
{
Arguments args = Main_Arguments_Parser.create().parseOrExit(arguments);
System.out.println("The file '" + args.file() + "' was provided and verbosity is set to '" + args.verbose() + "'.");
}
}
|
package engine.gameobject;
import java.util.ArrayList;
import java.util.List;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import xml.DataManager;
import engine.fieldsetting.Settable;
import engine.gameobject.units.BuffableUnit;
import engine.gameobject.weapon.BasicWeapon;
import engine.gameobject.weapon.Weapon;
import engine.pathfinding.EndOfPathException;
import engine.pathfinding.PathFixed;
import engine.pathfinding.PathSegmentBezier;
import gameworld.ObjectCollection;
/**
* This is a test class for GameObjects, to be used only by the Game Engine for testing purposes.
* The
* GameObjectSimpleTest has a Node that is a Circle.
*
* @author Jeremy
*
*/
public class GameObjectSimpleTest extends BuffableUnit{
private Node myNode;
private String myImagePath;
private String myLabel;
private PointSimple myPoint;
private Health myHealth;
private Mover myMover;
private Weapon myWeapon;
private Graphic myGraphic;
public GameObjectSimpleTest () {
//createNode();
myImagePath = "robertDuvall.jpg";
myLabel = "test object";
myPoint = new PointSimple(300,300);
myHealth = new HealthSimple(3);
// myMover = new MoverPoint(new PointSimple(600,600), .2);
PathFixed myPath = new PathFixed();
PathSegmentBezier myBez = new PathSegmentBezier();
List<PointSimple> points = new ArrayList<PointSimple>();
points.add(new PointSimple(0,0));
points.add(new PointSimple(100,800));
points.add(new PointSimple(800,100));
points.add(new PointSimple(500,500));
myBez.setPoints(points);
myPath.addPathSegment(myBez);
myPath = DataManager.readFromXML(PathFixed.class, "src/gae/listView/Test.xml");
// XStream xstream = new XStream(new DomDriver());
// File file = new File("src/gae/listView/Test.xml");
// myPath = (PathFixed) xstream.fromXML(file);
myMover = new MoverPath(myPath,1);
myWeapon = new BasicWeapon();
myGraphic = new Graphic(100, 100, myImagePath);
myGraphic.setPoint(myPoint);
}
//This method is outdated. Now encapsulated in graphics class.
// private void createNode () {
// Circle circle = new Circle();
// circle.setFill(Color.ALICEBLUE);
// myNode = circle;
@Override
public boolean isDead () {
return myHealth.isDead();
}
@Override
public void changeHealth (double amount) {
myHealth.changeHealth(amount);
}
// temporary
public GameObject clone () {
return (GameObject) super.clone();
}
@Override
public String getLabel () {
return myLabel;
}
@Override
public PointSimple getPoint () {
return new PointSimple(myPoint);
}
public void initializeNode () {
Image image = new Image(myImagePath);
ImageView imageView = new ImageView();
imageView.setImage(image);
myNode = imageView;
}
@Override
public void move () throws EndOfPathException {
// TODO Auto-generated method stub
PointSimple point = myMover.move(myPoint);
myPoint = new PointSimple(new Point2D(point.getX(), point.getY()));
myGraphic.setPoint(myPoint);
}
@Settable
@Override
public void setSpeed (double speed) {
// TODO Auto-generated method stub
}
@Override
public Graphic getGraphic () {
// TODO Auto-generated method stub
return myGraphic;
}
@Settable
public void setImagePath (String imgpath) {
myImagePath = imgpath;
}
@Settable
public void setLabel (String label) {
myLabel = label;
}
@Settable
public void setPoint (PointSimple point) {
myPoint = point;
myGraphic.setPoint(point);
}
@Settable
public void setHealth (Health health) {
myHealth = health;
}
@Settable
public void setMover (Mover mover) {
myMover = mover;
}
@Settable
public void setGraphic (Graphic graphic) {
myGraphic = graphic;
}
@Override
public Weapon getWeapon () {
return myWeapon;
}
@Settable
@Override
public void setWeapon (Weapon weapon) {
myWeapon = weapon;
}
@Override
public BasicMover getMover() {
// TODO Auto-generated method stub
return null;
}
@Override
public void update (ObjectCollection world) {
if (isDead()){
onDeath();
return;
}
try{
move();
}
catch (EndOfPathException e){
}
}
}
|
package org.mwc.cmap.tote.views;
import java.beans.*;
import java.util.Vector;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.jface.action.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.*;
import org.eclipse.ui.part.ViewPart;
import org.mwc.cmap.core.DataTypes.Temporal.*;
import org.mwc.cmap.core.DataTypes.TrackData.*;
import org.mwc.cmap.core.DataTypes.TrackData.TrackDataProvider.TrackDataListener;
import org.mwc.cmap.core.property_support.ColorHelper;
import org.mwc.cmap.core.ui_support.PartMonitor;
import org.mwc.cmap.tote.calculations.CalculationLoaderManager;
import Debrief.Tools.Tote.*;
import Debrief.Wrappers.FixWrapper;
import MWC.GenericData.HiResDate;
/**
* View which provides a track tote. The track tote is a table of values who are
* calculated using the current status of one or more vessel tracks
* <p>
*/
public class ToteView extends ViewPart
{
// private Action _followTimeToggle;
private Action _removeTrackAction;
// Extension point tag and attributes in plugin.xml
private static final String EXTENSION_POINT_ID = "ToteCalculation";
private static final String EXTENSION_TAG = "calculation";
private static final String EXTENSION_TAG_LABEL_ATTRIB = "name";
private static final String EXTENSION_TAG_ICON_ATTRIB = "icon";
// Plug-in ID from <plugin> tag in plugin.xml
private static final String PLUGIN_ID = "org.mwc.cmap.tote";
private static final String SHOW_UNITS = "SHOW_UNITS";
/**
* the table showing the calcs
*/
private TableViewer _tableViewer;
/**
* the table content provider (containing both the calculations and the
* tracks)
*/
private IStructuredContentProvider _content;
/**
* helper application to help track creation/activation of new plots
*/
private PartMonitor _myPartMonitor = null;
/**
* the listener we use to track time changes
*/
private PropertyChangeListener _temporalListener = null;
/**
* where we get our track data from
*/
TrackManager _trackData = null;
/**
* where we get/store what the current set of calcs are
*/
ToteCalculationProvider _toteCalcs = null;
/**
* our current set of calculations
*/
Vector _myCalculations = null;
/**
* the temporal dataset controlling the narrative entry currently displayed
*/
private TimeProvider _myTemporalDataset;
/**
* the "write" interface for the plot which tracks the narrative, where
* avaialable
*/
private ControllableTime _controllableTime;
/**
* the editor currently providing our narrative
*/
protected IEditorPart _currentEditor;
/**
* helper object which loads plugin file-loaders
*/
private CalculationLoaderManager _loader;
private ToteLabelProvider _labelProvider;
/**
* action to put watchables on the tote
*/
private Action _autoGenerate;
/**
* action to put tracks on the tote
*/
private Action _autoGenerateJustTracks;
/**
* action to hide/reveal the units column
*/
private Action _showUnits;
/**
* The constructor.
*/
public ToteView()
{
_myCalculations = new Vector(0, 1);
}
/**
* This is a callback that will allow us to create the _tableViewer and
* initialize it.
*/
public void createPartControl(Composite parent)
{
// _tempStatus = new Label(parent, SWT.NONE);
// _tempStatus.setText("pending");
_tableViewer = new TableViewer(createTableWithColumns(parent));
_content = new ToteContentProvider();
_tableViewer.setContentProvider(_content);
_labelProvider = new ToteLabelProvider(parent.getFont());
_tableViewer.setLabelProvider(_labelProvider);
_tableViewer.setInput(this);
// _tableViewer.setSorter(new NameSorter());
// Create Action instances
createViewActions();
makeActions();
hookContextMenu();
contributeToActionBars();
// try to add ourselves to listen out for page changes
// getSite().getWorkbenchWindow().getPartService().addPartListener(this);
_myPartMonitor = new PartMonitor(getSite().getWorkbenchWindow().getPartService());
_myPartMonitor.addPartListener(TrackManager.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
public void eventTriggered(String type, Object part, IWorkbenchPart parentPart)
{
TrackManager provider = (TrackManager) part;
// is this different to our current one?
if (provider != _trackData)
storeDetails(provider, parentPart);
}
});
_myPartMonitor.addPartListener(TrackManager.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
public void eventTriggered(String type, Object part, IWorkbenchPart parentPart)
{
if (part == _trackData)
{
_trackData = null;
redoTableAfterTrackChanges();
}
}
});
_myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.ACTIVATED,
new PartMonitor.ICallback()
{
public void eventTriggered(String type, Object part, IWorkbenchPart parentPart)
{
// just check we're not already looking at it
if (part != _myTemporalDataset)
{
// ok, stop listening to the old one
if (_myTemporalDataset != null)
_myTemporalDataset.removeListener(_temporalListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
// store the new one
_myTemporalDataset = (TimeProvider) part;
_myTemporalDataset = (TimeProvider) part;
if (_temporalListener == null)
{
_temporalListener = new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent event)
{
// ok, use the new time
HiResDate newDTG = (HiResDate) event.getNewValue();
timeUpdated(newDTG);
}
};
}
_myTemporalDataset.addListener(_temporalListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
// artificially fire time updated event
timeUpdated(_myTemporalDataset.getTime());
}
}
});
_myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.CLOSED,
new PartMonitor.ICallback()
{
public void eventTriggered(String type, Object part, IWorkbenchPart parentPart)
{
// was it our one?
if (_myTemporalDataset == part)
{
// ok, stop listening to this object (just in case we were,
// anyway).
_myTemporalDataset.removeListener(_temporalListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
_myTemporalDataset = null;
}
}
});
// ok we're all ready now. just try and see if the current part is valid
_myPartMonitor.fireActivePart(getSite().getWorkbenchWindow().getActivePage());
}
private void updateTableLayout()
{
// check we have some data
// if (_trackData == null)
// // aah = no track data. better disable the table
// timeUpdated(null);
// // _tableViewer.getTable().setEnabled(false);
// // return;
Table tbl = _tableViewer.getTable();
tbl.setEnabled(true);
// ok, remove all of the columns
TableColumn[] cols = tbl.getColumns();
for (int i = 0; i < cols.length; i++)
{
TableColumn column = cols[i];
column.dispose();
}
TableLayout layout = new TableLayout();
tbl.setLayout(layout);
// first put in the labels
layout.addColumnData(new ColumnWeightData(5, true));
TableColumn tc0 = new TableColumn(tbl, SWT.NONE);
tc0.setText("Calculation");
if (_trackData != null)
{
// first sort out the primary track column
WatchableList priTrack = _trackData.getPrimaryTrack();
// if (priTrack != null)
layout.addColumnData(new ColumnWeightData(10, true));
TableColumn pri = new TableColumn(tbl, SWT.NONE);
if (priTrack != null)
pri.setText(priTrack.getName());
else
pri.setText("n/a");
// and now the secondary track columns
WatchableList[] secTracks = _trackData.getSecondaryTracks();
if (secTracks != null)
{
for (int i = 0; i < secTracks.length; i++)
{
WatchableList secTrack = secTracks[i];
if (secTrack != null)
{
layout.addColumnData(new ColumnWeightData(10, true));
TableColumn thisSec = new TableColumn(tbl, SWT.NONE);
thisSec.setText(secTrack.getName());
}
}
}
}
if (_showUnits.isChecked())
{
// and the units column
layout.addColumnData(new ColumnWeightData(5, true));
TableColumn thisSec = new TableColumn(tbl, SWT.NONE);
thisSec.setText("Units");
}
}
/**
* @param parent
* what we have to fit into
*/
private static Table createTableWithColumns(Composite parent)
{
Table table = new Table(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
table.setLinesVisible(true);
TableLayout layout = new TableLayout();
table.setLayout(layout);
table.setLinesVisible(true);
table.setHeaderVisible(true);
layout.addColumnData(new ColumnWeightData(5, 40, true));
TableColumn tc0 = new TableColumn(table, SWT.NONE);
tc0.setText("Calculation");
tc0.setAlignment(SWT.LEFT);
tc0.setResizable(true);
return table;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.ViewPart#init(org.eclipse.ui.IViewSite,
* org.eclipse.ui.IMemento)
*/
public void init(IViewSite site, IMemento memento) throws PartInitException
{
// let the parent do its bits
super.init(site, memento);
_showUnits = new Action("Show units column", Action.AS_CHECK_BOX)
{
public void run()
{
redoTableAfterTrackChanges();
}
};
// are we showing the units column?
if (memento != null)
{
String unitsVal = memento.getString(SHOW_UNITS);
if (unitsVal != null)
{
_showUnits.setChecked(Boolean.getBoolean(memento.getString(SHOW_UNITS)));
}
}
// ok - declare and load the supplemental plugins which can load datafiles
initialiseCalcLoaders();
toteCalculation[] calcs = _loader.findCalculations();
for (int i = 0; i < calcs.length; i++)
{
toteCalculation thisCalc = calcs[i];
_myCalculations.add(thisCalc);
}
}
/**
* right - store ourselves into the supplied memento object
*
* @param memento
*/
public void saveState(IMemento memento)
{
// let our parent go for it first
super.saveState(memento);
String unitsVal = Boolean.toString(_showUnits.isChecked());
memento.putString(SHOW_UNITS, unitsVal);
}
private void createViewActions()
{
// Toggle filter action
_removeTrackAction = new Action("Remove this track", Action.AS_PUSH_BUTTON)
{
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#runWithEvent(org.eclipse.swt.widgets.Event)
*/
public void runWithEvent(Event event)
{
// cool. sorted.
int index = findSelectedColumn(event.x, event.y, _tableViewer.getTable());
if (index != -1)
{
System.out.println("removing col number:" + index);
}
}
};
_removeTrackAction.setToolTipText("Remove this track from the tote");
_removeTrackAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
.getImageDescriptor(ISharedImages.IMG_TOOL_REDO));
// put watchables on the tote
_autoGenerate = new Action("Auto-populate Tote", Action.AS_PUSH_BUTTON)
{
public void run()
{
autoGenerate(false);
}
};
// put watchables on the tote
_autoGenerateJustTracks = new Action("Auto-populate Tote (tracks only)",
Action.AS_PUSH_BUTTON)
{
public void run()
{
autoGenerate(true);
}
};
//
// part of the memento
}
/**
* automatically pass through the data, and automatically assign the relevant
* watchable items to primary, secondary, etc.
*
* @param onlyAssignTracks -
* as we scan through the layers, only put TrackWrappers onto the
* tote
*/
protected void autoGenerate(boolean onlyAssignTracks)
{
if(_trackData != null)
_trackData.autoAssign(onlyAssignTracks);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
public void dispose()
{
super.dispose();
if (_myPartMonitor != null)
{
// and stop listening for part activity
_myPartMonitor.dispose(getSite().getWorkbenchWindow().getPartService());
}
// also stop listening for time events
if (_controllableTime != null)
{
_myTemporalDataset.removeListener(_temporalListener,
TimeProvider.TIME_CHANGED_PROPERTY_NAME);
}
}
private void hookContextMenu()
{
Table theTable = _tableViewer.getTable();
theTable.addMouseListener(new MouseAdapter()
{
public void mouseUp(MouseEvent e)
{
// so, right-click>
if (e.button == 3)
{
// cool. sorted.
int index = findSelectedColumn(e.x, e.y, _tableViewer.getTable());
if (index != -1)
{
MenuManager mmgr = new MenuManager();
fillContextMenu(mmgr, index);
Menu thisM = mmgr.createContextMenu(_tableViewer.getTable());
thisM.setVisible(true);
}
}
}
});
// MenuManager menuMgr = new MenuManager("#PopupMenu");
// menuMgr.setRemoveAllWhenShown(true);
// menuMgr.addMenuListener(new IMenuListener()
// public void menuAboutToShow(IMenuManager manager)
// ToteView.this.fillContextMenu(manager);
// menuMgr.addMenuListener(new IMenuListener(){
// public void menuAboutToShow(IMenuManager manager)
// TableItem[] ti = _tableViewer.getTable().getSelection();
// System.out.println("ti is:" + ti);
// Menu menu = menuMgr.createContextMenu(_tableViewer.getControl());
// _tableViewer.getControl().setMenu(menu);
// getSite().registerContextMenu(menuMgr, _tableViewer);
}
private void contributeToActionBars()
{
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager)
{
// manager.add(new Separator());
manager.add(_autoGenerate);
manager.add(_autoGenerateJustTracks);
manager.add(_showUnits);
}
private void fillContextMenu(IMenuManager manager, final int index)
{
// Toggle filter action
_removeTrackAction = new Action("Remove this track", Action.AS_PUSH_BUTTON)
{
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#runWithEvent(org.eclipse.swt.widgets.Event)
*/
public void runWithEvent(Event event)
{
// ok, is this the primary?
if (index == 1)
{
// yes, go for it
_trackData.setPrimary(null);
}
else
{
// ok, inform the removal of the secondary
WatchableList thisSec = _trackData.getSecondaryTracks()[index - 2];
_trackData.removeSecondary(thisSec);
}
}
};
_removeTrackAction.setToolTipText("Remove this track from the tote");
_removeTrackAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
.getImageDescriptor(ISharedImages.IMG_TOOL_REDO));
// Other plug-ins can contribute there actions here
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
manager.add(_removeTrackAction);
}
private void fillLocalToolBar(IToolBarManager manager)
{
// manager.add(action1);
// manager.add(action2);
// manager.add(_followTimeToggle);
}
private void makeActions()
{
}
/**
* Passing the focus request to the _tableViewer's control.
*/
public void setFocus()
{
// _tableViewer.getControl().setFocus();
}
/**
* @param part
* @param parentPart
*/
private void storeDetails(TrackManager part, IWorkbenchPart parentPart)
{
// hmm - are we already looking at this one?
if (part != _trackData)
{
// ok, store it
_trackData = part;
_tableViewer.setInput(this);
// ok - now update the content of our table
redoTableAfterTrackChanges();
// lastly listen out for any future changes
part.addTrackDataListener(new TrackDataListener()
{
public void tracksUpdated(WatchableList primary, WatchableList[] secondaries)
{
// ok - now update the content of our table
redoTableAfterTrackChanges();
}
});
}
}
private void redoTableAfterTrackChanges()
{
// suspend updates
_tableViewer.getTable().setRedraw(false);
// and update the table column layout
updateTableLayout();
// and fire the update
_tableViewer.getTable().layout(true);
Color greyCol = Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
_tableViewer.getTable().setBackground(greyCol);
// hmm, check if we have any track data
if (_trackData == null)
{
// don't bother with any further processing.
_tableViewer.getTable().setRedraw(true);
return;
}
// lastly color-code the columns
TableItem[] items = _tableViewer.getTable().getItems();
Color thisCol = null;
WatchableList[] secs = _trackData.getSecondaryTracks();
if (secs != null)
{
for (int i = 0; i < secs.length; i++)
{
WatchableList thisSec = secs[i];
if (thisSec != null)
{
thisCol = ColorHelper.getColor(thisSec.getColor());
for (int j = 0; j < items.length; j++)
{
TableItem thisRow = items[j];
thisRow.setForeground(2 + i, thisCol);
Color whiteCol = ColorHelper.getColor(new java.awt.Color(255, 255, 255));
thisRow.setBackground(2 + i, whiteCol);
}
}
}
}
WatchableList pri = _trackData.getPrimaryTrack();
if (pri != null)
{
thisCol = ColorHelper.getColor(pri.getColor());
for (int j = 0; j < items.length; j++)
{
TableItem thisRow = items[j];
thisRow.setForeground(1, thisCol);
Color lightCol = ColorHelper.getColor(new java.awt.Color(240, 240, 245));
thisRow.setBackground(1, lightCol);
}
}
// lastly, fire a time-update to fill in the calcs
if (_myTemporalDataset != null)
{
timeUpdated(_myTemporalDataset.getTime());
}
// resume updates
_tableViewer.getTable().setRedraw(true);
}
// temporal data management
/**
* the data we are looking at has updated. If we're set to follow that time,
* update ourselves
*/
private void timeUpdated(final HiResDate newDTG)
{
if (!_tableViewer.getTable().isDisposed())
{
Display.getDefault().asyncExec(new Runnable()
{
public void run()
{
// double-check that we haven't lost the table.
if (!_tableViewer.getTable().isDisposed())
{
_labelProvider.setDTG(newDTG);
_tableViewer.refresh(true);
}
}
});
}
else
System.out.println("not updating. table is disposed");
}
// selection listener bits
private void initialiseCalcLoaders()
{
// hey - sort out our plot readers
_loader = new CalculationLoaderManager(EXTENSION_POINT_ID, EXTENSION_TAG, PLUGIN_ID)
{
public toteCalculation createInstance(IConfigurationElement configElement,
String label)
{
// get the attributes
label = configElement.getAttribute(EXTENSION_TAG_LABEL_ATTRIB);
String icon = configElement.getAttribute(EXTENSION_TAG_ICON_ATTRIB);
// create the instance
toteCalculation res = null;
// create the instance
res = new CalculationLoaderManager.DeferredCalculation(configElement, label, icon);
// and return it.
return res;
}
};
}
public class ToteContentProvider implements IStructuredContentProvider
{
public ToteContentProvider()
{
}
public Object[] getElements(Object inputElement)
{
return _myCalculations.toArray();
}
public void dispose()
{
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
}
}
public class ToteLabelProvider implements ITableLabelProvider, ITableFontProvider
{
/**
* the DTG we're updating for.
*/
private HiResDate _theDTG;
/**
* remember the fonts we're going to use Start off with the font for
* secondary tracks
*/
private final Font _secondaryFont;
/**
* and now the font for the primary track
*/
private final Font _primaryFont;
/**
* and the font for interpolated data-sets
*/
private final Font _interpolatedSecondaryFont;
/**
* and the font for interpolated data-sets
*/
private final Font _interpolatedPrimaryFont;
/**
* constructor - base the primary /secondary fonts on the supplied font
*
* @param coreFont
* the font to base ourselves upon
*/
public ToteLabelProvider(Font coreFont)
{
// ok, just take a copy for the sec font
_secondaryFont = coreFont;
// but now generate a changed font for the primary
FontData[] fontData = _secondaryFont.getFontData();
FontData theOnly = fontData[0];
_primaryFont = new Font(Display.getCurrent(), theOnly.getName(), theOnly
.getHeight(), theOnly.getStyle() | SWT.BOLD);
_interpolatedSecondaryFont = new Font(Display.getCurrent(), theOnly.getName(),
theOnly.getHeight(), theOnly.getStyle() | SWT.ITALIC);
_interpolatedPrimaryFont = new Font(Display.getCurrent(), theOnly.getName(),
theOnly.getHeight(), theOnly.getStyle() | SWT.ITALIC | SWT.BOLD);
}
/**
* store the new DTG (ready for our updates)
*
* @param theDTG
*/
public void setDTG(HiResDate theDTG)
{
_theDTG = theDTG;
}
public Image getColumnImage(Object element, int columnIndex)
{
return null;
}
public Font getFont(Object element, int columnIndex)
{
final Font res;
boolean isPrimary = false;
boolean isInterpolated = false;
// is this already sorted?
if (_theDTG != null)
{
if (_trackData != null)
{
WatchableList _thePrimary = _trackData.getPrimaryTrack();
WatchableList[] secLists = _trackData.getSecondaryTracks();
// get the data for the right col
if (columnIndex == 0)
{
// ignore, we just use the primary font anyway
isPrimary = true;
}
else if (columnIndex == 1)
{
// check that we've got a primary
if (_thePrimary != null)
{
isPrimary = true;
// so, we the calculations have been added to the tote list
// in order going across the page
// get the primary ready,
Watchable[] list = _thePrimary.getNearestTo(_theDTG);
Watchable pw = null;
if (list.length > 0)
pw = list[0];
if (pw instanceof FixWrapper.InterpolatedFixWrapper)
isInterpolated = true;
}
}
else
{
if (secLists != null)
{
if (columnIndex - 2 < secLists.length)
{
// prepare the list of secondary watchables
WatchableList wList = secLists[columnIndex - 2];
if (wList != null)
{
Watchable[] list = wList.getNearestTo(_theDTG);
Watchable nearest = null;
if (list.length > 0)
{
nearest = list[0];
if (nearest instanceof FixWrapper.InterpolatedFixWrapper)
isInterpolated = true;
}
}
}
}
}
}
}
if (isPrimary)
{
if (isInterpolated)
res = _interpolatedPrimaryFont;
else
res = _primaryFont;
}
else
{
if (isInterpolated)
res = _interpolatedSecondaryFont;
else
res = _secondaryFont;
}
return res;
}
public String getColumnText(Object element, int columnIndex)
{
String res = null;
toteCalculation tc = (toteCalculation) element;
// right, is this the title column?
if (columnIndex == 0)
{
res = tc.getTitle();
}
else
{
if (_showUnits.isChecked())
{
// hmm, could it be the units column?
int numCols = _tableViewer.getTable().getColumnCount();
if (columnIndex == numCols - 1)
{
res = tc.getUnits();
}
}
}
// is this already sorted?
if ((res == null) && (_theDTG != null))
{
if (_trackData != null)
{
WatchableList _thePrimary = _trackData.getPrimaryTrack();
WatchableList[] secLists = _trackData.getSecondaryTracks();
// check that we've got a primary
if (_thePrimary != null)
{
// so, we the calculations have been added to the tote list
// in order going across the page
// get the primary ready,
Watchable[] list = _thePrimary.getNearestTo(_theDTG);
Watchable pw = null;
if (list.length > 0)
pw = list[0];
// are we only looking at the primary?
if (columnIndex == 1)
{
res = tc.update(null, pw, _theDTG);
}
else
{
if (secLists != null)
{
if (columnIndex - 2 < secLists.length)
{
// prepare the list of secondary watchables
WatchableList wList = secLists[columnIndex - 2];
if (wList != null)
{
list = wList.getNearestTo(_theDTG);
Watchable nearest = null;
if (list.length > 0)
nearest = list[0];
res = tc.update(pw, nearest, _theDTG);
}
}
}
}
}
}
}
return res;
}
public void addListener(ILabelProviderListener listener)
{
}
public void dispose()
{
}
public boolean isLabelProperty(Object element, String property)
{
return true;
}
public void removeListener(ILabelProviderListener listener)
{
}
}
private int findSelectedColumn(int x, int y, Table table)
{
int index = -1;
TableItem[] selectedCols = table.getSelection();
if (selectedCols != null)
{
TableItem selection = selectedCols[0];
TableColumn[] tc = table.getColumns();
// sort out how many c
int numCols = tc.length;
if (_showUnits.isChecked())
numCols
for (int i = 1; i < numCols; i++)
{
Rectangle bounds = selection.getBounds(i);
if (bounds.contains(x, bounds.y))
{
index = i;
}
}
}
return index;
}
}
|
package io.tus.java.client;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpResponse;
import org.mockserver.socket.PortFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
public class TestTusUploader extends TestCase {
private MockServerClient mockServer;
public URL mockServerURL;
@Before
protected void setUp() throws Exception {
super.setUp();
int port = PortFactory.findFreePort();
mockServerURL = new URL("http://localhost:" + port + "/files");
mockServer = startClientAndServer(port);
}
@After
protected void tearDown() {
mockServer.stop();
}
public void testTusUploader() throws IOException, ProtocolException {
byte[] content = "hello world".getBytes();
mockServer.when(new HttpRequest()
.withPath("/files/foo")
.withHeader("Tus-Resumable", TusClient.TUS_VERSION)
.withHeader("Upload-Offset", "3")
.withBody(Arrays.copyOfRange(content, 3, 11)))
.respond(new HttpResponse()
.withStatusCode(204)
.withHeader("Tus-Resumable", TusClient.TUS_VERSION));
TusClient client = new TusClient();
URL uploadUrl = new URL(mockServerURL + "/foo");
InputStream input = new ByteArrayInputStream(content);
long offset = 3;
TusUploader uploader = new TusUploader(client, uploadUrl, input, offset);
assertEquals(5, uploader.uploadChunk(5));
assertEquals(3, uploader.uploadChunk(5));
assertEquals(-1, uploader.uploadChunk(5));
assertEquals(11, uploader.getOffset());
uploader.finish();
}
}
|
package com.intellij.uiDesigner.componentTree;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
import com.intellij.ide.DeleteProvider;
import com.intellij.ide.util.EditSourceUtil;
import com.intellij.ide.util.treeView.NodeDescriptor;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.SyntaxHighlighterColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.ui.ColoredTreeCellRenderer;
import com.intellij.ui.PopupHandler;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.TreeToolTipHandler;
import com.intellij.uiDesigner.*;
import com.intellij.uiDesigner.actions.StartInplaceEditingAction;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.designSurface.*;
import com.intellij.uiDesigner.editor.UIFormEditor;
import com.intellij.uiDesigner.lw.LwInspectionSuppression;
import com.intellij.uiDesigner.palette.ComponentItem;
import com.intellij.uiDesigner.palette.Palette;
import com.intellij.uiDesigner.quickFixes.QuickFixManager;
import com.intellij.uiDesigner.radComponents.*;
import com.intellij.util.ui.Tree;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.plaf.TreeUI;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class ComponentTree extends Tree implements DataProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.componentTree.ComponentTree");
private SimpleTextAttributes myBindingAttributes; // exists only for performance reason
private SimpleTextAttributes myClassAttributes; // exists only for performance reason
private SimpleTextAttributes myPackageAttributes; // exists only for performance reason
private SimpleTextAttributes myUnknownAttributes; // exists only for performance reason
private SimpleTextAttributes myTitleAttributes; // exists only for performance reason
private Map<HighlightSeverity, Map<SimpleTextAttributes, SimpleTextAttributes>> myHighlightAttributes;
private GuiEditor myEditor;
private UIFormEditor myFormEditor;
private QuickFixManager myQuickFixManager;
private RadComponent myDropTargetComponent = null;
private StartInplaceEditingAction myStartInplaceEditingAction;
private MyDeleteProvider myDeleteProvider = new MyDeleteProvider();
private Icon myButtonGroupIcon = IconLoader.getIcon("/com/intellij/uiDesigner/icons/buttonGroup.png");
private Icon myInspectionSuppressionIcon = IconLoader.getIcon("/com/intellij/uiDesigner/icons/inspectionSuppression.png");
@NonNls private static final String ourHelpID = "guiDesigner.uiTour.compsTree";
private final Project myProject;
public ComponentTree(@NotNull final Project project) {
super(new DefaultTreeModel(new DefaultMutableTreeNode()));
myProject = project;
setCellRenderer(new MyTreeCellRenderer());
setRootVisible(false);
setShowsRootHandles(true);
// Enable tooltips
ToolTipManager.sharedInstance().registerComponent(this);
// Install convenient keyboard navigation
TreeUtil.installActions(this);
// Install advanced tooltips
TreeToolTipHandler.install(this);
// Popup menu
PopupHandler.installPopupHandler(
this,
(ActionGroup)ActionManager.getInstance().getAction(IdeActions.GROUP_GUI_DESIGNER_COMPONENT_TREE_POPUP),
ActionPlaces.GUI_DESIGNER_COMPONENT_TREE_POPUP, ActionManager.getInstance());
// F2 should start inplace editing
myStartInplaceEditingAction = new StartInplaceEditingAction(null);
myStartInplaceEditingAction.registerCustomShortcutSet(
new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)),
this
);
if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
setDragEnabled(true);
setTransferHandler(new TransferHandler() {
public int getSourceActions(JComponent c) {
return DnDConstants.ACTION_COPY_OR_MOVE;
}
protected Transferable createTransferable(JComponent c) {
return DraggedComponentList.pickupSelection(myEditor, null);
}
});
setDropTarget(new DropTarget(this, new MyDropTargetListener()));
}
}
@NotNull
public Project getProject() {
return myProject;
}
public void initQuickFixManager(JViewport viewPort) {
myQuickFixManager = new QuickFixManagerImpl(null, this, viewPort);
}
public void setEditor(final GuiEditor editor) {
myEditor = editor;
myDeleteProvider.setEditor(editor);
myQuickFixManager.setEditor(editor);
myStartInplaceEditingAction.setEditor(editor);
}
public void refreshIntentionHint() {
myQuickFixManager.refreshIntentionHint();
}
@Nullable
public String getToolTipText(final MouseEvent e) {
final TreePath path = getPathForLocation(e.getX(), e.getY());
final RadComponent component = getComponentFromPath(path);
if (component != null) {
final ErrorInfo errorInfo = ErrorAnalyzer.getErrorForComponent(component);
if (errorInfo != null) {
return errorInfo.myDescription;
}
}
return null;
}
@Nullable
private static RadComponent getComponentFromPath(TreePath path) {
if (path != null) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
LOG.assertTrue(node != null);
final Object userObject = node.getUserObject();
if (userObject instanceof ComponentPtrDescriptor) {
final NodeDescriptor descriptor = (NodeDescriptor)userObject;
final ComponentPtr ptr = (ComponentPtr)descriptor.getElement();
if (ptr != null && ptr.isValid()) {
final RadComponent component = ptr.getComponent();
LOG.assertTrue(component != null);
return component;
}
}
}
return null;
}
/**
* TODO[vova] should return pair <RadComponent, TreePath>
*
* @return first selected component. The method returns <code>null</code>
* if there is no selection in the tree.
*/
@Nullable
public RadComponent getSelectedComponent() {
final RadComponent[] selectedComponents = getSelectedComponents();
return selectedComponents.length > 0 ? selectedComponents[0] : null;
}
/**
* TODO[vova] should return pair <RadComponent, TreePath>
*
* @return currently selected components.
*/
@NotNull public RadComponent[] getSelectedComponents() {
final TreePath[] paths = getSelectionPaths();
if (paths == null) {
return RadComponent.EMPTY_ARRAY;
}
final ArrayList<RadComponent> result = new ArrayList<RadComponent>(paths.length);
for (TreePath path : paths) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
LOG.assertTrue(node != null);
if (node.getUserObject() instanceof ComponentPtrDescriptor) {
final ComponentPtrDescriptor descriptor = (ComponentPtrDescriptor)node.getUserObject();
final ComponentPtr ptr = (ComponentPtr)descriptor.getElement();
LOG.assertTrue(ptr != null && ptr.isValid());
result.add(ptr.getComponent());
}
}
return result.toArray(new RadComponent[result.size()]);
}
/**
* Provides {@link DataConstants#NAVIGATABLE} to navigate to
* binding of currently selected component (if any)
*/
public Object getData(final String dataId) {
if (GuiEditor.class.getName().equals(dataId)) {
return myEditor;
}
if (DataConstants.DELETE_ELEMENT_PROVIDER.equals(dataId)) {
return myDeleteProvider;
}
if (
DataConstants.COPY_PROVIDER.equals(dataId) ||
DataConstants.CUT_PROVIDER.equals(dataId) ||
DataConstants.PASTE_PROVIDER.equals(dataId)) {
return myEditor == null ? null : myEditor.getData(dataId);
}
if (LwInspectionSuppression.class.getName().equals(dataId)) {
Collection<LwInspectionSuppression> elements = getSelectedElements(LwInspectionSuppression.class);
return elements.size() == 0 ? null : elements.toArray(new LwInspectionSuppression[elements.size()]);
}
if (DataConstants.HELP_ID.equals(dataId)) {
return ourHelpID;
}
if (DataConstants.FILE_EDITOR.equals(dataId)) {
return myFormEditor;
}
if (!DataConstants.NAVIGATABLE.equals(dataId)) {
return null;
}
final RadComponent selectedComponent = getSelectedComponent();
if (selectedComponent == null) {
return null;
}
final String classToBind = myEditor.getRootContainer().getClassToBind();
if (classToBind == null) {
return null;
}
final PsiClass aClass = FormEditingUtil.findClassToBind(myEditor.getModule(), classToBind);
if (aClass == null) {
return null;
}
if (selectedComponent instanceof RadRootContainer) {
return EditSourceUtil.getDescriptor(aClass);
}
final String binding = selectedComponent.getBinding();
if (binding == null) {
return null;
}
final PsiField[] fields = aClass.getFields();
for (final PsiField field : fields) {
if (binding.equals(field.getName())) {
return EditSourceUtil.getDescriptor(field);
}
}
return null;
}
public <T> List<T> getSelectedElements(Class<? extends T> elementClass) {
final TreePath[] paths = getSelectionPaths();
if (paths == null) {
return Collections.emptyList();
}
final ArrayList<T> result = new ArrayList<T>(paths.length);
for (TreePath path : paths) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
Object userObject = node.getUserObject();
if (userObject instanceof NodeDescriptor && elementClass.isInstance(((NodeDescriptor) userObject).getElement())) {
//noinspection unchecked
result.add((T)((NodeDescriptor) node.getUserObject()).getElement());
}
}
return result;
}
private SimpleTextAttributes getAttribute(@NotNull final SimpleTextAttributes attrs,
@Nullable HighlightDisplayLevel level) {
if (level == null) {
return attrs;
}
Map<SimpleTextAttributes, SimpleTextAttributes> highlightMap = myHighlightAttributes.get(level.getSeverity());
if (highlightMap == null) {
highlightMap = new HashMap<SimpleTextAttributes, SimpleTextAttributes>();
myHighlightAttributes.put(level.getSeverity(), highlightMap);
}
SimpleTextAttributes result = highlightMap.get(attrs);
if (result == null) {
final TextAttributesKey attrKey = SeverityRegistrar.getInstance(myProject).getHighlightInfoTypeBySeverity(level.getSeverity()).getAttributesKey();
TextAttributes textAttrs = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(attrKey);
textAttrs = TextAttributes.merge(attrs.toTextAttributes(), textAttrs);
result = SimpleTextAttributes.fromTextAttributes(textAttrs);
highlightMap.put(attrs, result);
}
return result;
}
public void setUI(final TreeUI ui) {
super.setUI(ui);
// [vova] we cannot create this hash in constructor and just clear it here. The
// problem is that setUI is invoked by constructor of superclass.
myHighlightAttributes = new HashMap<HighlightSeverity, Map<SimpleTextAttributes, SimpleTextAttributes>>();
final EditorColorsScheme globalScheme = EditorColorsManager.getInstance().getGlobalScheme();
final TextAttributes attributes = globalScheme.getAttributes(SyntaxHighlighterColors.STRING);
myBindingAttributes = new SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, UIUtil.getTreeForeground());
myClassAttributes = new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, UIUtil.getTreeForeground());
myPackageAttributes = new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, Color.GRAY);
myTitleAttributes =new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, attributes.getForegroundColor());
myUnknownAttributes = new SimpleTextAttributes(SimpleTextAttributes.STYLE_WAVED, Color.RED);
}
public static Icon getComponentIcon(final RadComponent component) {
if (!(component instanceof RadErrorComponent)) {
final Palette palette = Palette.getInstance(component.getModule().getProject());
final ComponentItem item = palette.getItem(component.getComponentClassName());
final Icon icon;
if (item != null) {
icon = item.getSmallIcon();
}
else {
icon = IconLoader.getIcon("/com/intellij/uiDesigner/icons/unknown-small.png");
}
return icon;
}
else {
return IconLoader.getIcon("/com/intellij/uiDesigner/icons/error-small.png");
}
}
public void setDropTargetComponent(final RadComponent dropTargetComponent) {
if (dropTargetComponent != myDropTargetComponent) {
myDropTargetComponent = dropTargetComponent;
repaint();
}
}
public void setFormEditor(final UIFormEditor formEditor) {
myFormEditor = formEditor;
}
private final class MyTreeCellRenderer extends ColoredTreeCellRenderer {
@NonNls private static final String SWING_PACKAGE = "javax.swing";
public void customizeCellRenderer(
final JTree tree,
final Object value,
final boolean selected,
final boolean expanded,
final boolean leaf,
final int row,
final boolean hasFocus
) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
if (node.getUserObject() instanceof ComponentPtrDescriptor) {
final ComponentPtrDescriptor descriptor = (ComponentPtrDescriptor)node.getUserObject();
final ComponentPtr ptr = (ComponentPtr)descriptor.getElement();
if (ptr == null) return;
final RadComponent component = ptr.getComponent();
LOG.assertTrue(component != null);
final HighlightDisplayLevel level = ErrorAnalyzer.getHighlightDisplayLevel(myProject, component);
// Text
boolean hasText = false;
final String binding = component.getBinding();
if (binding != null) {
append(binding, getAttribute(myBindingAttributes, level));
append(" : ", getAttribute(myClassAttributes, level));
hasText = true;
}
else {
String componentTitle = component.getComponentTitle();
if (componentTitle != null) {
append(componentTitle, getAttribute(myTitleAttributes, level));
append(" : ", getAttribute(myClassAttributes, level));
hasText = true;
}
}
final String componentClassName = component.getComponentClassName();
if (component instanceof RadVSpacer) {
append(UIDesignerBundle.message("component.vertical.spacer"), getAttribute(myClassAttributes, level));
}
else if (component instanceof RadHSpacer) {
append(UIDesignerBundle.message("component.horizontal.spacer"), getAttribute(myClassAttributes, level));
}
else if (component instanceof RadErrorComponent) {
final RadErrorComponent c = (RadErrorComponent)component;
append(c.getErrorDescription(), getAttribute(myUnknownAttributes, level));
}
else if (component instanceof RadRootContainer) {
append(UIDesignerBundle.message("component.form"), getAttribute(myClassAttributes, level));
append("(", getAttribute(myPackageAttributes, level));
final String classToBind = ((RadRootContainer)component).getClassToBind();
if (classToBind != null) {
append(classToBind, getAttribute(myPackageAttributes, level));
}
else {
append(UIDesignerBundle.message("component.no.binding"), getAttribute(myPackageAttributes, level));
}
append(")", getAttribute(myPackageAttributes, level));
}
else {
String packageName = null;
int pos = componentClassName.lastIndexOf('.');
if (pos >= 0) {
packageName = componentClassName.substring(0, pos);
}
SimpleTextAttributes classAttributes = hasText ? myPackageAttributes : myClassAttributes;
if (packageName != null) {
append(componentClassName.substring(packageName.length() + 1).replace('$', '.'),
getAttribute(classAttributes, level));
if (!packageName.equals(SWING_PACKAGE)) {
append(" (", getAttribute(myPackageAttributes, level));
append(packageName, getAttribute(myPackageAttributes, level));
append(")", getAttribute(myPackageAttributes, level));
}
}
else {
append(componentClassName.replace('$', '.'), getAttribute(classAttributes, level));
}
}
// Icon
setIcon(getComponentIcon(component));
if (component == myDropTargetComponent) {
setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
}
}
else if (node.getUserObject() != null) {
final String fragment = node.getUserObject().toString();
if (fragment != null) {
append(fragment, SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
if (node.getUserObject() instanceof SuppressionDescriptor) {
setIcon(myInspectionSuppressionIcon);
}
else if (node.getUserObject() instanceof ButtonGroupDescriptor) {
setIcon(myButtonGroupIcon);
}
}
}
}
private final class MyDropTargetListener extends DropTargetAdapter {
public void dragOver(DropTargetDragEvent dtde) {
try {
RadComponent dropTargetComponent = null;
ComponentDragObject dragObject = null;
final DraggedComponentList dcl = DraggedComponentList.fromTransferable(dtde.getTransferable());
if (dcl != null) {
dragObject = dcl;
}
else {
ComponentItem componentItem = SimpleTransferable.getData(dtde.getTransferable(), ComponentItem.class);
if (componentItem != null) {
dragObject = new ComponentItemDragObject(componentItem);
}
}
boolean canDrop = false;
if (dragObject != null) {
final TreePath path = getPathForLocation((int) dtde.getLocation().getX(),
(int) dtde.getLocation().getY());
final RadComponent targetComponent = getComponentFromPath(path);
if (path != null && targetComponent instanceof RadContainer) {
final ComponentDropLocation dropLocation = ((RadContainer)targetComponent).getDropLocation(null);
canDrop = dropLocation.canDrop(dragObject);
if (dcl != null && FormEditingUtil.isDropOnChild(dcl, dropLocation)) {
canDrop = false;
}
if (canDrop) {
dropTargetComponent = targetComponent;
dtde.acceptDrag(dtde.getDropAction());
}
}
}
if (!canDrop) {
dtde.rejectDrag();
}
setDropTargetComponent(dropTargetComponent);
}
catch (Exception e) {
LOG.error(e);
}
}
public void dragExit(DropTargetEvent dte) {
setDropTargetComponent(null);
}
public void drop(DropTargetDropEvent dtde) {
try {
final DraggedComponentList dcl = DraggedComponentList.fromTransferable(dtde.getTransferable());
ComponentItem componentItem = SimpleTransferable.getData(dtde.getTransferable(), ComponentItem.class);
if (dcl != null || componentItem != null) {
final TreePath path = getPathForLocation((int) dtde.getLocation().getX(),
(int) dtde.getLocation().getY());
final RadComponent targetComponent = getComponentFromPath(path);
if (targetComponent instanceof RadContainer) {
final ComponentDropLocation dropLocation = ((RadContainer)targetComponent).getDropLocation(null);
if (dcl != null) {
if (!FormEditingUtil.isDropOnChild(dcl, dropLocation)) {
RadComponent[] components = dcl.getComponents().toArray(new RadComponent [dcl.getComponents().size()]);
RadContainer[] originalParents = dcl.getOriginalParents();
final GridConstraints[] originalConstraints = dcl.getOriginalConstraints();
for(int i=0; i<components.length; i++) {
originalParents [i].removeComponent(components [i]);
}
dropLocation.processDrop(myEditor, components, null, dcl);
for (int i = 0; i < originalConstraints.length; i++) {
if (originalParents[i].getLayoutManager().isGrid()) {
FormEditingUtil.deleteEmptyGridCells(originalParents[i], originalConstraints[i]);
}
}
}
}
else {
new InsertComponentProcessor(myEditor).processComponentInsert(componentItem, dropLocation);
}
}
myEditor.refreshAndSave(true);
}
setDropTargetComponent(null);
}
catch (Exception e) {
LOG.error(e);
}
}
}
private static class MyDeleteProvider implements DeleteProvider {
private GuiEditor myEditor;
public void setEditor(final GuiEditor editor) {
myEditor = editor;
}
public void deleteElement(DataContext dataContext) {
if (myEditor != null) {
LwInspectionSuppression[] suppressions = (LwInspectionSuppression[]) dataContext.getData(LwInspectionSuppression.class.getName());
if (suppressions != null) {
if (!myEditor.ensureEditable()) return;
for(LwInspectionSuppression suppression: suppressions) {
myEditor.getRootContainer().removeInspectionSuppression(suppression);
}
myEditor.refreshAndSave(true);
}
else {
DeleteProvider baseProvider = (DeleteProvider) myEditor.getData(DataConstants.DELETE_ELEMENT_PROVIDER);
if (baseProvider != null) {
baseProvider.deleteElement(dataContext);
}
}
}
}
public boolean canDeleteElement(DataContext dataContext) {
if (myEditor != null) {
LwInspectionSuppression[] suppressions = (LwInspectionSuppression[]) dataContext.getData(LwInspectionSuppression.class.getName());
if (suppressions != null) {
return true;
}
DeleteProvider baseProvider = (DeleteProvider) myEditor.getData(DataConstants.DELETE_ELEMENT_PROVIDER);
if (baseProvider != null) {
return baseProvider.canDeleteElement(dataContext);
}
}
return false;
}
}
}
|
package minestra.resource;
import static org.junit.Assert.*;
import java.util.Locale;
import org.junit.Ignore;
import org.junit.Test;
@SuppressWarnings("deprecation")
public class I18nResourceTest {
static final String rootPackageName = getRootPackageName();
static final Locale JA = Locale.JAPANESE;
static final I18nResource rootBase = I18nResource.create(Locale.JAPAN);
static final I18nResource pkgBase = I18nResource.create("/" + rootPackageName + "/", JA);
static final I18nResource pkgBaseHere = I18nResource.create(I18nResourceTest.class.getPackage());
static final I18nResource res = rootBase.derive(I18nResourceTest.class, JA);
static final I18nResource resEn = rootBase.derive(I18nResourceTest.class, Locale.ENGLISH, JA);
static String getRootPackageName() {
return I18nResourceTest.class.getPackage().getName().replaceFirst("\\..+", "");
}
@Ignore
@Test
public void testX() {
// base
assertEquals("value1ja", rootBase.string("key1"));
assertEquals("value1ja", rootBase.s("key1"));
assertEquals(336, rootBase.integer("key2"));
assertEquals(336, rootBase.i("key2"));
// pkg-base
assertEquals("pkg-default", pkgBase.string("key1"));
assertEquals(910, pkgBase.integer("key2"));
// pkg-base-here
assertEquals("pkg:minestra.collection", pkgBaseHere.string("key1"));
// res
assertEquals("true", res.string("key3a"));
assertEquals("false", res.string("key3b"));
assertEquals("TRUE", res.string("key3c"));
assertEquals("", res.string("key1"));
assertEquals(687, res.integer("key2"));
assertEquals(true, res.isTrue("key3a"));
assertEquals(false, res.isTrue("key3b"));
assertEquals(true, res.isTrue("key3c"));
assertEquals("", res.string("no-key"));
assertEquals("x", res.string("no-key", "x"));
assertEquals(0, res.integer("no-key"));
assertEquals(-1, res.integer("no-key", -1));
// res-en
assertEquals("the", resEn.string("key1"));
}
}
|
package net.imagej.legacy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue;
import java.net.URL;
import net.imagej.patcher.LegacyInjector;
import org.junit.Test;
import org.scijava.Context;
import org.scijava.script.ScriptModule;
import org.scijava.script.ScriptService;
/**
* Verifies that opening image works as expected.
*
* @author Johannes Schindelin
*/
public class LegacyOpenerTest {
static {
LegacyInjector.preinit();
}
/**
* This regression test is based on a macro provided by Paul van Schayck.
*
* @throws Exception
*/
@Test
public void testPaulsMacro() throws Exception {
final URL url = getClass().getResource("/icons/imagej-256.png");
assertNotNull(url);
assumeTrue("file".equals(url.getProtocol()));
final String path = url.getPath();
final String macro = "// @OUTPUT int nResults\n"
+ "open('" + path + "');\n"
+ "if (nImages() != 1) exit('Oh no!');\n"
+ "run('8-bit');"
+ "setThreshold(150,255);"
+ "run('Analyze Particles...', 'size=20-Infinity circularity=0.40-1.00');\n"
+ "close();";
final Context context = new Context();
try {
final ScriptService script = context.getService(ScriptService.class);
assertNotNull(script);
final ScriptModule module =
script.run("pauls-macro.ijm", macro, true).get();
final Integer nResults = (Integer) module.getOutput("nResults");
assertNotNull(nResults);
assertEquals(10, (int) nResults);
}
finally {
context.dispose();
}
}
@Test
public void testSliceLabels() throws Exception {
final URL url = getClass().getResource("/with-slice-label.tif");
assertNotNull(url);
assumeTrue("file".equals(url.getProtocol()));
final String path = url.getPath();
final String macro = "// @OUTPUT String label\n"
+ "open('" + path + "');\n"
+ "if (nImages() != 1) exit('Oh no!');\n"
+ "label = getMetadata('Label');\n"
+ "close();";
final Context context = new Context();
try {
final ScriptService script = context.getService(ScriptService.class);
assertNotNull(script);
final ScriptModule module = script.run("bobs-macro.ijm", macro, true).get();
final String label = (String) module.getOutput("label");
assertNotNull(label);
assertEquals("Hello, World!", label);
}
finally {
context.dispose();
}
}
}
|
package org.cactoos.collection;
import java.util.ArrayList;
import java.util.Collection;
import org.cactoos.iterable.IterableOf;
import org.cactoos.list.ListOf;
import org.hamcrest.collection.IsEmptyCollection;
import org.hamcrest.core.IsEqual;
import org.hamcrest.core.IsNot;
import org.hamcrest.object.HasToString;
import org.hamcrest.text.StringContainsInOrder;
import org.junit.jupiter.api.Test;
import org.llorllale.cactoos.matchers.Assertion;
import org.llorllale.cactoos.matchers.HasValues;
import org.llorllale.cactoos.matchers.IsTrue;
import org.llorllale.cactoos.matchers.Throws;
/**
* Test cases for {@link NoNulls}.
*
* <p>
* There is no thread-safety guarantee.
*
* @since 0.35
* @checkstyle JavadocMethodCheck (500 lines)
* @checkstyle MagicNumberCheck (500 lines)
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
@SuppressWarnings("PMD.TooManyMethods")
final class NoNullsTest {
@Test
void throwsErrorIfNullInToArray() {
new Assertion<>(
"Must throw exception",
() -> new NoNulls<>(
new ListOf<>(1, null, 3)
).toArray(),
new Throws<>(
"Item #1 of #toArray() is NULL",
IllegalStateException.class
)
).affirm();
}
@Test
void throwsErrorIfNullInToArrayWithArg() {
new Assertion<>(
"Must throw exception for the item
() -> new NoNulls<>(
new ListOf<>(1, null, 3)
).toArray(new Object[3]),
new Throws<>(
"Item #1 of #toArray(array) is NULL",
IllegalStateException.class
)
).affirm();
}
@Test
void throwsErrorIfNullInContainsArg() {
new Assertion<>(
"Must throw exception for #contains(null)",
() -> new NoNulls<>(
new ListOf<>(1, 2, 3)
).contains(null),
new Throws<>(
"Argument of #contains(T) is NULL",
IllegalArgumentException.class
)
).affirm();
}
@Test
void testSuccessNotNullArg() {
new Assertion<>(
"Must contain not null argument",
new NoNulls<>(
new ListOf<>(1)
).contains(1),
new IsTrue()
).affirm();
}
@Test
void testSuccessAddAll() {
final Collection<Integer> nonulls = new NoNulls<>(new ArrayList<>(0));
nonulls.addAll(new ListOf<>(1, 2));
new Assertion<>(
"Must add all",
nonulls,
new IsEqual<>(
new ListOf<>(1, 2)
)
).affirm();
}
@Test
void throwsErrorIfNullInAddAll() {
final Collection<Integer> nonulls = new NoNulls<>(new ArrayList<>(0));
new Assertion<>(
"Must throw exception for nullable #addAll() parameter collection",
() -> nonulls.addAll(new ListOf<>(1, 2, null)),
new Throws<>(
"Item #2 of #toArray() is NULL",
IllegalStateException.class
)
).affirm();
}
@Test
void behavesAsCollection() {
new Assertion<>(
"Must behave as a no-null collection",
new NoNulls<>(
new ListOf<>(1)
),
new BehavesAsCollection<>(1)
).affirm();
}
@Test
void hasToString() {
new Assertion<>(
"Must have correct NoNulls#toString() and contain value of its elements",
new NoNulls<>(
new ListOf<>(1, 2, 3)
),
new HasToString<>(
new StringContainsInOrder(new IterableOf<>("1", "2", "3"))
)
).affirm();
}
@Test
void emptyWhenCleared() {
final Collection<Integer> col = new NoNulls<>(
new ListOf<>(1, 2, 3)
);
col.clear();
new Assertion<>(
"Must be empty after NoNulls#clear() is called",
col,
new IsEmptyCollection<>()
).affirm();
}
@Test
void whenItemRemoved() {
final Collection<Integer> col = new NoNulls<>(
new ListOf<>(1, 2, 3)
);
col.remove(1);
new Assertion<>(
"Must have item removed from no-null collection",
col,
new IsEqual<>(new ListOf<>(2, 3))
).affirm();
}
@Test
void whenItemAdded() {
final Collection<Integer> col = new NoNulls<>(
new ListOf<>(1, 2)
);
col.add(3);
new Assertion<>(
"Must have item added to no-null collection",
col,
new IsEqual<>(new ListOf<>(1, 2, 3))
).affirm();
}
@Test
void throwsAtAttemptToAddNull() {
new Assertion<>(
"Must throw exception when add NULL",
() -> new NoNulls<>(
new ListOf<>(1, 3)
).add(null),
new Throws<>(
"Item of #add(T) is NULL",
IllegalStateException.class
)
).affirm();
}
@Test
void removesAll() {
final Collection<Integer> col = new NoNulls<>(
new ListOf<>(1, 2, 3)
);
col.removeAll(new ListOf<>(1, null));
new Assertion<>(
"Must have an item removed",
col,
new HasValues<>(2, 3)
).affirm();
}
@Test
void retainsAll() {
final Collection<Integer> col = new NoNulls<>(
new ListOf<>(1, 2, 3)
);
new Assertion<>(
"NoNulls#retainAll(...) must return false for the same elements",
col.retainAll(new ListOf<>(1, 2, 3)),
new IsNot<>(new IsTrue())
).affirm();
}
@Test
void retainsAllWithNulls() {
final Collection<Integer> col = new NoNulls<>(
new ListOf<>(1, 2, 3)
);
new Assertion<>(
"NoNulls#retailAll(..) must return true for different elements",
col.retainAll(new ListOf<>(1, null, 3)),
new IsTrue()
).affirm();
}
@Test
void throwsAtAttemptToRemoveNull() {
new Assertion<>(
"Must throw exception when removing NULL for NoNull collection",
() -> new NoNulls<>(
new ListOf<>(1, 2, 3)
).remove(null),
new Throws<>(
"Item of #remove(T) is NULL",
IllegalStateException.class
)
).affirm();
}
@Test
void hashCodeIsTheSame() {
final Collection<Integer> items = new ListOf<>(1, 2);
new Assertion<>(
"Must have the same hashCode",
new NoNulls<>(items).hashCode(),
new IsEqual<>(
items.hashCode()
)
).affirm();
}
@Test
void shouldBeEmpty() {
final Collection<Integer> col = new NoNulls<>(
new ListOf<>()
);
new Assertion<>(
"Must be empty if created from an empty list",
col.isEmpty(),
new IsTrue()
).affirm();
}
@Test
void addsToEmptyCollection() {
final Collection<Integer> col = new NoNulls<>(
new ListOf<>()
);
col.add(1);
new Assertion<>(
"Must not be empty after an item was added",
col.isEmpty(),
new IsNot<>(new IsTrue())
).affirm();
}
}
|
package org.commcare.android.tests.processing;
import org.commcare.CommCareTestApplication;
import org.commcare.android.CommCareTestRunner;
import org.commcare.android.resource.installers.XFormAndroidInstaller;
import org.commcare.android.util.TestUtils;
import org.commcare.dalvik.BuildConfig;
import org.commcare.models.AndroidClassHasher;
import org.commcare.models.AndroidPrototypeFactory;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xform.util.XFormUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import java.io.IOException;
/**
* Tests for the serializaiton and deserialzation of XForms.
*
* @author ctsims
*/
@Config(application = CommCareTestApplication.class,
constants = BuildConfig.class)
@RunWith(CommCareTestRunner.class)
public class FormStorageTest {
private static final String[] classNames =
{"org.commcare.android.database.app.models.ResourceModelUpdater"
, "org.commcare.android.database.app.models.UserKeyRecord"
, "org.commcare.android.database.app.models.UserKeyRecordV1"
, "org.commcare.android.database.global.models.AndroidSharedKeyRecord"
, "org.commcare.android.database.global.models.ApplicationRecord"
, "org.commcare.android.database.global.models.ApplicationRecordV1"
, "org.commcare.android.database.user.models.ACase"
, "org.commcare.android.database.user.models.ACasePreV6Model$CaseIndexUpdater"
, "org.commcare.android.database.user.models.ACasePreV6Model"
, "org.commcare.android.database.user.models.AUser"
, "org.commcare.android.database.user.models.FormRecord"
, "org.commcare.android.database.user.models.FormRecordV1"
, "org.commcare.android.database.user.models.GeocodeCacheModel"
, "org.commcare.android.database.user.models.SessionStateDescriptor"
, "org.commcare.android.javarosa.AndroidLogEntry"
, "org.commcare.android.javarosa.DeviceReportRecord"
, "org.commcare.android.logging.ForceCloseLogEntry"
, "org.commcare.android.resource.installers.LocaleAndroidInstaller"
, "org.commcare.android.resource.installers.MediaFileAndroidInstaller"
, "org.commcare.android.resource.installers.ProfileAndroidInstaller"
, "org.commcare.android.resource.installers.SuiteAndroidInstaller"
, "org.commcare.android.resource.installers.XFormAndroidInstaller"
, "org.commcare.android.storage.framework.Persisted"
, "org.commcare.cases.instance.CaseDataInstance"
, "org.commcare.cases.ledger.Ledger"
, "org.commcare.cases.model.Case"
, "org.commcare.cases.model.CaseIndex"
, "org.commcare.logging.XPathErrorEntry"
, "org.commcare.resources.model.Resource"
, "org.commcare.resources.model.ResourceLocation"
, "org.commcare.resources.model.installers.BasicInstaller"
, "org.commcare.resources.model.installers.CacheInstaller"
, "org.commcare.resources.model.installers.LocaleFileInstaller"
, "org.commcare.resources.model.installers.LoginImageInstaller"
, "org.commcare.resources.model.installers.MediaInstaller"
, "org.commcare.resources.model.installers.ProfileInstaller"
, "org.commcare.resources.model.installers.SuiteInstaller"
, "org.commcare.resources.model.installers.XFormInstaller"
, "org.commcare.session.SessionFrame"
, "org.commcare.suite.model.Action"
, "org.commcare.suite.model.AssertionSet"
, "org.commcare.suite.model.Callout"
, "org.commcare.suite.model.ComputedDatum"
, "org.commcare.suite.model.Detail"
, "org.commcare.suite.model.DetailField"
, "org.commcare.suite.model.DisplayUnit"
, "org.commcare.suite.model.EntityDatum"
, "org.commcare.suite.model.Entry"
, "org.commcare.suite.model.FormEntry"
, "org.commcare.suite.model.FormIdDatum"
, "org.commcare.suite.model.Menu"
, "org.commcare.suite.model.Profile"
, "org.commcare.suite.model.PropertySetter"
, "org.commcare.suite.model.RemoteQuery"
, "org.commcare.suite.model.SessionDatum"
, "org.commcare.suite.model.StackFrameStep"
, "org.commcare.suite.model.StackOperation"
, "org.commcare.suite.model.Suite"
, "org.commcare.suite.model.SyncEntry"
, "org.commcare.suite.model.SyncPost"
, "org.commcare.suite.model.Text"
, "org.commcare.suite.model.ViewEntry"
, "org.commcare.suite.model.graph.Annotation"
, "org.commcare.suite.model.graph.BubbleSeries"
, "org.commcare.suite.model.graph.Graph"
, "org.commcare.suite.model.graph.XYSeries"
, "org.commcare.xml.DummyGraphParser$DummyGraphDetailTemplate"
, "org.javarosa.core.log.LogEntry"
, "org.javarosa.core.model.DataBinding"
, "org.javarosa.core.model.FormDef"
, "org.javarosa.core.model.GroupDef"
, "org.javarosa.core.model.ItemsetBinding"
, "org.javarosa.core.model.QuestionDef"
, "org.javarosa.core.model.QuestionString"
, "org.javarosa.core.model.SelectChoice"
, "org.javarosa.core.model.SubmissionProfile"
, "org.javarosa.core.model.UploadQuestionExtension"
, "org.javarosa.core.model.User"
, "org.javarosa.core.model.actions.Action"
, "org.javarosa.core.model.actions.ActionController"
, "org.javarosa.core.model.actions.SetValueAction"
, "org.javarosa.core.model.condition.Condition"
, "org.javarosa.core.model.condition.Constraint"
, "org.javarosa.core.model.condition.Recalculate"
, "org.javarosa.core.model.condition.Triggerable"
, "org.javarosa.core.model.data.BooleanData"
, "org.javarosa.core.model.data.DateData"
, "org.javarosa.core.model.data.DateTimeData"
, "org.javarosa.core.model.data.DecimalData"
, "org.javarosa.core.model.data.GeoPointData"
, "org.javarosa.core.model.data.IntegerData"
, "org.javarosa.core.model.data.LongData"
, "org.javarosa.core.model.data.PointerAnswerData"
, "org.javarosa.core.model.data.SelectMultiData"
, "org.javarosa.core.model.data.SelectOneData"
, "org.javarosa.core.model.data.StringData"
, "org.javarosa.core.model.data.TimeData"
, "org.javarosa.core.model.data.UncastData"
, "org.javarosa.core.model.data.helper.Selection"
, "org.javarosa.core.model.instance.DataInstance"
, "org.javarosa.core.model.instance.ExternalDataInstance"
, "org.javarosa.core.model.instance.FormInstance"
, "org.javarosa.core.model.instance.TreeElement"
, "org.javarosa.core.model.instance.TreeReference"
, "org.javarosa.core.model.instance.TreeReferenceLevel"
, "org.javarosa.core.reference.ReferenceDataSource"
, "org.javarosa.core.reference.RootTranslator"
, "org.javarosa.core.services.locale.Localizer"
, "org.javarosa.core.services.locale.ResourceFileDataSource"
, "org.javarosa.core.services.locale.TableLocaleSource"
, "org.javarosa.core.services.properties.Property"
, "org.javarosa.core.services.transport.payload.ByteArrayPayload"
, "org.javarosa.core.services.transport.payload.DataPointerPayload"
, "org.javarosa.core.services.transport.payload.MultiMessagePayload"
, "org.javarosa.core.util.SortedIntSet"
, "org.javarosa.core.util.externalizable.ExtWrapIntEncoding"
, "org.javarosa.core.util.externalizable.ExtWrapIntEncodingSmall"
, "org.javarosa.core.util.externalizable.ExtWrapIntEncodingUniform"
, "org.javarosa.core.util.externalizable.ExtWrapList"
, "org.javarosa.core.util.externalizable.ExtWrapListPoly"
, "org.javarosa.core.util.externalizable.ExtWrapMap"
, "org.javarosa.core.util.externalizable.ExtWrapMapPoly"
, "org.javarosa.core.util.externalizable.ExtWrapNullable"
, "org.javarosa.core.util.externalizable.ExtWrapTagged"
, "org.javarosa.core.util.externalizable.ExternalizableWrapper"
, "org.javarosa.form.api.FormEntryAction"
, "org.javarosa.form.api.FormEntrySession"
, "org.javarosa.model.xform.XPathReference"
, "org.javarosa.xpath.XPathConditional"
, "org.javarosa.xpath.expr.XPathArithExpr"
, "org.javarosa.xpath.expr.XPathBinaryOpExpr"
, "org.javarosa.xpath.expr.XPathBoolExpr"
, "org.javarosa.xpath.expr.XPathCmpExpr"
, "org.javarosa.xpath.expr.XPathEqExpr"
, "org.javarosa.xpath.expr.XPathExpression"
, "org.javarosa.xpath.expr.XPathFilterExpr"
, "org.javarosa.xpath.expr.XPathFuncExpr"
, "org.javarosa.xpath.expr.XPathNumNegExpr"
, "org.javarosa.xpath.expr.XPathNumericLiteral"
, "org.javarosa.xpath.expr.XPathOpExpr"
, "org.javarosa.xpath.expr.XPathPathExpr"
, "org.javarosa.xpath.expr.XPathQName"
, "org.javarosa.xpath.expr.XPathStep"
, "org.javarosa.xpath.expr.XPathStringLiteral"
, "org.javarosa.xpath.expr.XPathUnaryOpExpr"
, "org.javarosa.xpath.expr.XPathUnionExpr"
, "org.javarosa.xpath.expr.XPathVariableReference"
, "org.odk.collect.android.jr.extensions.AndroidXFormExtensions"
, "org.odk.collect.android.jr.extensions.IntentCallout"
, "org.odk.collect.android.jr.extensions.PollSensorAction"};
@Before
public void setup() {
XFormAndroidInstaller.registerAndroidLevelFormParsers();
}
@Test
public void testAllExternalizablesInPrototypeFactory() {
PrototypeFactory pf = TestUtils.getStaticPrototypeFactory();
for (String className : classNames) {
Assert.assertNotNull(pf.getClass(AndroidClassHasher.getInstance().getClassnameHash(className)));
}
}
@Test
public void testRegressionXFormSerializations() {
FormDef def = XFormUtils.getFormFromResource("/forms/placeholder.xml");
try {
ExtUtil.deserialize(ExtUtil.serialize(def), FormDef.class,
TestUtils.getStaticPrototypeFactory());
} catch (IOException | DeserializationException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
/**
* Ensure that a form that has intent callouts can be serialized and deserialized
*/
@Test
public void testCalloutSerializations() {
FormDef def =
XFormUtils.getFormFromResource("/forms/intent_callout_serialization_test.xml");
try {
ExtUtil.deserialize(ExtUtil.serialize(def), FormDef.class, TestUtils.getStaticPrototypeFactory());
} catch (IOException | DeserializationException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
}
|
package twitter4j;
import twitter4j.internal.http.HttpParameter;
import java.util.ArrayList;
import java.util.List;
public final class Query {
private String query = null;
private String lang = null;
private String locale = null;
private long maxId = -1l;
private int rpp = -1;
private int page = -1;
private String since = null;
private long sinceId = -1;
private String geocode = null;
private String until = null;
public Query(){
}
public Query(String query){
this.query = query;
}
/**
* Returns the specified query
* @return query
*/
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public Query query(String query) {
setQuery(query);
return this;
}
/**
* Returns the lang
* @return lang
*/
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public Query lang(String lang) {
setLang(lang);
return this;
}
/**
* Returns the language of the query you are sending (only ja is currently effective). This is intended for language-specific clients and the default should work in the majority of cases.
* @return locale
* @since Twitter4J 2.1.1
*/
public String getLocale() {
return locale;
}
/**
* Specify the language of the query you are sending (only ja is currently effective). This is intended for language-specific clients and the default should work in the majority of cases.
* @param locale the locale
* @since Twitter4J 2.1.1
*/
public void setLocale(String locale) {
this.locale = locale;
}
/**
* Specify the language of the query you are sending (only ja is currently effective). This is intended for language-specific clients and the default should work in the majority of cases.
* @param locale the locale
* @since Twitter4J 2.1.1
* @return the instance
*/
public Query locale(String locale) {
setLocale(locale);
return this;
}
/**
* Returns tweets with status ids less than the given id.
* @return maxId
* @since Twitter4J 2.1.1
*/
public long getMaxId() {
return maxId;
}
/**
* If specified, returns tweets with status ids less than the given id.
* @param maxId maxId
* @since Twitter4J 2.1.1
*/
public void setMaxId(long maxId) {
this.maxId = maxId;
}
/**
* If specified, returns tweets with status ids less than the given id.
* @param maxId maxId
* @return this instance
* @since Twitter4J 2.1.1
*/
public Query maxId(long maxId) {
setMaxId(maxId);
return this;
}
/**
* Returns the number of tweets to return per page, up to a max of 100
* @return
*/
public int getRpp() {
return rpp;
}
/**
* sets the number of tweets to return per page, up to a max of 100
* @param rpp the number of tweets to return per page
*/
public void setRpp(int rpp) {
this.rpp = rpp;
}
/**
* sets the number of tweets to return per page, up to a max of 100
* @param rpp the number of tweets to return per page
* @return the instance
* @since Twitter4J 2.1.0
*/
public Query rpp(int rpp) {
setRpp(rpp);
return this;
}
/**
* Returns the page number (starting at 1) to return, up to a max of roughly 1500 results
* @return the page number (starting at 1) to return
*/
public int getPage() {
return page;
}
/**
* sets the page number (starting at 1) to return, up to a max of roughly 1500 results
* @param page the page number (starting at 1) to return
*/
public void setPage(int page) {
this.page = page;
}
/**
* sets the page number (starting at 1) to return, up to a max of roughly 1500 results
* @param page the page number (starting at 1) to return
* @return the instance
* @since Twitter4J 2.1.0
*/
public Query page(int page) {
setPage(page);
return this;
}
/**
* Returns tweets with since the given date. Date should be formatted as YYYY-MM-DD
* @return since
* @since Twitter4J 2.1.1
*/
public String getSince() {
return since;
}
/**
* If specified, returns tweets with since the given date. Date should be formatted as YYYY-MM-DD
* @param since since
* @since Twitter4J 2.1.1
*/
public void setSince(String since) {
this.since = since;
}
/**
* If specified, returns tweets with since the given date. Date should be formatted as YYYY-MM-DD
* @param since since
* @return since
* @since Twitter4J 2.1.1
*/
public Query since(String since) {
setSince(since);
return this;
}
/**
* returns sinceId
* @return sinceId
*/
public long getSinceId() {
return sinceId;
}
/**
* returns tweets with status ids greater than the given id.
* @param sinceId returns tweets with status ids greater than the given id
*/
public void setSinceId(long sinceId) {
this.sinceId = sinceId;
}
/**
* returns tweets with status ids greater than the given id.
* @param sinceId returns tweets with status ids greater than the given id
* @return the instance
* @since Twitter4J 2.1.0
*/
public Query sinceId(long sinceId) {
setSinceId(sinceId);
return this;
}
/**
* Returns the specified geocode
* @return geocode
*/
public String getGeocode() {
return geocode;
}
public static final String MILES = "mi";
public static final String KILOMETERS = "km";
/**
* returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile
* @param location geo location
* @param radius radius
* @param unit Query.MILES or Query.KILOMETERS
*/
public void setGeoCode(GeoLocation location, double radius
, String unit) {
this.geocode = location.getLatitude() + "," + location.getLongitude() + "," + radius + unit;
}
/**
* returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile
* @param location geo location
* @param radius radius
* @param unit Query.MILES or Query.KILOMETERS
* @return the instance
* @since Twitter4J 2.1.0
*/
public Query geoCode(GeoLocation location, double radius
, String unit) {
setGeoCode(location, radius, unit);
return this;
}
/**
* Returns until
* @return until
* @since Twitter4J 2.1.1
*/
public String getUntil() {
return until;
}
/**
* If specified, returns tweets with generated before the given date. Date should be formatted as YYYY-MM-DD
* @param until until
* @since Twitter4J 2.1.1
*/
public void setUntil(String until) {
this.until = until;
}
/**
* If specified, returns tweets with generated before the given date. Date should be formatted as YYYY-MM-DD
* @param until until
* @return until
* @since Twitter4J 2.1.1
*/
public Query until(String until) {
setUntil(until);
return this;
}
/*package*/ HttpParameter[] asPostParameters(){
ArrayList<HttpParameter> params = new ArrayList<HttpParameter>();
appendParameter("q", query, params);
appendParameter("lang", lang, params);
appendParameter("locale", locale, params);
appendParameter("max_id", maxId, params);
appendParameter("rpp",rpp , params);
appendParameter("page", page, params);
appendParameter("since",since , params);
appendParameter("since_id",sinceId , params);
appendParameter("geocode", geocode, params);
appendParameter("untli", until, params);
HttpParameter[] paramArray = new HttpParameter[params.size()];
return params.toArray(paramArray);
}
private void appendParameter(String name, String value, List<HttpParameter> params) {
if (null != value) {
params.add(new HttpParameter(name, value));
}
}
private void appendParameter(String name, long value, List<HttpParameter> params) {
if (0 <= value) {
params.add(new HttpParameter(name, String.valueOf(value)));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Query query1 = (Query) o;
if (maxId != query1.maxId) return false;
if (page != query1.page) return false;
if (rpp != query1.rpp) return false;
if (sinceId != query1.sinceId) return false;
if (geocode != null ? !geocode.equals(query1.geocode) : query1.geocode != null)
return false;
if (lang != null ? !lang.equals(query1.lang) : query1.lang != null)
return false;
if (locale != null ? !locale.equals(query1.locale) : query1.locale != null)
return false;
if (query != null ? !query.equals(query1.query) : query1.query != null)
return false;
if (since != null ? !since.equals(query1.since) : query1.since != null)
return false;
if (until != null ? !until.equals(query1.until) : query1.until != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = query != null ? query.hashCode() : 0;
result = 31 * result + (lang != null ? lang.hashCode() : 0);
result = 31 * result + (locale != null ? locale.hashCode() : 0);
result = 31 * result + (int) (maxId ^ (maxId >>> 32));
result = 31 * result + rpp;
result = 31 * result + page;
result = 31 * result + (since != null ? since.hashCode() : 0);
result = 31 * result + (int) (sinceId ^ (sinceId >>> 32));
result = 31 * result + (geocode != null ? geocode.hashCode() : 0);
result = 31 * result + (until != null ? until.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Query{" +
"query='" + query + '\'' +
", lang='" + lang + '\'' +
", locale='" + locale + '\'' +
", maxId=" + maxId +
", rpp=" + rpp +
", page=" + page +
", since='" + since + '\'' +
", sinceId=" + sinceId +
", geocode='" + geocode + '\'' +
", until='" + until + '\'' +
'}';
}
}
|
package io.brooklyn.camp.brooklyn;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.io.StringReader;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import brooklyn.entity.Entity;
import brooklyn.location.Location;
import brooklyn.location.basic.LocalhostMachineProvisioningLocation;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
@Test
public class LocationsYamlTest extends AbstractYamlTest {
private static final Logger log = LoggerFactory.getLogger(LocationsYamlTest.class);
@Test
public void testLocationString() throws Exception {
String yaml =
"location: localhost\n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
Entity app = createStartWaitAndLogApplication(new StringReader(yaml));
LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) Iterables.getOnlyElement(app.getLocations());
assertNotNull(loc);
}
@Test
public void testLocationComplexString() throws Exception {
String yaml =
"location: localhost:(name=myname)\n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
Entity app = createStartWaitAndLogApplication(new StringReader(yaml));
LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) Iterables.getOnlyElement(app.getLocations());
assertEquals(loc.getDisplayName(), "myname");
}
@Test
public void testLocationSplitLineWithNoConfig() throws Exception {
String yaml =
"location:\n"+
" localhost\n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
Entity app = createStartWaitAndLogApplication(new StringReader(yaml));
LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) Iterables.getOnlyElement(app.getLocations());
assertNotNull(loc);
}
@Test
public void testMultiLocations() throws Exception {
String yaml =
"locations:\n"+
"- localhost:(name=loc1)\n"+
"- localhost:(name=loc2)\n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
Entity app = createStartWaitAndLogApplication(new StringReader(yaml));
List<Location> locs = ImmutableList.copyOf(app.getLocations());
assertEquals(locs.size(), 2, "locs="+locs);
LocalhostMachineProvisioningLocation loc1 = (LocalhostMachineProvisioningLocation) locs.get(0);
LocalhostMachineProvisioningLocation loc2 = (LocalhostMachineProvisioningLocation) locs.get(1);
assertEquals(loc1.getDisplayName(), "loc1");
assertEquals(loc2.getDisplayName(), "loc2");
}
@Test
public void testLocationConfig() throws Exception {
String yaml =
"location:\n"+
" localhost:\n"+
" displayName: myname\n"+
" myconfkey: myconfval\n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
Entity app = createStartWaitAndLogApplication(new StringReader(yaml));
LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) Iterables.getOnlyElement(app.getLocations());
assertEquals(loc.getDisplayName(), "myname");
assertEquals(loc.getAllConfig(false).get("myconfkey"), "myconfval");
}
@Test
public void testMultiLocationConfig() throws Exception {
String yaml =
"locations:\n"+
"- localhost:\n"+
" displayName: myname1\n"+
" myconfkey: myconfval1\n"+
"- localhost:\n"+
" displayName: myname2\n"+
" myconfkey: myconfval2\n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
Entity app = createStartWaitAndLogApplication(new StringReader(yaml));
List<Location> locs = ImmutableList.copyOf(app.getLocations());
assertEquals(locs.size(), 2, "locs="+locs);
LocalhostMachineProvisioningLocation loc1 = (LocalhostMachineProvisioningLocation) locs.get(0);
LocalhostMachineProvisioningLocation loc2 = (LocalhostMachineProvisioningLocation) locs.get(1);
assertEquals(loc1.getDisplayName(), "myname1");
assertEquals(loc1.getAllConfig(false).get("myconfkey"), "myconfval1");
assertEquals(loc2.getDisplayName(), "myname2");
assertEquals(loc2.getAllConfig(false).get("myconfkey"), "myconfval2");
}
// TODO Fails because PlanInterpretationContext constructor throws NPE on location's value (using ImmutableMap).
@Test(groups="WIP")
public void testLocationBlank() throws Exception {
String yaml =
"location: \n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
Entity app = createStartWaitAndLogApplication(new StringReader(yaml));
assertTrue(app.getLocations().isEmpty(), "locs="+app.getLocations());
}
@Test
public void testInvalidLocationAndLocations() throws Exception {
String yaml =
"location: localhost\n"+
"locations:\n"+
"- localhost\n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
try {
createStartWaitAndLogApplication(new StringReader(yaml));
} catch (IllegalStateException e) {
if (!e.toString().contains("Conflicting 'location' and 'locations'")) throw e;
}
}
@Test
public void testInvalidLocationList() throws Exception {
// should have used "locations:" instead of "location:"
String yaml =
"location:\n"+
"- localhost\n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
try {
createStartWaitAndLogApplication(new StringReader(yaml));
} catch (IllegalStateException e) {
if (!e.toString().contains("must be a string or map")) throw e;
}
}
@Test
public void testRootLocationPassedToChild() throws Exception {
String yaml =
"locations:\n"+
"- localhost:(name=loc1)\n"+
"services:\n"+
"- serviceType: brooklyn.test.entity.TestEntity\n";
Entity app = createStartWaitAndLogApplication(new StringReader(yaml));
Entity child = Iterables.getOnlyElement(app.getChildren());
LocalhostMachineProvisioningLocation loc = (LocalhostMachineProvisioningLocation) Iterables.getOnlyElement(child.getLocations());
assertEquals(loc.getDisplayName(), "loc1");
}
@Override
protected Logger getLogger() {
return log;
}
}
|
package unquietcode.tools.esm;
import org.junit.Test;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
/**
* @author Ben Fagin
* @version 2013-07-15
*/
public class Reflective_T {
@Test
public void testSimpleReflective() {
final AtomicInteger enteringBlue = new AtomicInteger();
final AtomicInteger exitingBlue = new AtomicInteger();
final AtomicInteger enteringGreen = new AtomicInteger();
final AtomicInteger enteringAny = new AtomicInteger();
final AtomicInteger exitingAny = new AtomicInteger();
final AtomicInteger transitionAny = new AtomicInteger();
ReflectiveStateMachine sm = new ReflectiveStateMachine() {
@Override
protected void declareTransitions() {
addTransition(null, "blue");
addTransition("blue", "green");
addTransition("green", null);
}
public void onEnteringBlue(String state) {
assertEquals("blue", state);
enteringBlue.incrementAndGet();
}
public void onBlue() {
enteringBlue.incrementAndGet();
}
public void onExitingBlue() {
exitingBlue.incrementAndGet();
}
public void onGreen() {
enteringGreen.incrementAndGet();
}
public void onEntering() {
enteringAny.incrementAndGet();
}
public void onExiting(String state) {
exitingAny.incrementAndGet();
}
public void onTransition(String from, String to) {
transitionAny.incrementAndGet();
}
};
sm.transition("blue");
sm.transition("green");
sm.transition(null);
assertEquals(2, enteringBlue.get());
assertEquals(1, exitingBlue.get());
assertEquals(1, enteringGreen.get());
assertEquals(3, enteringAny.get());
assertEquals(3, exitingAny.get());
assertEquals(3, transitionAny.get());
}
@Test(expected=UnsupportedOperationException.class)
public void testException() {
ReflectiveStateMachine sm = new ReflectiveStateMachine() {
public void onBlue() {
throw new UnsupportedOperationException("error");
}
};
sm.addTransition(null, "blue");
sm.transition("blue");
}
}
|
package experimentalcode.erich.minigui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.logging.ErrorManager;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import javax.swing.AbstractCellEditor;
import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import de.lmu.ifi.dbs.elki.KDDTask;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.elki.logging.MessageFormatter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ClassParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.FileParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Flag;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Option;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionUtil;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.UnusedParameterException;
import de.lmu.ifi.dbs.elki.utilities.output.FormatUtil;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
import de.lmu.ifi.dbs.elki.utilities.pairs.Triple;
public class MiniGUI extends JPanel {
/**
* Serial version
*/
private static final long serialVersionUID = 1L;
public static final int BIT_INCOMPLETE = 0;
public static final int BIT_INVALID = 1;
public static final int BIT_SYNTAX_ERROR = 2;
public static final int BIT_NO_NAME_BUT_VALUE = 3;
public static final int BIT_OPTIONAL = 4;
public static final int BIT_DEFAULT_VALUE = 5;
private static final String STRING_USE_DEFAULT = "(use default)";
private static final String STRING_OPTIONAL = "(optional)";
static final String[] columns = { "Parameter", "Value" };
private static final String NEWLINE = System.getProperty("line.separator");
protected Logging logger = Logging.getLogger(MiniGUI.class);
protected JTextArea outputArea;
protected ArrayList<Triple<Option<?>, String, BitSet>> parameters;
protected JTable parameterTable;
public MiniGUI() {
super();
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
parameters = new ArrayList<Triple<Option<?>, String, BitSet>>();
parameterTable = new JTable(new ParametersModel(parameters));
parameterTable.setPreferredScrollableViewportSize(new Dimension(600, 200));
parameterTable.setFillsViewportHeight(true);
parameterTable.setDefaultRenderer(String.class, new HighlightingRenderer(parameters));
final AdjustingEditor editor = new AdjustingEditor(parameters);
parameterTable.setDefaultEditor(String.class, editor);
// Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(parameterTable);
// Add the scroll pane to this panel.
add(scrollPane);
// Button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
// button to evaluate settings
JButton setButton = new JButton("Test Settings");
setButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
runSetParameters(false);
}
});
buttonPanel.add(setButton);
// button to evaluate settings
JButton helpButton = new JButton("Request usage help");
helpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
runSetParameters(true);
}
});
buttonPanel.add(helpButton);
// button to launch the task
JButton runButton = new JButton("Run Task");
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
runTask();
}
});
buttonPanel.add(runButton);
add(buttonPanel);
// setup text output area
outputArea = new JTextArea();
// Create the scroll pane and add the table to it.
JScrollPane outputPane = new JScrollPane(outputArea);
outputPane.setPreferredSize(new Dimension(600, 200));
// Add the output pane to the bottom
add(outputPane);
// reconfigure logging
LogHandler.setReceiver(this);
LoggingConfiguration.reconfigureLogging(MiniGUI.class.getPackage().getName(), "logging-minigui.properties");
// refresh Parameters
ArrayList<String> ps = new ArrayList<String>();
ps.add("-algorithm XXX");
doSetParameters(false, ps);
}
protected void runSetParameters(boolean help) {
ArrayList<String> params = serializeParameters();
if(!help) {
outputArea.setText("Testing parameters: " + FormatUtil.format(params, " ") + NEWLINE);
}
else {
outputArea.setText("");
}
List<Pair<Parameterizable, Option<?>>> options = doSetParameters(help, params);
if(help) {
StringBuffer buf = new StringBuffer();
buf.append("Parameters:").append(NEWLINE);
OptionUtil.formatForConsole(buf, 100, " ", options);
// TODO: global parameter constraints
outputArea.append(buf.toString());
}
}
private List<Pair<Parameterizable, Option<?>>> doSetParameters(boolean help, ArrayList<String> params) {
KDDTask<DatabaseObject> task = new KDDTask<DatabaseObject>();
try {
if(params.size() > 0) {
task.setParameters(params);
}
if(!help) {
outputArea.append("Test ok." + NEWLINE);
}
}
catch(ParameterException e) {
outputArea.append("Parameter Error: " + e.getMessage() + NEWLINE);
}
catch(Exception e) {
logger.exception(e);
}
// Collect options
ArrayList<Pair<Parameterizable, Option<?>>> options = task.collectOptions();
// update table:
parameterTable.setEnabled(false);
parameters.clear();
for(Pair<Parameterizable, Option<?>> p : options) {
Option<?> option = p.getSecond();
String value = option.getGivenValue();
if(value == null) {
if(option instanceof Flag) {
value = Flag.NOT_SET;
}
else {
value = "";
}
}
BitSet bits = new BitSet();
if(option instanceof Parameter<?, ?>) {
Parameter<?, ?> par = (Parameter<?, ?>) option;
if(par.isOptional()) {
bits.set(BIT_OPTIONAL);
}
if(par.hasDefaultValue() && par.tookDefaultValue()) {
bits.set(BIT_DEFAULT_VALUE);
}
}
else if(option instanceof Flag) {
bits.set(BIT_OPTIONAL);
}
else {
logger.warning("Option is neither Parameter nor Flag!");
}
if(value == "") {
if(!bits.get(BIT_DEFAULT_VALUE) && !bits.get(BIT_OPTIONAL)) {
bits.set(BIT_INCOMPLETE);
}
}
if(value != "") {
try {
if(!option.isValid(value)) {
bits.set(BIT_INVALID);
}
}
catch(ParameterException e) {
bits.set(BIT_INVALID);
}
}
Triple<Option<?>, String, BitSet> t = new Triple<Option<?>, String, BitSet>(option, value, bits);
parameters.add(t);
}
parameterTable.revalidate();
parameterTable.setEnabled(true);
return options;
}
private ArrayList<String> serializeParameters() {
parameterTable.setEnabled(false);
ArrayList<String> p = new ArrayList<String>(2 * parameters.size());
for(Triple<Option<?>, String, BitSet> t : parameters) {
if(t.getFirst() != null) {
if(t.getFirst() instanceof Parameter<?, ?> && t.getSecond() != null && t.getSecond().length() > 0) {
if(t.getSecond() != STRING_USE_DEFAULT && t.getSecond() != STRING_OPTIONAL) {
p.add("-" + t.getFirst().getOptionID().getName());
p.add(t.getSecond());
}
}
else if(t.getFirst() instanceof Flag) {
if(t.getSecond() == Flag.SET) {
p.add("-" + t.getFirst().getOptionID().getName());
}
}
}
}
parameterTable.setEnabled(true);
return p;
}
protected void runTask() {
ArrayList<String> params = serializeParameters();
outputArea.setText("Running: " + FormatUtil.format(params, " ") + NEWLINE);
KDDTask<DatabaseObject> task = new KDDTask<DatabaseObject>();
try {
task.setParameters(params);
task.run();
}
catch(ParameterException e) {
outputArea.setText(e.getMessage());
}
catch(Exception e) {
logger.exception(e);
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
protected static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("ELKI MiniGUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Create and set up the content pane.
MiniGUI newContentPane = new MiniGUI();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
class ParametersModel extends AbstractTableModel {
/**
* Serial version
*/
private static final long serialVersionUID = 1L;
private ArrayList<Triple<Option<?>, String, BitSet>> parameters;
public ParametersModel(ArrayList<Triple<Option<?>, String, BitSet>> parameters) {
super();
this.parameters = parameters;
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public int getRowCount() {
return parameters.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if(rowIndex < parameters.size()) {
Triple<Option<?>, String, BitSet> p = parameters.get(rowIndex);
if(columnIndex == 0) {
String ret = p.getFirst().getOptionID().getName();
if(ret == null) {
ret = "";
}
return ret;
}
else if(columnIndex == 1) {
String ret = p.getSecond();
if(ret == null) {
ret = "";
}
return ret;
}
return "";
}
else {
return "";
}
}
@Override
public String getColumnName(int column) {
return columns[column];
}
@Override
public Class<?> getColumnClass(@SuppressWarnings("unused") int columnIndex) {
return String.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return (columnIndex == 1) || (rowIndex > parameters.size());
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
if(value instanceof String) {
String s = (String) value;
Triple<Option<?>, String, BitSet> p;
if(rowIndex < parameters.size()) {
p = parameters.get(rowIndex);
}
else {
BitSet flags = new BitSet();
// flags.set(BIT_INCOMPLETE);
p = new Triple<Option<?>, String, BitSet>(null, "", flags);
parameters.add(p);
}
BitSet flags = p.getThird();
if(columnIndex == 0) {
p.setFirst(null); // TODO: allow editing!
}
else if(columnIndex == 1) {
p.setSecond(s);
if(p.getFirst() instanceof Flag) {
if((!Flag.SET.equals(s)) && (!Flag.NOT_SET.equals(s))) {
flags.set(BIT_SYNTAX_ERROR);
}
else {
flags.clear(BIT_SYNTAX_ERROR);
}
}
}
// set flag when we have a key but no value
// flags.set(BIT_NO_NAME_BUT_VALUE, (p.getFirst().length() == 0 &&
// p.getSecond().length() > 0));
// no data at all?
// if(p.getFirst() == null || p.getFirst() == "") {
// if(p.getSecond() == null || p.getSecond() == "") {
// flags.clear();
p.setThird(flags);
runSetParameters(false);
}
else {
logger.warning("Edited value is not a String!");
}
}
}
protected static class HighlightingRenderer extends DefaultTableCellRenderer {
/**
* Serial Version
*/
private static final long serialVersionUID = 1L;
private ArrayList<Triple<Option<?>, String, BitSet>> parameters;
private static final Color COLOR_INCOMPLETE = new Color(0xAFAFFF);
private static final Color COLOR_SYNTAX_ERROR = new Color(0xFFAFAF);
private static final Color COLOR_OPTIONAL = new Color(0xAFFFAF);
private static final Color COLOR_DEFAULT_VALUE = new Color(0xBFBFBF);
public HighlightingRenderer(ArrayList<Triple<Option<?>, String, BitSet>> parameters) {
super();
this.parameters = parameters;
}
@Override
public void setValue(Object value) {
if(value instanceof String) {
setText((value == null) ? "" : (String) value);
}
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(row < parameters.size()) {
Triple<Option<?>, String, BitSet> p = parameters.get(row);
if((p.getThird().get(BIT_INVALID))) {
c.setBackground(COLOR_SYNTAX_ERROR);
}
else if((p.getThird().get(BIT_SYNTAX_ERROR))) {
c.setBackground(COLOR_SYNTAX_ERROR);
}
else if((p.getThird().get(BIT_NO_NAME_BUT_VALUE))) {
c.setBackground(COLOR_SYNTAX_ERROR);
}
else if((p.getThird().get(BIT_INCOMPLETE))) {
c.setBackground(COLOR_INCOMPLETE);
}
else if((p.getThird().get(BIT_OPTIONAL))) {
c.setBackground(COLOR_OPTIONAL);
}
else if((p.getThird().get(BIT_DEFAULT_VALUE))) {
c.setBackground(COLOR_DEFAULT_VALUE);
}
else {
c.setBackground(null);
}
}
return c;
}
}
protected static class DropdownEditor extends DefaultCellEditor {
/**
* Serial Version
*/
private static final long serialVersionUID = 1L;
private ArrayList<Triple<Option<?>, String, BitSet>> parameters;
private final JComboBox comboBox;
public DropdownEditor(ArrayList<Triple<Option<?>, String, BitSet>> parameters, JComboBox comboBox) {
super(comboBox);
this.comboBox = comboBox;
this.parameters = parameters;
}
/*
* (non-Javadoc)
*
* @see
* javax.swing.DefaultCellEditor#getTableCellEditorComponent(javax.swing
* .JTable, java.lang.Object, boolean, int, int)
*/
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
comboBox.removeAllItems();
Object val = table.getValueAt(row, column);
if(val != null) {
comboBox.addItem(val);
comboBox.setSelectedIndex(0);
}
if(row < parameters.size()) {
Triple<Option<?>, String, BitSet> p = parameters.get(row);
if(p.getFirst() instanceof ClassParameter<?>) {
ClassParameter<?> cp = (ClassParameter<?>) p.getFirst();
if(cp.hasDefaultValue()) {
comboBox.addItem(STRING_USE_DEFAULT);
}
else if(cp.isOptional()) {
comboBox.addItem(STRING_OPTIONAL);
}
String prefix = cp.getRestrictionClass().getPackage().getName() + ".";
for(Class<?> impl : cp.getKnownImplementations()) {
String name = impl.getName();
if(name.startsWith(prefix)) {
comboBox.addItem(name.substring(prefix.length()));
}
else {
comboBox.addItem(name);
}
}
}
else if(p.getFirst() instanceof Flag) {
if(!Flag.SET.equals(val)) {
comboBox.addItem(Flag.SET);
}
if(!Flag.NOT_SET.equals(val)) {
comboBox.addItem(Flag.NOT_SET);
}
}
else if(p.getFirst() instanceof Parameter<?, ?>) {
// no completion.
}
}
return c;
}
}
protected static class FileNameEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
/**
* Serial version number
*/
private static final long serialVersionUID = 1L;
final JPanel panel = new JPanel();
final JTextField textfield = new JTextField();
final JButton button = new JButton("...");
final JFileChooser fc = new JFileChooser();
private ArrayList<Triple<Option<?>, String, BitSet>> parameters;
public FileNameEditor(ArrayList<Triple<Option<?>, String, BitSet>> parameters) {
this.parameters = parameters;
button.addActionListener(this);
panel.setLayout(new BorderLayout());
panel.add(textfield, BorderLayout.CENTER);
panel.add(button, BorderLayout.EAST);
}
public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
int returnVal = fc.showOpenDialog(button);
if(returnVal == JFileChooser.APPROVE_OPTION) {
textfield.setText(fc.getSelectedFile().getPath());
}
else {
// Do nothing on cancel.
}
fireEditingStopped();
}
public Object getCellEditorValue() {
return textfield.getText();
}
public Component getTableCellEditorComponent(@SuppressWarnings("unused") JTable table, @SuppressWarnings("unused") Object value, @SuppressWarnings("unused") boolean isSelected, int row, @SuppressWarnings("unused") int column) {
if(row < parameters.size()) {
Triple<Option<?>, String, BitSet> p = parameters.get(row);
if(p.getFirst() instanceof FileParameter) {
FileParameter fp = (FileParameter) p.getFirst();
File f;
try {
f = fp.getValue();
}
catch(UnusedParameterException e) {
f = null;
}
if (f != null) {
String fn = f.getPath();
textfield.setText(fn);
fc.setSelectedFile(f);
} else {
textfield.setText("");
fc.setSelectedFile(null);
}
}
}
return panel;
}
}
protected static class AdjustingEditor extends AbstractCellEditor implements TableCellEditor {
/**
* Serial version
*/
private static final long serialVersionUID = 1L;
private final DropdownEditor dropdownEditor;
private final DefaultCellEditor defaultEditor;
private final FileNameEditor fileNameEditor;
private TableCellEditor activeEditor;
private final ArrayList<Triple<Option<?>, String, BitSet>> parameters;
public AdjustingEditor(ArrayList<Triple<Option<?>, String, BitSet>> parameters) {
final JComboBox combobox = new JComboBox();
combobox.setEditable(true);
this.parameters = parameters;
this.dropdownEditor = new DropdownEditor(parameters, combobox);
this.defaultEditor = new DefaultCellEditor(new JTextField());
this.fileNameEditor = new FileNameEditor(parameters);
}
@Override
public Object getCellEditorValue() {
if(activeEditor == null) {
return null;
}
return activeEditor.getCellEditorValue();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if(row < parameters.size()) {
Triple<Option<?>, String, BitSet> p = parameters.get(row);
if(p.getFirst() instanceof Flag) {
activeEditor = dropdownEditor;
return dropdownEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
}
if(p.getFirst() instanceof ClassParameter) {
activeEditor = dropdownEditor;
return dropdownEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
}
if (p.getFirst() instanceof FileParameter) {
activeEditor = fileNameEditor;
return fileNameEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
activeEditor = defaultEditor;
return defaultEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
public static class LogHandler extends Handler {
private static MiniGUI logReceiver = null;
/**
* Formatter for regular messages (informational records)
*/
private Formatter msgformat = new MessageFormatter();
/**
* Formatter for debugging messages
*/
private Formatter debugformat = new SimpleFormatter();
/**
* Formatter for error messages
*/
private Formatter errformat = new SimpleFormatter();
@Override
public void close() throws SecurityException {
// Do nothing
}
@Override
public void flush() {
// Do nothing
}
@Override
public void publish(LogRecord record) {
// choose an appropriate formatter
final Formatter fmt;
// always format progress messages using the progress formatter.
if(record.getLevel().intValue() >= Level.WARNING.intValue()) {
// format errors using the error formatter
fmt = errformat;
}
else if(record.getLevel().intValue() <= Level.FINE.intValue()) {
// format debug statements using the debug formatter.
fmt = debugformat;
}
else {
// default to the message formatter.
fmt = msgformat;
}
// format
final String m;
try {
m = fmt.format(record);
}
catch(Exception ex) {
reportError(null, ex, ErrorManager.FORMAT_FAILURE);
return;
}
if(logReceiver != null) {
logReceiver.publish(m, record.getLevel());
}
else {
// fall back to standard error.
System.err.println(m);
}
}
protected static void setReceiver(MiniGUI receiver) {
logReceiver = receiver;
}
}
/**
* @param record log message.
* @param level unused for now
*/
protected void publish(String record, Level level) {
outputArea.append(record);
}
}
|
package experimentalcode.erich.newdblayer;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
/**
* Database ID object.
*
* While this currently is just an Integer, it should be avoided to store the
* object IDs in regular integers to reduce problems if this API ever changes
* (for example if someone needs to support {@code long}, it should not require
* changes in too many places!)
*
* In particular, a developer should not make any assumption of these IDs being
* consistent across multiple results/databases.
*
* @author Erich Schubert
*/
// TODO: remove "implements DatabaseObject", getID and setID.
public final class DBID implements DatabaseObject, Comparable<DBID> {
/**
* The actual object ID.
*/
protected int id;
/**
* Constructor from integer id.
*
* @param id integer id.
*/
public DBID(int id) {
super();
this.id = id;
}
/**
* Constructor from integer id.
*
* @param id integer id.
*/
public DBID(Integer id) {
super();
this.id = id;
}
/**
* Return the integer value of the object ID.
*
* @return integer id
*/
public int getIntegerID() {
return this.id;
}
@Override
public String toString() {
return Integer.toString(id);
}
@Override
public int hashCode() {
return id;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof DBID)) {
return false;
}
DBID other = (DBID) obj;
return this.id == other.id;
}
@Override
@Deprecated
public Integer getID() {
return id;
}
@Override
@Deprecated
public void setID(@SuppressWarnings("unused") Integer id) {
throw new UnsupportedOperationException("IDs in new DB layer are static.");
}
@Override
public int compareTo(DBID o) {
return o.id - this.id;
}
}
|
package net.sourceforge.jtds.test;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.GregorianCalendar;
import net.sourceforge.jtds.jdbc.Driver;
import net.sourceforge.jtds.util.Logger;
import junit.framework.TestSuite;
/**
* test getting timestamps from the database.
*/
public class TimestampTest extends DatabaseTestCase {
public TimestampTest(String name) {
super(name);
}
public static void main(String args[]) {
boolean loggerActive = args.length > 0;
Logger.setActive(loggerActive);
if (args.length > 0) {
junit.framework.TestSuite s = new TestSuite();
for (int i = 0; i < args.length; i++) {
s.addTest(new TimestampTest(args[i]));
}
junit.textui.TestRunner.run(s);
} else {
junit.textui.TestRunner.run(TimestampTest.class);
}
// new TimestampTest("test").testOutputParams();
}
public void testBigint0000() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0000 "
+ " (i decimal(28,10) not null, "
+ " s char(10) not null) ");
final int rowsToAdd = 20;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
String sql = "insert into #t0000 values (" + i + ", 'row" + i + "')";
count += stmt.executeUpdate(sql);
}
stmt.close();
assertEquals(count, rowsToAdd);
PreparedStatement pstmt = con.prepareStatement("select i from #t0000 where i = ?");
pstmt.setLong(1, 7);
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getLong(1), 7);
assertTrue("Expected no result set", !rs.next());
pstmt.setLong(1, 8);
rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getLong(1), 8);
assertTrue("Expected no result set", !rs.next());
pstmt.close();
}
public void testTimestamps0001() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0001 "
+ " (t1 datetime not null, "
+ " t2 datetime null, "
+ " t3 smalldatetime not null, "
+ " t4 smalldatetime null)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0001 values (?, '1998-03-09 15:35:06.4', "
+ " ?, '1998-03-09 15:35:00')");
Timestamp t0 = Timestamp.valueOf("1998-03-09 15:35:06.4");
Timestamp t1 = Timestamp.valueOf("1998-03-09 15:35:00");
pstmt.setTimestamp(1, t0);
pstmt.setTimestamp(2, t1);
int count = pstmt.executeUpdate();
assertTrue(count == 1);
pstmt.close();
pstmt = con.prepareStatement("select t1, t2, t3, t4 from #t0001");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(t0, rs.getTimestamp(1));
assertEquals(t0, rs.getTimestamp(2));
assertEquals(t1, rs.getTimestamp(3));
assertEquals(t1, rs.getTimestamp(4));
pstmt.close();
}
public void testTimestamps0004() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0004 "
+ " (mytime datetime not null, "
+ " mytime2 datetime null, "
+ " mytime3 datetime null )");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0004 values ('1964-02-14 10:00:00.0', ?, ?)");
Timestamp t0 = Timestamp.valueOf("1964-02-14 10:00:00.0");
pstmt.setTimestamp(1, t0);
pstmt.setTimestamp(2, t0);
assertEquals(1, pstmt.executeUpdate());
pstmt.setNull(2, java.sql.Types.TIMESTAMP);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
pstmt = con.prepareStatement("select mytime, mytime2, mytime3 from #t0004");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
Timestamp t1, t2, t3;
assertTrue("Expected a result set", rs.next());
t1 = rs.getTimestamp(1);
t2 = rs.getTimestamp(2);
t3 = rs.getTimestamp(3);
assertEquals(t0, t1);
assertEquals(t0, t2);
assertEquals(t0, t3);
assertTrue("Expected a result set", rs.next());
t1 = rs.getTimestamp(1);
t2 = rs.getTimestamp(2);
t3 = rs.getTimestamp(3);
assertEquals(t0, t1);
assertEquals(t0, t2);
assertEquals(null, t3);
pstmt.close();
}
public void testEscape(String sql, String expected) throws Exception {
String tmp = con.nativeSQL(sql);
assertEquals(tmp, expected);
}
public void testEscapes0006() throws Exception {
testEscape("select * from tmp where d={d 1999-09-19}",
"select * from tmp where d='19990919'");
testEscape("select * from tmp where d={d '1999-09-19'}",
"select * from tmp where d='19990919'");
testEscape("select * from tmp where t={t 12:34:00}",
"select * from tmp where t='12:34:00'");
testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00.1234}",
"select * from tmp where ts='19981215 12:34:00.123'");
testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00}",
"select * from tmp where ts='19981215 12:34:00.000'");
testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00.1}",
"select * from tmp where ts='19981215 12:34:00.100'");
testEscape("select * from tmp where ts={ts 1998-12-15 12:34:00}",
"select * from tmp where ts='19981215 12:34:00.000'");
testEscape("select * from tmp where d={d 1999-09-19}",
"select * from tmp where d='19990919'");
testEscape("select * from tmp where a like '\\%%'",
"select * from tmp where a like '\\%%'");
testEscape("select * from tmp where a like 'b%%' {escape 'b'}",
"select * from tmp where a like 'b%%' escape 'b'");
testEscape("select * from tmp where a like 'bbb' {escape 'b'}",
"select * from tmp where a like 'bbb' escape 'b'");
testEscape("select * from tmp where a='{fn user}'",
"select * from tmp where a='{fn user}'");
testEscape("select * from tmp where a={fn user()}",
"select * from tmp where a=user_name()");
}
public void testPreparedStatement0007() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0007 "
+ " (i integer not null, "
+ " s char(10) not null) ");
final int rowsToAdd = 20;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
String sql = "insert into #t0007 values (" + i + ", 'row" + i + "')";
count += stmt.executeUpdate(sql);
}
stmt.close();
assertEquals(count, rowsToAdd);
PreparedStatement pstmt = con.prepareStatement("select s from #t0007 where i = ?");
pstmt.setInt(1, 7);
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString(1).trim(), "row7");
// assertTrue("Expected no result set", !rs.next());
pstmt.setInt(1, 8);
rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString(1).trim(), "row8");
assertTrue("Expected no result set", !rs.next());
pstmt.close();
}
public void testPreparedStatement0008() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0008 "
+ " (i integer not null, "
+ " s char(10) not null) ");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0008 values (?, ?)");
final int rowsToAdd = 8;
final String theString = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
pstmt.close();
ResultSet rs = stmt.executeQuery("select s, i from #t0008");
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertTrue(count == rowsToAdd);
stmt.close();
pstmt.close();
}
public void testPreparedStatement0009() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0009 "
+ " (i integer not null, "
+ " s char(10) not null) ");
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0009 values (?, ?)");
int rowsToAdd = 8;
final String theString = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
pstmt.close();
assertEquals(count, rowsToAdd);
con.rollback();
ResultSet rs = stmt.executeQuery("select s, i from #t0009");
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertEquals(count, 0);
con.commit();
pstmt = con.prepareStatement("insert into #t0009 values (?, ?)");
rowsToAdd = 6;
count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
con.commit();
pstmt.close();
rs = stmt.executeQuery("select s, i from #t0009");
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertEquals(count, rowsToAdd);
con.commit();
stmt.close();
con.setAutoCommit(true);
}
public void testTransactions0010() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0010 "
+ " (i integer not null, "
+ " s char(10) not null) ");
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0010 values (?, ?)");
int rowsToAdd = 8;
final String theString = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
con.rollback();
ResultSet rs = stmt.executeQuery("select s, i from #t0010");
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
}
assertEquals(count, 0);
rowsToAdd = 6;
for (int j = 1; j <= 2; j++) {
count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i + ((j - 1) * rowsToAdd));
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
con.commit();
}
rs = stmt.executeQuery("select s, i from #t0010");
count = 0;
while (rs.next()) {
count++;
int i = rs.getInt(2);
if (i > rowsToAdd) {
i -= rowsToAdd;
}
assertEquals(rs.getString(1).trim().length(), i);
}
assertEquals(count, (2 * rowsToAdd));
stmt.close();
pstmt.close();
con.setAutoCommit(true);
}
public void testEmptyResults0011() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0011 "
+ " (mytime datetime not null, "
+ " mytime2 datetime null )");
ResultSet rs = stmt.executeQuery("select mytime, mytime2 from #t0011");
assertNotNull(rs);
assertTrue("Expected no result set", !rs.next());
rs = stmt.executeQuery("select mytime, mytime2 from #t0011");
assertTrue("Expected no result set", !rs.next());
stmt.close();
}
public void testEmptyResults0012() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0012 "
+ " (mytime datetime not null, "
+ " mytime2 datetime null )");
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"select mytime, mytime2 from #t0012");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected no result", !rs.next());
rs.close();
rs = pstmt.executeQuery();
assertTrue("Expected no result", !rs.next());
pstmt.close();
}
public void testEmptyResults0013() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0013 "
+ " (mytime datetime not null, "
+ " mytime2 datetime null )");
ResultSet rs1 = stmt.executeQuery("select mytime, mytime2 from #t0013");
assertNotNull(rs1);
assertTrue("Expected no result set", !rs1.next());
stmt.close();
PreparedStatement pstmt = con.prepareStatement(
"select mytime, mytime2 from #t0013");
ResultSet rs2 = pstmt.executeQuery();
assertNotNull(rs2);
assertTrue("Expected no result", !rs2.next());
pstmt.close();
}
public void testForBrowse0014() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0014 (i integer not null)");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0014 values (?)");
final int rowsToAdd = 100;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
pstmt.close();
pstmt = con.prepareStatement("select i from #t0014 for browse");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
count = 0;
while (rs.next()) {
rs.getInt("i");
count++;
}
assertEquals(count, rowsToAdd);
pstmt.close();
rs = stmt.executeQuery("select * from #t0014");
assertNotNull(rs);
count = 0;
while (rs.next()) {
rs.getInt("i");
count++;
}
assertEquals(count, rowsToAdd);
rs = stmt.executeQuery("select * from #t0014");
assertNotNull(rs);
count = 0;
while (rs.next() && count < 5) {
rs.getInt("i");
count++;
}
assertTrue(count == 5);
rs = stmt.executeQuery("select * from #t0014");
assertNotNull(rs);
count = 0;
while (rs.next()) {
rs.getInt("i");
count++;
}
assertEquals(count, rowsToAdd);
stmt.close();
}
public void testMultipleResults0015() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0015 "
+ " (i integer not null, "
+ " s char(10) not null) ");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0015 values (?, ?)");
int rowsToAdd = 8;
final String theString = "abcdefghijklmnopqrstuvwxyz";
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(count, rowsToAdd);
pstmt.close();
stmt.execute("select s from #t0015 select i from #t0015");
ResultSet rs = stmt.getResultSet();
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
}
assertEquals(count, rowsToAdd);
assertTrue(stmt.getMoreResults());
rs = stmt.getResultSet();
assertNotNull(rs);
count = 0;
while (rs.next()) {
count++;
}
assertEquals(count, rowsToAdd);
rs = stmt.executeQuery("select i, s from #t0015");
count = 0;
while (rs.next()) {
count++;
}
assertEquals(count, rowsToAdd);
stmt.close();
}
public void testMissingParameter0016() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0016 "
+ " (i integer not null, "
+ " s char(10) not null) ");
final int rowsToAdd = 20;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
String sql = "insert into #t0016 values (" + i + ", 'row" + i + "')";
count += stmt.executeUpdate(sql);
}
stmt.close();
assertEquals(count, rowsToAdd);
PreparedStatement pstmt = con.prepareStatement(
"select s from #t0016 where i=? and s=?");
// see what happens if neither is set
try {
pstmt.executeQuery();
assertTrue("Failed to throw exception", false);
} catch (SQLException e) {
assertTrue("07000".equals(e.getSQLState())
&& (e.getMessage().indexOf('1') >= 0
|| e.getMessage().indexOf('2') >= 0));
}
pstmt.clearParameters();
try {
pstmt.setInt(1, 7);
pstmt.setString(2, "row7");
pstmt.clearParameters();
pstmt.executeQuery();
assertTrue("Failed to throw exception", false);
} catch (SQLException e) {
assertTrue("07000".equals(e.getSQLState())
&& (e.getMessage().indexOf('1') >= 0
|| e.getMessage().indexOf('2') >= 0));
}
pstmt.clearParameters();
try {
pstmt.setInt(1, 7);
pstmt.executeQuery();
assertTrue("Failed to throw exception", false);
} catch (SQLException e) {
assertTrue("07000".equals(e.getSQLState())
&& e.getMessage().indexOf('2') >= 0);
}
pstmt.clearParameters();
try {
pstmt.setString(2, "row7");
pstmt.executeQuery();
assertTrue("Failed to throw exception", false);
} catch (SQLException e) {
assertTrue("07000".equals(e.getSQLState())
&& e.getMessage().indexOf('1') >= 0);
}
pstmt.close();
}
Object[][] getDatatypes() {
return new Object[][] {
/* { "binary(272)",
"0x101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f" +
"101112131415161718191a1b1c1d1e1f",
new byte[] {
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
} },
*/
{"float(6)", "65.4321", new BigDecimal("65.4321")},
{"binary(5)", "0x1213141516", new byte[] { 0x12, 0x13, 0x14, 0x15, 0x16}},
{"varbinary(4)", "0x1718191A", new byte[] { 0x17, 0x18, 0x19, 0x1A}},
{"varchar(8)", "'12345678'", "12345678"},
{"datetime", "'19990815 21:29:59.01'", Timestamp.valueOf("1999-08-15 21:29:59.01")},
{"smalldatetime", "'19990215 20:45'", Timestamp.valueOf("1999-02-15 20:45:00")},
{"float(6)", "65.4321", new Float(65.4321)/* new BigDecimal("65.4321") */},
{"float(14)", "1.123456789", new Double(1.123456789) /*new BigDecimal("1.123456789") */},
{"real", "7654321.0", new Double(7654321.0)},
{"int", "4097", new Integer(4097)},
{"float(6)", "65.4321", new BigDecimal("65.4321")},
{"float(14)", "1.123456789", new BigDecimal("1.123456789")},
{"decimal(10,3)", "1234567.089", new BigDecimal("1234567.089")},
{"numeric(5,4)", "1.2345", new BigDecimal("1.2345")},
{"smallint", "4094", new Short((short) 4094)},
// {"tinyint", "127", new Byte((byte) 127)},
// {"tinyint", "-128", new Byte((byte) -128)},
{"tinyint", "127", new Byte((byte) 127)},
{"tinyint", "128", new Short((short) 128)},
{"money", "19.95", new BigDecimal("19.95")},
{"smallmoney", "9.97", new BigDecimal("9.97")},
{"bit", "1", Boolean.TRUE},
// { "text", "'abcedefg'", "abcdefg" },
/* { "char(1000)",
"'123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'",
"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" },
*/
// { "char(1000)", "'1234567890'", "1234567890" },
// { "image", "0x0a0a0b", new byte[] { 0x0a, 0x0a, 0x0b } },
};
}
public void testOutputParams() throws Exception {
Statement stmt = con.createStatement();
dropProcedure("#jtds_outputTest");
Object[][] datatypes = getDatatypes();
for (int i = 0; i < datatypes.length; i++) {
String valueToAssign;
boolean bImage = datatypes[i][0].equals("image");
if (bImage) {
valueToAssign = "";
} else {
valueToAssign = " = " + datatypes[i][1];
}
String sql = "create procedure #jtds_outputTest "
+ "@a1 " + datatypes[i][0] + " = null out "
+ "as select @a1" + valueToAssign;
stmt.executeUpdate(sql);
for (int pass = 0; (pass < 2 && !bImage) || pass < 1; pass++) {
CallableStatement cstmt = con.prepareCall("{call #jtds_outputTest(?)}");
int jtype = getType(datatypes[i][2]);
if (pass == 1)
cstmt.setObject(1, null, jtype, 10);
if (jtype == java.sql.Types.NUMERIC || jtype == java.sql.Types.DECIMAL) {
cstmt.registerOutParameter(1, jtype, 10);
if (pass == 0) {
cstmt.setObject(1, datatypes[i][2], jtype, 10);
}
} else if (jtype == java.sql.Types.VARCHAR) {
cstmt.registerOutParameter(1, jtype);
if (pass == 0) {
cstmt.setObject(1, datatypes[i][2]);
}
} else {
cstmt.registerOutParameter(1, jtype);
if (pass == 0) {
cstmt.setObject(1, datatypes[i][2]);
}
}
assertEquals(bImage, cstmt.execute());
while (cstmt.getMoreResults() || cstmt.getUpdateCount() != -1) ;
if (jtype == java.sql.Types.VARBINARY) {
assertTrue(compareBytes(cstmt.getBytes(1), (byte[]) datatypes[i][2]) == 0);
} else if (datatypes[i][2] instanceof Number) {
Number n = (Number) cstmt.getObject(1);
if (n != null) {
assertEquals("Failed on " + datatypes[i][0], n.doubleValue(),
((Number) datatypes[i][2]).doubleValue(), 0.001);
} else {
assertEquals("Failed on " + datatypes[i][0], n, datatypes[i][2]);
}
} else {
assertEquals("Failed on " + datatypes[i][0], cstmt.getObject(1), datatypes[i][2]);
}
cstmt.close();
} // for (pass
stmt.executeUpdate(" drop procedure #jtds_outputTest");
} // for (int
stmt.close();
}
public void testStatements0020() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0020a ( " +
" i1 int not null, " +
" s1 char(10) not null " +
") " +
"");
stmt.executeUpdate("create table #t0020b ( " +
" i2a int not null, " +
" i2b int not null, " +
" s2 char(10) not null " +
") " +
"");
stmt.executeUpdate("create table #t0020c ( " +
" i3 int not null, " +
" s3 char(10) not null " +
") " +
"");
int nextB = 1;
int nextC = 1;
for (int i = 1; i < 50; i++) {
stmt.executeUpdate("insert into #t0020a " +
" values(" + i + ", " +
" 'row" + i + "') " +
"");
for (int j = nextB; (nextB % 5) != 0; j++, nextB++) {
stmt.executeUpdate("insert into #t0020b " +
" values(" + i + ", " +
" " + j + ", " +
" 'row" + i + "." + j + "' " +
" )" +
"");
for (int k = nextC; (nextC % 3) != 0; k++, nextC++) {
stmt.executeUpdate("insert into #t0020c " +
" values(" + j + ", " +
" 'row" + i + "." + j + "." + k + "' " +
" )" +
"");
}
}
}
Statement stmtA = con.createStatement();
PreparedStatement stmtB = con.prepareStatement(
"select i2b, s2 from #t0020b where i2a=?");
PreparedStatement stmtC = con.prepareStatement(
"select s3 from #t0020c where i3=?");
ResultSet rs1 = stmtA.executeQuery("select i1 from #t0020a");
assertNotNull(rs1);
while (rs1.next()) {
stmtB.setInt(1, rs1.getInt("i1"));
ResultSet rs2 = stmtB.executeQuery();
assertNotNull(rs2);
while (rs2.next()) {
stmtC.setInt(1, rs2.getInt(1));
ResultSet rs3 = stmtC.executeQuery();
assertNotNull(rs3);
rs3.next();
}
}
stmt.close();
stmtA.close();
stmtB.close();
stmtC.close();
}
public void testBlob0021() throws Exception {
byte smallarray[] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10
};
byte array1[] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
};
String bigtext1 =
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"abcdefghijklmnop" +
"";
Statement stmt = con.createStatement();
dropTable("#t0021");
stmt.executeUpdate(
"create table #t0021 ( " +
" mybinary binary(16) not null, " +
" myimage image not null, " +
" mynullimage image null, " +
" mytext text not null, " +
" mynulltext text null) ");
// Insert a row without nulls via a Statement
PreparedStatement insert = con.prepareStatement(
"insert into #t0021( " +
" mybinary, " +
" myimage, " +
" mynullimage, " +
" mytext, " +
" mynulltext " +
") " +
"values(?, ?, ?, ?, ?) ");
insert.setBytes(1, smallarray);
insert.setBytes(2, array1);
insert.setBytes(3, array1);
insert.setString(4, bigtext1);
insert.setString(5, bigtext1);
int count = insert.executeUpdate();
assertEquals(count, 1);
insert.close();
ResultSet rs = stmt.executeQuery("select * from #t0021");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
byte[] a1 = rs.getBytes("myimage");
byte[] a2 = rs.getBytes("mynullimage");
String s1 = rs.getString("mytext");
String s2 = rs.getString("mynulltext");
assertEquals(0, compareBytes(a1, array1));
assertEquals(0, compareBytes(a2, array1));
assertEquals(bigtext1, s1);
assertEquals(bigtext1, s2);
stmt.close();
}
public void testNestedStatements0022() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0022a "
+ " (i integer not null, "
+ " str char(254) not null) ");
stmt.executeUpdate("create table #t0022b "
+ " (i integer not null, "
+ " t datetime not null) ");
PreparedStatement pStmtA = con.prepareStatement(
"insert into #t0022a values (?, ?)");
PreparedStatement pStmtB = con.prepareStatement(
"insert into #t0022b values (?, getdate())");
final int rowsToAdd = 100;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pStmtA.setInt(1, i);
StringBuffer tmp = new StringBuffer(255);
while (tmp.length() < 240) {
tmp.append("row ").append(i).append(". ");
}
pStmtA.setString(2, tmp.toString());
count += pStmtA.executeUpdate();
pStmtB.setInt(1, i);
pStmtB.executeUpdate();
}
pStmtA.close();
pStmtB.close();
assertEquals(count, rowsToAdd);
Statement stmtA = con.createStatement();
Statement stmtB = con.createStatement();
count = 0;
ResultSet rsA = stmtA.executeQuery("select * from #t0022a");
assertNotNull(rsA);
while (rsA.next()) {
count++;
ResultSet rsB = stmtB.executeQuery(
"select * from #t0022b where i=" + rsA.getInt("i"));
assertNotNull(rsB);
assertTrue("Expected a result set", rsB.next());
assertTrue("Expected no result set", !rsB.next());
}
assertEquals(count, rowsToAdd);
stmt.close();
stmtA.close();
stmtB.close();
}
public void testPrimaryKeyFloat0023() throws Exception {
Double d[] = {
new Double(-1.0),
new Double(1234.543),
new Double(0.0),
new Double(1),
new Double(-2.0),
new Double(0.14),
new Double(0.79),
new Double(1000000.12345),
new Double(-1000000.12345),
new Double(1000000),
new Double(-1000000),
new Double(1.7E+308),
new Double(1.7E-307) // jikes 1.04 has a bug and can't handle 1.7E-308
};
Statement stmt = con.createStatement();
stmt.executeUpdate(""
+ "create table #t0023 "
+ " (pk float not null, "
+ " type char(30) not null, "
+ " b bit, "
+ " str char(30) not null, "
+ " t int identity(1,1), "
+ " primary key (pk, type)) ");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0023 (pk, type, b, str) values(?, 'prepared', 0, ?)");
for (int i = 0; i < d.length; i++) {
pstmt.setDouble(1, d[i].doubleValue());
pstmt.setString(2, (d[i]).toString());
int preparedCount = pstmt.executeUpdate();
assertEquals(preparedCount, 1);
int adhocCount = stmt.executeUpdate(""
+ "insert into #t0023 "
+ " (pk, type, b, str) "
+ " values("
+ " " + d[i] + ", "
+ " 'adhoc', "
+ " 1, "
+ " '" + d[i] + "') ");
assertEquals(adhocCount, 1);
}
int count = 0;
ResultSet rs = stmt.executeQuery("select * from #t0023 where type='prepared' order by t");
assertNotNull(rs);
while (rs.next()) {
assertEquals(d[count].toString(), "" + rs.getDouble("pk"));
count++;
}
assertEquals(count, d.length);
count = 0;
rs = stmt.executeQuery("select * from #t0023 where type='adhoc' order by t");
while (rs.next()) {
assertEquals(d[count].toString(), "" + rs.getDouble("pk"));
count++;
}
assertEquals(count, d.length);
stmt.close();
pstmt.close();
}
public void testPrimaryKeyReal0024() throws Exception {
Float d[] = {
new Float(-1.0),
new Float(1234.543),
new Float(0.0),
new Float(1),
new Float(-2.0),
new Float(0.14),
new Float(0.79),
new Float(1000000.12345),
new Float(-1000000.12345),
new Float(1000000),
new Float(-1000000),
new Float(3.4E+38),
new Float(3.4E-38)
};
Statement stmt = con.createStatement();
stmt.executeUpdate(""
+ "create table #t0024 "
+ " (pk real not null, "
+ " type char(30) not null, "
+ " b bit, "
+ " str char(30) not null, "
+ " t int identity(1,1), "
+ " primary key (pk, type)) ");
PreparedStatement pstmt = con.prepareStatement(
"insert into #t0024 (pk, type, b, str) values(?, 'prepared', 0, ?)");
for (int i=0; i < d.length; i++) {
pstmt.setFloat(1, d[i].floatValue());
pstmt.setString(2, (d[i]).toString());
int preparedCount = pstmt.executeUpdate();
assertTrue(preparedCount == 1);
int adhocCount = stmt.executeUpdate(""
+ "insert into #t0024 "
+ " (pk, type, b, str) "
+ " values("
+ " " + d[i] + ", "
+ " 'adhoc', "
+ " 1, "
+ " '" + d[i] + "') ");
assertEquals(adhocCount, 1);
}
int count = 0;
ResultSet rs = stmt.executeQuery("select * from #t0024 where type='prepared' order by t");
assertNotNull(rs);
while (rs.next()) {
String s1 = d[count].toString().trim();
String s2 = ("" + rs.getFloat("pk")).trim();
assertTrue(s1.equalsIgnoreCase(s2));
count++;
}
assertEquals(count, d.length);
count = 0;
rs = stmt.executeQuery("select * from #t0024 where type='adhoc' order by t");
while (rs.next()) {
String s1 = d[count].toString().trim();
String s2 = ("" + rs.getFloat("pk")).trim();
assertTrue(s1.equalsIgnoreCase(s2));
count++;
}
assertEquals(count, d.length);
stmt.close();
pstmt.close();
}
public void testGetBoolean0025() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0025 " +
" (i integer, " +
" b bit, " +
" s char(5), " +
" f float) ");
// @todo Check which CHAR/VARCHAR values should be true and which should be false.
assertTrue(stmt.executeUpdate("insert into #t0025 values(0, 0, 'false', 0.0)") == 1);
assertTrue(stmt.executeUpdate("insert into #t0025 values(0, 0, '0', 0.0)") == 1);
assertTrue(stmt.executeUpdate("insert into #t0025 values(1, 1, 'true', 7.0)") == 1);
assertTrue(stmt.executeUpdate("insert into #t0025 values(2, 1, '1', -5.0)") == 1);
ResultSet rs = stmt.executeQuery("select * from #t0025 order by i");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertTrue(!rs.getBoolean("i"));
assertTrue(!rs.getBoolean("b"));
assertTrue(!rs.getBoolean("s"));
assertTrue(!rs.getBoolean("f"));
assertTrue("Expected a result set", rs.next());
assertTrue(!rs.getBoolean("i"));
assertTrue(!rs.getBoolean("b"));
assertTrue(!rs.getBoolean("s"));
assertTrue(!rs.getBoolean("f"));
assertTrue("Expected a result set", rs.next());
assertTrue(rs.getBoolean("i"));
assertTrue(rs.getBoolean("b"));
assertTrue(rs.getBoolean("s"));
assertTrue(rs.getBoolean("f"));
assertTrue("Expected a result set", rs.next());
assertTrue(rs.getBoolean("i"));
assertTrue(rs.getBoolean("b"));
assertTrue(rs.getBoolean("s"));
assertTrue(rs.getBoolean("f"));
assertTrue("Expected no result set", !rs.next());
stmt.close();
}
/**
* <b>SAfe</b> Tests whether cursor-based statements still work ok when
* nested. Similar to <code>testNestedStatements0022</code>, which tests
* the same with plain (non-cursor-based) statements (and unfortunately
* fails).
*
* @throws Exception if an Exception occurs (very relevant, huh?)
*/
public void testNestedStatements0026() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0026a "
+ " (i integer not null, "
+ " str char(254) not null) ");
stmt.executeUpdate("create table #t0026b "
+ " (i integer not null, "
+ " t datetime not null) ");
stmt.close();
PreparedStatement pstmtA = con.prepareStatement(
"insert into #t0026a values (?, ?)");
PreparedStatement pstmtB = con.prepareStatement(
"insert into #t0026b values (?, getdate())");
final int rowsToAdd = 100;
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmtA.setInt(1, i);
StringBuffer tmp = new StringBuffer(255);
while (tmp.length() < 240) {
tmp.append("row ").append(i).append(". ");
}
pstmtA.setString(2, tmp.toString());
count += pstmtA.executeUpdate();
pstmtB.setInt(1, i);
pstmtB.executeUpdate();
}
assertEquals(count, rowsToAdd);
pstmtA.close();
pstmtB.close();
Statement stmtA = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Statement stmtB = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
count = 0;
ResultSet rsA = stmtA.executeQuery("select * from #t0026a");
assertNotNull(rsA);
while (rsA.next()) {
count++;
ResultSet rsB = stmtB.executeQuery(
"select * from #t0026b where i=" + rsA.getInt("i"));
assertNotNull(rsB);
assertTrue("Expected a result set", rsB.next());
assertTrue("Expected no result set", !rsB.next());
rsB.close();
}
assertEquals(count, rowsToAdd);
stmtA.close();
stmtB.close();
}
public void testErrors0036() throws Exception {
Statement stmt = con.createStatement();
final int numberToTest = 5;
for (int i = 0; i < numberToTest; i++) {
String table = "#t0036_no_create_" + i;
try {
stmt.executeUpdate("drop table " + table);
fail("Did not expect to reach here");
} catch (SQLException e) {
assertEquals("42S02", e.getSQLState());
}
}
stmt.close();
}
public void testTimestamps0037() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(
"select " +
" convert(smalldatetime, '1999-01-02') a, " +
" convert(smalldatetime, null) b, " +
" convert(datetime, '1999-01-02') c, " +
" convert(datetime, null) d ");
assertNotNull(rs);
assertTrue("Expected a result", rs.next());
assertNotNull(rs.getDate("a"));
assertNull(rs.getDate("b"));
assertNotNull(rs.getDate("c"));
assertNull(rs.getDate("d"));
assertNotNull(rs.getTime("a"));
assertNull(rs.getTime("b"));
assertNotNull(rs.getTime("c"));
assertNull(rs.getTime("d"));
assertNotNull(rs.getTimestamp("a"));
assertNull(rs.getTimestamp("b"));
assertNotNull(rs.getTimestamp("c"));
assertNull(rs.getTimestamp("d"));
assertTrue("Expected no more results", !rs.next());
stmt.close();
}
public void testConnection0038() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0038 ("
+ " keyField char(255) not null, "
+ " descField varchar(255) not null) ");
int count = stmt.executeUpdate("insert into #t0038 values ('value', 'test')");
assertEquals(count, 1);
con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("update #t0038 set descField=descField where keyField=?");
ps.setString(1, "value");
ps.executeUpdate();
ps.close();
con.commit();
// conn.rollback();
ResultSet resultSet = stmt.executeQuery(
"select descField from #t0038 where keyField='value'");
assertTrue(resultSet.next());
stmt.close();
}
public void testConnection0039() throws Exception {
for (int i = 0; i < 10; i++) {
Connection conn = getConnection();
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("select 5");
assertNotNull(resultSet);
resultSet.close();
statement.close();
conn.close();
}
}
public void testPreparedStatement0040() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0040 ("
+ " c255 char(255) not null, "
+ " v255 varchar(255) not null) ");
PreparedStatement pstmt = con.prepareStatement("insert into #t0040 values (?, ?)");
String along = getLongString('a');
String blong = getLongString('b');
pstmt.setString(1, along);
pstmt.setString(2, along);
int count = pstmt.executeUpdate();
assertEquals(count, 1);
pstmt.close();
count = stmt.executeUpdate(""
+ "insert into #t0040 values ( "
+ "'" + blong + "', "
+ "'" + blong + "')");
assertEquals(count, 1);
pstmt = con.prepareStatement("select c255, v255 from #t0040 order by c255");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString("c255"), along);
assertEquals(rs.getString("v255"), along);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString("c255"), blong);
assertEquals(rs.getString("v255"), blong);
assertTrue("Expected no result set", !rs.next());
pstmt.close();
rs = stmt.executeQuery("select c255, v255 from #t0040 order by c255");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString("c255"), along);
assertEquals(rs.getString("v255"), along);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getString("c255"), blong);
assertEquals(rs.getString("v255"), blong);
assertTrue("Expected no result set", !rs.next());
stmt.close();
}
public void testPreparedStatement0041() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0041 "
+ " (i integer not null, "
+ " s text not null) ");
PreparedStatement pstmt = con.prepareStatement("insert into #t0041 values (?, ?)");
// TODO: Check values
final int rowsToAdd = 400;
final String theString = getLongString(400);
int count = 0;
for (int i = 1; i <= rowsToAdd; i++) {
pstmt.setInt(1, i);
pstmt.setString(2, theString.substring(0, i));
count += pstmt.executeUpdate();
}
assertEquals(rowsToAdd, count);
pstmt.close();
ResultSet rs = stmt.executeQuery("select s, i from #t0041");
assertNotNull(rs);
count = 0;
while (rs.next()) {
rs.getString("s");
count++;
}
assertEquals(rowsToAdd, count);
stmt.close();
}
public void testPreparedStatement0042() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0042 (s char(5) null, i integer null, j integer not null)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #t0042 (s, i, j) values (?, ?, ?)");
pstmt.setString(1, "hello");
pstmt.setNull(2, java.sql.Types.INTEGER);
pstmt.setInt(3, 1);
int count = pstmt.executeUpdate();
assertEquals(count, 1);
pstmt.setInt(2, 42);
pstmt.setInt(3, 2);
count = pstmt.executeUpdate();
assertEquals(count, 1);
pstmt.close();
pstmt = con.prepareStatement("select i from #t0042 order by j");
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
rs.getInt(1);
assertTrue(rs.wasNull());
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getInt(1), 42);
assertTrue(!rs.wasNull());
assertTrue("Expected no result set", !rs.next());
pstmt.close();
}
public void testResultSet0043() throws Exception {
Statement stmt = con.createStatement();
try {
ResultSet rs = stmt.executeQuery("select 1");
assertNotNull(rs);
rs.getInt(1);
fail("Did not expect to reach here");
} catch (SQLException e) {
assertEquals("24000", e.getSQLState());
}
stmt.close();
}
public void testResultSet0044() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select 1");
assertNotNull(rs);
rs.close();
try {
rs.next();
fail("Was expecting ResultSet.next() to throw an exception if the ResultSet was closed");
} catch (SQLException e) {
assertEquals("HY010", e.getSQLState());
}
stmt.close();
}
public void testResultSet0045() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select 1");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
rs.getInt(1);
assertTrue("Expected no result set", !rs.next());
try {
rs.getInt(1);
fail("Did not expect to reach here");
} catch (java.sql.SQLException e) {
assertEquals("24000", e.getSQLState());
}
stmt.close();
}
public void testMetaData0046() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate("create table #t0046 ("
+ " i integer identity, "
+ " a integer not null, "
+ " b integer null ) ");
int count = stmt.executeUpdate("insert into #t0046 (a, b) values (-2, -3)");
assertEquals(count, 1);
ResultSet rs = stmt.executeQuery("select i, a, b, 17 c from #t0046");
assertNotNull(rs);
ResultSetMetaData md = rs.getMetaData();
assertNotNull(md);
assertTrue(md.isAutoIncrement(1));
assertTrue(!md.isAutoIncrement(2));
assertTrue(!md.isAutoIncrement(3));
assertTrue(!md.isAutoIncrement(4));
assertTrue(md.isReadOnly(1));
assertTrue(!md.isReadOnly(2));
assertTrue(!md.isReadOnly(3));
// assertTrue(md.isReadOnly(4)); SQL 6.5 does not report this one correctly!
assertEquals(md.isNullable(1),java.sql.ResultSetMetaData.columnNoNulls);
assertEquals(md.isNullable(2),java.sql.ResultSetMetaData.columnNoNulls);
assertEquals(md.isNullable(3),java.sql.ResultSetMetaData.columnNullable);
// assert(md.isNullable(4) == java.sql.ResultSetMetaData.columnNoNulls);
rs.close();
stmt.close();
}
public void testTimestamps0047() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate(
"create table #t0047 " +
"( " +
" t1 datetime not null, " +
" t2 datetime null, " +
" t3 smalldatetime not null, " +
" t4 smalldatetime null " +
")");
String query =
"insert into #t0047 (t1, t2, t3, t4) " +
" values('2000-01-02 19:35:01.333', " +
" '2000-01-02 19:35:01.333', " +
" '2000-01-02 19:35:01.333', " +
" '2000-01-02 19:35:01.333' " +
")";
int count = stmt.executeUpdate(query);
assertEquals(count, 1);
ResultSet rs = stmt.executeQuery("select t1, t2, t3, t4 from #t0047");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
java.sql.Timestamp t1 = rs.getTimestamp("t1");
java.sql.Timestamp t2 = rs.getTimestamp("t2");
java.sql.Timestamp t3 = rs.getTimestamp("t3");
java.sql.Timestamp t4 = rs.getTimestamp("t4");
java.sql.Timestamp r1 = Timestamp.valueOf("2000-01-02 19:35:01.333");
java.sql.Timestamp r2 = Timestamp.valueOf("2000-01-02 19:35:00");
assertEquals(r1, t1);
assertEquals(r1, t2);
assertEquals(r2, t3);
assertEquals(r2, t4);
stmt.close();
}
public void testTimestamps0048() throws Exception {
Statement stmt = con.createStatement();
stmt.executeUpdate(
"create table #t0048 " +
"( " +
" t1 datetime not null, " +
" t2 datetime null, " +
" t3 smalldatetime not null, " +
" t4 smalldatetime null " +
")");
java.sql.Timestamp r1;
java.sql.Timestamp r2;
r1 = Timestamp.valueOf("2000-01-02 19:35:01");
r2 = Timestamp.valueOf("2000-01-02 19:35:00");
java.sql.PreparedStatement pstmt = con.prepareStatement(
"insert into #t0048 (t1, t2, t3, t4) values(?, ?, ?, ?)");
pstmt.setTimestamp(1, r1);
pstmt.setTimestamp(2, r1);
pstmt.setTimestamp(3, r1);
pstmt.setTimestamp(4, r1);
int count = pstmt.executeUpdate();
assertEquals(count, 1);
pstmt.close();
ResultSet rs = stmt.executeQuery("select t1, t2, t3, t4 from #t0048");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
java.sql.Timestamp t1 = rs.getTimestamp("t1");
java.sql.Timestamp t2 = rs.getTimestamp("t2");
java.sql.Timestamp t3 = rs.getTimestamp("t3");
java.sql.Timestamp t4 = rs.getTimestamp("t4");
assertEquals(r1, t1);
assertEquals(r1, t2);
assertEquals(r2, t3);
assertEquals(r2, t4);
stmt.close();
}
public void testDecimalConversion0058() throws Exception {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select convert(DECIMAL(4,0), 0)");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getInt(1), 0);
assertTrue("Expected no result set", !rs.next());
rs = stmt.executeQuery("select convert(DECIMAL(4,0), 1)");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getInt(1), 1);
assertTrue("Expected no result set", !rs.next());
rs = stmt.executeQuery("select convert(DECIMAL(4,0), -1)");
assertNotNull(rs);
assertTrue("Expected a result set", rs.next());
assertEquals(rs.getInt(1), -1);
assertTrue("Expected no result set", !rs.next());
stmt.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding1() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.990
// Receive: 01/01/98 23:59:59.990
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 990);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 990);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr1 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr1 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr1");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding2() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.991
// Receive: 01/01/98 23:59:59.990
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 991);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 990);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr2 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr2 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr2");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding3() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.992
// Receive: 01/01/98 23:59:59.993
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 992);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 993);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr3 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr3 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr3");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding4() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.993
// Receive: 01/01/98 23:59:59.993
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 993);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 993);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr4 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr4 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr4");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding5() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.994
// Receive: 01/01/98 23:59:59.993
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 994);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 993);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr5 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr5 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr5");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding6() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.995
// Receive: 01/01/98 23:59:59.997
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 995);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 997);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr6 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr6 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr6");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding7() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.996
// Receive: 01/01/98 23:59:59.997
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 996);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 997);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr7 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr7 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr7");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding8() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.997
// Receive: 01/01/98 23:59:59.997
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 997);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 997);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr8 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr8 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr8");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding9() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.998
// Receive: 01/01/98 23:59:59.997
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 998);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 1);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 23);
receiveValue.set(Calendar.MINUTE, 59);
receiveValue.set(Calendar.SECOND, 59);
receiveValue.set(Calendar.MILLISECOND, 997);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr9 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr9 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr9");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [994916] datetime decoding in TdsData.java
*/
public void testDatetimeRounding10() throws Exception {
// Per the SQL Server documentation
// Send: 01/01/98 23:59:59.999
// Receive: 01/02/98 00:00:00.000
Calendar sendValue = Calendar.getInstance();
Calendar receiveValue = Calendar.getInstance();
sendValue.set(Calendar.MONTH, Calendar.JANUARY);
sendValue.set(Calendar.DAY_OF_MONTH, 1);
sendValue.set(Calendar.YEAR, 1998);
sendValue.set(Calendar.HOUR_OF_DAY, 23);
sendValue.set(Calendar.MINUTE, 59);
sendValue.set(Calendar.SECOND, 59);
sendValue.set(Calendar.MILLISECOND, 999);
receiveValue.set(Calendar.MONTH, Calendar.JANUARY);
receiveValue.set(Calendar.DAY_OF_MONTH, 2);
receiveValue.set(Calendar.YEAR, 1998);
receiveValue.set(Calendar.HOUR_OF_DAY, 0);
receiveValue.set(Calendar.MINUTE, 0);
receiveValue.set(Calendar.SECOND, 0);
receiveValue.set(Calendar.MILLISECOND, 0);
Statement stmt = con.createStatement();
stmt.execute("create table #dtr10 (data datetime)");
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #dtr10 (data) values (?)");
pstmt.setTimestamp(1, new Timestamp(sendValue.getTime().getTime()));
assertEquals(pstmt.executeUpdate(), 1);
pstmt.close();
pstmt = con.prepareStatement("select data from #dtr10");
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertEquals(receiveValue.getTime().getTime(), getTimeInMs(rs));
assertTrue(!rs.next());
pstmt.close();
rs.close();
}
/**
* Test for bug [1036059] getTimestamp with Calendar applies tzone offset
* wrong way.
*/
public void testTimestampTimeZone() throws SQLException {
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE #testTimestampTimeZone ("
+ "ref INT NOT NULL, "
+ "tstamp DATETIME NOT NULL)");
stmt.close();
Calendar calNY = Calendar.getInstance
(TimeZone.getTimeZone("America/New_York"));
Timestamp tsStart = new Timestamp(System.currentTimeMillis());
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO #testTimestampTimeZone (ref, tstamp) VALUES (?, ?)");
pstmt.setInt(1, 0);
pstmt.setTimestamp(2, tsStart, calNY);
assertEquals(1, pstmt.executeUpdate());
pstmt.close();
pstmt = con.prepareStatement(
"SELECT * FROM #testTimestampTimeZone WHERE ref = ?");
pstmt.setInt(1, 0);
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
Timestamp ts = rs.getTimestamp("tstamp", calNY);
// The difference should be less than 3 milliseconds (i.e. 1 or 2)
assertTrue(Math.abs(tsStart.getTime()-ts.getTime()) < 3);
rs.close();
pstmt.close();
}
/**
* Test for bug [1040475] Possible bug when converting to and from
* datetime.
* <p>
* jTDS seems to accept dates outside the range accepted by SQL
* Server (i.e. 1753-9999).
*/
public void testTimestampRange() throws SQLException {
Statement stmt = con.createStatement();
stmt.executeUpdate(
"CREATE TABLE #testTimestampRange (id INT, d DATETIME)");
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO #testTimestampRange VALUES (?, ?)");
pstmt.setInt(1, 1);
try {
pstmt.setDate(2, Date.valueOf("0012-03-03")); // This should fail
pstmt.executeUpdate();
fail("Expecting an exception to be thrown. Date out of range.");
} catch (SQLException ex) {
assertEquals("22003", ex.getSQLState());
}
pstmt.close();
ResultSet rs = stmt.executeQuery("SELECT * FROM #testTimestampRange");
assertFalse("Row was inserted even though date was out of range.", rs.next());
rs.close();
stmt.close();
}
/**
* Test that <code>java.sql.Date</code> objects are inserted and retrieved
* correctly (ie no time component).
*/
public void testWriteDate() throws SQLException {
Statement stmt = con.createStatement();
stmt.executeUpdate(
"CREATE TABLE #testWriteDate (d DATETIME)");
stmt.close();
long time = System.currentTimeMillis();
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO #testWriteDate VALUES (?)");
pstmt.setDate(1, new Date(time));
pstmt.executeUpdate();
pstmt.close();
pstmt = con.prepareStatement("SELECT * FROM #testWriteDate WHERE d=?");
pstmt.setDate(1, new Date(time + 10));
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
assertTrue(time - rs.getDate(1).getTime() < 24 * 60 * 60 * 1000);
Calendar c1 = new GregorianCalendar(), c2 = new GregorianCalendar();
c1.setTime(rs.getTimestamp(1));
c2.setTime(new Timestamp(time));
assertEquals(c2.get(Calendar.YEAR), c1.get(Calendar.YEAR));
assertEquals(c2.get(Calendar.MONTH), c1.get(Calendar.MONTH));
assertEquals(c2.get(Calendar.DAY_OF_MONTH), c1.get(Calendar.DAY_OF_MONTH));
assertEquals(0, c1.get(Calendar.HOUR));
assertEquals(0, c1.get(Calendar.MINUTE));
assertEquals(0, c1.get(Calendar.SECOND));
assertEquals(0, c1.get(Calendar.MILLISECOND));
rs.close();
pstmt.close();
stmt = con.createStatement();
rs = stmt.executeQuery("select datepart(hour, d), datepart(minute, d),"
+ " datepart(second, d), datepart(millisecond, d)"
+ " from #testWriteDate");
assertTrue(rs.next());
assertEquals(0, rs.getInt(1));
assertEquals(0, rs.getInt(2));
assertEquals(0, rs.getInt(3));
assertEquals(0, rs.getInt(4));
assertFalse(rs.next());
rs.close();
stmt.close();
}
/**
* Test for bug [1226210] {fn dayofweek()} depends on the language.
*/
public void testDayOfWeek() throws Exception {
PreparedStatement pstmt =
con.prepareStatement("SELECT {fn dayofweek({fn curdate()})}");
// Execute and retrieve the day of week with the default @@DATEFIRST
ResultSet rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue(rs.next());
int day = rs.getInt(1);
// Set a new (very unlikely) value for @@DATEFIRST (Thursday)
Statement stmt = con.createStatement();
assertEquals(0, stmt.executeUpdate("SET DATEFIRST 4"));
stmt.close();
// Now re-execute and compare the two values
rs = pstmt.executeQuery();
assertNotNull(rs);
assertTrue(rs.next());
assertEquals(day, rs.getInt(1));
pstmt.close();
}
public void testGetString() throws SQLException {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select getdate()");
assertTrue(rs.next());
String stringValue = rs.getString(1);
String timestampValue = rs.getTimestamp(1).toString();
assertEquals(stringValue, timestampValue);
rs.close();
stmt.close();
}
/**
* Test for bug [1234531] Dates before 01/01/1900 broken due to DateTime
* value markers.
*/
public void test1899Date() throws Exception {
// Per the SQL Server documentation
// Send: 12/31/1899 23:59:59.990
// Receive: 12/31/1899 23:59:59.990
Calendar originalValue = Calendar.getInstance();
originalValue.set(Calendar.MONTH, Calendar.DECEMBER);
originalValue.set(Calendar.DAY_OF_MONTH, 31);
originalValue.set(Calendar.YEAR, 1899);
originalValue.set(Calendar.HOUR_OF_DAY, 23);
originalValue.set(Calendar.MINUTE, 59);
originalValue.set(Calendar.SECOND, 59);
originalValue.set(Calendar.MILLISECOND, 990);
PreparedStatement pstmt = con.prepareStatement("select ?");
pstmt.setTimestamp(1, new Timestamp(originalValue.getTime().getTime()));
ResultSet rs = pstmt.executeQuery();
assertTrue(rs.next());
final long expectedTime = originalValue.getTime().getTime();
final long actualTime = getTimeInMs(rs);
assertEquals(expectedTime, actualTime);
assertFalse(rs.next());
rs.close();
pstmt.close();
}
/**
* Java 1.3 Timestamp.getDate() does not add the nano seconds to
* the millisecond value returned. This causes the timestamp tests
* to fail. If running under java 1.3 we add the nanos ourselves.
*
* @param rs the result set returning the Timstamp value in column 1
* @return the millisecond date value as a <code>long</code>.
*/
public long getTimeInMs(ResultSet rs)
throws SQLException {
Timestamp value = rs.getTimestamp(1);
long ms = value.getTime();
if (!Driver.JDBC3) {
// Not Running under 1.4 so need to add milliseconds
ms += ((java.sql.Timestamp)value).getNanos() / 1000000;
}
return ms;
}
/**
* Test for bug [2508201], date field is changed by 3 milliseconds.
*
* Note: This test will fail for some server types due to "DATE" and "TIME"
* data types not being available.
*/
public void testDateTimeDegeneration() throws Exception {
Timestamp ts1 = Timestamp.valueOf("1970-01-01 00:00:00.000");
String[] types = new String[] {"datetime","date","time"};
for (int t = 0; t < types.length; t++) {
String type = types[t];
// create table and insert initial value
Statement stmt = con.createStatement();
stmt.execute("create table #t_" + type + " (id int,data " + type + ")");
stmt.execute("insert into #t_" + type + " values (0,'" + ts1.toString() + "')");
PreparedStatement ps1 = con.prepareStatement("update #t_" + type + " set data=? where id=0");
PreparedStatement ps2 = con.prepareStatement("select data from #t_" + type);
// read previous value
ResultSet rs = ps2.executeQuery();
rs.next();
Timestamp ts2 = rs.getTimestamp(1);
// compare current value to initial value
assertEquals(type + " value degenerated: ", ts1.toString(), ts2.toString());
rs.close();
// update DB with current value
ps1.setTimestamp(1, ts2);
ps1.executeUpdate();
ps1.close();
ps2.close();
stmt.close();
}
}
}
|
package io.vertx.ext.web.client;
import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder;
import io.vertx.core.*;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.dns.AddressResolverOptions;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.http.*;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.ProxyOptions;
import io.vertx.core.net.ProxyType;
import io.vertx.core.streams.ReadStream;
import io.vertx.core.streams.WriteStream;
import io.vertx.ext.web.client.jackson.WineAndCheese;
import io.vertx.ext.web.client.predicate.ErrorConverter;
import io.vertx.ext.web.client.predicate.ResponsePredicate;
import io.vertx.ext.web.client.predicate.ResponsePredicateResult;
import io.vertx.ext.web.codec.BodyCodec;
import io.vertx.ext.web.multipart.MultipartForm;
import io.vertx.test.core.TestUtils;
import io.vertx.test.tls.Cert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.net.ConnectException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public class WebClientTest extends HttpTestBase {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
private File testFile;
private WebClient client;
@Override
protected VertxOptions getOptions() {
return super.getOptions().setAddressResolverOptions(new AddressResolverOptions().
setHostsValue(Buffer.buffer(
"127.0.0.1 somehost\n" +
"127.0.0.1 localhost")));
}
@Override
public void setUp() throws Exception {
super.setUp();
super.client = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(8080).setDefaultHost("localhost"));
client = WebClient.wrap(super.client);
server.close();
server = vertx.createHttpServer(new HttpServerOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST));
testFile = testFolder.newFile("test.txt");
}
@Test
public void testDefaultHostAndPort() throws Exception {
testRequest(client -> client.get("somepath"), req -> assertEquals("localhost:8080", req.host()));
}
@Test
public void testDefaultPort() throws Exception {
testRequest(client -> client.get("somehost", "somepath"), req -> assertEquals("somehost:8080", req.host()));
}
@Test
public void testDefaultUserAgent() throws Exception {
testRequest(client -> client.get("somehost", "somepath"), req -> {
String ua = req.headers().get(HttpHeaders.USER_AGENT);
assertTrue("Was expecting use agent header " + ua + " to start with Vert.x-WebClient/", ua.startsWith("Vert.x-WebClient/"));
});
}
@Test
public void testCustomUserAgent() throws Exception {
client = WebClient.wrap(super.client, new WebClientOptions().setUserAgent("smith"));
testRequest(client -> client.get("somehost", "somepath"), req -> assertEquals(Collections.singletonList("smith"), req.headers().getAll(HttpHeaders.USER_AGENT)));
}
@Test
public void testUserAgentDisabled() throws Exception {
client = WebClient.wrap(super.client, new WebClientOptions().setUserAgentEnabled(false));
testRequest(client -> client.get("somehost", "somepath"), req -> assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT)));
}
@Test
public void testUserAgentHeaderOverride() throws Exception {
testRequest(client -> client.get("somehost", "somepath").putHeader(HttpHeaders.USER_AGENT.toString(), "smith"), req -> assertEquals(Collections.singletonList("smith"), req.headers().getAll(HttpHeaders.USER_AGENT)));
}
@Test
public void testUserAgentHeaderRemoved() throws Exception {
testRequest(client -> {
HttpRequest<Buffer> request = client.get("somehost", "somepath");
request.headers().remove(HttpHeaders.USER_AGENT);
return request;
}, req -> assertEquals(Collections.emptyList(), req.headers().getAll(HttpHeaders.USER_AGENT)));
}
@Test
public void testGet() throws Exception {
testRequest(HttpMethod.GET);
}
@Test
public void testHead() throws Exception {
testRequest(HttpMethod.HEAD);
}
@Test
public void testDelete() throws Exception {
testRequest(HttpMethod.DELETE);
}
private void testRequest(HttpMethod method) throws Exception {
testRequest(client -> {
switch (method) {
case GET:
return client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
case HEAD:
return client.head(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
case DELETE:
return client.delete(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
default:
fail("Invalid HTTP method");
return null;
}
}, req -> assertEquals(method, req.method()));
}
private void testRequest(Function<WebClient, HttpRequest<Buffer>> reqFactory, Consumer<HttpServerRequest> reqChecker) throws Exception {
waitFor(4);
server.requestHandler(req -> {
try {
reqChecker.accept(req);
complete();
} finally {
req.response().end();
}
});
startServer();
HttpRequest<Buffer> builder = reqFactory.apply(client);
builder.send(onSuccess(resp -> complete()));
builder.send(onSuccess(resp -> complete()));
await();
}
@Test
public void testPost() throws Exception {
testRequestWithBody(HttpMethod.POST, false);
}
@Test
public void testPostChunked() throws Exception {
testRequestWithBody(HttpMethod.POST, true);
}
@Test
public void testPut() throws Exception {
testRequestWithBody(HttpMethod.PUT, false);
}
@Test
public void testPutChunked() throws Exception {
testRequestWithBody(HttpMethod.PUT, true);
}
@Test
public void testPatch() throws Exception {
testRequestWithBody(HttpMethod.PATCH, false);
}
private void testRequestWithBody(HttpMethod method, boolean chunked) throws Exception {
String expected = TestUtils.randomAlphaString(1024 * 1024);
File f = File.createTempFile("vertx", ".data");
f.deleteOnExit();
Files.write(f.toPath(), expected.getBytes());
waitFor(2);
server.requestHandler(req -> req.bodyHandler(buff -> {
assertEquals(method, req.method());
assertEquals(Buffer.buffer(expected), buff);
complete();
req.response().end();
}));
startServer();
vertx.runOnContext(v -> {
AsyncFile asyncFile = vertx.fileSystem().openBlocking(f.getAbsolutePath(), new OpenOptions());
HttpRequest<Buffer> builder = null;
switch (method) {
case POST:
builder = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
break;
case PUT:
builder = client.put(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
break;
case PATCH:
builder = client.patch(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
break;
default:
fail("Invalid HTTP method");
}
if (!chunked) {
builder = builder.putHeader("Content-Length", "" + expected.length());
}
builder.sendStream(asyncFile, onSuccess(resp -> {
assertEquals(200, resp.statusCode());
complete();
}));
});
await();
}
@Test
public void testSendJsonObjectBody() throws Exception {
JsonObject body = new JsonObject().put("wine", "Chateauneuf Du Pape").put("cheese", "roquefort");
testSendBody(body, (contentType, buff) -> {
assertEquals("application/json", contentType);
assertEquals(body, buff.toJsonObject());
});
}
@Test
public void testSendJsonPojoBody() throws Exception {
testSendBody(new WineAndCheese().setCheese("roquefort").setWine("Chateauneuf Du Pape"),
(contentType, buff) -> {
assertEquals("application/json", contentType);
assertEquals(new JsonObject().put("wine", "Chateauneuf Du Pape").put("cheese", "roquefort"), buff.toJsonObject());
});
}
@Test
public void testSendJsonArrayBody() throws Exception {
JsonArray body = new JsonArray().add(0).add(1).add(2);
testSendBody(body, (contentType, buff) -> {
assertEquals("application/json", contentType);
assertEquals(body, buff.toJsonArray());
});
}
@Test
public void testSendBufferBody() throws Exception {
Buffer body = TestUtils.randomBuffer(2048);
testSendBody(body, (contentType, buff) -> assertEquals(body, buff));
}
private void testSendBody(Object body, BiConsumer<String, Buffer> checker) throws Exception {
waitFor(2);
server.requestHandler(req -> req.bodyHandler(buff -> {
checker.accept(req.getHeader("content-type"), buff);
complete();
req.response().end();
}));
startServer();
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
if (body instanceof Buffer) {
post.sendBuffer((Buffer) body, onSuccess(resp -> complete()));
} else if (body instanceof JsonObject) {
post.sendJsonObject((JsonObject) body, onSuccess(resp -> complete()));
} else {
post.sendJson(body, onSuccess(resp -> complete()));
}
await();
}
@Test
public void testConnectError() throws Exception {
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onFailure(err -> {
assertTrue(err instanceof ConnectException);
complete();
}));
await();
}
@Test
public void testRequestSendError() throws Exception {
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<HttpConnection> conn = new AtomicReference<>();
server.requestHandler(req -> {
conn.set(req.connection());
req.pause();
latch.countDown();
});
startServer();
AtomicReference<Handler<Buffer>> dataHandler = new AtomicReference<>();
AtomicReference<Handler<Void>> endHandler = new AtomicReference<>();
AtomicBoolean paused = new AtomicBoolean();
post.sendStream(new ReadStream<Buffer>() {
@Override
public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public ReadStream<Buffer> handler(Handler<Buffer> handler) {
dataHandler.set(handler);
return this;
}
@Override
public ReadStream<Buffer> pause() {
paused.set(true);
return this;
}
@Override
public ReadStream<Buffer> fetch(long amount) {
throw new UnsupportedOperationException();
}
@Override
public ReadStream<Buffer> resume() {
paused.set(false);
return this;
}
@Override
public ReadStream<Buffer> endHandler(Handler<Void> handler) {
endHandler.set(handler);
return this;
}
}, onFailure(err -> {
// Should be a connection reset by peer or closed
assertNull(endHandler.get());
assertNull(dataHandler.get());
assertFalse(paused.get());
complete();
}));
assertWaitUntil(() -> dataHandler.get() != null);
dataHandler.get().handle(TestUtils.randomBuffer(1024));
awaitLatch(latch);
while (!paused.get()) {
dataHandler.get().handle(TestUtils.randomBuffer(1024));
}
conn.get().close();
await();
}
@Test
public void testRequestPumpError() throws Exception {
waitFor(2);
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
CompletableFuture<Void> done = new CompletableFuture<>();
server.requestHandler(req -> {
req.response().closeHandler(v -> complete());
req.handler(buff -> done.complete(null));
});
Throwable cause = new Throwable();
startServer();
post.sendStream(new ReadStream<Buffer>() {
@Override
public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
if (handler != null) {
done.thenAccept(v -> handler.handle(cause));
}
return this;
}
@Override
public ReadStream<Buffer> handler(Handler<Buffer> handler) {
if (handler != null) {
handler.handle(TestUtils.randomBuffer(1024));
}
return this;
}
@Override
public ReadStream<Buffer> fetch(long amount) {
return this;
}
@Override
public ReadStream<Buffer> pause() {
return this;
}
@Override
public ReadStream<Buffer> resume() {
return this;
}
@Override
public ReadStream<Buffer> endHandler(Handler<Void> endHandler) {
return this;
}
}, onFailure(err -> {
if (cause == err) {
complete();
} else {
fail(new Exception("Unexpected failure", err));
}
}));
await();
}
@Test
public void testRequestPumpErrorNotYetConnected() throws Exception {
HttpRequest<Buffer> post = client.post(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
server.requestHandler(req -> fail());
Throwable cause = new Throwable();
startServer();
post.sendStream(new ReadStream<Buffer>() {
Handler<Throwable> exceptionHandler;
@Override
public ReadStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
exceptionHandler = handler;
return this;
}
@Override
public ReadStream<Buffer> handler(Handler<Buffer> handler) {
if (handler != null) {
vertx.runOnContext(v -> exceptionHandler.handle(cause));
}
return this;
}
@Override
public ReadStream<Buffer> fetch(long amount) {
return this;
}
@Override
public ReadStream<Buffer> pause() {
return this;
}
@Override
public ReadStream<Buffer> resume() {
return this;
}
@Override
public ReadStream<Buffer> endHandler(Handler<Void> endHandler) {
return this;
}
}, onFailure(err -> {
assertSame(cause, err);
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsBuffer() throws Exception {
Buffer expected = TestUtils.randomBuffer(2000);
server.requestHandler(req -> req.response().end(expected));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonObject() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> req.response().end(expected.encode()));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonObject())
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonMapped() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> req.response().end(expected.encode()));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.json(WineAndCheese.class))
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(new WineAndCheese().setCheese("Goat Cheese").setWine("Condrieu"), resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonArray() throws Exception {
JsonArray expected = new JsonArray().add("cheese").add("wine");
server.requestHandler(req -> req.response().end(expected.encode()));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonArray())
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyAsAsJsonArrayMapped() throws Exception {
JsonArray expected = new JsonArray().add("cheese").add("wine");
server.requestHandler(req -> req.response().end(expected.encode()));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.json(List.class))
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected.getList(), resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseBodyDiscarded() throws Exception {
server.requestHandler(req -> req.response().end(TestUtils.randomAlphaString(1024)));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.none())
.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(null, resp.body());
testComplete();
}));
await();
}
@Test
public void testResponseUnknownContentTypeBodyAsJsonObject() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> req.response().end(expected.encode()));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.bodyAsJsonObject());
testComplete();
}));
await();
}
@Test
public void testResponseUnknownContentTypeBodyAsJsonArray() throws Exception {
JsonArray expected = new JsonArray().add("cheese").add("wine");
server.requestHandler(req -> req.response().end(expected.encode()));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(expected, resp.bodyAsJsonArray());
testComplete();
}));
await();
}
@Test
public void testResponseUnknownContentTypeBodyAsJsonMapped() throws Exception {
JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
server.requestHandler(req -> req.response().end(expected.encode()));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.send(onSuccess(resp -> {
assertEquals(200, resp.statusCode());
assertEquals(new WineAndCheese().setCheese("Goat Cheese").setWine("Condrieu"), resp.bodyAsJson(WineAndCheese.class));
testComplete();
}));
await();
}
@Test
public void testResponseBodyUnmarshallingError() throws Exception {
server.requestHandler(req -> req.response().end("not-json-object"));
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonObject())
.send(onFailure(err -> {
assertTrue(err instanceof DecodeException);
testComplete();
}));
await();
}
@Test
public void testResponseBodyStream() throws Exception {
AtomicBoolean paused = new AtomicBoolean();
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true);
vertx.setPeriodic(1, id -> {
if (!resp.writeQueueFull()) {
resp.write(TestUtils.randomAlphaString(1024));
} else {
resp.drainHandler(v -> resp.end());
paused.set(true);
vertx.cancelTimer(id);
}
});
});
startServer();
CompletableFuture<Void> resume = new CompletableFuture<>();
AtomicInteger size = new AtomicInteger();
AtomicBoolean ended = new AtomicBoolean();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
boolean paused = true;
Handler<Void> drainHandler;
{
resume.thenAccept(v -> {
paused = false;
if (drainHandler != null) {
drainHandler.handle(null);
}
});
}
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
size.addAndGet(data.length());
return this;
}
@Override
public void end() {
ended.set(true);
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return paused;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
drainHandler = handler;
return this;
}
};
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.pipe(stream))
.send(onSuccess(resp -> {
assertTrue(ended.get());
assertEquals(200, resp.statusCode());
assertEquals(null, resp.body());
testComplete();
}));
assertWaitUntil(paused::get);
resume.complete(null);
await();
}
@Test
public void testResponseBodyStreamError() throws Exception {
CompletableFuture<Void> fail = new CompletableFuture<>();
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true);
resp.write(TestUtils.randomBuffer(2048));
fail.thenAccept(v -> resp.close());
});
startServer();
AtomicInteger received = new AtomicInteger();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
received.addAndGet(data.length());
return this;
}
@Override
public void end() {
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return false;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
return this;
}
};
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.pipe(stream))
.send(onFailure(err -> testComplete()));
assertWaitUntil(() -> received.get() == 2048);
fail.complete(null);
await();
}
@Test
public void testResponseBodyCodecError() throws Exception {
server.requestHandler(req -> {
HttpServerResponse resp = req.response();
resp.setChunked(true);
resp.end(TestUtils.randomBuffer(2048));
});
startServer();
RuntimeException cause = new RuntimeException();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
Handler<Throwable> exceptionHandler;
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
exceptionHandler = handler;
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
exceptionHandler.handle(cause);
return this;
}
@Override
public void end() {
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return false;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
return this;
}
};
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.pipe(stream))
.send(onFailure(err -> {
assertSame(cause, err);
testComplete();
}));
await();
}
@Test
public void testResponseJsonObjectMissingBody() throws Exception {
testResponseMissingBody(BodyCodec.jsonObject());
}
@Test
public void testResponseJsonMissingBody() throws Exception {
testResponseMissingBody(BodyCodec.json(WineAndCheese.class));
}
@Test
public void testResponseWriteStreamMissingBody() throws Exception {
AtomicInteger length = new AtomicInteger();
AtomicBoolean ended = new AtomicBoolean();
WriteStream<Buffer> stream = new WriteStream<Buffer>() {
@Override
public WriteStream<Buffer> exceptionHandler(Handler<Throwable> handler) {
return this;
}
@Override
public WriteStream<Buffer> write(Buffer data) {
length.addAndGet(data.length());
return this;
}
@Override
public void end() {
ended.set(true);
}
@Override
public WriteStream<Buffer> setWriteQueueMaxSize(int maxSize) {
return this;
}
@Override
public boolean writeQueueFull() {
return false;
}
@Override
public WriteStream<Buffer> drainHandler(Handler<Void> handler) {
return this;
}
};
testResponseMissingBody(BodyCodec.pipe(stream));
assertTrue(ended.get());
assertEquals(0, length.get());
}
private <R> void testResponseMissingBody(BodyCodec<R> codec) throws Exception {
server.requestHandler(req -> req.response().setStatusCode(403).end());
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(codec)
.send(onSuccess(resp -> {
assertEquals(403, resp.statusCode());
assertNull(resp.body());
testComplete();
}));
await();
}
@Test
public void testHttpResponseError() throws Exception {
server.requestHandler(req -> req.response().setChunked(true).write(Buffer.buffer("some-data")).close());
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get
.as(BodyCodec.jsonObject())
.send(onFailure(err -> {
assertTrue(err instanceof VertxException);
testComplete();
}));
await();
}
@Test
public void testTimeout() throws Exception {
AtomicInteger count = new AtomicInteger();
server.requestHandler(req -> count.incrementAndGet());
startServer();
HttpRequest<Buffer> get = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
get.timeout(50).send(onFailure(err -> {
assertTrue(err instanceof TimeoutException);
testComplete();
}));
await();
}
@Test
public void testQueryParam() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/").addQueryParam("param", "param_value"), req -> {
assertEquals("param=param_value", req.query());
assertEquals("param_value", req.getParam("param"));
});
}
@Test
public void testQueryParamMulti() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/").addQueryParam("param", "param_value1").addQueryParam("param", "param_value2"), req -> {
assertEquals("param=param_value1¶m=param_value2", req.query());
assertEquals(Arrays.asList("param_value1", "param_value2"), req.params().getAll("param"));
});
}
@Test
public void testQueryParamAppend() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/?param1=param1_value1").addQueryParam("param1", "param1_value2").addQueryParam("param2", "param2_value"), req -> {
assertEquals("param1=param1_value1¶m1=param1_value2¶m2=param2_value", req.query());
assertEquals("param1_value1", req.getParam("param1"));
assertEquals("param2_value", req.getParam("param2"));
});
}
@Test
public void testOverwriteQueryParams() throws Exception {
testRequest(client -> client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/?param=param_value1").setQueryParam("param", "param_value2"), req -> {
assertEquals("param=param_value2", req.query());
assertEquals("param_value2", req.getParam("param"));
});
}
@Test
public void testQueryParamEncoding() throws Exception {
testRequest(client -> client
.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/")
.addQueryParam("param1", " ")
.addQueryParam("param2", "\u20AC"), req -> {
assertEquals("param1=%20¶m2=%E2%82%AC", req.query());
assertEquals(" ", req.getParam("param1"));
assertEquals("\u20AC", req.getParam("param2"));
});
}
@Test
public void testFormUrlEncoded() throws Exception {
server.requestHandler(req -> {
req.setExpectMultipart(true);
req.endHandler(v -> {
assertEquals("param1_value", req.getFormAttribute("param1"));
req.response().end();
});
});
startServer();
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.add("param1", "param1_value");
HttpRequest<Buffer> builder = client.post("/somepath");
builder.sendForm(form, onSuccess(resp -> complete()));
await();
}
@Test
public void testFormMultipart() throws Exception {
server.requestHandler(req -> {
req.setExpectMultipart(true);
req.endHandler(v -> {
assertEquals("param1_value", req.getFormAttribute("param1"));
req.response().end();
});
});
startServer();
MultiMap form = MultiMap.caseInsensitiveMultiMap();
form.add("param1", "param1_value");
HttpRequest<Buffer> builder = client.post("/somepath");
builder.putHeader("content-type", "multipart/form-data");
builder.sendForm(form, onSuccess(resp -> complete()));
await();
}
@Test
public void testFileUploadFormMultipart32B() throws Exception {
testFileUploadFormMultipart(32);
}
@Test
public void testFileUploadFormMultipart32K() throws Exception {
testFileUploadFormMultipart(32 * 1024);
}
@Test
public void testFileUploadFormMultipart32M() throws Exception {
testFileUploadFormMultipart(32 * 1024 * 1024);
}
private void testFileUploadFormMultipart(int size) throws Exception {
Buffer content = Buffer.buffer(TestUtils.randomAlphaString(size));
vertx.fileSystem().writeFileBlocking(testFile.getPath(), content);
server.requestHandler(req -> {
req.setExpectMultipart(true);
req.uploadHandler(upload -> {
Buffer fileBuffer = Buffer.buffer();
assertEquals("file", upload.name());
assertEquals("test.txt", upload.filename());
assertEquals("text/plain", upload.contentType());
upload.handler(fileBuffer::appendBuffer);
upload.endHandler(v -> assertEquals(content, fileBuffer));
});
req.endHandler(v -> {
assertEquals("vert.x", req.getFormAttribute("toolkit"));
assertEquals("jvm", req.getFormAttribute("runtime"));
req.response().end();
});
});
startServer();
MultipartForm form = MultipartForm.create()
.attribute("toolkit", "vert.x")
.attribute("runtime", "jvm")
.textFileUpload("file", testFile.getName(), testFile.getPath(), "text/plain");
HttpRequest<Buffer> builder = client.post("somepath");
builder.sendMultipartForm(form, onSuccess(resp -> complete()));
await();
}
@Test
public void testFileUploadWhenFileDoesNotExist() {
HttpRequest<Buffer> builder = client.post("somepath");
MultipartForm form = MultipartForm.create()
.textFileUpload("file", "nonexistentFilename", "nonexistentPathname", "text/plain");
builder.sendMultipartForm(form, onFailure(err -> {
assertEquals(err.getClass(), HttpPostRequestEncoder.ErrorDataEncoderException.class);
complete();
}));
await();
}
@Test
public void testDefaultFollowRedirects() throws Exception {
testFollowRedirects(null, true);
}
@Test
public void testFollowRedirects() throws Exception {
testFollowRedirects(true, true);
}
@Test
public void testDoNotFollowRedirects() throws Exception {
testFollowRedirects(false, false);
}
private void testFollowRedirects(Boolean set, boolean expect) throws Exception {
waitFor(2);
String location = "http://" + DEFAULT_HTTP_HOST + ":" + DEFAULT_HTTP_PORT + "/ok";
server.requestHandler(req -> {
if (req.path().equals("/redirect")) {
req.response().setStatusCode(301).putHeader("Location", location).end();
if (!expect) {
complete();
}
} else {
req.response().end(req.path());
if (expect) {
complete();
}
}
});
startServer();
HttpRequest<Buffer> builder = client.get("/redirect");
if (set != null) {
builder = builder.followRedirects(set);
}
builder.send(onSuccess(resp -> {
if (expect) {
assertEquals(200, resp.statusCode());
assertEquals("/ok", resp.body().toString());
} else {
assertEquals(301, resp.statusCode());
assertEquals(location, resp.getHeader("location"));
}
complete();
}));
await();
}
@Test
public void testInvalidRedirection() throws Exception {
server.requestHandler(req -> {
assertEquals(HttpMethod.POST, req.method());
assertEquals("/redirect", req.path());
req.response().setStatusCode(302).putHeader("Location", "http:
});
startServer();
HttpRequest<Buffer> builder = client
.post("/redirect")
.followRedirects(true);
builder.send(onSuccess(resp -> {
assertEquals(302, resp.statusCode());
assertEquals("http:
assertNull(resp.body());
complete();
}));
await();
}
@Test
public void testRedirectLimit() throws Exception {
String location = "http://" + DEFAULT_HTTP_HOST + ":" + DEFAULT_HTTP_PORT + "/redirect";
server.requestHandler(req -> {
assertEquals(HttpMethod.GET, req.method());
assertEquals("/redirect", req.path());
req.response().setStatusCode(302).putHeader("Location", location).end();
});
startServer();
HttpRequest<Buffer> builder = client
.get("/redirect")
.followRedirects(true);
builder.send(onSuccess(resp -> {
assertEquals(302, resp.statusCode());
assertEquals(location, resp.getHeader("Location"));
assertNull(resp.body());
complete();
}));
await();
}
@Test
public void testVirtualHost() throws Exception {
server.requestHandler(req -> {
assertEquals("another-host:8080", req.host());
req.response().end();
});
startServer();
HttpRequest<Buffer> req = client.get("/test").virtualHost("another-host");
req.send(onSuccess(resp -> testComplete()));
await();
}
@Test
public void testTLSEnabled() throws Exception {
testTLS(true, true, client -> client.get("/"));
}
@Test
public void testTLSEnabledDisableRequestTLS() throws Exception {
testTLS(true, false, client -> client.get("/").ssl(false));
}
@Test
public void testTLSEnabledEnableRequestTLS() throws Exception {
testTLS(true, true, client -> client.get("/").ssl(true));
}
@Test
public void testTLSDisabledDisableRequestTLS() throws Exception {
testTLS(false, false, client -> client.get("/").ssl(false));
}
@Test
public void testTLSDisabledEnableRequestTLS() throws Exception {
testTLS(false, true, client -> client.get("/").ssl(true));
}
@Test
public void testTLSEnabledDisableRequestTLSAbsURI() throws Exception {
testTLS(true, false, client -> client.getAbs("http://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSEnabledEnableRequestTLSAbsURI() throws Exception {
testTLS(true, true, client -> client.getAbs("https://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSDisabledDisableRequestTLSAbsURI() throws Exception {
testTLS(false, false, client -> client.getAbs("http://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSDisabledEnableRequestTLSAbsURI() throws Exception {
testTLS(false, true, client -> client.getAbs("https://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT));
}
@Test
public void testTLSQueryParametersIssue563() throws Exception {
testTLS(false, true,
client -> client.getAbs("https://" + DEFAULT_HTTPS_HOST + ":" + DEFAULT_HTTPS_PORT)
.addQueryParam("query1", "value1")
.addQueryParam("query2", "value2"),
serverRequest -> assertEquals("query1=value1&query2=value2", serverRequest.query()));
}
private void testTLS(boolean clientSSL, boolean serverSSL, Function<WebClient, HttpRequest<Buffer>> requestProvider) throws Exception {
testTLS(clientSSL, serverSSL, requestProvider, null);
}
private void testTLS(boolean clientSSL, boolean serverSSL, Function<WebClient, HttpRequest<Buffer>> requestProvider, Consumer<HttpServerRequest> serverAssertions) throws Exception {
WebClientOptions clientOptions = new WebClientOptions()
.setSsl(clientSSL)
.setTrustAll(true)
.setDefaultHost(DEFAULT_HTTPS_HOST)
.setDefaultPort(DEFAULT_HTTPS_PORT);
HttpServerOptions serverOptions = new HttpServerOptions()
.setSsl(serverSSL)
.setKeyStoreOptions(Cert.SERVER_JKS.get())
.setPort(DEFAULT_HTTPS_PORT)
.setHost(DEFAULT_HTTPS_HOST);
testTLS(clientOptions, serverOptions, requestProvider, serverAssertions);
}
@Test
public void testVirtualHostSNI() throws Exception {
WebClientOptions clientOptions = new WebClientOptions()
.setTrustAll(true)
.setDefaultHost(DEFAULT_HTTPS_HOST)
.setDefaultPort(DEFAULT_HTTPS_PORT);
HttpServerOptions serverOptions = new HttpServerOptions()
.setSsl(true)
.setSni(true)
.setKeyStoreOptions(Cert.SNI_JKS.get())
.setPort(DEFAULT_HTTPS_PORT)
.setHost(DEFAULT_HTTPS_HOST);
testTLS(clientOptions, serverOptions, req -> req.get("/").virtualHost("host2.com").ssl(true), req -> {
assertEquals("host2.com", req.connection().indicatedServerName());
System.out.println(req.host());
});
}
private void testTLS(WebClientOptions clientOptions, HttpServerOptions serverOptions, Function<WebClient, HttpRequest<Buffer>> requestProvider, Consumer<HttpServerRequest> serverAssertions) throws Exception {
WebClient sslClient = WebClient.create(vertx, clientOptions);
HttpServer sslServer = vertx.createHttpServer(serverOptions);
sslServer.requestHandler(req -> {
assertEquals(serverOptions.isSsl(), req.isSSL());
if (serverAssertions != null) {
serverAssertions.accept(req);
}
req.response().end();
});
try {
startServer(sslServer);
HttpRequest<Buffer> builder = requestProvider.apply(sslClient);
builder.send(onSuccess(resp -> testComplete()));
await();
} finally {
sslClient.close();
sslServer.close();
}
}
@Test
public void testHttpProxyFtpRequest() throws Exception {
startProxy(null, ProxyType.HTTP);
proxy.setForceUri("http://" + DEFAULT_HTTP_HOST + ":" + DEFAULT_HTTP_PORT);
server.requestHandler(req -> req.response().setStatusCode(200).end());
startServer();
WebClientOptions options = new WebClientOptions();
options.setProxyOptions(new ProxyOptions().setPort(proxy.getPort()));
WebClient client = WebClient.create(vertx, options);
client
.getAbs("ftp://ftp.gnu.org/gnu/")
.send(ar -> {
if (ar.succeeded()) {
// Obtain response
HttpResponse<Buffer> response = ar.result();
assertEquals(200, response.statusCode());
assertEquals("ftp://ftp.gnu.org/gnu/", proxy.getLastUri());
testComplete();
} else {
fail(ar.cause());
}
});
await();
}
@Test
public void testStreamHttpServerRequest() throws Exception {
Buffer expected = TestUtils.randomBuffer(10000);
HttpServer server2 = vertx.createHttpServer(new HttpServerOptions().setPort(8081)).requestHandler(req -> req.bodyHandler(body -> {
assertEquals(body, expected);
req.response().end();
}));
startServer(server2);
WebClient webClient = WebClient.create(vertx);
try {
server.requestHandler(req -> webClient.postAbs("http://localhost:8081/")
.sendStream(req, onSuccess(resp -> req.response().end("ok"))));
startServer();
webClient.post(8080, "localhost", "/").sendBuffer(expected, onSuccess(resp -> {
assertEquals("ok", resp.bodyAsString());
complete();
}));
await();
} finally {
server2.close();
}
}
@Test
public void testExpectFail() throws Exception {
testExpectation(true,
req -> req.expect(ResponsePredicate.create(r -> ResponsePredicateResult.failure("boom"))),
HttpServerResponse::end);
}
@Test
public void testExpectPass() throws Exception {
testExpectation(false,
req -> req.expect(ResponsePredicate.create(r -> ResponsePredicateResult.success())),
HttpServerResponse::end);
}
@Test
public void testExpectStatusFail() throws Exception {
testExpectation(true,
req -> req.expect(ResponsePredicate.status(200)),
resp -> resp.setStatusCode(201).end());
}
@Test
public void testExpectStatusPass() throws Exception {
testExpectation(false,
req -> req.expect(ResponsePredicate.status(200)),
resp -> resp.setStatusCode(200).end());
}
@Test
public void testExpectStatusRangeFail() throws Exception {
testExpectation(true,
req -> req.expect(ResponsePredicate.SC_SUCCESS),
resp -> resp.setStatusCode(500).end());
}
@Test
public void testExpectStatusRangePass1() throws Exception {
testExpectation(false,
req -> req.expect(ResponsePredicate.SC_SUCCESS),
resp -> resp.setStatusCode(200).end());
}
@Test
public void testExpectStatusRangePass2() throws Exception {
testExpectation(false,
req -> req.expect(ResponsePredicate.SC_SUCCESS),
resp -> resp.setStatusCode(299).end());
}
@Test
public void testExpectContentTypeFail() throws Exception {
testExpectation(true,
req -> req.expect(ResponsePredicate.JSON),
HttpServerResponse::end);
}
@Test
public void testExpectOneOfContentTypesFail() throws Exception {
testExpectation(true,
req -> req.expect(ResponsePredicate.contentType(Arrays.asList("text/plain", "text/csv"))),
httpServerResponse -> httpServerResponse.putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaders.TEXT_HTML).end());
}
@Test
public void testExpectContentTypePass() throws Exception {
testExpectation(false,
req -> req.expect(ResponsePredicate.JSON),
resp -> resp.putHeader("content-type", "application/JSON").end());
}
@Test
public void testExpectOneOfContentTypesPass() throws Exception {
testExpectation(false,
req -> req.expect(ResponsePredicate.contentType(Arrays.asList("text/plain", "text/HTML"))),
httpServerResponse -> httpServerResponse.putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaders.TEXT_HTML).end());
}
@Test
public void testExpectCustomException() throws Exception {
ResponsePredicate predicate = ResponsePredicate.create(r -> ResponsePredicateResult.failure("boom"), result -> new CustomException(result.message()));
testExpectation(true, req -> req.expect(predicate), HttpServerResponse::end, ar -> {
Throwable cause = ar.cause();
assertThat(cause, instanceOf(CustomException.class));
CustomException customException = (CustomException) cause;
assertEquals("boom", customException.getMessage());
});
}
@Test
public void testExpectCustomExceptionWithResponseBody() throws Exception {
UUID uuid = UUID.randomUUID();
ResponsePredicate predicate = ResponsePredicate.create(ResponsePredicate.SC_SUCCESS, ErrorConverter.createFullBody(result -> {
JsonObject body = result.response().bodyAsJsonObject();
return new CustomException(UUID.fromString(body.getString("tag")), body.getString("message"));
}));
testExpectation(true, req -> req.expect(predicate), httpServerResponse -> {
httpServerResponse
.setStatusCode(400)
.end(new JsonObject().put("tag", uuid.toString()).put("message", "tilt").toBuffer());
}, ar -> {
Throwable cause = ar.cause();
assertThat(cause, instanceOf(CustomException.class));
CustomException customException = (CustomException) cause;
assertEquals("tilt", customException.getMessage());
assertEquals(uuid, customException.tag);
});
}
@Test
public void testExpectFunctionThrowsException() throws Exception {
ResponsePredicate predicate = ResponsePredicate.create(r -> {
throw new IndexOutOfBoundsException("boom");
});
testExpectation(true, req -> req.expect(predicate), HttpServerResponse::end, ar -> {
assertThat(ar.cause(), instanceOf(IndexOutOfBoundsException.class));
});
}
@Test
public void testErrorConverterThrowsException() throws Exception {
ResponsePredicate predicate = ResponsePredicate.create(r -> {
return ResponsePredicateResult.failure("boom");
}, result -> {
throw new IndexOutOfBoundsException();
});
testExpectation(true, req -> req.expect(predicate), HttpServerResponse::end, ar -> {
assertThat(ar.cause(), instanceOf(IndexOutOfBoundsException.class));
});
}
@Test
public void testErrorConverterReturnsNull() throws Exception {
ResponsePredicate predicate = ResponsePredicate.create(r -> {
return ResponsePredicateResult.failure("boom");
}, r -> null);
testExpectation(true, req -> req.expect(predicate), HttpServerResponse::end, ar -> {
assertThat(ar.cause(), not(instanceOf(NullPointerException.class)));
});
}
private static class CustomException extends Exception {
UUID tag;
CustomException(String message) {
super(message);
}
CustomException(UUID tag, String message) {
super(message);
this.tag = tag;
}
}
private void testExpectation(boolean shouldFail,
Consumer<HttpRequest<?>> modifier,
Consumer<HttpServerResponse> bilto) throws Exception {
testExpectation(shouldFail, modifier, bilto, null);
}
private void testExpectation(boolean shouldFail,
Consumer<HttpRequest<?>> modifier,
Consumer<HttpServerResponse> bilto,
Consumer<AsyncResult<?>> resultTest) throws Exception {
server.requestHandler(request -> bilto.accept(request.response()));
startServer();
HttpRequest<Buffer> request = client
.get("/test");
modifier.accept(request);
request.send(ar -> {
if (ar.succeeded()) {
assertFalse("Expected response success", shouldFail);
} else {
assertTrue("Expected response failure", shouldFail);
}
if (resultTest != null) resultTest.accept(ar);
testComplete();
});
await();
}
}
|
package br.usp.ime.retrobreaker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.preference.PreferenceManager;
import android.util.Log;
import br.usp.ime.retrobreaker.Constants.Collision;
import br.usp.ime.retrobreaker.Constants.Colors;
import br.usp.ime.retrobreaker.Constants.Config;
import br.usp.ime.retrobreaker.Constants.Difficult;
import br.usp.ime.retrobreaker.Constants.Hit;
import br.usp.ime.retrobreaker.Constants.Lives;
import br.usp.ime.retrobreaker.Constants.Scales;
import br.usp.ime.retrobreaker.Constants.Score;
import br.usp.ime.retrobreaker.Constants.ScoreMultiplier;
import br.usp.ime.retrobreaker.effects.Explosion;
import br.usp.ime.retrobreaker.forms.Ball;
import br.usp.ime.retrobreaker.forms.Brick;
import br.usp.ime.retrobreaker.forms.MobileBrick;
import br.usp.ime.retrobreaker.forms.Paddle;
import br.usp.ime.retrobreaker.forms.Brick.Type;
public class Game {
// Constants
private static final String TAG = Game.class.getSimpleName();
private static final int SCREEN_INITIAL_X = 0;
private static final int SCREEN_INITIAL_Y = 0;
//Game objects
private Paddle mPaddle;
private Ball mBall;
private Brick[][] mBricks;
private SoundPool mSoundPool;
private HashMap<String, Integer> mSoundIds;
private Context mContext;
private List<Explosion> mExplosions;
private List<MobileBrick> mMobileBricks;
private int mConsecutiveCollision;
// Game State preferences
private static int sDifficult;
public Game(Context context) {
mContext = context;
// Load user difficult choice
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
sDifficult = sharedPrefs.getInt("difficult_prefs", -1);
if (sDifficult < 0) {
Log.e(TAG, "Invalid difficult preference: " + sDifficult);
// If there is some problem on difficult setting, set it to debug ("Can't die")
sDifficult = 0;
}
// Load sound pool, audio shouldn't change between levels
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundIds = new HashMap<String, Integer>(4);
mSoundIds.put("lost_life", mSoundPool.load(mContext, R.raw.lost_life, 1));
mSoundIds.put("wall_hit", mSoundPool.load(mContext, R.raw.wall_hit, 1));
mSoundIds.put("paddle_hit", mSoundPool.load(mContext, R.raw.paddle_hit, 1));
mSoundIds.put("brick_hit", mSoundPool.load(mContext, R.raw.brick_hit, 1));
mSoundIds.put("explosive_brick", mSoundPool.load(mContext, R.raw.explosive_brick, 1));
// Create level elements
resetElements();
}
public void resetElements() {
mExplosions = new ArrayList<Explosion>();
mMobileBricks = new ArrayList<MobileBrick>();
/* We don't have the screen measures on the first call of this function,
* so set to a sane default. */
State.setScreenMeasures(2.0f, 2.0f);
// Initialize game state
State.setGamePaused(true);
State.setGameOver(false);
State.setLives(Lives.RESTART_LEVEL);
State.setScore(Score.RESTART_LEVEL);
State.setScoreMultiplier(ScoreMultiplier.RESTART_LEVEL);
mConsecutiveCollision = 0;
// Initialize graphics
mPaddle = new Paddle(Colors.WHITE, Config.PADDLE_INITIAL_POS_X, Config.PADDLE_INITIAL_POS_Y,
Scales.PADDLE);
Log.d(TAG, "Created paddle:" +
" BottomY: " + mPaddle.getBottomY() +
" TopY: " + mPaddle.getTopY() +
" LeftX: " + mPaddle.getLeftX() +
" RightX: " + mPaddle.getRightX()
);
mBall = new Ball(Colors.WHITE, Config.BALL_INITIAL_POS_X, Config.BALL_INITIAL_POS_Y,
Config.BALL_AFTER_POS_X, Config.BALL_AFTER_POS_Y, Scales.BALL, Difficult.BALL_SPEED[sDifficult]);
Log.d(TAG, "Created ball:" +
" BottomY: " + mBall.getBottomY() +
" TopY: " + mBall.getTopY() +
" LeftX: " + mBall.getLeftX() +
" RightX: " + mBall.getRightX()
);
createLevel(Config.NUMBER_OF_LINES_OF_BRICKS, Config.NUMBER_OF_COLUMNS_OF_BRICKS,
Config.BRICKS_INITIAL_POS_X, Config.BRICKS_INITIAL_POS_Y);
mExplosions = new ArrayList<Explosion>();
}
private void createLevel (int blocksX, int blocksY, float initialX, float initialY) {
mBricks = new Brick[blocksX][blocksY];
// The initial position of the brick should be the one passed from the call of this function
float newPosX = initialX;
float newPosY = initialY;
for (int i = 0; i < blocksX; i++) {
float sign = 1;
for (int j = 0; j < blocksY; j++) {
sign *= -1; //consecutive bricks start moving to different directions
// Create special bricks (explosive and hard types) on a random probability
double prob = Math.random();
if (prob <= (Difficult.MOBILE_BRICK_PROB[sDifficult] + Difficult.EX_BRICK_PROB[sDifficult]
+ Difficult.GREY_BRICK_PROB[sDifficult]))
{
if (prob <= Difficult.MOBILE_BRICK_PROB[sDifficult]) {
MobileBrick mBrick = new MobileBrick(Colors.GREEN, newPosX, newPosY, Scales.BRICK, Type.MOBILE, 3);
mBrick.setXVelocity(sign * mBrick.getWidth()/30);
mBrick.setGlobalBrickMatrixIndex(i, j);
mBricks[i][j] = mBrick;
mMobileBricks.add(mBrick);
} else if ((prob - Difficult.MOBILE_BRICK_PROB[sDifficult]) <= Difficult.EX_BRICK_PROB[sDifficult]) {
mBricks[i][j] = new Brick(Colors.RED, newPosX, newPosY, Scales.BRICK, Type.EXPLOSIVE);
} else {
mBricks[i][j] = new Brick(Colors.GRAY, newPosX, newPosY, Scales.BRICK, Type.HARD);
}
} else {
mBricks[i][j] = new Brick(Colors.WHITE, newPosX, newPosY, Scales.BRICK, Type.NORMAL);
}
// The position of the next brick on the same line should be on the right side of the last brick
newPosX += mBricks[i][j].getSizeX() + Config.SPACE_BETWEEN_BRICKS;
}
// Finished filling a line of bricks, resetting to initial X position so we can do the same on the next line
newPosX = initialX;
// Same as the X position, put the next line of bricks on bottom of the last one
newPosY += mBricks[i][0].getSizeY() + Config.SPACE_BETWEEN_BRICKS;
}
}
public void drawElements(GL10 gl) {
// Draw ball and paddle elements on surface
mPaddle.draw(gl);
mBall.draw(gl);
// Need to draw each block on surface
for (int i=0; i<mBricks.length; i++) {
for (int j=0; j<mBricks[i].length; j++) {
// Checking if the brick is not destroyed
if (mBricks[i][j] != null) {
mBricks[i][j].draw(gl);
}
}
}
// Initialize explosives
for (int i = 0; i < mExplosions.size(); i++) {
mExplosions.get(i).draw(gl);
}
}
private void updateBrickExplosion() {
for (int i = 0; i < mExplosions.size(); i++) {
Explosion explosion = mExplosions.get(i);
if (explosion.isAlive()) {
explosion.update2();
}
}
}
public void updatePaddlePosX(float x) {
/* We need to update Paddle position from touch, but we can't access touch updates
* directly from TouchSurfaceView, so create a wrapper and call it a day. */
mPaddle.setPosX(x);
}
private float calcReflectedAngle(float x2, float x1) {
return Constants.ANGLE_OF_REFLECTION_BOUND * (x2 - x1)/(mPaddle.getWidth()/2);
}
public void updateState() {
float reflectedAngle = 0.0f, angleOfBallSlope = 0.0f;
Collision collisionType = detectCollision();
switch (collisionType) {
case WALL_RIGHT_LEFT_SIDE:
/* Wall hit collision is almost the same, but the equation is different so we
* need to differentiate here */
Log.d(TAG, "Right/Left side collision detected");
Log.d(TAG, "previous slope: " + mBall.getSlope());
mSoundPool.play(mSoundIds.get("wall_hit"), 100, 100, 1, 0, 1.0f);
mBall.turnToPerpendicularDirection(Hit.RIGHT_LEFT);
Log.d(TAG, "next slope: " + mBall.getSlope());
break;
case WALL_TOP_BOTTOM_SIDE:
Log.d(TAG, "Top/Bottom side collision detected");
Log.d(TAG, "previous slope: " + mBall.getSlope());
mSoundPool.play(mSoundIds.get("wall_hit"), 100, 100, 1, 0, 1.0f);
mBall.turnToPerpendicularDirection(Hit.TOP_BOTTOM);
Log.d(TAG, "next slope: " + mBall.getSlope());
break;
case BRICK_BALL:
// When the user hits a brick, increase the score and multiplier and play the sound effect
State.setScore(Score.BRICK_HIT);
Log.i(TAG, "Score multiplier: " + State.getScoreMultiplier() + " Score: " + State.getScore());
State.setScoreMultiplier(ScoreMultiplier.BRICK_HIT); // Update multiplier for the next brick hit
mSoundPool.play(mSoundIds.get("brick_hit"), 100, 100, 1, 0, 1.0f);
mBall.turnToPerpendicularDirection(Hit.TOP_BOTTOM);
break;
case EX_BRICK_BALL:
// Explosive brick has a different sound effect and score, but the rest is the same
State.setScore(Score.EX_BRICK_HIT);
Log.i(TAG, "Score multiplier: " + State.getScoreMultiplier() + " Score: " + State.getScore());
State.setScoreMultiplier(ScoreMultiplier.BRICK_HIT);
mSoundPool.play(mSoundIds.get("explosive_brick"), 100, 100, 1, 0, 1.0f);
mBall.turnToPerpendicularDirection(Hit.TOP_BOTTOM);
break;
case PADDLE_BALL:
/* Sometimes the ball can enter a state where it would detect various hits between ball
* and paddle (when the ball get a position that would detect both a top hit and a
* bottom hit for example). Since this is physically impossible, add a delay every time
* the ball hit the paddle, so we can just skip paddle/ball detection for sometime. */
if(mConsecutiveCollision > 0) break;
mConsecutiveCollision += Config.MS_PER_UPDATE;
Log.d(TAG, "collided into the top left part of the paddle");
Log.d(TAG, "paddlePosX: " + mPaddle.getPosX());
State.setScoreMultiplier(ScoreMultiplier.PADDLE_HIT);
mSoundPool.play(mSoundIds.get("paddle_hit"), 100, 100, 1, 0, 1.0f);
if (mPaddle.getPosX() >= mBall.getPosX()) { //the ball hit the paddle in the right half-part.
reflectedAngle = calcReflectedAngle(mBall.getPosX(), mPaddle.getPosX());
angleOfBallSlope = (Constants.RIGHT_ANGLE - reflectedAngle);
} else { //the ball hit the paddle in the left half-part.
reflectedAngle = calcReflectedAngle(mPaddle.getPosX(), mBall.getPosX());
/* Besides being the complement, the angle of the slope is the negative complement,
* since the ball is going to the left. */
angleOfBallSlope = -1 * (Constants.RIGHT_ANGLE - reflectedAngle);
}
mBall.turnByAngle(angleOfBallSlope);
break;
case LIFE_LOST:
State.setLives(Lives.LOST_LIFE);
mSoundPool.play(mSoundIds.get("lost_life"), 100, 100, 1, 0, 1.0f);
// If the user still has lives left, create a new ball and reset score multiplier
if (!State.getGameOver()) {
mBall = new Ball(Colors.WHITE, Config.BALL_INITIAL_POS_X, Config.BALL_INITIAL_POS_Y,
Config.BALL_AFTER_POS_X, Config.BALL_AFTER_POS_Y, Scales.BALL, Difficult.BALL_SPEED[sDifficult]);
State.setScoreMultiplier(ScoreMultiplier.LOST_LIFE);
State.setGamePaused(true);
}
break;
case NOT_AVAILABLE:
// Nothing to do here
break;
default:
Log.e(TAG, "Invalid collision");
break;
}
updateBrickExplosion();
moveMobileBricks();
mBall.move();
}
private void moveMobileBricks() {
for (int a = 0; a < mMobileBricks.size(); a++) {
Log.d(TAG, "going to call move, brick: ["+mMobileBricks.get(a).getIndexI()+"]["+mMobileBricks.get(a).getIndexJ()+"]");
mMobileBricks.get(a).move();
}
}
private void explosiveBrick(int i, int j) {
// Deleting surrounding bricks
for (int a=Math.max(i-1, 0); a< Math.min(i+2, mBricks.length); a++) {
for (int b=Math.max(j-1, 0); b<Math.min(j+2, mBricks[i].length); b++) {
if (mBricks[a][b] != null) {
if (mBricks[a][b].getLives() == 0) {
mBricks[a][b] = null; // Deleting brick
State.setScore(Score.BRICK_HIT); // And add brick to score
}
else {
decrementBrickLife(a, b);
}
}
}
}
}
private void decrementBrickLife(int i, int j) {
mBricks[i][j].decrementLives();
if (mBricks[i][j].getType() == Type.HARD) {
mBricks[i][j].setColor(Colors.WHITE);
}
}
private void detectCollisionOfMobileBricks() {
for (int a = 0; a < mMobileBricks.size(); a++) {
boolean collided = false;
MobileBrick mBrick = mMobileBricks.get(a);
int i = mBrick.getIndexI();
int j = mBrick.getIndexJ();
for (int x = 0; x < Config.NUMBER_OF_COLUMNS_OF_BRICKS; x++) {
if (x != j) {
Brick brick = mBricks[i][x];
if ((brick != null) && (mBrick.detectCollisionWithBrick(brick))) {
Log.d(TAG, "going to call invert, brick: ["+i+"]["+j+"]");
mBrick.invertDirection();
collided = true;
break;
}
}
}
if (!collided && mBrick.detectCollisionWithWall()) {
mBrick.invertDirection();
}
}
}
private Collision detectCollision() {
if(mConsecutiveCollision > 0) {
mConsecutiveCollision
}
detectCollisionOfMobileBricks();
// Detecting collision between ball and wall
if ((mBall.getRightX() >= State.getScreenHigherX()) //collided in the right wall
|| (mBall.getLeftX() <= State.getScreenLowerX())) //collided in the left wall
{
return Collision.WALL_RIGHT_LEFT_SIDE;
} else if ((mBall.getTopY() >= State.getScreenHigherY()) //collided in the top wall
|| (mBall.getBottomY() <= State.getScreenLowerY()) //collided in the bottom wall...
&& Difficult.INVINCIBILITY[sDifficult]) //and invincibility is on
{
return Collision.WALL_TOP_BOTTOM_SIDE;
} else if (mBall.getBottomY() <= State.getScreenLowerY() //if invincibility is off and the ball
&& !Difficult.INVINCIBILITY[sDifficult]) //collided with bottom wall, user loses a life
{
return Collision.LIFE_LOST;
}
//detecting collision between the ball and the paddle
if (mBall.getTopY() >= mPaddle.getBottomY() && mBall.getBottomY() <= mPaddle.getTopY() &&
mBall.getRightX() >= mPaddle.getLeftX() && mBall.getLeftX() <= mPaddle.getRightX())
{
return Collision.PADDLE_BALL;
}
// If the game is finished, there should be no bricks left
boolean gameFinish = true;
for (int i=0; i<mBricks.length; i++) {
for (int j=0; j<mBricks[i].length; j++) {
// Check if the brick is not destroyed yet
if(mBricks[i][j] != null) {
// If there are still bricks, the game is not over yet
gameFinish = false;
// Detecting collision between the ball and the bricks
if (mBall.getTopY() >= mBricks[i][j].getBottomY()
&& mBall.getBottomY() <= mBricks[i][j].getTopY()
&& mBall.getRightX() >= mBricks[i][j].getLeftX()
&& mBall.getLeftX() <= mBricks[i][j].getRightX()
)
{
Log.d(TAG, "Detected collision between ball and brick[" + i + "][" + j + "]");
/* Since the update happens so fast (on each draw frame) we can update the brick
* state on the next frame. */
if (mBricks[i][j].getLives() == 0) {
if (mBricks[i][j].getType() == Type.EXPLOSIVE) {
Log.d(TAG, "inserted explosion");
mExplosions.add(new Explosion
(Brick.GRAY_EXPLOSION_SIZE, mBricks[i][j].getPosX(), mBricks[i][j].getPosY()));
// Explosive brick is a special type of collision, treat this case
explosiveBrick(i, j);
return Collision.EX_BRICK_BALL;
} else if (mBricks[i][j].getType() == Type.MOBILE){
deleteMobileBrick(i, j);
}
mBricks[i][j] = null; // Deleting brick
} else {
decrementBrickLife(i, j);
}
return Collision.BRICK_BALL;
}
}
}
}
// If there is no more blocks, the game is over
State.setGameOver(gameFinish);
return Collision.NOT_AVAILABLE;
}
public void deleteMobileBrick(int i, int j) {
for (int a = 0; a < mMobileBricks.size(); a++) {
if (mMobileBricks.get(a).equal(i, j)) {
mMobileBricks.remove(a);
return;
}
}
}
/**
* Represents the game state, like the actual game score and multiplier, number of lives and
* if the game is over or not.
*
* This class should be static since we need to access these informations outside the game object,
* like on UI activity.
*/
public static class State {
private static long sScore;
private static int sScoreMultiplier;
private static int sLives;
private static boolean sGameOver;
private static float sScreenHigherY;
private static float sScreenLowerY;
private static float sScreenHigherX;
private static float sScreenLowerX;
private static boolean sGamePaused;
public static void setScore (Score event) {
switch(event) {
case BRICK_HIT:
sScore += Difficult.HIT_SCORE[sDifficult] * getScoreMultiplier();
break;
case RESTART_LEVEL:
sScore = 0;
break;
case EX_BRICK_HIT:
sScore += Difficult.HIT_SCORE[sDifficult] * 2 * getScoreMultiplier();
break;
}
}
public static void setScoreMultiplier(ScoreMultiplier event) {
switch(event) {
case RESTART_LEVEL:
case LOST_LIFE:
sScoreMultiplier = 1;
break;
case BRICK_HIT:
if (sScoreMultiplier < Difficult.MAX_SCORE_MULTIPLIER[sDifficult]) {
sScoreMultiplier *= 2;
}
break;
case PADDLE_HIT:
if (sScoreMultiplier > 1) {
sScoreMultiplier /= 2;
}
break;
}
}
public static void setLives(Lives event) {
switch(event) {
case RESTART_LEVEL:
sGameOver = false;
sLives = Difficult.LIFE_STOCK[sDifficult];
break;
case LOST_LIFE:
if (sLives > 0) {
sLives
} else {
sGameOver = true;
}
break;
}
}
public static void setGameOver(boolean gameIsOver) {
sGameOver = gameIsOver;
}
public static void setGamePaused(boolean gamePaused) {
sGamePaused = gamePaused;
}
public static boolean getGameOver() {
return sGameOver;
}
public static boolean getGamePaused() {
return sGamePaused;
}
public static long getScore() {
return sScore;
}
public static int getScoreMultiplier() {
return sScoreMultiplier;
}
public static int getLifes() {
return sLives;
}
public static float getScreenLowerX() {
return sScreenLowerX;
}
public static float getScreenHigherX() {
return sScreenHigherX;
}
public static float getScreenLowerY() {
return sScreenLowerY;
}
public static float getScreenHigherY() {
return sScreenHigherY;
}
public static void setScreenMeasures(float screenWidth, float screenHeight) {
/* Calculate the new screen measure. This is important since we need to delimit a wall
* to the ball. */
sScreenLowerX = SCREEN_INITIAL_X - screenWidth/2;
sScreenHigherX = SCREEN_INITIAL_X + screenWidth/2;
sScreenLowerY = SCREEN_INITIAL_Y - screenHeight/2;
sScreenHigherY = SCREEN_INITIAL_Y + screenHeight/2;
}
}
}
|
package fi_81.cwp_morse_mangle.morse;
import java.util.ArrayList;
/*
* Bit format string, originally implemented with BitSet as backing buffer, but as
* it appeared to be too slow (profiling results on Motorola Defy+), reverted to String.
*/
public class BitString implements Comparable<BitString>, CharSequence {
private String bits;
/* Format input to BitString */
private static String makeBits(CharSequence chars) {
int i, len;
/* Check if can accept input as is */
for (i = 0, len = chars.length(); i < len; i++) {
char ch = chars.charAt(i);
if (ch != '0' && ch != '1')
break;
}
if (i == len) {
/* Already in correct bit-format */
return chars.toString();
}
StringBuffer sb = localStringBuffer.get();
sb.setLength(0);
sb.append(chars, 0, i);
for (; i < len; i++) {
char ch = chars.charAt(i);
sb.append(ch == '1' ? '1' : '0');
}
return sb.toString();
}
/* Internal constructor for buffer that already is in bit-format */
private BitString(String str, boolean alreadyBits) {
if (alreadyBits)
bits = str;
else
this.bits = makeBits(str);
}
/* Public constructor */
public BitString(CharSequence chars) {
this.bits = makeBits(chars);
}
/* Empty constructor */
public BitString() {
this.bits = "";
}
/*
* Helper builders
*/
public static BitString newFilled(char oneOrZero, int numChars) {
StringBuffer sb = localStringBuffer.get();
sb.setLength(0);
for (int i = 0; i < numChars; i++)
sb.append(oneOrZero);
return new BitString(sb.toString(), true);
}
public static BitString newZeros(int numZeros) {
return newFilled('0', numZeros);
}
public static BitString newOnes(int numOnes) {
return newFilled('1', numOnes);
}
public static BitString newBits(String onesAndZeros) {
return new BitString(onesAndZeros, true);
}
@Override
public char charAt(int index) {
return bits.charAt(index);
}
@Override
public int length() {
return bits.length();
}
@Override
public CharSequence subSequence(int start, int end) {
return bits.subSequence(start, end);
}
@Override
public int compareTo(BitString another) {
return bits.compareTo(another.bits);
}
@Override
public String toString() {
return bits;
}
public BitString substring(int start, int end) {
return new BitString(bits.substring(start, end), true);
}
/* Check if object is same as this. */
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof BitString))
return false;
BitString obs = (BitString) o;
return (bits == null ? obs.bits == null : bits.equals(obs.bits));
}
/** Append another BitString at end of this and return resulting BitString */
public BitString append(BitString endBits) {
StringBuffer sb = localStringBuffer.get();
sb.setLength(0);
sb.append(bits);
sb.append(endBits.bits);
return new BitString(sb.toString(), true);
}
public BitString[] split(BitString splitString) {
/* Emulate String.split() as closely as possible */
int stringLength = bits.length();
int splitStringLength = splitString.bits.length();
/*
* Empty string gives array with one cell, and that cell is empty
* string.
*/
if (stringLength == 0) {
BitString array[] = new BitString[1];
array[0] = this;
return array;
}
ArrayList<BitString> list = localArrayList.get();
int idx = 0, prev = 0;
list.clear();
/* Iterate through all split strings and copy to array */
while ((idx = bits.indexOf(splitString.bits, idx)) >= 0) {
list.add(new BitString(bits.substring(prev, idx), true));
if (splitStringLength > 0)
idx += splitStringLength;
else
idx++; /* Avoid endless loop */
prev = idx;
}
/* Finally, copy the last split string */
idx = stringLength;
list.add(new BitString(bits.substring(prev, idx), true));
BitString splits[] = new BitString[list.size()];
list.toArray(splits);
list.clear();
return splits;
}
public boolean endWith(BitString suffix) {
return bits.endsWith(suffix.bits);
}
/* static ThreadLocal helpers for thread-safe preallocation */
private static final ThreadLocal<StringBuffer> localStringBuffer = new ThreadLocal<StringBuffer>() {
@Override
protected StringBuffer initialValue() {
return new StringBuffer();
}
};
private static final ThreadLocal<ArrayList<BitString>> localArrayList = new ThreadLocal<ArrayList<BitString>>() {
@Override
protected ArrayList<BitString> initialValue() {
return new ArrayList<BitString>();
}
};
}
|
package com.psddev.dari.util;
import java.util.concurrent.locks.ReadWriteLock;
/**
* For making sure that something runs only once safely and efficiently.
*
* <p>Typical usage looks like:</p>
*
* <p><blockquote><code>
* public class Foo {
* private static final Once INIT_ONCE = new Once() {
* {@literal @}Override
* protected void run() {
* // Do something.
* }
* }
*
* private void bar() {
* INIT_ONCE.ensure();
* // Do something else that depends on the init.
* }
* }
* </code></blockquote></p>
*/
public abstract class Once {
private volatile boolean ran;
/**
* Creates an instance.
*
* @param lock Not used.
* @deprecated Use {@link Once()} instead.
*/
@Deprecated
public Once(ReadWriteLock lock) {
}
/**
* Creates an instance.
*/
public Once() {
}
/**
* Runs some code.
*/
protected abstract void run() throws Exception;
/**
* Ensures that {@link #run} has been called at least once.
*/
public final void ensure() {
if (Thread.holdsLock(this)) {
return;
}
if (!ran) {
synchronized (this) {
if (!ran) {
try {
run();
ran = true;
} catch (Exception error) {
ErrorUtils.rethrow(error);
}
}
}
}
}
/**
* Resets so that the next invocation of {@link #ensure} can call
* {@link #run} again.
*/
public final void reset() {
synchronized (this) {
ran = false;
}
}
}
|
package thinwire.render.web;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import thinwire.render.web.WebApplication.Timer;
import thinwire.ui.Dialog;
import thinwire.ui.Frame;
import thinwire.ui.event.PropertyChangeEvent;
import thinwire.ui.event.PropertyChangeListener;
class ApplicationEventListener implements WebComponentListener {
private static final Logger log = Logger.getLogger(ApplicationEventListener.class.getName());
private static final Level LEVEL = Level.FINER;
static final Integer ID = new Integer(Integer.MAX_VALUE);
//private static final String SHUTDOWN_INSTANCE = "tw_shutdownInstance";
private static final String INIT = "INIT";
private static final String STARTUP = "STARTUP";
private static final String REPAINT = "REPAINT";
static final String SHUTDOWN = "SHUTDOWN";
private static final String RUN_TIMER = "RUN_TIMER";
private static final class StartupInfo {
String mainClass;
String[] args;
StartupInfo(String mainClass, String[] args) {
this.mainClass = mainClass;
this.args = args;
}
}
static final WebComponentEvent newRunTimerEvent(String timerId) {
return new WebComponentEvent(ID, RUN_TIMER, timerId);
}
static final WebComponentEvent newInitEvent() {
return new WebComponentEvent(ID, INIT, null);
}
static final WebComponentEvent newStartEvent(String mainClass, String[] args) {
if (mainClass == null || mainClass.length() == 0) throw new IllegalArgumentException("The init-param 'mainClass' is required and must point to your application's entry point");
StartupInfo info = new StartupInfo(mainClass, args);
return new WebComponentEvent(ID, STARTUP, info);
}
static final WebComponentEvent newRepaintEvent() {
return new WebComponentEvent(ID, REPAINT, null);
}
static final WebComponentEvent newShutdownEvent() {
return new WebComponentEvent(ID, SHUTDOWN, null);
}
private WebApplication app;
ApplicationEventListener(WebApplication app) {
this.app = app;
}
public void componentChange(WebComponentEvent event) {
String name = event.getName();
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": handling application event name=" + name);
if (INIT.equals(name)) {
app.sendStyleInitInfo();
Frame f = app.getFrame();
f.setVisible(true);
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": testing synchornized client-side call by retrieving client time");
String time = app.clientSideFunctionCallWaitForReturn("tw_getTime");
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": client time in milliseconds is " + time);
//When the frame is set to non-visible, fire a shutdown event
f.addPropertyChangeListener(Frame.PROPERTY_VISIBLE, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent pce) {
if (pce.getNewValue() == Boolean.FALSE) {
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": frame visibility set to false, signaling shutdown");
app.signalShutdown();
}
}
});
} else if (STARTUP.equals(name)) {
ApplicationEventListener.StartupInfo info = (ApplicationEventListener.StartupInfo)event.getValue();
try {
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": calling entry point class=" + info.mainClass);
Class clazz = Class.forName(info.mainClass);
clazz.getMethod("main", new Class[] { String[].class }).invoke(clazz, new Object[] { info.args });
} catch (Exception e) {
Throwable th = e;
while (th.getCause() != null) th = th.getCause();
if (th instanceof EventProcessor.GracefulShutdown) {
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": graceful shutdown from entry point main: " + info.mainClass);
} else {
if (!(e instanceof RuntimeException)) e = new RuntimeException(e);
throw (RuntimeException)e;
}
}
} else if (REPAINT.equals(name)) {
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": repainting the application frame");
app.sendStyleInitInfo();
Frame f = app.getFrame();
WindowRenderer fr = app.getWindowRenderer(f);
app.sendDefaultComponentStyles(fr);
fr.render(fr, f, null);
for (Dialog d : f.getDialogs()) {
WindowRenderer dr = app.getWindowRenderer(d);
dr.render(dr, d, fr);
}
} else if (SHUTDOWN.equals(name)) {
Frame f = app.getFrame();
if (f.isVisible()) {
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": shutdown event changing frame visibility to false");
boolean captured = false;
for (Dialog d : f.getDialogs()) {
if (d.isWaitForWindow()) captured = true;
}
//TODO Depends on this listener being the last listener executed once we toggle visibility of frame to false
//This code attempts to force an exception that won't be caught so that the call stack unrolls properly in
//cases where a waitForWindow dialog is in use. It's important that this execute as the last listener so
//that all other visibility listeners have a chance to execute properly.
if (captured) {
f.addPropertyChangeListener(Frame.PROPERTY_VISIBLE, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent pce) {
if (pce.getNewValue() == Boolean.FALSE) {
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": attempting to unroll stack naturally since their is a waitForWindow Dialog");
throw new EventProcessor.GracefulShutdown();
}
}
});
}
f.setVisible(false);
} else {
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": shutdown event doesn't need to do anything, frame already has visible set to false");
}
} else if (RUN_TIMER.equals(name)) {
String timerId = (String)event.getValue();
Timer timer = app.timerMap.get(timerId);
if (log.isLoggable(LEVEL)) log.log(LEVEL, Thread.currentThread().getName() + ": attempting to run timerId=" + timerId +
", timer=" + timer + (timer == null ? "" : ",repeat=" + timer.repeat));
if (timer != null) {
timer.task.run();
if (timer.repeat) {
app.resetTimerTask(timer.task);
} else {
app.removeTimerTask(timer.task);
}
}
}
}
}
|
package core.index.key;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.primitives.Bytes;
import core.utils.BinaryUtils;
import core.utils.Pair;
import core.utils.RangeUtils.SimpleDateRange.SimpleDate;
import core.utils.SchemaUtils.TYPE;
import core.utils.TypeUtils;
/**
* A class to collect a set of keys during index building.
* Example use case is to collect samples before inserting them into an index structure.
*
* @author alekh
*
*/
public class CartilageIndexKeySet {
private List<Object[]> values;
private TYPE[] types;
private int sampleSize;
/**
* Create an empty key set.
*/
public CartilageIndexKeySet() {
values = Lists.newArrayList();
sampleSize = 0;
}
/**
* Instantiate a key set with a given set of keys.
* @param values
*/
public CartilageIndexKeySet(List<Object[]> values, TYPE[] types) {
this.values = values;
this.types = types;
this.sampleSize = 0;
}
/**
* Insert into the key set.
* @param key
*/
public void insert(CartilageIndexKey key){
if(types==null)
this.types = key.types;
Object[] keyValues = new Object[types.length];
for(int i=0; i<types.length; i++){
switch(types[i]){
case INT: keyValues[i] = key.getIntAttribute(i);
break;
case LONG: keyValues[i] = key.getLongAttribute(i);
break;
case FLOAT: keyValues[i] = key.getFloatAttribute(i);
break;
case DATE: keyValues[i] = key.getDateAttribute(i);
break;
case STRING: keyValues[i] = key.getStringAttribute(i,20);
break;
case VARCHAR: break; // skip partitioning on varchar attribute
default: throw new RuntimeException("Unknown dimension type: "+key.types[i]);
}
}
values.add(keyValues);
sampleSize++;
}
/**
* Return the last entry in the keyset
*/
public Object getLast(int dim) {
assert values.size() > 0;
assert dim < types.length;
return values.get(values.size() - 1)[dim];
}
// TODO: Make this compatible with the one in TypeUtils
public Comparator<Object[]> getComparatorForType(TYPE type, final int attributeIdx) {
switch(type){
case INT:
return new Comparator<Object[]> (){
public int compare(Object[] o1, Object[] o2) {
return ((Integer)o1[attributeIdx]).compareTo((Integer)o2[attributeIdx]);
}
};
case LONG:
return new Comparator<Object[]> (){
public int compare(Object[] o1, Object[] o2) {
return ((Long)o1[attributeIdx]).compareTo((Long)o2[attributeIdx]);
}
};
case FLOAT:
return new Comparator<Object[]> (){
public int compare(Object[] o1, Object[] o2) {
return ((Float)o1[attributeIdx]).compareTo((Float)o2[attributeIdx]);
}
};
case DATE:
return new Comparator<Object[]> (){
public int compare(Object[] o1, Object[] o2) {
return ((SimpleDate)o1[attributeIdx]).compareTo((SimpleDate)o2[attributeIdx]);
}
};
case STRING:
return new Comparator<Object[]> (){
public int compare(Object[] o1, Object[] o2) {
return ((String)o1[attributeIdx]).compareTo((String)o2[attributeIdx]);
}
};
case VARCHAR:
throw new RuntimeException("sorting over varchar is not supported"); // skip partitioning on varchar attribute
default:
throw new RuntimeException("Unknown dimension type: "+ type);
}
}
/**
* Sort the key set on the given attribute.
*
* @param attributeIdx -- the index of the sort attribute relative to the key attributes.
*
* Example -- if we have 5 attributes ids (0,1,2,3,4) and we extract 3 of them
* in the CartilageIndexKey, e.g. (1,3,4) and now if we want to sort on attribute
* 3 then the attributeIdx parameter will pass 1 (sorting on the second key attribute).
*
*/
public void sort(final int attributeIdx){
final TYPE sortType = types[attributeIdx];
Collections.sort(values, this.getComparatorForType(sortType, attributeIdx));
}
/**
* Split this key set into two equal sized key sets.
* If the length is odd, the extra value goes in the second set.
* This function assumes that the key set has already been sorted.
*
* Note that we do not copy the keys into a new object (we simply create a view using the subList() method).
* Therefore, the original key set must not be destroyed after the split.
*
* @return
*/
public Pair<CartilageIndexKeySet,CartilageIndexKeySet> splitInTwo(){
CartilageIndexKeySet k1 = new CartilageIndexKeySet(values.subList(0, values.size()/2), types);
CartilageIndexKeySet k2 = new CartilageIndexKeySet(values.subList(values.size()/2, values.size()), types);
return new Pair<CartilageIndexKeySet,CartilageIndexKeySet>(k1,k2);
}
/**
* Split this key set by the median on the specified attribute.
* All keys with the specified attribute equal to the median go in the second set.
* @return
*/
public Pair<CartilageIndexKeySet,CartilageIndexKeySet> splitByMedian(int attributeIdx) {
Object medianVal = values.get(values.size()/2)[attributeIdx];
int firstIndex = getFirstIndexOfAttributeVal(attributeIdx, types[attributeIdx], medianVal, values, 0);
CartilageIndexKeySet k1 = new CartilageIndexKeySet(values.subList(0, firstIndex), types);
CartilageIndexKeySet k2 = new CartilageIndexKeySet(values.subList(firstIndex, values.size()), types);
return new Pair<CartilageIndexKeySet,CartilageIndexKeySet>(k1,k2);
}
/**
* Split this key set by the value on the specified attribute.
* @return
*/
public Pair<CartilageIndexKeySet,CartilageIndexKeySet> splitAt(int attributeIdx, Object value) {
final TYPE sortType = types[attributeIdx];
Comparator<Object> comp = TypeUtils.getComparatorForType(sortType);
// Finds the least k such that k >= value
int lo = 0;
int hi = values.size() - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
Object midVal = this.values.get(mid)[attributeIdx];
if (comp.compare(value, midVal) < 0) hi = mid;
else lo = mid + 1;
}
CartilageIndexKeySet k1 = new CartilageIndexKeySet(values.subList(0, lo), types);
CartilageIndexKeySet k2 = new CartilageIndexKeySet(values.subList(lo, values.size()), types);
return new Pair<CartilageIndexKeySet,CartilageIndexKeySet>(k1,k2);
}
private static int getFirstIndexOfAttributeVal(int attributeIdx, TYPE type, Object val, List<Object[]> sublist, int start) {
if (sublist.size() == 0) {
return -1;
}
Object middle = sublist.get(sublist.size()/2)[attributeIdx];
int comparison;
switch(type) {
case INT: comparison = ((Integer)middle).compareTo((Integer)val); break;
case LONG: comparison = ((Long)middle).compareTo((Long)val); break;
case FLOAT: comparison = ((Float)middle).compareTo((Float)val); break;
case DATE: comparison = ((SimpleDate)middle).compareTo((SimpleDate)val); break;
case STRING: comparison = ((String)middle).compareTo((String)val); break;
case VARCHAR: throw new RuntimeException("sorting over varchar is not supported"); // skip partitioning on varchar attribute
default: throw new RuntimeException("Unknown dimension type: "+type);
}
if (comparison == 0) {
int firstIndex = getFirstIndexOfAttributeVal(attributeIdx, type, val, sublist.subList(0,sublist.size()/2), start);
if (firstIndex == -1) {
return start + sublist.size()/2;
} else {
return firstIndex;
}
} else if (comparison > 0) {
return getFirstIndexOfAttributeVal(attributeIdx, type, val, sublist.subList(0,sublist.size()/2), start);
} else {
return getFirstIndexOfAttributeVal(attributeIdx, type, val, sublist.subList(sublist.size()/2+1, sublist.size()), start+sublist.size()/2+1);
}
}
/**
* Sort and then split the key set.
* @param attributeIdx
* @return
*/
public Pair<CartilageIndexKeySet,CartilageIndexKeySet> sortAndSplit(final int attributeIdx){
sort(attributeIdx);
return splitByMedian(attributeIdx);
}
public List<Object[]> getValues(){
return values;
}
public void addValues(List<Object[]> e) {
this.values.addAll(e);
}
public void setTypes(TYPE[] types) {
this.types = types;
}
public TYPE[] getTypes() {
return this.types;
}
public int size() { return values.size(); }
public void reset(){
values = Lists.newArrayList();
types = null;
}
/**
* Iterate over the keys in the key set.
* @return
*/
public KeySetIterator iterator(){
return new KeySetIterator(values);
}
/**
* An iterator to iterate over the key in a key set.
* The Iterator returns an instance of ParsedIndexKey which extends CartilageIndexKey.
*
* @author alekh
*
*/
public static class KeySetIterator implements Iterator<CartilageIndexKey>{
private Iterator<Object[]> valueItr;
private ParsedIndexKey key;
public KeySetIterator(List<Object[]> values){
this.valueItr = values.iterator();
key = new ParsedIndexKey();
}
public boolean hasNext() {
return valueItr.hasNext();
}
public CartilageIndexKey next() {
key.setValues(valueItr.next());
return key;
}
public void remove() {
next();
}
}
public byte[] marshall(){
List<byte[]> byteArrays = Lists.newArrayList();
byteArrays.add(Joiner.on(",").join(types).getBytes());
byteArrays.add(new byte[]{'\n'});
int initialSize = sampleSize * 100; // assumption: each record could be of max size 100 bytes
byte[] recordBytes = new byte[initialSize];
int offset = 0;
for(Object[] v: values){
byte[] vBytes = Joiner.on(",").join(v).getBytes();
if(offset + vBytes.length + 1 < recordBytes.length){
byteArrays.add(recordBytes);
recordBytes = new byte[initialSize];
offset = 0;
}
BinaryUtils.append(recordBytes, offset, vBytes);
offset += vBytes.length;
recordBytes[offset++] = '\n';
}
byte[][] finalByteArrays = new byte[byteArrays.size()][];
for(int i=0; i<finalByteArrays.length; i++)
finalByteArrays[i] = byteArrays.get(i);
return Bytes.concat(finalByteArrays);
}
public void unmarshall(byte[] bytes){
CartilageIndexKey record = new CartilageIndexKey(',');
int offset=0, previous=0;
for ( ; offset<bytes.length; offset++ ){
if(bytes[offset]=='\n'){
byte[] lineBytes = ArrayUtils.subarray(bytes, previous, offset);
if(previous==0){
String[] tokens = new String(lineBytes).split(",");
this.types = new TYPE[tokens.length];
for(int i=0;i <tokens.length; i++)
types[i] = TYPE.valueOf(tokens[i]);
}
else{
record.setBytes(lineBytes);
insert(record);
}
previous = ++offset;
}
}
}
}
|
package org.jpos.qi;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.*;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.ValoTheme;
import org.jdom2.DataConversionException;
import org.jdom2.Element;
import org.jpos.core.ConfigurationException;
import org.jpos.ee.DB;
import org.jpos.ee.User;
import org.jpos.ee.Visitor;
import org.jpos.ee.VisitorManager;
import org.jpos.iso.ISOUtil;
import org.jpos.q2.Q2;
import org.jpos.q2.qbean.QXmlConfig;
import org.jpos.qi.login.LoginView;
import org.jpos.util.Log;
import org.jpos.util.NameRegistrar;
import javax.servlet.http.Cookie;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;
@Theme("jpos")
@Title("jPOS")
public class QI extends UI {
private Locale locale;
private List<Element> availableLocales;
private HashMap<Locale,SortedMap<String,Object>> messagesMap;
private List<Element> messageFiles;
private Log log;
private Q2 q2;
private static final String CONFIG_NAME = "QI";
private static final long CONFIG_TIMEOUT = 5000L;
private static ThreadLocal<DB> tldb = new ThreadLocal<>();
private HashMap<String,ViewConfig> views;
private Visitor visitor;
private QILayout qiLayout;
private Header header;
private Sidebar sidebar;
private LoginView loginView;
public QI() {
locale = Locale.getDefault();
log = Log.getLog(Q2.LOGGER_NAME, "QI");
qiLayout = new QILayout();
views = new HashMap<>();
try {
q2 = (Q2) NameRegistrar.get("Q2");
} catch (NameRegistrar.NotFoundException e) {
throw new IllegalStateException ("Q2 not available");
}
messagesMap = new HashMap<>();
}
private void parseMessages() {
Properties master = new Properties();
for (Element element: availableLocales) {
String localeCode = element.getValue();
Locale l = Locale.forLanguageTag(localeCode);
Iterator<Element> iterator = messageFiles.iterator();
if (iterator.hasNext()) {
String masterName = iterator.next().getValue();
try {
master.load(getClass().getResourceAsStream("/" + masterName.concat("_" + localeCode + ".properties")));
while (iterator.hasNext()) {
Properties additionalProp = new Properties();
String additionalName = iterator.next().getValue();
additionalProp.load(getClass().getResourceAsStream("/" + additionalName.concat("_" + localeCode + ".properties")));
master.putAll(additionalProp);
}
} catch (NullPointerException n) {
//Log but continue
//Show notification only if main locale is faulty
if (locale.toString().equals(localeCode))
displayNotification("Invalid locale '" + localeCode +"' : check configuration");
log.error(ErrorMessage.SYSERR_INVALID_LOCALE);
} catch (IOException e) {
//Log but continue.
//Show notification only if main locale is faulty
if (locale.toString().equals(localeCode))
displayNotification("Invalid locale '" + localeCode +"' : check configuration");
log.error(ErrorMessage.SYSERR_INVALID_LOCALE);
}
TreeMap<String, Object> treeMap = new TreeMap<>((Map) master);
messagesMap.put(l, treeMap);
}
}
}
@Override
protected void init(VaadinRequest request) {
Element cfg = getXmlConfiguration();
if (cfg != null) {
setContent(qiLayout);
setResponsive(true);
addStyleName(ValoTheme.UI_WITH_MENU);
init(request, cfg);
try (DB db = new DB()) {
db.open();
db.beginTransaction();
visitor = getVisitor(db);
User user = getUser();
if (user == null) {
user = visitor.getUser();
if (user != null) {
setUser(user);
}
}
if (user == null || !user.isActive())
createLoginView();
else
createMainView();
db.commit();
}
}
}
public String getMessage (String id, Object... obj) {
if (messagesMap.containsKey(locale)) {
SortedMap map = messagesMap.get(locale);
MessageFormat mf = new MessageFormat((String) map.getOrDefault(id, id));
mf.setLocale(locale);
return mf.format(obj);
}
return id;
}
public String getMessage (ErrorMessage em) {
if (messagesMap.containsKey(locale)) {
SortedMap map = messagesMap.get(locale);
return (String) map.getOrDefault(em.getPropertyName(), em.getDefaultMessage());
}
return em.getPropertyName();
}
public String getMessage (ErrorMessage em, Object... obj) {
System.out.println("messagesMap: " + messagesMap);
if (messagesMap.containsKey(locale)) {
SortedMap map = messagesMap.get(locale);
String format = (String) map.getOrDefault(em.getPropertyName(), em.getDefaultMessage());
MessageFormat mf = new MessageFormat(format, locale);
return mf.format(obj);
}
return em.getPropertyName();
}
@SuppressWarnings("unused")
private void init (VaadinRequest vr, Element cfg) {
String title = cfg.getChildText("title");
String theme = cfg.getChildText("theme");
String logger = cfg.getAttributeValue("logger");
messageFiles = cfg.getChildren("messages");
if (logger != null) {
String realm = cfg.getAttributeValue("realm");
log = Log.getLog(logger, realm != null ? realm : "QI");
}
if (title != null)
getPage().setTitle(title);
if (theme != null) {
setTheme(theme);
}
//Get all the available locales
//The first one will be the default.
availableLocales = cfg.getChildren("locale");
if (availableLocales.size() > 0) {
String localeName = availableLocales.get(0).getValue();
if (localeName != null) {
Locale l = Locale.forLanguageTag(localeName);
if (l.hashCode() == 0) {
Notification.show(
getMessage(ErrorMessage.SYSERR_INVALID_LOCALE, localeName),
Notification.Type.ERROR_MESSAGE);
} else {
locale = l;
}
}
}
parseMessages();
}
public Log getLog() {
return log;
}
public void displayNotification (String message) {
Notification n = new Notification(message,Notification.Type.TRAY_NOTIFICATION);
n.setHtmlContentAllowed(true);
n.show(Page.getCurrent());
}
public void displayNotificationMessage (String message) {
Notification n = new Notification(getMessage(message),Notification.Type.TRAY_NOTIFICATION);
n.setHtmlContentAllowed(true);
n.show(Page.getCurrent());
}
public void displayError (String error, String detail, Object... obj) {
Notification.show(
getMessage(error),
getMessage(detail, obj),
Notification.Type.ERROR_MESSAGE
);
}
public void login (User user, boolean rememberMe) {
setUser(user);
try (DB db = new DB()) {
db.open();
db.beginTransaction();
db.session().refresh(user);
db.session().refresh(visitor);
if (rememberMe)
visitor.setUser(user);
String users = visitor.getProps().get("USERS");
users = users == null ? "" : users;
if (!users.contains(user.getNickAndId())) {
if (users.length() > 0)
users = users + ",";
visitor.getProps().put("USERS", users + user.getNickAndId());
}
user.setLastLogin(new Date());
db.session().update(visitor);
db.session().update(user);
db.commit();
}
getLog().info(String.format(
"LOGIN user=%s[id=%d], visitor='%s'%s",
user.getNick(),
user.getId(),
ISOUtil.protect(visitor.getId()),
rememberMe ? ", remember=yes" : ""));
qiLayout.getContentLayout().removeComponent(loginView);
createMainView();
String fragment = UI.getCurrent().getPage().getUriFragment();
if (fragment != null && !fragment.isEmpty() && fragment.startsWith("!"))
navigateTo(fragment.substring(1));
}
void logout() {
qiLayout.removeAllComponents();
getSession().close();
if (visitor.getUser() != null) {
try (DB db = new DB()) {
db.open();
db.beginTransaction();
db.session().refresh(visitor);
visitor.setUser(null);
db.session().update(visitor);
db.commit();
}
}
getUI().getPage().setLocation("/");
// Invalidate underlying session instead if login info is stored there
// VaadinService.getCurrentRequest().getWrappedSession().invalidate();
// Redirect to avoid keeping the removed UI open in the browser
// createLoginView();
}
public User getUser() {
try {
VaadinSession.getCurrent().getLockInstance().lock();
return VaadinSession.getCurrent().getAttribute(User.class);
} finally {
VaadinSession.getCurrent().getLockInstance().unlock();
}
}
public void setUser (User user) {
// Store user in VaadinSession.
if (user != null) {
try {
VaadinSession.getCurrent().getLockInstance().lock();
if (VaadinSession.getCurrent().getAttribute(User.class) == null)
VaadinSession.getCurrent().setAttribute(User.class, user);
} finally {
VaadinSession.getCurrent().getLockInstance().unlock();
}
}
}
public static QI getQI() {
return (QI) UI.getCurrent();
}
public static DB getDB() {
DB db = tldb.get();
if (db == null) {
db = new DB();
db.open();
tldb.set(db);
}
return db;
}
static void closeDB() {
DB db = tldb.get();
if (db != null) {
db.close();
tldb.remove();
}
}
void navigateTo(String navigationState) {
getNavigator().navigateTo(navigationState);
}
Element getXmlConfiguration() {
Element cfg = QXmlConfig.getConfiguration (CONFIG_NAME, CONFIG_TIMEOUT);
if (cfg == null) {
Notification.show(getMessage(ErrorMessage.SYSERR_CONFIG_NOT_FOUND), Notification.Type.ERROR_MESSAGE);
return null;
}
return cfg;
}
Sidebar sidebar() {
return sidebar;
}
private void createLoginView () {
qiLayout.getContentLayout().addComponent(loginView = new LoginView());
}
private Visitor getVisitor(DB db) {
VaadinRequest request = VaadinService.getCurrentRequest();
Cookie[] cookies = request.getCookies();
if (cookies == null)
cookies = new Cookie[0];
VisitorManager vmgr = new VisitorManager(db, cookies);
Visitor v = vmgr.getVisitor(true);
if (v != null) {
vmgr.set (v, "IP", request.getRemoteAddr());
vmgr.set (v,"HOST", request.getRemoteHost());
}
VaadinService.getCurrentResponse().addCookie(vmgr.getCookie());
return v;
}
private void createMainView() {
setNavigator(new QINavigator(this, qiLayout.getContentLayout()));
if (qiLayout.getHeaderLayout() != null) {
header = new Header(this);
qiLayout.getHeaderLayout().addComponent(header);
}
sidebar = new Sidebar();
if (sidebar.isEnabled()) {
qiLayout.addMenu(sidebar);
Page.getCurrent().addBrowserWindowResizeListener(
(Page.BrowserWindowResizeListener) event -> {
if (sidebar != null && event.getWidth() < 1100)
sidebar.expandSidebar();
});
}
if (getUser().isForcePasswordChange())
navigateTo("/users/" + getUser().getId() + "/profile/password_change");
}
public Header getHeader() {
return header;
}
public HashMap<String, ViewConfig> getViews() {
return views;
}
public void setViews(HashMap<String, ViewConfig> views) {
this.views = views;
}
void addView(String route, Element e) {
ViewConfig vc = new ViewConfig();
try {
vc.setXmlElement(e);
vc.setConfiguration(getQ2().getFactory().getConfiguration(e));
this.views.put(route, vc);
} catch (ConfigurationException | DataConversionException exc) {
getLog().warn(exc);
}
}
public ViewConfig getView(String route) {
return views.get(route);
}
public Q2 getQ2() {
return q2;
}
}
|
package de.felixbruns.jotify.crypto;
public class Shannon {
/*
* Fold is how many register cycles need to be performed after combining the
* last byte of key and non-linear feedback, before every byte depends on every
* byte of the key. This depends on the feedback and nonlinear functions, and
* on where they are combined into the register. Making it same as the register
* length is a safe and conservative choice.
*/
private static final int N = 16;
private static final int FOLD = N; /* How many iterations of folding to do. */
private static final int INITKONST = 0x6996c53a; /* Value of konst to use during key loading. */
private static final int KEYP = 13; /* Where to insert key/MAC/counter words. */
private int[] R; /* Working storage for the shift register. */
private int[] CRC; /* Working storage for CRC accumulation. */
private int[] initR; /* Saved register contents. */
private int konst; /* Key dependant semi-constant. */
private int sbuf; /* Encryption buffer. */
private int mbuf; /* Partial word MAC buffer. */
private int nbuf; /* Number of part-word stream bits buffered. */
public Shannon(){
/* Registers with length N. */
this.R = new int[N];
this.CRC = new int[N];
this.initR = new int[N];
}
/* Nonlinear transform (sbox) of a word. There are two slightly different combinations. */
private int sbox(int i){
i ^= Integer.rotateLeft(i, 5) | Integer.rotateLeft(i, 7);
i ^= Integer.rotateLeft(i, 19) | Integer.rotateLeft(i, 22);
return i;
}
private int sbox2(int i){
i ^= Integer.rotateLeft(i, 7) | Integer.rotateLeft(i, 22);
i ^= Integer.rotateLeft(i, 5) | Integer.rotateLeft(i, 19);
return i;
}
/* Cycle the contents of the register and calculate output word in sbuf. */
private void cycle(){
/* Temporary variable. */
int t;
/* Nonlinear feedback function. */
t = this.R[12] ^ this.R[13] ^ this.konst;
t = this.sbox(t) ^ Integer.rotateLeft(this.R[0], 1);
/* Shift register. */
for(int i = 1; i < N; i++){
this.R[i - 1] = this.R[i];
}
this.R[N - 1] = t;
t = sbox2(this.R[2] ^ this.R[15]);
this.R[0] ^= t;
this.sbuf = t ^ this.R[8] ^ this.R[12];
}
/*
* The Shannon MAC function is modelled after the concepts of Phelix and SHA.
* Basically, words to be accumulated in the MAC are incorporated in two
* different ways:
* 1. They are incorporated into the stream cipher register at a place
* where they will immediately have a nonlinear effect on the state.
* 2. They are incorporated into bit-parallel CRC-16 registers; the
* contents of these registers will be used in MAC finalization.
*/
/*
* Accumulate a CRC of input words, later to be fed into MAC.
* This is actually 32 parallel CRC-16s, using the IBM CRC-16
* polynomian x^16 + x^15 + x^2 + 1
*/
private void crcFunc(int i){
/* Temporary variable. */
int t;
/* Accumulate CRC of input. */
t = this.CRC[0] ^ this.CRC[2] ^ this.CRC[15] ^ i;
for(int j = 1; j < N; j++){
this.CRC[j - 1] = this.CRC[j];
}
this.CRC[N - 1] = t;
}
/* Normal MAC word processing: do both stream register and CRC. */
private void macFunc(int i){
this.crcFunc(i);
this.R[KEYP] ^= i;
}
/* Initialize to known state. */
private void initState(){
/* Register initialized to Fibonacci numbers. */
this.R[0] = 1;
this.R[1] = 1;
for(int i = 2; i < N; i++){
this.R[i] = this.R[i - 1] + this.R[i - 2];
}
/* Initialization constant. */
this.konst = INITKONST;
}
/* Save the current register state. */
private void saveState(){
for(int i = 0; i < N; i++){
this.initR[i] = this.R[i];
}
}
/* Inisialize to previously saved register state. */
private void reloadState(){
for(int i = 0; i < N; i++){
this.R[i] = this.initR[i];
}
}
/* Initialize 'konst'. */
private void genKonst(){
this.konst = this.R[0];
}
/* Load key material into the register. */
private void addKey(int k){
this.R[KEYP] ^= k;
}
/* Extra nonlinear diffusion of register for key and MAC. */
private void diffuse(){
for(int i = 0; i < FOLD; i++){
this.cycle();
}
}
/*
* Common actions for loading key material.
* Allow non-word-multiple key and nonce material.
* Note: Also initializes the CRC register as a side effect.
*/
private void loadKey(byte[] key){
byte[] extra = new byte[4];
int i, j;
int t;
/* Start folding key. */
for(i = 0; i < (key.length & ~0x03); i += 4){
/* Shift 4 bytes into one word. */
t = ((key[i + 3] & 0xFF) << 24) |
((key[i + 2] & 0xFF) << 16) |
((key[i + 1] & 0xFF) << 8) |
((key[i ] & 0xFF));
/* Insert key word at index 13. */
this.addKey(t);
/* Cycle register. */
this.cycle();
}
/* If there were any extra bytes, zero pad to a word. */
if(i < key.length){
/* i remains unchanged at start of loop. */
for(j = 0; i < key.length; i++){
extra[j++] = key[i];
}
/* j remains unchanged at start of loop. */
for(; j < 4; j++){
extra[j] = 0;
}
/* Shift 4 extra bytes into one word. */
t = ((extra[3] & 0xFF) << 24) |
((extra[2] & 0xFF) << 16) |
((extra[1] & 0xFF) << 8) |
((extra[0] & 0xFF));
/* Insert key word at index 13. */
this.addKey(t);
/* Cycle register. */
this.cycle();
}
/* Also fold in the length of the key. */
this.addKey(key.length);
/* Cycle register. */
this.cycle();
/* Save a copy of the register. */
for(i = 0; i < N; i++){
this.CRC[i] = this.R[i];
}
/* Now diffuse. */
this.diffuse();
/* Now XOR the copy back -- makes key loading irreversible. */
for(i = 0; i < N; i++){
this.R[i] ^= this.CRC[i];
}
}
/* Set key */
public void key(byte[] key){
/* Initializet known state. */
this.initState();
/* Load key material. */
this.loadKey(key);
/* In case we proceed to stream generation. */
this.genKonst();
/* Save register state. */
this.saveState();
/* Set 'nbuf' value to zero. */
this.nbuf = 0;
}
/* Set IV */
public void nonce(byte[] nonce){
/* Reload register state. */
this.reloadState();
/* Set initialization constant. */
this.konst = INITKONST;
/* Load "IV" material. */
this.loadKey(nonce);
/* Set 'konst'. */
this.genKonst();
/* Set 'nbuf' value to zero. */
this.nbuf = 0;
}
/*
* XOR pseudo-random bytes into buffer.
* Note: doesn't play well with MAC functions.
*/
public void stream(byte[] buffer){
int i = 0, j, n = buffer.length;
/* Handle any previously buffered bytes. */
while(this.nbuf != 0 && n != 0){
buffer[i++] ^= this.sbuf & 0xFF;
this.sbuf >>= 8;
this.nbuf -= 8;
n
}
/* Handle whole words. */
j = n & ~0x03;
while(i < j){
/* Cycle register. */
this.cycle();
/* XOR word. */
buffer[i + 3] ^= (this.sbuf >> 24) & 0xFF;
buffer[i + 2] ^= (this.sbuf >> 16) & 0xFF;
buffer[i + 1] ^= (this.sbuf >> 8) & 0xFF;
buffer[i ] ^= (this.sbuf ) & 0xFF;
i += 4;
}
/* Handle any trailing bytes. */
n &= 0x03;
if(n != 0){
/* Cycle register. */
this.cycle();
this.nbuf = 32;
while(this.nbuf != 0 && n != 0){
buffer[i++] ^= this.sbuf & 0xFF;
this.sbuf >>= 8;
this.nbuf -= 8;
n
}
}
}
/*
* Accumulate words into MAC without encryption.
* Note that plaintext is accumulated for MAC.
*/
public void macOnly(byte[] buffer){
int i = 0, j, n = buffer.length;
int t;
/* Handle any previously buffered bytes. */
if(this.nbuf != 0){
while(this.nbuf != 0 && n != 0){
this.mbuf ^= buffer[i++] << (32 - this.nbuf);
this.nbuf -= 8;
n
}
/* Not a whole word yet. */
if(this.nbuf != 0){
return;
}
/* LFSR already cycled. */
this.macFunc(this.mbuf);
}
/* Handle whole words. */
j = n & ~0x03;
while(i < j){
/* Cycle register. */
this.cycle();
/* Shift 4 bytes into one word. */
t = ((buffer[i + 3] & 0xFF) << 24) |
((buffer[i + 2] & 0xFF) << 16) |
((buffer[i + 1] & 0xFF) << 8) |
((buffer[i ] & 0xFF));
this.macFunc(t);
i += 4;
}
/* Handle any trailing bytes. */
n &= 0x03;
if(n != 0){
/* Cycle register. */
this.cycle();
this.mbuf = 0;
this.nbuf = 32;
while(this.nbuf != 0 && n != 0){
this.mbuf ^= buffer[i++] << (32 - this.nbuf);
this.nbuf -= 8;
n
}
}
}
/*
* Combined MAC and encryption.
* Note that plaintext is accumulated for MAC.
*/
public void encrypt(byte[] buffer){
this.encrypt(buffer, buffer.length);
}
/*
* Combined MAC and encryption.
* Note that plaintext is accumulated for MAC.
*/
public void encrypt(byte[] buffer, int n){
int i = 0, j;
int t;
/* Handle any previously buffered bytes. */
if(this.nbuf != 0){
while(this.nbuf != 0 && n != 0){
this.mbuf ^= (buffer[i] & 0xFF) << (32 - this.nbuf);
buffer[i] ^= (this.sbuf >> (32 - this.nbuf)) & 0xFF;
i++;
this.nbuf -= 8;
n
}
/* Not a whole word yet. */
if(this.nbuf != 0){
return;
}
/* LFSR already cycled. */
this.macFunc(this.mbuf);
}
/* Handle whole words. */
j = n & ~0x03;
while(i < j){
/* Cycle register. */
this.cycle();
/* Shift 4 bytes into one word. */
t = ((buffer[i + 3] & 0xFF) << 24) |
((buffer[i + 2] & 0xFF) << 16) |
((buffer[i + 1] & 0xFF) << 8) |
((buffer[i ] & 0xFF));
this.macFunc(t);
t ^= this.sbuf;
/* Put word into byte buffer. */
buffer[i + 3] = (byte)((t >> 24) & 0xFF);
buffer[i + 2] = (byte)((t >> 16) & 0xFF);
buffer[i + 1] = (byte)((t >> 8) & 0xFF);
buffer[i ] = (byte)((t ) & 0xFF);
i += 4;
}
/* Handle any trailing bytes. */
n &= 0x03;
if(n != 0){
/* Cycle register. */
this.cycle();
this.mbuf = 0;
this.nbuf = 32;
while(this.nbuf != 0 && n != 0){
this.mbuf ^= (buffer[i] & 0xFF) << (32 - this.nbuf);
buffer[i] ^= (this.sbuf >> (32 - this.nbuf)) & 0xFF;
i++;
this.nbuf -= 8;
n
}
}
}
/*
* Combined MAC and decryption.
* Note that plaintext is accumulated for MAC.
*/
public void decrypt(byte[] buffer){
this.decrypt(buffer, buffer.length);
}
/*
* Combined MAC and decryption.
* Note that plaintext is accumulated for MAC.
*/
public void decrypt(byte[] buffer, int n){
int i = 0, j;
int t;
/* Handle any previously buffered bytes. */
if(this.nbuf != 0){
while(this.nbuf != 0 && n != 0){
buffer[i] ^= (this.sbuf >> (32 - this.nbuf)) & 0xFF;
this.mbuf ^= (buffer[i] & 0xFF) << (32 - this.nbuf);
i++;
this.nbuf -= 8;
n
}
/* Not a whole word yet. */
if(this.nbuf != 0){
return;
}
/* LFSR already cycled. */
this.macFunc(this.mbuf);
}
/* Handle whole words. */
j = n & ~0x03;
while(i < j){
/* Cycle register. */
this.cycle();
/* Shift 4 bytes into one word. */
t = ((buffer[i + 3] & 0xFF) << 24) |
((buffer[i + 2] & 0xFF) << 16) |
((buffer[i + 1] & 0xFF) << 8) |
((buffer[i ] & 0xFF));
t ^= this.sbuf;
this.macFunc(t);
/* Put word into byte buffer. */
buffer[i + 3] = (byte)((t >> 24) & 0xFF);
buffer[i + 2] = (byte)((t >> 16) & 0xFF);
buffer[i + 1] = (byte)((t >> 8) & 0xFF);
buffer[i ] = (byte)((t ) & 0xFF);
i += 4;
}
/* Handle any trailing bytes. */
n &= 0x03;
if(n != 0){
/* Cycle register. */
this.cycle();
this.mbuf = 0;
this.nbuf = 32;
while(this.nbuf != 0 && n != 0){
buffer[i] ^= (this.sbuf >> (32 - this.nbuf)) & 0xFF;
this.mbuf ^= (buffer[i] & 0xFF) << (32 - this.nbuf);
i++;
this.nbuf -= 8;
n
}
}
}
/*
* Having accumulated a MAC, finish processing and return it.
* Note that any unprocessed bytes are treated as if they were
* encrypted zero bytes, so plaintext (zero) is accumulated.
*/
public void finish(byte[] buffer){
this.finish(buffer, buffer.length);
}
/*
* Having accumulated a MAC, finish processing and return it.
* Note that any unprocessed bytes are treated as if they were
* encrypted zero bytes, so plaintext (zero) is accumulated.
*/
public void finish(byte[] buffer, int n){
int i = 0, j;
/* Handle any previously buffered bytes. */
if(this.nbuf != 0){
/* LFSR already cycled. */
this.macFunc(this.mbuf);
}
/*
* Perturb the MAC to mark end of input.
* Note that only the stream register is updated, not the CRC.
* This is an action that can't be duplicated by passing in plaintext,
* hence defeating any kind of extension attack.
*/
this.cycle();
this.addKey(INITKONST ^ (this.nbuf << 3));
this.nbuf = 0;
/* Now add the CRC to the stream register and diffuse it. */
for(j = 0; j < N; j++){
this.R[j] ^= this.CRC[j];
}
this.diffuse();
/* Produce output from the stream buffer. */
while(n > 0){
this.cycle();
if(n >= 4){
/* Put word into byte buffer. */
buffer[i + 3] = (byte)((this.sbuf >> 24) & 0xFF);
buffer[i + 2] = (byte)((this.sbuf >> 16) & 0xFF);
buffer[i + 1] = (byte)((this.sbuf >> 8) & 0xFF);
buffer[i ] = (byte)((this.sbuf ) & 0xFF);
n -= 4;
i += 4;
}
else{
for(j = 0; j < n; j++){
buffer[i + j] = (byte)((this.sbuf >> (i * 8)) & 0xFF);
}
break;
}
}
}
}
|
package de.gurkenlabs.litiengine;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;
import de.gurkenlabs.litiengine.graphics.IRenderComponent;
import de.gurkenlabs.litiengine.graphics.IRenderable;
/**
* The Class RenderLoop.
*/
public class RenderLoop extends Thread {
private final IRenderComponent component;
/** The game is running. */
private boolean gameIsRunning = true;
private final List<IRenderable> renderables;
private int maxFps;
public RenderLoop(final IRenderComponent component) {
this.renderables = new CopyOnWriteArrayList<>();
this.component = component;
this.maxFps = Game.getConfiguration().client().getMaxFps();
}
public void register(final IRenderable render) {
this.renderables.add(render);
}
/*
* (non-Javadoc)
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while (this.gameIsRunning) {
final long fpsWait = (long) (1.0 / this.maxFps * 1000);
final long renderStart = System.nanoTime();
try {
Game.getCamera().updateFocus();
for (final IRenderable render : this.renderables) {
this.component.render(render);
}
final long renderTime = (System.nanoTime() - renderStart) / 1000000;
Thread.sleep(Math.max(0, fpsWait - renderTime));
} catch (final InterruptedException e) {
this.interrupt();
break;
}
}
}
/**
* Terminate.
*/
public void terminate() {
this.gameIsRunning = false;
}
public void unregister(final IRenderable render) {
this.renderables.remove(render);
}
public int getMaxFps() {
return maxFps;
}
public void setMaxFps(int maxFps) {
this.maxFps = maxFps;
}
}
|
package de.wota.gameobjects;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import de.wota.utility.Modulo;
import de.wota.utility.Vector;
/**
* When determining which objects are visible to an ant, we would like to avoid
* iterating over all objects. We subdivide the torus into cells and only look
* at the cells adjacent to the ant and the cell containing it.
*
* The game takes place on a torus. Periodicity is implemented having the zeroth
* row point to the same cells as the second to last and the last point to the same
* cells as the first.
*
* @author daniel
*
*/
public class SpacePartioning {
public SpacePartioning(double width, double height, double minimumCellSize) {
this.minimumCellSize = minimumCellSize;
numberOfHorizontalCells = (int) Math.round(Math.floor(width/minimumCellSize));
numberOfVerticalCells = (int) Math.round(Math.floor(height/minimumCellSize));
cellWidth = width / numberOfHorizontalCells;
cellHeight = height / numberOfVerticalCells;
cells = new Cell[numberOfHorizontalCells + 2][numberOfVerticalCells + 2];
for (int i = 1; i < numberOfHorizontalCells + 1; i++) {
for (int j = 1; j < numberOfVerticalCells + 1; j++) {
cells[i][j] = new Cell();
}
}
for (int i = 0; i < numberOfHorizontalCells + 2; i++) {
cells[i][0] = cells[i][numberOfVerticalCells];
cells[i][numberOfVerticalCells+1] = cells[i][1];
}
for (int j = 0; j < numberOfVerticalCells + 2; j++) {
cells[0][j] = cells[numberOfHorizontalCells][j];
cells[numberOfHorizontalCells+1][j] = cells[1][j];
}
}
public void addAntObject(AntObject antObject) {
addT(antObject, Cell.antObjectsField);
}
public void addHillObject(HillObject hillObject) {
addT(hillObject, Cell.hillObjectsField);
}
public void addSugarObject(SugarObject sugarObject) {
addT(sugarObject, Cell.sugarObjectsField);
}
public void addMessageObject(MessageObject messageObject) {
addT(messageObject, Cell.messageObjectsField);
}
private <T extends GameObject> void addT(T t, GameObjectListField<T> field) {
field.get(coordinatesToCell(t.getPosition())).add(t);
}
// WARNING: The methods for removing objects depend on the object being in the correct cell.
public void removeAntObject(AntObject antObject) {
removeT(antObject, Cell.antObjectsField);
}
public void removeHillObject(HillObject hillObject) {
removeT(hillObject, Cell.hillObjectsField);
}
public void removeSugarObject(SugarObject sugarObject) {
removeT(sugarObject, Cell.sugarObjectsField);
}
private <T extends GameObject> void removeT(T t, GameObjectListField<T> field) {
field.get(coordinatesToCell(t.getPosition())).remove(t);
}
public void update() {
for (int i = 1; i < numberOfHorizontalCells + 1; i++) {
for (int j = 1; j < numberOfVerticalCells + 1; j++) {
Cell cell = cells[i][j];
update(cell, i, j, Cell.antObjectsField);
update(cell, i, j, Cell.hillObjectsField);
update(cell, i, j, Cell.sugarObjectsField);
cell.messageObjects.clear();
}
}
}
private <T extends GameObject> void update(Cell cell, int i, int j, GameObjectListField<T> field) {
List<T> listOfTs = field.get(cell);
Iterator<T> iterator = listOfTs.iterator();
while (iterator.hasNext()) {
T t = iterator.next();
Vector p = t.getPosition();
int newI = coordinatesToCellXIndex(p);
int newJ = coordinatesToCellYIndex(p);
if (i != newI || j != newJ) {
iterator.remove();
field.get(cells[newI][newJ]).add(t);
}
}
}
// Relative coordinates of visible cells, i.e. the cell itself and the adjacent ones.
private final int numberOfVisibleCells = 9;
private final int[] deltaX = {0, 1, 1, 0, -1, -1, -1, 0, 1};
private final int[] deltaY = {0, 0, 1, 1, 1, 0, -1, -1, -1};
private <T extends GameObject> List<T> TsInsideCircle(double radius, Vector center, GameObjectListField<T> field) {
if (radius > minimumCellSize) {
throw new Error("radius > minimumCellSize");
}
List<T> listOfTsInsideCircle = new LinkedList<T>();
int x = coordinatesToCellXIndex(center);
int y = coordinatesToCellYIndex(center);
for (int i = 0; i < numberOfVisibleCells; i++) {
for (T t : field.get(cells[x+deltaX[i]][y+deltaY[i]])) {
if (GameWorldParameters.distance(t.getPosition(), center) < radius) {
listOfTsInsideCircle.add(t);
}
}
}
return listOfTsInsideCircle;
}
public List<AntObject> antObjectsInsideCircle(double radius, Vector center) {
return TsInsideCircle(radius, center, Cell.antObjectsField);
}
public List<HillObject> hillObjectsInsideCircle(double radius, Vector center) {
return TsInsideCircle(radius, center, Cell.hillObjectsField);
}
public List<SugarObject> sugarObjectsInsideCircle(double radius, Vector center) {
return TsInsideCircle(radius, center, Cell.sugarObjectsField);
}
public List<MessageObject> messageObjectsInsideCircle(double radius, Vector center) {
return TsInsideCircle(radius, center, Cell.messageObjectsField);
}
public final int coordinatesToCellXIndex(Vector p) {
return Modulo.mod((int) Math.round(Math.floor(p.x/cellWidth)), numberOfHorizontalCells) + 1;
}
public final int coordinatesToCellYIndex(Vector p) {
return Modulo.mod((int) Math.round(Math.floor(p.y/cellHeight)), numberOfVerticalCells) + 1;
}
public final Cell coordinatesToCell(Vector p) {
return cells[coordinatesToCellXIndex(p)][coordinatesToCellYIndex(p)];
}
private final double minimumCellSize;
private int numberOfHorizontalCells;
private int numberOfVerticalCells;
private final double cellWidth;
private final double cellHeight;
private final Cell[][] cells;
private static class Cell {
public final List<AntObject> antObjects = new LinkedList<AntObject>();
private static final GameObjectListField<AntObject> antObjectsField = new GameObjectListField<AntObject>() {
@Override
public List<AntObject> get(Cell cell) {
return cell.antObjects;
}
};
public final List<HillObject> hillObjects = new LinkedList<HillObject>();
private static final GameObjectListField<HillObject> hillObjectsField = new GameObjectListField<HillObject>() {
@Override
public List<HillObject> get(Cell cell) {
return cell.hillObjects;
}
};
public final List<SugarObject> sugarObjects = new LinkedList<SugarObject>();
private static final GameObjectListField<SugarObject> sugarObjectsField = new GameObjectListField<SugarObject>() {
@Override
public List<SugarObject> get(Cell cell) {
return cell.sugarObjects;
}
};
public final List<MessageObject> messageObjects = new LinkedList<MessageObject>();
private static final GameObjectListField<MessageObject> messageObjectsField = new GameObjectListField<MessageObject>() {
@Override
public List<MessageObject> get(Cell cell) {
return cell.messageObjects;
}
};
}
public int totalNumberOfAntObjects() {
int n = 0;
for (int i=0; i<numberOfHorizontalCells; i++) {
for (int j=0; j<numberOfVerticalCells; j++) {
n += cells[i][j].antObjects.size();
}
}
return n;
}
static abstract class GameObjectListField<T extends GameObject> {
public abstract List<T> get(Cell cell);
}
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of the <organization> nor the
// names of its contributors may be used to endorse or promote products
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package wyil.builders;
import static wybs.lang.SyntaxError.internalFailure;
import static wybs.lang.SyntaxError.syntaxError;
import static wyil.util.ErrorMessages.errorMessage;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.*;
import wybs.lang.*;
import wybs.util.Pair;
import wybs.util.Trie;
import wyil.lang.*;
import wyil.util.ErrorMessages;
import wycs.core.NormalForms;
import wycs.core.SemanticType;
import wycs.core.Value;
import wycs.io.WyalFileClassicalPrinter;
import wycs.syntax.*;
import wycs.transforms.ConstraintInline;
import wycs.transforms.VerificationCheck;
/**
* Responsible for converting a given Wyil bytecode into an appropriate
* constraint which encodes its semantics.
*
* @author David J. Pearce
*
*/
public class VcTransformer {
private final Builder builder;
// private final WyilFile.Case method;
private final WyalFile wycsFile;
private final String filename;
private final boolean assume;
public VcTransformer(Builder builder, WyalFile wycsFile,
String filename, boolean assume) {
this.builder = builder;
this.filename = filename;
this.assume = assume;
this.wycsFile = wycsFile;
}
public String filename() {
return filename;
}
public void end(VcBranch.LoopScope scope,
VcBranch branch) {
// not sure what really needs to be done here, in fact.
}
public void exit(VcBranch.LoopScope scope,
VcBranch branch) {
branch.addAll(scope.constraints);
}
private static int indexCount = 0;
public void end(VcBranch.ForScope scope, VcBranch branch) {
// we need to build up a quantified formula here.
ArrayList<Expr> constraints = new ArrayList<Expr>();
constraints.addAll(scope.constraints);
Expr root = Expr.Nary(Expr.Nary.Op.AND, constraints, branch.entry()
.attributes());
SyntacticType type = convert(scope.loop.type.element(), branch.entry());
Pair<TypePattern, Expr>[] vars;
Expr index;
if (scope.loop.type instanceof Type.EffectiveList) {
// FIXME: hack to work around limitations of whiley for
// loops.
Expr.Variable idx = Expr.Variable("i" + indexCount++);
TypePattern tp1 = new TypePattern.Leaf(new SyntacticType.Primitive(SemanticType.Int),idx.name);
TypePattern tp2 = new TypePattern.Leaf(type, "_" + scope.index.name);
vars = new Pair[] {
new Pair<TypePattern, Expr>(tp1,null),
new Pair<TypePattern, Expr>(tp2,null)
};
index = Expr.Nary(Expr.Nary.Op.TUPLE, new Expr[] {idx,scope.index});
} else {
vars = new Pair[] { new Pair<TypePattern, Expr>(
new TypePattern.Leaf(type, "_" + scope.index.name), null) };
index = scope.index;
}
root = Expr.Binary(Expr.Binary.Op.IMPLIES,
Expr.Binary(Expr.Binary.Op.IN, index, scope.source), root);
// Now, we have to rename the index variable in the soon-to-be
// quantified expression. This is necessary to prevent conflicts with
// same named registers used later in the method.
HashMap<String,Expr> binding = new HashMap<String,Expr>();
binding.put(scope.index.name, Expr.Variable("_" + scope.index.name));
root = root.substitute(binding);
branch.add(Expr.ForAll(vars, root, branch.entry().attributes()));
}
public void exit(VcBranch.ForScope scope,
VcBranch branch) {
ArrayList<Expr> constraints = new ArrayList<Expr>();
constraints.addAll(scope.constraints);
Expr root = Expr.Nary(Expr.Nary.Op.AND, constraints, branch.entry()
.attributes());
SyntacticType type = convert(scope.loop.type.element(), branch.entry());
Pair<TypePattern, Expr>[] vars;
Expr index;
if (scope.loop.type instanceof Type.EffectiveList) {
// FIXME: hack to work around limitations of whiley for
// loops.
Expr.Variable idx = Expr.Variable("i" + indexCount++);
TypePattern tp1 = new TypePattern.Leaf(new SyntacticType.Primitive(SemanticType.Int),idx.name);
TypePattern tp2 = new TypePattern.Leaf(type,"_" + scope.index.name);
vars = new Pair[] {
new Pair<TypePattern, Expr>(tp1,null),
new Pair<TypePattern, Expr>(tp2,null)
};
index = Expr.Nary(Expr.Nary.Op.TUPLE, new Expr[] {idx,scope.index});
} else {
vars = new Pair[] { new Pair<TypePattern, Expr>(
new TypePattern.Leaf(type, "_" + scope.index.name), null) };
index = scope.index;
}
root = Expr.Nary(
Expr.Nary.Op.AND,
new Expr[] {
Expr.Binary(Expr.Binary.Op.IN, index, scope.source),
root });
// Now, we have to rename the index variable in the soon-to-be
// quantified expression. This is necessary to prevent conflicts with
// same named registers used later in the method.
HashMap<String,Expr> binding = new HashMap<String,Expr>();
binding.put(scope.index.name, Expr.Variable("_" + scope.index.name));
root = root.substitute(binding);
branch.add(Expr.Exists(vars, root, branch.entry().attributes()));
}
public void exit(VcBranch.TryScope scope,
VcBranch branch) {
}
protected void transform(Code.Assert code, VcBranch branch) {
Expr test = buildTest(code.op, code.leftOperand, code.rightOperand,
code.type, branch);
if (!assume) {
Expr assumptions = branch.constraints();
Expr implication = Expr.Binary(Expr.Binary.Op.IMPLIES, assumptions,
test);
// build up list of used variables
HashSet<String> uses = new HashSet<String>();
implication.freeVariables(uses);
// Now, parameterise the assertion appropriately
Expr assertion = buildAssertion(0, implication, uses, branch);
wycsFile.add(wycsFile.new Assert(code.msg, assertion, branch
.entry().attributes()));
} else {
branch.add(test);
}
}
protected Expr buildAssertion(int index, Expr implication,
HashSet<String> uses, VcBranch branch) {
if (index == branch.nScopes()) {
return implication;
} else {
ArrayList<Pair<TypePattern, Expr>> vars = new ArrayList<Pair<TypePattern, Expr>>();
Expr contents = buildAssertion(index + 1, implication, uses, branch);
VcBranch.Scope scope = branch.scope(index);
if (scope instanceof VcBranch.EntryScope) {
VcBranch.EntryScope es = (VcBranch.EntryScope) scope;
ArrayList<Type> parameters = es.declaration.type().params();
for (int i = 0; i != parameters.size(); ++i) {
Expr.Variable v = Expr.Variable("r" + i);
if (uses.contains(v.name)) {
// only include variable if actually used
uses.remove(v.name);
SyntacticType t = convert(parameters.get(i),
es.declaration);
vars.add(new Pair<TypePattern, Expr>(
new TypePattern.Leaf(t, v.name), null));
}
}
// Finally, scope any remaining free variables. Such variables
// occur from modified operands of loops which are no longer on
// the scope stack.
for (String v : uses) {
// FIXME: should not be INT here.
SyntacticType t = new SyntacticType.Primitive(
SemanticType.Int);
vars.add(new Pair<TypePattern, Expr>(new TypePattern.Leaf(
t, v), null));
}
} else if (scope instanceof VcBranch.ForScope) {
VcBranch.ForScope ls = (VcBranch.ForScope) scope;
SyntacticType type = convert(ls.loop.type.element(),
branch.entry());
// first, deal with index expression
int[] modifiedOperands = ls.loop.modifiedOperands;
if (uses.contains(ls.index.name)) {
// only parameterise the index variable if it is actually
// used.
uses.remove(ls.index.name);
Expr idx;
if (ls.loop.type instanceof Type.EffectiveList) {
// FIXME: hack to work around limitations of whiley for
// loops.
String i = "i" + indexCount++;
vars.add(new Pair<TypePattern, Expr>(
new TypePattern.Leaf(
new SyntacticType.Primitive(
SemanticType.Int), i), null));
vars.add(new Pair<TypePattern, Expr>(
new TypePattern.Leaf(type, ls.index.name), null));
idx = Expr.Nary(Expr.Nary.Op.TUPLE,
new Expr[] { Expr.Variable(i), ls.index });
} else {
vars.add(new Pair<TypePattern, Expr>(
new TypePattern.Leaf(type, ls.index.name), null));
idx = ls.index;
}
// since index is used, we need to imply that it is
// contained in the source expression.
contents = Expr.Binary(Expr.Binary.Op.IMPLIES,
Expr.Binary(Expr.Binary.Op.IN, idx, ls.source),
contents);
}
// second, deal with modified operands
for (int i = 0; i != modifiedOperands.length; ++i) {
int reg = modifiedOperands[i];
Expr.Variable v = Expr.Variable("r" + reg);
if (uses.contains(v.name)) {
// Only parameterise a modified operand if it is
// actually used.
uses.remove(v.name);
// FIXME: should not be INT here.
SyntacticType t = new SyntacticType.Primitive(
SemanticType.Int);
vars.add(new Pair<TypePattern, Expr>(
new TypePattern.Leaf(t, v.name), null));
}
}
} else if (scope instanceof VcBranch.LoopScope) {
VcBranch.LoopScope ls = (VcBranch.LoopScope) scope;
// now, deal with modified operands
int[] modifiedOperands = ls.loop.modifiedOperands;
for (int i = 0; i != modifiedOperands.length; ++i) {
int reg = modifiedOperands[i];
Expr.Variable v = Expr.Variable("r" + reg);
if (uses.contains(v.name)) {
// Only parameterise a modified operand if it is
// actually used.
uses.remove(v.name);
// FIXME: should not be INT here.
SyntacticType t = new SyntacticType.Primitive(
SemanticType.Int);
vars.add(new Pair<TypePattern, Expr>(
new TypePattern.Leaf(t, v.name), null));
}
}
}
if (vars.size() == 0) {
// we have nothing to parameterise, so ignore it.
return contents;
} else {
return Expr.ForAll(vars.toArray(new Pair[vars.size()]),
contents);
}
}
}
protected void transform(Code.Assume code, VcBranch branch) {
// At this point, what we do is invert the condition being asserted and
// check that it is unsatisfiable.
Expr test = buildTest(code.op, code.leftOperand, code.rightOperand,
code.type, branch);
branch.add(test);
}
protected void transform(Code.Assign code, VcBranch branch) {
branch.write(code.target, branch.read(code.operand));
}
protected void transform(Code.BinArithOp code, VcBranch branch) {
Expr lhs = branch.read(code.leftOperand);
Expr rhs = branch.read(code.rightOperand);
Expr.Binary.Op op;
switch (code.kind) {
case ADD:
op = Expr.Binary.Op.ADD;
break;
case SUB:
op = Expr.Binary.Op.SUB;
break;
case MUL:
op = Expr.Binary.Op.MUL;
break;
case DIV:
op = Expr.Binary.Op.DIV;
break;
case RANGE:
op = Expr.Binary.Op.RANGE;
break;
default:
internalFailure("unknown binary operator", filename, branch.entry());
return;
}
branch.write(code.target,
Expr.Binary(op, lhs, rhs, branch.entry().attributes()));
}
protected void transform(Code.BinListOp code, VcBranch branch) {
Expr lhs = branch.read(code.leftOperand);
Expr rhs = branch.read(code.rightOperand);
switch (code.kind) {
case APPEND:
// do nothing
break;
case LEFT_APPEND:
rhs = Expr.Nary(Expr.Nary.Op.LIST,new Expr[] { rhs }, branch.entry().attributes());
break;
case RIGHT_APPEND:
lhs = Expr.Nary(Expr.Nary.Op.LIST,new Expr[] { lhs }, branch.entry().attributes());
break;
default:
internalFailure("unknown binary operator", filename, branch.entry());
return;
}
branch.write(code.target,
Expr.Binary(Expr.Binary.Op.LISTAPPEND,lhs, rhs, branch.entry().attributes()));
}
protected void transform(Code.BinSetOp code, VcBranch branch) {
Collection<Attribute> attributes = branch.entry().attributes();
Expr lhs = branch.read(code.leftOperand);
Expr rhs = branch.read(code.rightOperand);
Expr val;
switch (code.kind) {
case UNION:
val = Expr.Binary(Expr.Binary.Op.SETUNION,lhs, rhs, attributes);
break;
case LEFT_UNION:
rhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { rhs }, branch
.entry().attributes());
val = Expr.Binary(Expr.Binary.Op.SETUNION,lhs, rhs, attributes);
break;
case RIGHT_UNION:
lhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { lhs }, branch
.entry().attributes());
val = Expr.Binary(Expr.Binary.Op.SETUNION,lhs, rhs, attributes);
break;
case INTERSECTION:
val = Expr.Binary(Expr.Binary.Op.SETINTERSECTION,lhs, rhs, attributes);
break;
case LEFT_INTERSECTION:
rhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { rhs }, branch
.entry().attributes());
val = Expr.Binary(Expr.Binary.Op.SETINTERSECTION,lhs, rhs, attributes);
break;
case RIGHT_INTERSECTION:
lhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { lhs }, branch
.entry().attributes());
val = Expr.Binary(Expr.Binary.Op.SETINTERSECTION,lhs, rhs, attributes);
break;
case LEFT_DIFFERENCE:
rhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { rhs }, branch
.entry().attributes());
val = Expr.Binary(Expr.Binary.Op.SETDIFFERENCE,lhs, rhs, attributes);
break;
case DIFFERENCE:
val = Expr.Binary(Expr.Binary.Op.SETDIFFERENCE,lhs, rhs, attributes);
break;
default:
internalFailure("unknown binary operator", filename, branch.entry());
return;
}
branch.write(code.target, val);
}
protected void transform(Code.BinStringOp code, VcBranch branch) {
Collection<Attribute> attributes = branch.entry().attributes();
Expr lhs = branch.read(code.leftOperand);
Expr rhs = branch.read(code.rightOperand);
switch (code.kind) {
case APPEND:
// do nothing
break;
case LEFT_APPEND:
rhs = Expr.Nary(Expr.Nary.Op.LIST,new Expr[] { rhs }, branch.entry().attributes());
break;
case RIGHT_APPEND:
lhs = Expr.Nary(Expr.Nary.Op.LIST,new Expr[] { lhs }, branch.entry().attributes());
break;
default:
internalFailure("unknown binary operator", filename, branch.entry());
return;
}
branch.write(code.target,
Expr.Binary(Expr.Binary.Op.LISTAPPEND,lhs, rhs, branch.entry().attributes()));
}
protected void transform(Code.Convert code, VcBranch branch) {
Expr result = branch.read(code.operand);
// TODO: actually implement some or all coercions?
branch.write(code.target, result);
}
protected void transform(Code.Const code, VcBranch branch) {
Value val = convert(code.constant, branch.entry());
branch.write(code.target,
Expr.Constant(val, branch.entry().attributes()));
}
protected void transform(Code.Debug code, VcBranch branch) {
// do nout
}
protected void transform(Code.Dereference code, VcBranch branch) {
// TODO
}
protected void transform(Code.FieldLoad code, VcBranch branch) {
Collection<Attribute> attributes = branch.entry().attributes();
// Expr src = branch.read(code.operand);
// branch.write(code.target, Exprs.FieldOf(src, code.field,
// attributes));
ArrayList<String> fields = new ArrayList<String>(code.type.fields()
.keySet());
Collections.sort(fields);
Expr src = branch.read(code.operand);
Expr index = Expr.Constant(Value.Integer(BigInteger.valueOf(fields.indexOf(code.field))));
Expr result = Expr.IndexOf(src, index, branch.entry().attributes());
branch.write(code.target, result);
}
protected void transform(Code.If code, VcBranch falseBranch,
VcBranch trueBranch) {
// First, cover true branch
Expr.Binary trueTest = buildTest(code.op, code.leftOperand,
code.rightOperand, code.type, trueBranch);
trueBranch.add(trueTest);
falseBranch.add(invert(trueTest));
}
protected void transform(Code.IfIs code, VcBranch falseBranch,
VcBranch trueBranch) {
// TODO
}
protected void transform(Code.IndirectInvoke code, VcBranch branch) {
// TODO
}
protected void transform(Code.Invoke code, VcBranch branch)
throws Exception {
SyntacticElement entry = branch.entry();
Collection<Attribute> attributes = entry.attributes();
int[] code_operands = code.operands;
if (code.target != Code.NULL_REG) {
// Need to assume the post-condition holds.
Block postcondition = findPostcondition(code.name, code.type,
branch.entry());
Expr[] operands = new Expr[code_operands.length];
for (int i = 0; i != code_operands.length; ++i) {
operands[i] = branch.read(code_operands[i]);
}
Expr argument = Expr.Nary(Expr.Nary.Op.TUPLE, operands, attributes);
branch.write(code.target, Expr.FunCall(toIdentifier(code.name),
new SyntacticType[0], argument, attributes));
// Here, we must add a WycsFile Function to represent the function being called, and to prototype it.
TypePattern from = new TypePattern.Leaf(convert(code.type.params(),entry), null, attributes);
TypePattern to = new TypePattern.Leaf(convert(code.type.ret(),entry), null, attributes);
wycsFile.add(wycsFile.new Function(toIdentifier(code.name),
Collections.EMPTY_LIST, from, to, null));
if (postcondition != null) {
// operands = Arrays.copyOf(operands, operands.length);
Expr[] arguments = new Expr[operands.length + 1];
System.arraycopy(operands, 0, arguments, 1, operands.length);
arguments[0] = branch.read(code.target);
Expr constraint = transformExternalBlock(postcondition,
arguments, branch);
// assume the post condition holds
branch.add(constraint);
}
}
}
protected void transform(Code.Invert code, VcBranch branch) {
// TODO
}
protected void transform(Code.IndexOf code, VcBranch branch) {
Expr src = branch.read(code.leftOperand);
Expr idx = branch.read(code.rightOperand);
branch.write(code.target,
Expr.IndexOf(src, idx, branch.entry().attributes()));
}
protected void transform(Code.LengthOf code, VcBranch branch) {
Expr src = branch.read(code.operand);
branch.write(code.target, Expr.Unary(Expr.Unary.Op.LENGTHOF, src,
branch.entry().attributes()));
}
protected void transform(Code.Loop code, VcBranch branch) {
// FIXME: assume loop invariant?
}
protected void transform(Code.Move code, VcBranch branch) {
branch.write(code.target, branch.read(code.operand));
}
protected void transform(Code.NewMap code, VcBranch branch) {
// TODO
}
protected void transform(Code.NewList code, VcBranch branch) {
int[] code_operands = code.operands;
Expr[] vals = new Expr[code_operands.length];
for (int i = 0; i != vals.length; ++i) {
vals[i] = branch.read(code_operands[i]);
}
branch.write(code.target,
Expr.Nary(Expr.Nary.Op.LIST, vals, branch.entry().attributes()));
}
protected void transform(Code.NewSet code, VcBranch branch) {
int[] code_operands = code.operands;
Expr[] vals = new Expr[code_operands.length];
for (int i = 0; i != vals.length; ++i) {
vals[i] = branch.read(code_operands[i]);
}
branch.write(code.target,
Expr.Nary(Expr.Nary.Op.SET, vals, branch.entry().attributes()));
}
protected void transform(Code.NewRecord code, VcBranch branch) {
int[] code_operands = code.operands;
Type.Record type = code.type;
ArrayList<String> fields = new ArrayList<String>(type.fields().keySet());
Collections.sort(fields);
Expr[] vals = new Expr[fields.size()];
for (int i = 0; i != fields.size(); ++i) {
vals[i] = branch.read(code_operands[i]);
}
branch.write(code.target, new Expr.Nary(Expr.Nary.Op.TUPLE, vals,
branch.entry().attributes()));
}
protected void transform(Code.NewObject code, VcBranch branch) {
// TODO
}
protected void transform(Code.NewTuple code, VcBranch branch) {
int[] code_operands = code.operands;
Expr[] vals = new Expr[code_operands.length];
for (int i = 0; i != vals.length; ++i) {
vals[i] = branch.read(code_operands[i]);
}
branch.write(code.target, Expr.Nary(Expr.Nary.Op.TUPLE, vals, branch
.entry().attributes()));
}
protected void transform(Code.Nop code, VcBranch branch) {
// do nout
}
protected void transform(Code.Return code, VcBranch branch) {
// nothing to do
}
protected void transform(Code.SubString code, VcBranch branch) {
Expr src = branch.read(code.operands[0]);
Expr start = branch.read(code.operands[1]);
Expr end = branch.read(code.operands[2]);
Expr result = Expr.Nary(Expr.Nary.Op.SUBLIST, new Expr[] { src, start,
end }, branch.entry().attributes());
branch.write(code.target, result);
}
protected void transform(Code.SubList code, VcBranch branch) {
Expr src = branch.read(code.operands[0]);
Expr start = branch.read(code.operands[1]);
Expr end = branch.read(code.operands[2]);
Expr result = Expr.Nary(Expr.Nary.Op.SUBLIST, new Expr[] { src, start,
end }, branch.entry().attributes());
branch.write(code.target, result);
}
protected void transform(Code.Throw code, VcBranch branch) {
// TODO
}
protected void transform(Code.TupleLoad code, VcBranch branch) {
Expr src = branch.read(code.operand);
Expr index = Expr
.Constant(Value.Integer(BigInteger.valueOf(code.index)));
Expr result = Expr.IndexOf(src, index, branch.entry().attributes());
branch.write(code.target, result);
}
protected void transform(Code.TryCatch code, VcBranch branch) {
// FIXME: do something here?
}
protected void transform(Code.UnArithOp code, VcBranch branch) {
if (code.kind == Code.UnArithKind.NEG) {
Expr operand = branch.read(code.operand);
branch.write(code.target, Expr.Unary(Expr.Unary.Op.NEG, operand,
branch.entry().attributes()));
} else {
// TODO
}
}
protected void transform(Code.Update code, VcBranch branch) {
Expr result = branch.read(code.operand);
Expr source = branch.read(code.target);
branch.write(code.target,
updateHelper(code.iterator(), source, result, branch));
}
protected Expr updateHelper(Iterator<Code.LVal> iter, Expr source,
Expr result, VcBranch branch) {
if (!iter.hasNext()) {
return result;
} else {
Collection<Attribute> attributes = branch.entry().attributes();
Code.LVal lv = iter.next();
if (lv instanceof Code.RecordLVal) {
Code.RecordLVal rlv = (Code.RecordLVal) lv;
// result = updateHelper(iter,
// Exprs.FieldOf(source, rlv.field, attributes), result,
// branch);
// return Exprs.FieldUpdate(source, rlv.field, result,
// attributes);
// FIXME: following is broken for open records.
ArrayList<String> fields = new ArrayList<String>(rlv.rawType()
.fields().keySet());
Collections.sort(fields);
int index = fields.indexOf(rlv.field);
Expr[] operands = new Expr[fields.size()];
for (int i = 0; i != fields.size(); ++i) {
Expr _i = Expr
.Constant(Value.Integer(BigInteger.valueOf(i)));
if (i != index) {
operands[i] = Expr.IndexOf(source, _i, attributes);
} else {
operands[i] = updateHelper(iter,
Expr.IndexOf(source, _i, attributes), result,
branch);
}
}
return Expr.Nary(Expr.Nary.Op.TUPLE, operands, attributes);
} else if (lv instanceof Code.ListLVal) {
Code.ListLVal rlv = (Code.ListLVal) lv;
Expr index = branch.read(rlv.indexOperand);
result = updateHelper(iter,
Expr.IndexOf(source, index, attributes),
result, branch);
return Expr.Nary(Expr.Nary.Op.LISTUPDATE, new Expr[] { source,
index, result }, branch.entry().attributes());
} else if (lv instanceof Code.MapLVal) {
return source; // TODO
} else if (lv instanceof Code.StringLVal) {
return source; // TODO
} else {
return source; // TODO
}
}
}
protected Block findPrecondition(NameID name, Type.FunctionOrMethod fun,
SyntacticElement elem) throws Exception {
Path.Entry<WyilFile> e = builder.namespace().get(name.module(),
WyilFile.ContentType);
if (e == null) {
syntaxError(
errorMessage(ErrorMessages.RESOLUTION_ERROR, name.module()
.toString()), filename, elem);
}
WyilFile m = e.read();
WyilFile.MethodDeclaration method = m.method(name.name(), fun);
for (WyilFile.Case c : method.cases()) {
// FIXME: this is a hack for now
return c.precondition();
}
return null;
}
protected Block findPostcondition(NameID name, Type.FunctionOrMethod fun,
SyntacticElement elem) throws Exception {
Path.Entry<WyilFile> e = builder.namespace().get(name.module(),
WyilFile.ContentType);
if (e == null) {
syntaxError(
errorMessage(ErrorMessages.RESOLUTION_ERROR, name.module()
.toString()), filename, elem);
}
WyilFile m = e.read();
WyilFile.MethodDeclaration method = m.method(name.name(), fun);
for (WyilFile.Case c : method.cases()) {
// FIXME: this is a hack for now
return c.postcondition();
}
return null;
}
protected Expr transformExternalBlock(Block externalBlock, Expr[] operands,
VcBranch branch) {
// first, generate a constraint representing the post-condition.
VcBranch master = new VcBranch(externalBlock);
// second, set initial environment
for (int i = 0; i != operands.length; ++i) {
master.write(i, operands[i]);
}
return master.transform(new VcTransformer(builder, wycsFile,
filename, true));
}
/**
* Generate a formula representing a condition from an Code.IfCode or
* Code.Assert bytecodes.
*
* @param op
* @param stack
* @param elem
* @return
*/
private Expr.Binary buildTest(Code.Comparator cop, int leftOperand,
int rightOperand, Type type, VcBranch branch) {
Expr lhs = branch.read(leftOperand);
Expr rhs = branch.read(rightOperand);
Expr.Binary.Op op;
switch (cop) {
case EQ:
op = Expr.Binary.Op.EQ;
break;
case NEQ:
op = Expr.Binary.Op.NEQ;
break;
case GTEQ:
op = Expr.Binary.Op.GTEQ;
break;
case GT:
op = Expr.Binary.Op.GT;
break;
case LTEQ:
op = Expr.Binary.Op.LTEQ;
break;
case LT:
op = Expr.Binary.Op.LT;
break;
case SUBSET:
op = Expr.Binary.Op.SUBSET;
break;
case SUBSETEQ:
op = Expr.Binary.Op.SUBSETEQ;
break;
case ELEMOF:
op = Expr.Binary.Op.IN;
break;
default:
internalFailure("unknown comparator (" + cop + ")", filename,
branch.entry());
return null;
}
return Expr.Binary(op, lhs, rhs, branch.entry().attributes());
}
/**
* Generate the logically inverted expression corresponding to this
* comparator.
*
* @param cop
* @param leftOperand
* @param rightOperand
* @param type
* @param branch
* @return
*/
private Expr invert(Expr.Binary test) {
Expr.Binary.Op op;
switch (test.op) {
case EQ:
op = Expr.Binary.Op.NEQ;
break;
case NEQ:
op = Expr.Binary.Op.EQ;
break;
case GTEQ:
op = Expr.Binary.Op.LT;
break;
case GT:
op = Expr.Binary.Op.LTEQ;
break;
case LTEQ:
op = Expr.Binary.Op.GT;
break;
case LT:
op = Expr.Binary.Op.GTEQ;
break;
case SUBSET:
op = Expr.Binary.Op.SUPSETEQ;
break;
case SUBSETEQ:
op = Expr.Binary.Op.SUPSET;
break;
case SUPSET:
op = Expr.Binary.Op.SUBSETEQ;
break;
case SUPSETEQ:
op = Expr.Binary.Op.SUBSET;
break;
case IN:
op = Expr.Binary.Op.IN;
return Expr.Unary(
Expr.Unary.Op.NOT,
Expr.Binary(op, test.leftOperand, test.rightOperand,
test.attributes()), test.attributes());
default:
internalFailure("unknown comparator (" + test.op + ")", filename,
test);
return null;
}
return Expr.Binary(op, test.leftOperand, test.rightOperand,
test.attributes());
}
public Value convert(Constant c, SyntacticElement elem) {
if (c instanceof Constant.Null) {
// TODO: is this the best translation?
return wycs.core.Value.Integer(BigInteger.ZERO);
} else if (c instanceof Constant.Bool) {
Constant.Bool cb = (Constant.Bool) c;
return wycs.core.Value.Bool(cb.value);
} else if (c instanceof Constant.Byte) {
Constant.Byte cb = (Constant.Byte) c;
return wycs.core.Value.Integer(BigInteger.valueOf(cb.value));
} else if (c instanceof Constant.Char) {
Constant.Char cb = (Constant.Char) c;
return wycs.core.Value.Integer(BigInteger.valueOf(cb.value));
} else if (c instanceof Constant.Integer) {
Constant.Integer cb = (Constant.Integer) c;
return wycs.core.Value.Integer(cb.value);
} else if (c instanceof Constant.Rational) {
Constant.Rational cb = (Constant.Rational) c;
return wycs.core.Value.Rational(cb.value);
} else if (c instanceof Constant.Strung) {
Constant.Strung cb = (Constant.Strung) c;
String str = cb.value;
ArrayList<Value> pairs = new ArrayList<Value>();
for (int i = 0; i != str.length(); ++i) {
ArrayList<Value> pair = new ArrayList<Value>();
pair.add(Value.Integer(BigInteger.valueOf(i)));
pair.add(Value.Integer(BigInteger.valueOf(str.charAt(i))));
pairs.add(Value.Tuple(pair));
}
return Value.Set(pairs);
} else if (c instanceof Constant.List) {
Constant.List cb = (Constant.List) c;
List<Constant> cb_values = cb.values;
ArrayList<Value> pairs = new ArrayList<Value>();
for (int i = 0; i != cb_values.size(); ++i) {
ArrayList<Value> pair = new ArrayList<Value>();
pair.add(Value.Integer(BigInteger.valueOf(i)));
pair.add(convert(cb_values.get(i), elem));
pairs.add(Value.Tuple(pair));
}
return Value.Set(pairs);
} else if (c instanceof Constant.Map) {
Constant.Map cb = (Constant.Map) c;
ArrayList<Value> pairs = new ArrayList<Value>();
for (Map.Entry<Constant, Constant> e : cb.values.entrySet()) {
ArrayList<Value> pair = new ArrayList<Value>();
pair.add(convert(e.getKey(), elem));
pair.add(convert(e.getValue(), elem));
pairs.add(Value.Tuple(pair));
}
return Value.Set(pairs);
} else if (c instanceof Constant.Set) {
Constant.Set cb = (Constant.Set) c;
ArrayList<Value> values = new ArrayList<Value>();
for (Constant v : cb.values) {
values.add(convert(v, elem));
}
return wycs.core.Value.Set(values);
} else if (c instanceof Constant.Tuple) {
Constant.Tuple cb = (Constant.Tuple) c;
ArrayList<Value> values = new ArrayList<Value>();
for (Constant v : cb.values) {
values.add(convert(v, elem));
}
return wycs.core.Value.Tuple(values);
} else {
internalFailure("unknown constant encountered (" + c + ")",
filename, elem);
return null;
}
}
private SyntacticType convert(List<Type> types, SyntacticElement elem) {
SyntacticType[] ntypes = new SyntacticType[types.size()];
for(int i=0;i!=ntypes.length;++i) {
ntypes[i] = convert(types.get(i),elem);
}
return new SyntacticType.Tuple(ntypes);
}
private SyntacticType convert(Type t, SyntacticElement elem) {
// FIXME: this is fundamentally broken in the case of recursive types.
if (t instanceof Type.Any) {
return new SyntacticType.Primitive(SemanticType.Any);
} else if (t instanceof Type.Void) {
return new SyntacticType.Primitive(SemanticType.Void);
} else if (t instanceof Type.Bool) {
return new SyntacticType.Primitive(SemanticType.Bool);
} else if (t instanceof Type.Char) {
return new SyntacticType.Primitive(SemanticType.Int);
} else if (t instanceof Type.Byte) {
return new SyntacticType.Primitive(SemanticType.Int);
} else if (t instanceof Type.Int) {
return new SyntacticType.Primitive(SemanticType.Int);
} else if (t instanceof Type.Real) {
return new SyntacticType.Primitive(SemanticType.Real);
} else if (t instanceof Type.Strung) {
return new SyntacticType.List(new SyntacticType.Primitive(SemanticType.Int));
} else if (t instanceof Type.Set) {
Type.Set st = (Type.Set) t;
SyntacticType element = convert(st.element(), elem);
return new SyntacticType.Set(element);
} else if (t instanceof Type.Map) {
Type.Map lt = (Type.Map) t;
SyntacticType from = convert(lt.key(), elem);
SyntacticType to = convert(lt.value(), elem);
// ugly.
return new SyntacticType.Map(from,to);
} else if (t instanceof Type.List) {
Type.List lt = (Type.List) t;
SyntacticType element = convert(lt.element(), elem);
// ugly.
return new SyntacticType.List(element);
} else if (t instanceof Type.Tuple) {
Type.Tuple tt = (Type.Tuple) t;
SyntacticType[] elements = new SyntacticType[tt.size()];
for (int i = 0; i != tt.size(); ++i) {
elements[i] = convert(tt.element(i), elem);
}
return new SyntacticType.Tuple(elements);
} else if (t instanceof Type.Record) {
Type.Record rt = (Type.Record) t;
// return new SyntacticType.Set(new SyntacticType.Tuple(
// new SyntacticType[] {
// new SyntacticType.Primitive(SemanticType.String),
// new SyntacticType.Primitive(SemanticType.Any) }));
HashMap<String, Type> fields = rt.fields();
ArrayList<String> names = new ArrayList<String>(fields.keySet());
SyntacticType[] elements = new SyntacticType[names.size()];
Collections.sort(names);
for (int i = 0; i != names.size(); ++i) {
String field = names.get(i);
elements[i] = convert(fields.get(field), elem);
}
return new SyntacticType.Tuple(elements);
} else if (t instanceof Type.Reference) {
// FIXME: how to translate this??
return new SyntacticType.Primitive(SemanticType.Any);
} else {
internalFailure("unknown type encountered (" + t + ")", filename,
elem);
return null;
}
}
/**
* Convert a wyil NameID into a string that is suitable to be used as a
* function name or variable identifier in WycsFiles.
*
* @param id
* @return
*/
private String toIdentifier(NameID id) {
return id.toString().replace(":","_").replace("/","_");
}
}
|
package wyone.io;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.util.*;
import wyone.util.*;
import wyone.core.Attribute;
import wyone.core.Type;
import wyone.spec.Expr;
import wyone.spec.Pattern;
import wyone.spec.SpecFile;
import static wyone.spec.SpecFile.*;
import static wyone.core.Attribute.*;
public class NewJavaFileWriter {
private PrintWriter out;
private ArrayList<Decl> spDecl;
private String pkgName = null;
private HashSet<Type> typeTests = new HashSet<Type>();
private HashSet<String> classSet = new HashSet<String>();
public NewJavaFileWriter(Writer os) {
out = new PrintWriter(os);
}
public NewJavaFileWriter(OutputStream os) {
out = new PrintWriter(os);
}
public void write(SpecFile spec) {
ArrayList<Decl> spDe = spec.declarations;
spDecl = spDe;
if (!spec.pkg.equals("")) {
myOut("package " + spec.pkg + ";");
myOut("");
}
writeImports();
myOut("public final class " + spec.name + " {");
HashMap<String, Set<String>> hierarchy = new HashMap<String, Set<String>>();
HashSet<String> used = new HashSet<String>();
for (Decl d : spDecl) {
if (d instanceof ClassDecl) {
ClassDecl cd = (ClassDecl) d;
classSet.add(cd.name);
for (String child : cd.children) {
Set<String> parents = hierarchy.get(child);
if (parents == null) {
parents = new HashSet<String>();
hierarchy.put(child, parents);
}
parents.add(cd.name);
}
}
}
for (Decl d : spDecl) {
if (d instanceof TermDecl) {
translate((TermDecl) d, hierarchy);
} else if (d instanceof ClassDecl) {
translate((ClassDecl) d, hierarchy);
} else if (d instanceof RewriteDecl) {
translate((RewriteDecl) d, used);
}
}
writeTypeTests(hierarchy);
writeSchema();
writeMainMethod();
myOut("}");
out.flush();
}
protected void writeImports() {
myOut("import java.io.*;");
myOut("import java.util.*;");
myOut("import java.math.BigInteger;");
myOut("import wyone.io.PrettyAutomataReader;");
myOut("import wyone.io.PrettyAutomataWriter;");
myOut("import wyone.core.*;");
myOut("import static wyone.util.Runtime.*;");
myOut();
}
public void translate(TermDecl decl, HashMap<String, Set<String>> hierarchy) {
myOut(1, "// term " + decl.type);
myOut(1, "public final static int K_" + decl.type.name + " = "
+ termCounter++ + ";");
if (decl.type.data == null) {
myOut(1, "public final static Automaton.Term " + decl.type.name
+ " = new Automaton.Term(K_" + decl.type.name + ");");
} else {
Type.Ref data = decl.type.data;
Type element = data.element;
if(element instanceof Type.Compound) {
// add two helpers
myOut(1, "public final static int " + decl.type.name
+ "(Automaton automaton, int... r0) {" );
if(element instanceof Type.Set) {
myOut(2,"int r1 = automaton.add(new Automaton.Set(r0));");
} else if(element instanceof Type.Bag) {
myOut(2,"int r1 = automaton.add(new Automaton.Bag(r0));");
} else {
myOut(2,"int r1 = automaton.add(new Automaton.List(r0));");
}
myOut(2,"return automaton.add(new Automaton.Term(K_" + decl.type.name + ", r1));");
myOut(1,"}");
myOut(1, "public final static int " + decl.type.name
+ "(Automaton automaton, List<Integer> r0) {" );
if(element instanceof Type.Set) {
myOut(2,"int r1 = automaton.add(new Automaton.Set(r0));");
} else if(element instanceof Type.Bag) {
myOut(2,"int r1 = automaton.add(new Automaton.Bag(r0));");
} else {
myOut(2,"int r1 = automaton.add(new Automaton.List(r0));");
}
myOut(2,"return automaton.add(new Automaton.Term(K_" + decl.type.name + ", r1));");
myOut(1,"}");
} else if(element instanceof Type.Int) {
// add two helpers
myOut(1, "public final static int " + decl.type.name
+ "(Automaton automaton, long r0) {" );
myOut(2,"int r1 = automaton.add(new Automaton.Int(r0));");
myOut(2,"return automaton.add(new Automaton.Term(K_" + decl.type.name + ", r1));");
myOut(1,"}");
myOut(1, "public final static int " + decl.type.name
+ "(Automaton automaton, BigInteger r0) {" );
myOut(2,"int r1 = automaton.add(new Automaton.Int(r0));");
myOut(2,"return automaton.add(new Automaton.Term(K_" + decl.type.name + ", r1));");
myOut(1,"}");
} else if(element instanceof Type.Strung) {
// add two helpers
myOut(1, "public final static int " + decl.type.name
+ "(Automaton automaton, String r0) {" );
myOut(2,"int r1 = automaton.add(new Automaton.Strung(r0));");
myOut(2,"return automaton.add(new Automaton.Term(K_" + decl.type.name + ", r1));");
myOut(1,"}");
} else {
myOut(1, "public final static int " + decl.type.name
+ "(Automaton automaton, " + type2JavaType(data) + " r0) {" );
myOut(2,"return automaton.add(new Automaton.Term(K_" + decl.type.name + ", r0));");
myOut(1,"}");
}
}
myOut();
}
private static int termCounter = 0;
public void translate(ClassDecl decl, HashMap<String, Set<String>> hierarchy) {
String lin = "// " + decl.name + " as ";
for (int i = 0; i != decl.children.size(); ++i) {
String child = decl.children.get(i);
if (i != 0) {
lin += " | ";
}
lin += child;
}
myOut(1, lin);
myOut();
}
public void translate(RewriteDecl decl, HashSet<String> used) {
Pattern.Term pattern = decl.pattern;
Type param = pattern.attribute(Attribute.Type.class).type;
myOut(1, "// " + decl.pattern);
myOut(1, "public static boolean rewrite_"
+ nameMangle(param, used) + "("
+ type2JavaType(param) + " r0, Automaton automaton) {");
// setup the environment
Environment environment = new Environment();
int thus = environment.allocate(param,"this");
// translate pattern
translate(pattern,thus,environment);
// translate expressions
myOut(1);
boolean conditional = true;
for(RuleDecl rd : decl.rules) {
conditional &= translate(rd,environment);
}
if(conditional) {
myOut(2,"return false;");
}
myOut(1,"}");
myOut();
}
public void translate(Pattern p, int source, Environment environment) {
if(p instanceof Pattern.Leaf) {
translate((Pattern.Leaf) p,source,environment);
} else if(p instanceof Pattern.Term) {
translate((Pattern.Term) p,source,environment);
} else if(p instanceof Pattern.Set) {
translate((Pattern.Set) p,source,environment);
} else if(p instanceof Pattern.Bag) {
translate((Pattern.Bag) p,source,environment);
} else {
translate((Pattern.List) p,source,environment);
}
}
public void translate(Pattern.Leaf p, int source, Environment environment) {
// do nothing?
}
public void translate(Pattern.Term p, int source, Environment environment) {
Type.Ref<Type.Term> type = (Type.Ref) p.attribute(Attribute.Type.class).type;
source = coerceFromRef(2,p,source,environment);
if(type.element.data != null) {
int target = environment.allocate(type.element.data,p.variable);
myOut(2,type2JavaType(type.element.data) + " r" + target + " = r" + source + ".contents;");
translate(p.data,target,environment);
}
}
public void translate(Pattern.Set p, int source, Environment environment) {
}
public void translate(Pattern.Bag p, int source, Environment environment) {
}
public void translate(Pattern.List p, int source, Environment environment) {
}
public boolean translate(RuleDecl decl, Environment environment) {
boolean conditional = false;
int thus = environment.get("this");
for(Pair<String,Expr> let : decl.lets) {
String letVar = let.first();
Expr letExpr = let.second();
int result = translate(2, letExpr, environment);
environment.put(result, letVar);
}
int level = 2;
if(decl.condition != null) {
int condition = translate(2, decl.condition, environment);
myOut(level++, "if(r" + condition + ") {");
}
int result = translate(level, decl.result, environment);
result = coerceFromValue(level,decl.result,result,environment);
myOut(level, "return automaton.rewrite(r" + thus + ", r" + result + ");");
if(decl.condition != null) {
myOut(--level,"}");
}
return conditional;
}
public void writeSchema() {
myOut(1,
"
myOut(1, "// Schema");
myOut(1,
"
myOut();
myOut(1, "public static final Type.Term[] SCHEMA = new Type.Term[]{");
for (int i = 0, j = 0; i != spDecl.size(); ++i) {
Decl d = spDecl.get(i);
if (d instanceof TermDecl) {
TermDecl td = (TermDecl) d;
if (j++ != 0) {
myOut(",");
}
indent(2);
writeTypeSchema(td.type);
}
}
myOut();
myOut(1, "};");
}
public void writeTypeSchema(Type t) {
if(t instanceof Type.Int) {
out.print("Type.T_INT");
} else if(t instanceof Type.Real) {
out.print("Type.T_REAL");
} else if(t instanceof Type.Strung) {
out.print("Type.T_STRING");
} else if(t instanceof Type.Any) {
out.print("Type.T_ANY");
} else if(t instanceof Type.Void) {
out.print("Type.T_VOID");
} else if(t instanceof Type.Ref) {
Type.Ref ref = (Type.Ref) t;
out.print("Type.T_REF(");
writeTypeSchema(ref.element);
out.print(")");
} else if(t instanceof Type.Compound) {
Type.Compound compound = (Type.Compound) t;
if(compound instanceof Type.List) {
out.print("Type.T_LIST(");
} else {
out.print("Type.T_SET(");
}
if(compound.unbounded) {
out.print("true");
} else {
out.print("false");
}
Type[] elements = compound.elements;
for(int i=0;i!=elements.length;++i) {
out.print(",");
writeTypeSchema(elements[i]);
}
out.print(")");
} else {
Type.Term term = (Type.Term) t;
out.print("Type.T_TERM(\"" + term.name + "\",");
if(term.data != null) {
writeTypeSchema(term.data);
} else {
out.print("null");
}
out.print(")");
}
}
public int translate(int level, Expr code, Environment environment) {
if (code instanceof Expr.Constant) {
return translate(level,(Expr.Constant) code, environment);
} else if (code instanceof Expr.UnOp) {
return translate(level,(Expr.UnOp) code, environment);
} else if (code instanceof Expr.BinOp) {
return translate(level,(Expr.BinOp) code, environment);
} else if (code instanceof Expr.NaryOp) {
return translate(level,(Expr.NaryOp) code, environment);
} else if (code instanceof Expr.Constructor) {
return translate(level,(Expr.Constructor) code, environment);
} if (code instanceof Expr.Variable) {
return translate(level,(Expr.Variable) code, environment);
} else {
throw new RuntimeException("unknown expression encountered - " + code);
}
}
public int translate(int level, Expr.Constant code, Environment environment) {
Type type = code.attribute(Attribute.Type.class).type;
Object v = code.value;
String rhs;
if (v instanceof Boolean) {
rhs = v.toString();
} else if (v instanceof BigInteger) {
BigInteger bi = (BigInteger) v;
if(bi.bitLength() <= 64) {
rhs = "new Automaton.Int(" + bi.longValue() + ")";
} else {
rhs = "new Automaton.Int(\"" + bi.toString() + "\")";
}
} else {
throw new RuntimeException("unknown constant encountered (" + v
+ ")");
}
int target = environment.allocate(type);
myOut(level,comment(type2JavaType(type) + " r" + target + " = " + rhs + ";",code.toString()));
return target;
}
public int translate(int level, Expr.UnOp code, Environment environment) {
Type type = code.attribute(Attribute.Type.class).type;
int rhs = translate(level,code.mhs,environment);
String body;
switch (code.op) {
case LENGTHOF:
body = "BigInteger.valueOf(r" + rhs + ".length)";
break;
case NEG:
body = "r" + rhs + ".negate()";
break;
case NOT:
body = "!r" + rhs;
break;
default:
throw new RuntimeException("unknown unary expression encountered");
}
int target = environment.allocate(type);
myOut(level,comment(type2JavaType(type) + " r" + target + " = " + body + ";",code.toString()));
return target;
}
public int translate(int level, Expr.BinOp code, Environment environment) {
Type type = code.attribute(Attribute.Type.class).type;
int lhs = translate(level,code.lhs,environment);
int rhs = translate(level,code.rhs,environment);
String body;
switch (code.op) {
case ADD:
body = "r" + lhs + ".add(r" + rhs + ")";
break;
case SUB:
body = "r" + lhs + ".subtract(r" + rhs + ")";
break;
case MUL:
body = "r" + lhs + ".multiply(r" + rhs + ")";
break;
case DIV:
body = "r" + lhs + ".divide(r" + rhs + ")";
break;
case AND:
body = "r" + lhs + " && r" + rhs ;
break;
case OR:
body = "r" + lhs + " || r" + rhs ;
break;
case EQ:
// FIXME: support lists as well!
body = "r" + lhs + " == r" + rhs ;
break;
case NEQ:
// FIXME: support lists as well!
body = "r" + lhs + " != r" + rhs ;
break;
case LT:
body = "r" + lhs + ".compareTo(r" + rhs + ")<0";
break;
case LTEQ:
body = "r" + lhs + ".compareTo(r" + rhs + ")<=0";
break;
case GT:
body = "r" + lhs + ".compareTo(r" + rhs + ")>0";
break;
case GTEQ:
body = "r" + lhs + ".compareTo(r" + rhs + ")>=0";
break;
case APPEND:
Type lhs_t = code.lhs.attribute(Attribute.Type.class).type;
if (lhs_t instanceof Type.Compound) {
body = "r" + lhs + ".append(r" + rhs + ")";
} else {
body = "r" + rhs + ".appendFront(r" + lhs + ")";
}
break;
case DIFFERENCE:
body = "r" + lhs + ".removeAll(r" + rhs + ")";
break;
default:
throw new RuntimeException("unknown binary operator encountered: "
+ code);
}
int target = environment.allocate(type);
myOut(level,comment( type2JavaType(type) + " r" + target + " = " + body + ";",code.toString()));
return target;
}
public int translate(int level, Expr.NaryOp code, Environment environment) {
Type type = code.attribute(Attribute.Type.class).type;
String body = "new Automaton.";
if(code.op == wyone.core.Code.NOp.LISTGEN) {
body += "List(";
} else if(code.op == wyone.core.Code.NOp.BAGGEN) {
body += "Bag(";
} else {
body += "Set(";
}
List<Expr> arguments = code.arguments;
for(int i=0;i!=arguments.size();++i) {
if(i != 0) {
body += ", ";
}
body += "r" + translate(level,arguments.get(i),environment);
}
int target = environment.allocate(type);
myOut(level,comment(type2JavaType(type) + " r" + target + " = " + body + ");",code.toString()));
return target;
}
public int translate(int level, Expr.Constructor code,
Environment environment) {
Type type = code.attribute(Attribute.Type.class).type;
String body;
if (code.argument == null) {
body = code.name;
} else {
body = "new Automaton.Term(K_" + code.name + ",r"
+ translate(level, code.argument, environment) + ")";
}
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + body + ";");
return target;
}
public int translate(int level, Expr.Variable code, Environment environment) {
Integer operand = environment.get(code.var);
if(operand != null) {
return environment.get(code.var);
} else {
Type type = code
.attribute(Attribute.Type.class).type;
int target = environment.allocate(type);
myOut(level, type2JavaType(type) + " r" + target + " = " + code.var + ";");
return target;
}
}
protected String nameMangle(Type type, HashSet<String> used) {
String mangle = null;
String _mangle = type2HexStr(type);
int i = 0;
do {
mangle = _mangle + "_" + i++;
} while (used.contains(mangle));
used.add(mangle);
return mangle;
}
protected void writeTypeTests(HashMap<String, Set<String>> hierarchy) {
myOut(1,
"
myOut(1, "// Type Tests");
myOut(1,
"
myOut();
HashSet<Type> worklist = new HashSet<Type>(typeTests);
while (!worklist.isEmpty()) {
Type t = worklist.iterator().next();
worklist.remove(t);
writeTypeTest(t, worklist, hierarchy);
}
}
protected void writeTypeTest(Type type, HashSet<Type> worklist,
HashMap<String, Set<String>> hierarchy) {
if (type instanceof Type.Any) {
writeTypeTest((Type.Any)type,worklist,hierarchy);
} else if (type instanceof Type.Int) {
writeTypeTest((Type.Int)type,worklist,hierarchy);
} else if (type instanceof Type.Strung) {
writeTypeTest((Type.Strung)type,worklist,hierarchy);
} else if (type instanceof Type.Ref) {
writeTypeTest((Type.Ref)type,worklist,hierarchy);
} else if (type instanceof Type.Term) {
writeTypeTest((Type.Term)type,worklist,hierarchy);
} else if (type instanceof Type.Compound) {
writeTypeTest((Type.Compound)type,worklist,hierarchy);
} else {
throw new RuntimeException(
"internal failure --- type test not implemented (" + type
+ ")");
}
}
protected void writeTypeTest(Type.Any type, HashSet<Type> worklist,
HashMap<String, Set<String>> hierarchy) {
String mangle = type2HexStr(type);
myOut(1, "// " + type);
myOut(1, "private static boolean typeof_" + mangle
+ "(Automaton.State state, Automaton automaton) {");
myOut(2, "return true;");
myOut(1, "}");
myOut();
}
protected void writeTypeTest(Type.Int type, HashSet<Type> worklist,
HashMap<String, Set<String>> hierarchy) {
String mangle = type2HexStr(type);
myOut(1, "// " + type);
myOut(1, "private static boolean typeof_" + mangle
+ "(Automaton.State state, Automaton automaton) {");
myOut(2, "return state.kind == Automaton.K_INT;");
myOut(1, "}");
myOut();
}
protected void writeTypeTest(Type.Strung type, HashSet<Type> worklist,
HashMap<String, Set<String>> hierarchy) {
String mangle = type2HexStr(type);
myOut(1, "// " + type);
myOut(1, "private static boolean typeof_" + mangle
+ "(Automaton.State state, Automaton automaton) {");
myOut(2, "return state.kind == Automaton.K_STRING;");
myOut(1, "}");
myOut();
}
protected void writeTypeTest(Type.Ref type, HashSet<Type> worklist,
HashMap<String, Set<String>> hierarchy) {
String mangle = type2HexStr(type);
String elementMangle = type2HexStr(type.element);
myOut(1, "// " + type);
myOut(1, "private static boolean typeof_" + mangle
+ "(int index, Automaton automaton) {");
myOut(2, "return typeof_" + elementMangle + "(automaton.get(index),automaton);");
myOut(1, "}");
myOut();
if (typeTests.add(type.element)) {
worklist.add(type.element);
}
}
protected void writeTypeTest(Type.Term type, HashSet<Type> worklist,
HashMap<String, Set<String>> hierarchy) {
String mangle = type2HexStr(type);
myOut(1, "// " + type);
myOut(1, "private static boolean typeof_" + mangle
+ "(Automaton.State state, Automaton automaton) {");
HashSet<String> expanded = new HashSet<String>();
expand(type.name, hierarchy, expanded);
indent(2);
out.print("if(state instanceof Automaton.Term && (");
boolean firstTime = true;
for (String n : expanded) {
myOut();
indent(2);
if(!firstTime) {
out.print(" || state.kind == K_" + n);
} else {
firstTime=false;
out.print(" state.kind == K_" + n);
}
}
myOut(")) {");
// FIXME: there is definitely a bug here since we need the offset within the automaton state
if (type.data != null) {
myOut(3,"int data = ((Automaton.Term)state).contents;");
myOut(3,"if(typeof_" + type2HexStr(type.data) + "(data,automaton)) { return true; }");
if (typeTests.add(type.data)) {
worklist.add(type.data);
}
} else {
myOut(3, "return true;");
}
myOut(2, "}");
myOut(2, "return false;");
myOut(1, "}");
myOut();
}
protected void writeTypeTest(Type.Compound type, HashSet<Type> worklist,
HashMap<String, Set<String>> hierarchy) {
String mangle = type2HexStr(type);
myOut(1, "// " + type);
myOut(1, "private static boolean typeof_" + mangle
+ "(Automaton.State _state, Automaton automaton) {");
myOut(2, "if(_state instanceof Automaton.Compound) {");
myOut(3, "Automaton.Compound state = (Automaton.Compound) _state;");
myOut(3, "int[] children = state.children;");
Type[] tt_elements = type.elements;
int min = tt_elements.length;
if (type.unbounded) {
myOut(3, "if(children.length < " + (min - 1)
+ ") { return false; }");
} else {
myOut(3, "if(children.length != " + min + ") { return false; }");
}
int level = 3;
if(type instanceof Type.List) {
// easy, sequential match case
for (int i = 0; i != tt_elements.length; ++i) {
myOut(3, "int s" + i + " = " + i + ";");
}
} else {
for (int i = 0; i != tt_elements.length; ++i) {
if(!type.unbounded || i+1 < tt_elements.length) {
String idx = "s" + i;
myOut(3+i, "for(int " + idx + "=0;" + idx + " < children.length;++" + idx + ") {");
if(i > 0) {
indent(3+i);out.print("if(");
for(int j=0;j<i;++j) {
if(j != 0) {
out.print(" || ");
}
out.print(idx + "==s" + j);
}
out.println(") { continue; }");
}
level++;
}
}
}
myOut(level, "boolean result=true;");
myOut(level, "for(int i=0;i!=children.length;++i) {");
myOut(level+1, "int child = children[i];");
for (int i = 0; i != tt_elements.length; ++i) {
Type pt = tt_elements[i];
String pt_mangle = type2HexStr(pt);
if (type.unbounded && (i + 1) == tt_elements.length) {
if(i == 0) {
myOut(level+1, "{");
} else {
myOut(level+1, "else {");
}
} else if(i == 0){
myOut(level+1, "if(i == s" + i + ") {");
} else {
myOut(level+1, "else if(i == s" + i + ") {");
}
myOut(level+2, "if(!typeof_" + pt_mangle
+ "(child,automaton)) { result=false; break; }");
myOut(level+1, "}");
if (typeTests.add(pt)) {
worklist.add(pt);
}
}
myOut(level,"}");
myOut(level,"if(result) { return true; } // found match");
if(type instanceof Type.Bag || type instanceof Type.Set) {
for (int i = 0; i != tt_elements.length; ++i) {
if(!type.unbounded || i+1 < tt_elements.length) {
myOut(level - (i+1),"}");
}
}
}
myOut(2, "}");
myOut(2,"return false;");
myOut(1, "}");
myOut();
}
protected void expand(String name, HashMap<String, Set<String>> hierarchy,
HashSet<String> result) {
// FIXME: this could be made more efficient by not expanding things
// which are already expanded!
ArrayList<String> worklist = new ArrayList<String>();
worklist.add(name);
while (!worklist.isEmpty()) {
String n = worklist.get(0);
worklist.remove(0);
boolean matched = false;
for (Map.Entry<String, Set<String>> e : hierarchy.entrySet()) {
Set<String> parents = e.getValue();
if (parents.contains(n)) {
worklist.add(e.getKey());
matched = true;
}
}
if (!matched) {
result.add(n);
}
}
}
protected void writeMainMethod() {
myOut(1,
"
myOut(1, "// Main Method");
myOut(1,
"
myOut();
myOut(1, "public static void main(String[] args) throws IOException {");
myOut(2, "try {");
myOut(3,
"PrettyAutomataReader reader = new PrettyAutomataReader(System.in,SCHEMA);");
myOut(3,
"PrettyAutomataWriter writer = new PrettyAutomataWriter(System.out,SCHEMA);");
myOut(3, "Automaton automaton = reader.read();");
myOut(3, "System.out.print(\"PARSED: \");");
myOut(3, "writer.write(automaton);");
myOut(3, "System.out.println();");
myOut(3, "boolean changed = true;");
myOut(3, "while(changed) {");
myOut(4, "changed = false;");
myOut(4, "for(int i=0;i<automaton.nStates();++i) {");
myOut(5, "if(automaton.get(i) != null) {");
myOut(6, "changed |= rewrite_" + nameMangle(Type.T_REFANY,new HashSet<String>()) + "(i,automaton);");
myOut(5, "}");
myOut(4, "}");
myOut(3, "}");
myOut(3, "System.out.print(\"REWROTE: \");");
myOut(3, "writer.write(automaton);");
myOut(3, "System.out.println();");
myOut(2, "} catch(PrettyAutomataReader.SyntaxError ex) {");
myOut(3, "System.err.println(ex.getMessage());");
myOut(2, "}");
myOut(1, "}");
}
public String comment(String code, String comment) {
int nspaces = 30 - code.length();
String r = "";
for(int i=0;i<nspaces;++i) {
r += " ";
}
return code + r + " // " + comment;
}
public String type2HexStr(Type t) {
String mangle = "";
String str = Type.type2str(t);
for (int i = 0; i != str.length(); ++i) {
char c = str.charAt(i);
mangle = mangle + Integer.toHexString(c);
}
return mangle;
}
/**
* Convert a Wyone type into its equivalent Java type.
*
* @param type
* @return
*/
public String type2JavaType(Type type) {
if (type instanceof Type.Any) {
return "Object";
} else if (type instanceof Type.Int) {
return "Automaton.Int";
} else if (type instanceof Type.Bool) {
// FIXME: not sure what to do here?
return "boolean";
} else if (type instanceof Type.Strung) {
return "Automaton.Strung";
} else if (type instanceof Type.Term) {
return "Automaton.Term";
} else if (type instanceof Type.Ref) {
return "int";
} else if (type instanceof Type.List) {
return "Automaton.List";
} else if (type instanceof Type.Bag) {
return "Automaton.Bag";
} else if (type instanceof Type.Set) {
return "Automaton.Set";
}
throw new RuntimeException("unknown type encountered: " + type);
}
public int coerceFromValue(int level, Expr expr, int register, Environment environment) {
Type type = expr.attribute(Attribute.Type.class).type;
if(type instanceof Type.Ref) {
return register;
} else {
Type.Ref refType = Type.T_REF(type);
int result = environment.allocate(refType);
myOut(level, type2JavaType(refType) + " r" + result + " = automaton.add(r" + register + ");");
return result;
}
}
public int coerceFromRef(int level, SyntacticElement elem, int register, Environment environment) {
Type type = elem.attribute(Attribute.Type.class).type;
if(type instanceof Type.Ref) {
Type.Ref refType = (Type.Ref) type;
int result = environment.allocate(refType.element);
String cast = type2JavaType(refType.element);
myOut(level, cast + " r" + result + " = (" + cast + ") automaton.get(r" + register + ");");
return result;
} else {
return register;
}
}
protected void myOut() {
myOut(0, "");
}
protected void myOut(int level) {
myOut(level, "");
}
protected void myOut(String line) {
myOut(0, line);
}
protected void myOut(int level, String line) {
for (int i = 0; i < level; ++i) {
out.print("\t");
}
out.println(line);
}
protected void indent(int level) {
for (int i = 0; i < level; ++i) {
out.print("\t");
}
}
private static class Environment {
private final HashMap<String, Integer> var2idx = new HashMap<String, Integer>();
private final ArrayList<Type> idx2type = new ArrayList<Type>();
public int allocate(Type t) {
int idx = idx2type.size();
idx2type.add(t);
return idx;
}
public int allocate(Type t, String v) {
int r = allocate(t);
var2idx.put(v, r);
return r;
}
public Integer get(String v) {
return var2idx.get(v);
}
public void put(int idx, String v) {
var2idx.put(v, idx);
}
public ArrayList<Type> asList() {
return idx2type;
}
public String toString() {
return idx2type.toString() + "," + var2idx.toString();
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package syncfiles.webserver;
/**
*
* @author andred
*/
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.StringTokenizer;
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n";
Socket socket;
// Constructor
public HttpRequest(Socket socket) throws Exception {
this.socket = socket;
}
// Implement the run() method of the Runnable interface.
@Override
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
private void processRequest() throws Exception {
// Get a reference to the socket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Set up input stream filters.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Get the request line of the HTTP request message.
String requestLine = br.readLine();
// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
String HTTP_REQUEST = tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory.
fileName = "." + fileName ;
// Open the requested file.
FileInputStream fis = null ;
boolean fileExists = true ;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false ;
}
// Debug info for private use
System.out.println("Incoming!!!");
System.out.println(requestLine);
String headerLine = null;
String bodyLine = null;
String contentLength = null;
String contentLine = "";
while ((headerLine = br.readLine()).length() != 0) {
System.out.println(headerLine);
if(headerLine.contains("Content-Length"))
{
contentLength = headerLine.replaceAll("\\D+","");
}
}
if(requestLine.contains("POST")){
for(int i = 0; i < Integer.parseInt(contentLength); i++ ){
//System.out.print((char)br.read());
contentLine += (char)br.read();
}
System.out.println(contentLine);
WebPage wp = new WebPage(contentLine);
}
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists) {
statusLine = "HTTP/1.0 200 OK" + CRLF;
contentTypeLine = "Content-Type: " +
contentType(fileName) + CRLF;
} else {
statusLine = "HTTP/1.0 404 Not Found" + CRLF;
contentTypeLine = "Content-Type: text/html" + CRLF;
entityBody = "<HTML>" +
"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
"<BODY>Not Found!</BODY></HTML>";
}
// Send the status line.
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
// Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody) ;
}
// Close streams and socket.
os.close();
br.close();
socket.close();
}
private static void sendBytes(FileInputStream fis,
OutputStream os) throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while ((bytes = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytes);
}
}
private static String contentType(String fileName) {
if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html; charset=utf-8";
}
if(fileName.endsWith(".ram") || fileName.endsWith(".ra")) {
return "audio/x-pn-realaudio";
}
if(fileName.endsWith(".css")){
return "text/css";
}
if(fileName.endsWith(".js")){
return "application/javascript";
}
if(fileName.endsWith(".jpg")){
return "image/jpeg";
}
if(fileName.endsWith(".png")){
return "image/png";
}
return "application/octet-stream" ;
}
}
|
package com.esri.arcgisruntime.sample.servicefeaturetablecache;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.esri.arcgisruntime.datasource.arcgis.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.Map;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.MapView;
public class MainActivity extends AppCompatActivity {
MapView mMapView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// inflate MapView from layout
mMapView = (MapView) findViewById(R.id.mapView);
// create a map with the light grey canvas basemap
Map map = new Map(Basemap.createLightGrayCanvas());
//set an initial viewpoint
map.setInitialViewpoint( new Viewpoint(new Envelope(-1.30758164047166E7, 4014771.46954516, -1.30730056797177E7
, 4016869.78617381, SpatialReferences.getWebMercator() )));
// create feature layer with its service feature table
// create the service feature table
ServiceFeatureTable serviceFeatureTable = new ServiceFeatureTable(getResources().getString(R.string.sample_service_url));
//explicitly set the mode to on interaction cache (which is also the default mode for service feature tables)
serviceFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.ON_INTERACTION_CACHE);
// create the feature layer using the service feature table
FeatureLayer featureLayer = new FeatureLayer(serviceFeatureTable);
// add the layer to the map
map.getOperationalLayers().add(featureLayer);
// set the map to be displayed in the mapview
mMapView.setMap(map);
}
@Override
protected void onPause(){
super.onPause();
// pause MapView
mMapView.pause();
}
@Override
protected void onResume(){
super.onResume();
// resume MapView
mMapView.resume();
}
}
|
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.animation.ui.editor;
import static java.lang.System.out;
import static phasereditor.ui.PhaserEditorUI.swtRun;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.preference.JFacePreferences;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPersistableEditor;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.CommandContributionItemParameter;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.json.JSONException;
import javafx.animation.Animation.Status;
import phasereditor.animation.ui.AnimationCanvas;
import phasereditor.animation.ui.AnimationCanvas.IndexTransition;
import phasereditor.animation.ui.editor.properties.AnimationsPGridPage;
import phasereditor.animation.ui.editor.wizards.AssetsSplitter;
import phasereditor.assetpack.core.AtlasAssetModel;
import phasereditor.assetpack.core.IAssetFrameModel;
import phasereditor.assetpack.core.IAssetKey;
import phasereditor.assetpack.core.ImageAssetModel;
import phasereditor.assetpack.core.MultiAtlasAssetModel;
import phasereditor.assetpack.core.SpritesheetAssetModel;
import phasereditor.assetpack.core.animations.AnimationModel;
import phasereditor.assetpack.ui.AssetPackUI;
import phasereditor.ui.EditorSharedImages;
import phasereditor.ui.FilteredTreeCanvas;
import phasereditor.ui.IEditorSharedImages;
import phasereditor.ui.ImageCanvas_Zoom_1_1_Action;
import phasereditor.ui.ImageCanvas_Zoom_FitWindow_Action;
import phasereditor.ui.SelectionProviderImpl;
import phasereditor.ui.TreeCanvasViewer;
/**
* @author arian
*
*/
public class AnimationsEditor extends EditorPart implements IPersistableEditor {
public static final String ID = "phasereditor.animation.ui.AnimationsEditor"; //$NON-NLS-1$
private AnimationsModel_in_Editor _model;
private AnimationCanvas _animCanvas;
Outliner _outliner;
ISelectionChangedListener _outlinerListener;
private AnimationTimelineCanvas_in_Editor _timelineCanvas;
private Action _playAction;
private Action _pauseAction;
private Action _stopAction;
private Action[] _playbackActions = { _playAction, _pauseAction, _stopAction };
private ImageCanvas_Zoom_1_1_Action _zoom_1_1_action;
private ImageCanvas_Zoom_FitWindow_Action _zoom_fitWindow_action;
private boolean _dirty;
private String _initialAnimtionKey;
public AnimationsEditor() {
}
/**
* Create contents of the editor part.
*
* @param parent
*/
@Override
public void createPartControl(Composite parent) {
SashForm sash = new SashForm(parent, SWT.VERTICAL);
Composite topComp = new Composite(sash, SWT.BORDER);
GridLayout layout = new GridLayout(1, false);
layout.verticalSpacing = 0;
layout.marginWidth = 0;
layout.marginHeight = 0;
topComp.setLayout(layout);
_animCanvas = new AnimationCanvas(topComp, SWT.NONE);
_animCanvas.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
createToolbar(topComp);
_timelineCanvas = new AnimationTimelineCanvas_in_Editor(sash, SWT.BORDER);
_timelineCanvas.setEditor(this);
sash.setWeights(new int[] { 2, 1 });
afterCreateWidgets();
}
private void afterCreateWidgets() {
getEditorSite().setSelectionProvider(new ISelectionProvider() {
private ISelection _selection;
private ListenerList<ISelectionChangedListener> _listeners = new ListenerList<>();
@Override
public void setSelection(ISelection selection) {
_selection = selection;
var event = new SelectionChangedEvent(this, selection);
for (var l : _listeners) {
l.selectionChanged(event);
}
}
@Override
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
_listeners.remove(listener);
}
@Override
public ISelection getSelection() {
return _selection;
}
@Override
public void addSelectionChangedListener(ISelectionChangedListener listener) {
_listeners.add(listener);
}
});
_animCanvas.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
var anim = getTimelineCanvas().getModel();
if (anim != null) {
getTimelineCanvas().clearSelection();
}
}
});
_animCanvas.setNoImageMessage("");
_animCanvas.setStepCallback(_timelineCanvas::redraw);
_animCanvas.setPlaybackCallback(this::animationStatusChanged);
_animCanvas.addPaintListener(e -> {
if (_animCanvas.getModel() != null) {
e.gc.setForeground(JFaceResources.getColorRegistry().get(JFacePreferences.DECORATIONS_COLOR));
e.gc.drawText(_animCanvas.getModel().getKey(), 0, 0, true);
}
});
disableToolbar();
createContextMenu();
AnimationModel_in_Editor anim = null;
if (!_model.getAnimations().isEmpty()) {
anim = (AnimationModel_in_Editor) _model.getAnimations().get(0);
}
if (_initialAnimtionKey != null) {
var opt = _model.getAnimations().stream().filter(a -> a.getKey().equals(_initialAnimtionKey)).findFirst();
if (opt.isPresent()) {
anim = (AnimationModel_in_Editor) opt.get();
}
}
if (anim != null) {
loadAnimation(anim);
}
init_DND_Support();
}
private void init_DND_Support() {
{
int options = DND.DROP_MOVE | DND.DROP_DEFAULT;
DropTarget target = new DropTarget(_animCanvas, options);
Transfer[] types = { LocalSelectionTransfer.getTransfer() };
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
@Override
public void drop(DropTargetEvent event) {
if (event.data instanceof Object[]) {
createAnimationsWithDrop((Object[]) event.data);
}
if (event.data instanceof IStructuredSelection) {
createAnimationsWithDrop(((IStructuredSelection) event.data).toArray());
}
}
});
}
}
protected final void openNewAnimationDialog(List<AnimationFrameModel_in_Editor> frames) {
String initialName = "untitled";
InputDialog dlg = new InputDialog(getAnimationCanvas().getShell(), "New Animation",
"Enter the name of the new animation.", initialName, new IInputValidator() {
@Override
public String isValid(String newText) {
if (getModel().getAnimations().stream().filter(a -> a.getKey().equals(newText)).findFirst()
.isPresent()) {
return "That name is used by other animation.";
}
return null;
}
});
if (dlg.open() == Window.OK) {
var anim = new AnimationModel_in_Editor(getModel());
anim.setKey(dlg.getValue());
if (frames != null) {
anim.getFrames().addAll(frames);
}
getModel().getAnimations().add(anim);
anim.buildTimeline();
if (_outliner != null) {
_outliner.refresh();
}
selectAnimation(anim);
setDirty();
}
}
private void createContextMenu() {
MenuManager menuManager = new MenuManager();
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
manager.removeAll();
manager.add(new Action("New Animation",
EditorSharedImages.getImageDescriptor(IEditorSharedImages.IMG_NEW_FRAME_ANIMATION)) {
@Override
public void run() {
openNewAnimationDialog(null);
}
});
manager.add(new CommandContributionItem(
new CommandContributionItemParameter(getEditorSite(),
"outline", "phasereditor.ui.quickOutline", SWT.PUSH)));
AnimationModel currentAnim = getAnimationCanvas().getModel();
if (currentAnim != null) {
manager.add(new Separator());
manager.add(new Action("Delete", Workbench.getInstance().getSharedImages()
.getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE)) {
@Override
public void run() {
deleteAnimations(List.of((AnimationModel_in_Editor) currentAnim));
}
});
}
}
});
var menu = menuManager.createContextMenu(_animCanvas);
_animCanvas.setMenu(menu);
}
private void disableToolbar() {
for (var btn : _playbackActions) {
btn.setEnabled(false);
}
_zoom_1_1_action.setEnabled(false);
_zoom_fitWindow_action.setEnabled(false);
}
private void animationStatusChanged(Status status) {
out.println("status: " + status);
switch (status) {
case RUNNING:
_playAction.setChecked(true);
_pauseAction.setChecked(false);
break;
case STOPPED:
// TODO: do we really want to do this? it breaks the animation, it looks like
// the first frame is actually the last frame of the animation.
// AnimationCanvas animCanvas = getAnimationCanvas();
// var anim = animCanvas.getModel();
// var frames = anim.getFrames();
// if (!frames.isEmpty()) {
// animCanvas.showFrame(0);
_playAction.setChecked(false);
_pauseAction.setChecked(false);
break;
case PAUSED:
_playAction.setChecked(false);
_pauseAction.setChecked(true);
break;
default:
break;
}
_playAction.setEnabled(!_playAction.isChecked());
_pauseAction.setEnabled(_playAction.isChecked());
_stopAction.setEnabled(_playAction.isChecked() || _pauseAction.isChecked());
}
public void gridPropertyChanged() {
setDirty();
var running = !_animCanvas.isStopped();
_animCanvas.stop();
var anim = _timelineCanvas.getModel();
anim.buildTimeline();
_timelineCanvas.redraw();
if (running) {
_animCanvas.play();
}
}
private ToolBar createToolbar(Composite parent) {
ToolBarManager manager = new ToolBarManager(SWT.BORDER);
_playAction = new Action("Play", IAction.AS_CHECK_BOX) {
{
setImageDescriptor(EditorSharedImages.getImageDescriptor(IEditorSharedImages.IMG_PLAY));
}
@Override
public void run() {
AnimationCanvas canvas = getAnimationCanvas();
IndexTransition transition = canvas.getTransition();
if (transition == null) {
canvas.play();
} else {
switch (transition.getStatus()) {
case PAUSED:
transition.play();
break;
case STOPPED:
canvas.play();
break;
default:
break;
}
}
getTimelineCanvas().redraw();
canvas.redraw();
}
};
_pauseAction = new Action("Pause", IAction.AS_CHECK_BOX) {
{
setImageDescriptor(EditorSharedImages.getImageDescriptor(IEditorSharedImages.IMG_PAUSE));
}
@Override
public void run() {
getAnimationCanvas().pause();
getTimelineCanvas().redraw();
getAnimationCanvas().redraw();
}
};
_stopAction = new Action("Stop", EditorSharedImages.getImageDescriptor(IEditorSharedImages.IMG_STOP)) {
@Override
public void run() {
getAnimationCanvas().stop();
getTimelineCanvas().redraw();
getAnimationCanvas().redraw();
}
};
_zoom_1_1_action = new ImageCanvas_Zoom_1_1_Action(_animCanvas);
_zoom_fitWindow_action = new ImageCanvas_Zoom_FitWindow_Action(_animCanvas);
manager.add(_playAction);
manager.add(_pauseAction);
manager.add(_stopAction);
manager.add(new Separator());
manager.add(_zoom_1_1_action);
manager.add(_zoom_fitWindow_action);
_playbackActions = new Action[] { _playAction, _pauseAction, _stopAction };
return manager.createControl(parent);
}
@Override
public void setFocus() {
_animCanvas.setFocus();
}
@Override
public void doSave(IProgressMonitor monitor) {
var file = getEditorInput().getFile();
try (ByteArrayInputStream source = new ByteArrayInputStream(_model.toJSON().toString(2).getBytes())) {
file.setContents(source, true, false, monitor);
_dirty = false;
firePropertyChange(PROP_DIRTY);
} catch (JSONException | CoreException | IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public void doSaveAs() {
// Do the Save As operation
}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
}
@Override
protected void setInput(IEditorInput input) {
super.setInput(input);
var file = ((IFileEditorInput) input).getFile();
setPartName(file.getName());
try {
_model = new AnimationsModel_in_Editor(this);
_model.build();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
public IFileEditorInput getEditorInput() {
return (IFileEditorInput) super.getEditorInput();
}
public AnimationsModel_in_Editor getModel() {
return _model;
}
@Override
public boolean isDirty() {
return _dirty;
}
public void setDirty() {
_dirty = true;
firePropertyChange(PROP_DIRTY);
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object getAdapter(Class adapter) {
if (adapter == IContentOutlinePage.class) {
return createOutliner();
}
if (adapter == IPropertySheetPage.class) {
return new AnimationsPGridPage(this);
}
return super.getAdapter(adapter);
}
public AnimationCanvas getAnimationCanvas() {
return _animCanvas;
}
public AnimationTimelineCanvas_in_Editor getTimelineCanvas() {
return _timelineCanvas;
}
private Object createOutliner() {
if (_outliner == null) {
_outliner = new Outliner();
_outlinerListener = new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
outliner_selectionChanged(event);
}
};
_outliner.addSelectionChangedListener(_outlinerListener);
} else {
_outliner.refresh();
}
if (_timelineCanvas.getModel() != null) {
swtRun(() -> {
if (_outliner != null) {
_outliner.setSelection(new StructuredSelection(_timelineCanvas.getModel()));
}
});
}
return _outliner;
}
public Outliner getOutliner() {
return _outliner;
}
protected void outliner_selectionChanged(SelectionChangedEvent event) {
var elem = event.getStructuredSelection().getFirstElement();
var anim = (AnimationModel_in_Editor) elem;
loadAnimation(anim);
getEditorSite().getSelectionProvider().setSelection(event.getStructuredSelection());
}
public void selectAnimation(AnimationModel_in_Editor anim) {
StructuredSelection selection = anim == null ? StructuredSelection.EMPTY : new StructuredSelection(anim);
if (_outliner == null) {
loadAnimation(anim);
getEditorSite().getSelectionProvider().setSelection(selection);
} else {
_outliner.setSelection(selection);
}
}
protected void loadAnimation(AnimationModel_in_Editor anim) {
if (anim == null) {
for (var btn : _playbackActions) {
btn.setChecked(false);
btn.setEnabled(false);
}
_zoom_1_1_action.setEnabled(false);
_zoom_fitWindow_action.setEnabled(false);
_animCanvas.setModel(null);
_timelineCanvas.setModel(null);
return;
}
_animCanvas.setModel(anim, false);
for (var btn : _playbackActions) {
btn.setChecked(false);
btn.setEnabled(btn == _playAction);
}
if (_timelineCanvas.getModel() != anim) {
_timelineCanvas.setModel(anim);
}
_zoom_1_1_action.setEnabled(true);
_zoom_fitWindow_action.setEnabled(true);
}
class Outliner extends Page implements IContentOutlinePage, ISelectionChangedListener {
private FilteredTreeCanvas _filteredTreeCanvas;
private SelectionProviderImpl _selProvider;
private TreeCanvasViewer _viewer;
public Outliner() {
}
@Override
public void createControl(Composite parent) {
_filteredTreeCanvas = new FilteredTreeCanvas(parent, SWT.NONE);
_viewer = new AnimationsTreeViewer(_filteredTreeCanvas.getCanvas());
AssetPackUI.installAssetTooltips(_filteredTreeCanvas.getCanvas(), _filteredTreeCanvas.getUtils());
{
int options = DND.DROP_MOVE | DND.DROP_DEFAULT;
DropTarget target = new DropTarget(_filteredTreeCanvas.getCanvas(), options);
Transfer[] types = { LocalSelectionTransfer.getTransfer() };
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
@Override
public void drop(DropTargetEvent event) {
if (event.data instanceof Object[]) {
createAnimationsWithDrop((Object[]) event.data);
}
if (event.data instanceof IStructuredSelection) {
createAnimationsWithDrop(((IStructuredSelection) event.data).toArray());
}
}
});
}
_viewer.setInput(getModel());
for (var l : _initialListeners) {
_filteredTreeCanvas.getUtils().addSelectionChangedListener(l);
}
if (_initialSelection != null) {
_filteredTreeCanvas.getUtils().setSelection(_initialSelection);
_filteredTreeCanvas.redraw();
}
_initialListeners.clear();
_initialSelection = null;
}
@Override
public void dispose() {
removeSelectionChangedListener(_outlinerListener);
AnimationsEditor.this._outliner = null;
super.dispose();
}
private ListenerList<ISelectionChangedListener> _initialListeners = new ListenerList<>();
private ISelection _initialSelection;
@Override
public void addSelectionChangedListener(ISelectionChangedListener listener) {
if (_filteredTreeCanvas == null) {
_initialListeners.add(listener);
return;
}
_filteredTreeCanvas.getUtils().addSelectionChangedListener(listener);
}
@Override
public ISelection getSelection() {
return _filteredTreeCanvas.getUtils().getSelection();
}
@Override
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
if (_filteredTreeCanvas == null) {
_initialListeners.remove(listener);
return;
}
_filteredTreeCanvas.getUtils().removeSelectionChangedListener(listener);
}
@Override
public void setSelection(ISelection selection) {
if (_filteredTreeCanvas == null) {
_initialSelection = selection;
return;
}
_filteredTreeCanvas.getUtils().setSelection(selection);
_filteredTreeCanvas.redraw();
}
@Override
public void selectionChanged(SelectionChangedEvent event) {
_selProvider.fireSelectionChanged();
}
@Override
public Control getControl() {
return _filteredTreeCanvas;
}
@Override
public void setFocus() {
_filteredTreeCanvas.setFocus();
}
public void refresh() {
if (_filteredTreeCanvas != null) {
_viewer.refreshContent();
}
}
}
public void build() {
_animCanvas.stop();
_model.build();
if (_outliner != null) {
_outliner.refresh();
}
AnimationModel model = _animCanvas.getModel();
if (model != null) {
_animCanvas.setModel(model, false);
}
_timelineCanvas.setModel(_timelineCanvas.getModel());
}
public void deleteAnimations(List<AnimationModel_in_Editor> animations) {
_model.getAnimations().removeAll(animations);
if (_outliner != null) {
_outliner.refresh();
}
if (animations.contains(_animCanvas.getModel())) {
var anim = _model.getAnimations().isEmpty() ? null : _model.getAnimations().get(0);
selectAnimation((AnimationModel_in_Editor) anim);
}
setDirty();
}
public void deleteFrames(List<AnimationFrameModel_in_Editor> frames) {
boolean running = !_animCanvas.isStopped();
_animCanvas.stop();
var animation = _animCanvas.getModel();
animation.getFrames().removeAll(frames);
animation.buildTimeline();
if (running) {
_animCanvas.play();
} else {
if (!animation.getFrames().isEmpty()) {
_animCanvas.showFrame(0);
}
}
_timelineCanvas.getSelectedFrames().clear();
_timelineCanvas.redraw();
setDirty();
}
public void playOrPause() {
_animCanvas.playOrPause();
}
@Override
public void saveState(IMemento memento) {
var anim = getAnimationCanvas().getModel();
if (anim != null) {
memento.putString("animation", anim.getKey());
}
}
@Override
public void restoreState(IMemento memento) {
_initialAnimtionKey = memento.getString("animation");
}
public void refreshOutline() {
if (_outliner != null) {
_outliner.refresh();
}
}
@SuppressWarnings("boxing")
public void createAnimationsWithDrop(Object[] data) {
var openFirstAnim = _model.getAnimations().isEmpty();
var splitter = new AssetsSplitter();
for (var obj : data) {
if (obj instanceof AtlasAssetModel) {
splitter.addAll(((AtlasAssetModel) obj).getSubElements());
} else if (obj instanceof MultiAtlasAssetModel) {
splitter.addAll(((MultiAtlasAssetModel) obj).getSubElements());
} else if (obj instanceof SpritesheetAssetModel) {
splitter.addAll(((SpritesheetAssetModel) obj).getFrames());
} else if (obj instanceof IAssetFrameModel) {
splitter.add((IAssetKey) obj);
} else if (obj instanceof ImageAssetModel) {
splitter.add(((ImageAssetModel) obj).getFrame());
}
}
var result = splitter.split();
for (var group : result) {
out.println(group.getPrefix());
for (var asset : group.getAssets()) {
out.println(" " + asset.getKey());
}
}
for (var group : result) {
var anim = new AnimationModel_in_Editor(_model);
_model.getAnimation(group.getPrefix());
anim.setKey(_model.getNewAnimationName(group.getPrefix()));
_model.getAnimations().add(anim);
for (var frame : group.getAssets()) {
var animFrame = new AnimationFrameModel_in_Editor(anim);
animFrame.setFrameAsset((IAssetFrameModel) frame);
animFrame.setTextureKey(frame.getAsset().getKey());
if (frame.getAsset() instanceof ImageAssetModel) {
// nothing
} else if (frame instanceof SpritesheetAssetModel.FrameModel) {
animFrame.setFrameName(((SpritesheetAssetModel.FrameModel) frame).getIndex());
} else {
animFrame.setFrameName(frame.getKey());
}
anim.getFrames().add(animFrame);
}
anim.buildTimeline();
}
// sort animations
_model.getAnimations().sort((a, b) -> a.getKey().compareTo(b.getKey()));
if (_outliner != null) {
_outliner.refresh();
}
if (openFirstAnim) {
if (!_model.getAnimations().isEmpty()) {
var anim = (AnimationModel_in_Editor) _model.getAnimations().get(0);
selectAnimation(anim);
}
}
setDirty();
}
}
|
package internal.org.springframework.content.fs.repository;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.content.commons.annotations.ContentId;
import org.springframework.content.commons.annotations.ContentLength;
import org.springframework.content.commons.io.DeletableResource;
import org.springframework.content.commons.repository.AssociativeStore;
import org.springframework.content.commons.repository.ContentStore;
import org.springframework.content.commons.repository.Store;
import org.springframework.content.commons.utils.BeanUtils;
import org.springframework.content.commons.utils.Condition;
import org.springframework.content.commons.utils.FileService;
import org.springframework.content.fs.io.FileSystemResourceLoader;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.WritableResource;
import javax.annotation.PostConstruct;
public class DefaultFilesystemStoreImpl<S, SID extends Serializable>
implements Store<SID>, AssociativeStore<S, SID>, ContentStore<S, SID> {
private static Log logger = LogFactory.getLog(DefaultFilesystemStoreImpl.class);
private FileSystemResourceLoader loader;
private ConversionService conversion;
private FileService fileService;
public DefaultFilesystemStoreImpl(FileSystemResourceLoader loader,
ConversionService conversion, FileService fileService) {
this.loader = loader;
this.conversion = conversion;
this.fileService = fileService;
}
@Override
public Resource getResource(SID id) {
return getResourceInternal(id);
}
@Override
public Resource getResource(S entity) {
Resource r = getResourceInternal(entity);
if (r != null) {
return r;
}
SID contentId = (SID) BeanUtils.getFieldWithAnnotation(entity, ContentId.class);
if (contentId == null) {
return null;
}
return getResourceInternal(contentId);
}
protected Resource getResourceInternal(S entity) {
String location = conversion.convert(entity, String.class);
Resource resource = loader.getResource(location);
return resource;
}
protected Resource getResourceInternal(SID id) {
String location = conversion.convert(id, String.class);
Resource resource = loader.getResource(location);
return resource;
}
@Override
public void associate(S entity, SID id) {
BeanUtils.setFieldWithAnnotation(entity, ContentId.class, id.toString());
}
@Override
public void unassociate(S entity) {
BeanUtils.setFieldWithAnnotationConditionally(entity, ContentId.class, null,
new Condition() {
@Override
public boolean matches(Field field) {
for (Annotation annotation : field.getAnnotations()) {
if ("javax.persistence.Id".equals(
annotation.annotationType().getCanonicalName())
|| "org.springframework.data.annotation.Id"
.equals(annotation.annotationType()
.getCanonicalName())) {
return false;
}
}
return true;
}
});
}
@Override
public void setContent(S property, InputStream content) {
Resource resource = getResource(property);
if (resource == null) {
UUID contentId = UUID.randomUUID();
Object convertedId = convertToExternalContentIdType(property, contentId);
resource = getResource((SID)convertedId);
BeanUtils.setFieldWithAnnotation(property, ContentId.class, convertedId);
}
OutputStream os = null;
try {
if (resource.exists() == false) {
File resourceFile = resource.getFile();
File parent = resourceFile.getParentFile();
this.fileService.mkdirs(parent);
}
if (resource instanceof WritableResource) {
os = ((WritableResource) resource).getOutputStream();
IOUtils.copy(content, os);
}
}
catch (IOException e) {
logger.error(String.format("Unexpected error setting content for resource %s",
property.toString()), e);
}
finally {
try {
if (os != null) {
os.close();
}
}
catch (IOException ioe) {
// ignore
}
}
try {
BeanUtils.setFieldWithAnnotation(property, ContentLength.class,
resource.contentLength());
}
catch (IOException e) {
logger.error(String.format(
"Unexpected error setting content length for content for resource %s",
resource.toString()), e);
}
}
@Override
public InputStream getContent(S property) {
if (property == null)
return null;
SID contentId = (SID) BeanUtils.getFieldWithAnnotation(property, ContentId.class);
if (contentId == null)
return null;
Resource resource = getResourceInternal(contentId);
try {
if (resource.exists()) {
return resource.getInputStream();
}
}
catch (IOException e) {
logger.error(String.format("Unexpected error getting content %s",
contentId.toString()), e);
}
return null;
}
@Override
public void unsetContent(S property) {
if (property == null)
return;
SID contentId = (SID) BeanUtils.getFieldWithAnnotation(property, ContentId.class);
if (contentId == null)
return;
// delete any existing content object
Resource resource = getResourceInternal(contentId);
if (resource.exists() && resource instanceof DeletableResource) {
((DeletableResource) resource).delete();
}
// reset content fields
unassociate(property);
BeanUtils.setFieldWithAnnotation(property, ContentLength.class, 0);
}
private Object convertToExternalContentIdType(S property, Object contentId) {
if (conversion.canConvert(TypeDescriptor.forObject(contentId),
TypeDescriptor.valueOf(BeanUtils.getFieldWithAnnotationType(property,
ContentId.class)))) {
contentId = conversion.convert(contentId, TypeDescriptor.forObject(contentId),
TypeDescriptor.valueOf(BeanUtils.getFieldWithAnnotationType(property,
ContentId.class)));
return contentId;
}
return contentId.toString();
}
}
|
package de.loskutov.gitignore;
import static de.loskutov.gitignore.Strings.*;
public class FastIgnoreRule {
private static final NoResultMatcher NO_MATCH = new NoResultMatcher();
private final IgnoreMatcher matcher;
private final boolean inverse;
private final boolean isDirectory;
public FastIgnoreRule(String pattern) {
if(pattern == null){
throw new IllegalArgumentException("Pattern must be not null!");
}
pattern = pattern.trim();
if(pattern.isEmpty()){
isDirectory = false;
inverse = false;
this.matcher = NO_MATCH;
return;
}
inverse = pattern.charAt(0) == '!';
if(inverse){
pattern = pattern.substring(1);
if(pattern.isEmpty()){
isDirectory = false;
this.matcher = NO_MATCH;
return;
}
}
if(pattern.charAt(0) == '
this.matcher = NO_MATCH;
isDirectory = false;
} else {
isDirectory = pattern.charAt(pattern.length() - 1) == '/';
if(isDirectory) {
pattern = stripSlashes(pattern);
if(pattern.isEmpty()){
this.matcher = NO_MATCH;
return;
}
}
this.matcher = createMatcher(pattern, isDirectory);
}
}
private static IgnoreMatcher createMatcher(String pattern, boolean dirOnly) {
pattern = pattern.trim();
// ignore possible leading and trailing slash
int slash = pattern.indexOf('/', 1);
if(slash > 0 && slash < pattern.length() - 1){
return new PathMatcher(pattern, dirOnly);
}
if(isWildCard(pattern)){
return new WildCardMatcher(pattern, dirOnly);
}
return new NameMatcher(pattern, dirOnly);
}
public boolean isMatch(String path, boolean directory) {
if(path == null){
return false;
}
path = path.trim();
if(path.isEmpty()){
return false;
}
boolean match = matcher.matches(path, directory);
return match;
}
public boolean dirOnly() {
return isDirectory;
}
public boolean isInverse() {
return inverse;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (inverse) {
sb.append('!');
}
sb.append(matcher);
if (isDirectory) {
sb.append('/');
}
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (inverse ? 1231 : 1237);
result = prime * result + (isDirectory ? 1231 : 1237);
result = prime * result + ((matcher == null) ? 0 : matcher.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof FastIgnoreRule)) {
return false;
}
FastIgnoreRule other = (FastIgnoreRule) obj;
if(inverse != other.inverse) {
return false;
}
if(isDirectory != other.isDirectory) {
return false;
}
return matcher.equals(other.matcher);
}
static final class NoResultMatcher implements IgnoreMatcher {
@Override
public boolean matches(String path, boolean dirOnly) {
return false;
}
@Override
public boolean matches(String segment, int startIncl, int endExcl, boolean dirOnly) {
return false;
}
}
}
|
package org.caleydo.view.relationshipexplorer.ui.column.item.factory.impl;
import gleem.linalg.Vec2f;
import java.net.URL;
import org.caleydo.core.data.collection.column.container.CategoricalClassDescription;
import org.caleydo.core.data.collection.column.container.CategoryProperty;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.perspective.variable.Perspective;
import org.caleydo.core.id.IDType;
import org.caleydo.core.io.NumericalProperties;
import org.caleydo.core.util.base.ICallback;
import org.caleydo.core.view.opengl.layout2.GLElement;
import org.caleydo.core.view.opengl.layout2.GLElementContainer;
import org.caleydo.core.view.opengl.layout2.PickableGLElement;
import org.caleydo.core.view.opengl.layout2.layout.GLMinSizeProviders;
import org.caleydo.core.view.opengl.layout2.layout.GLPadding;
import org.caleydo.core.view.opengl.layout2.layout.GLSizeRestrictiveFlowLayout2;
import org.caleydo.core.view.opengl.layout2.renderer.GLRenderers;
import org.caleydo.view.relationshipexplorer.ui.ConTourElement;
import org.caleydo.view.relationshipexplorer.ui.collection.IEntityCollection;
import org.caleydo.view.relationshipexplorer.ui.collection.TabularDataCollection;
import org.caleydo.view.relationshipexplorer.ui.column.AEntityColumn;
import org.caleydo.view.relationshipexplorer.ui.column.TabularDataColumn;
import org.caleydo.view.relationshipexplorer.ui.column.item.factory.IItemFactory;
import org.caleydo.view.relationshipexplorer.ui.column.item.factory.IItemFactoryConfigurationAddon;
import org.caleydo.view.relationshipexplorer.ui.column.item.factory.IItemFactoryCreator;
import org.caleydo.view.relationshipexplorer.ui.list.ColumnTreeRenderStyle;
import org.caleydo.view.relationshipexplorer.ui.list.EUpdateCause;
import org.caleydo.view.relationshipexplorer.ui.list.IColumnModel;
import org.caleydo.view.relationshipexplorer.ui.util.SimpleBarRenderer;
/**
* @author Christian
*
*/
public class HTSActivityConfigurationAddon implements IItemFactoryConfigurationAddon {
public static class HTSActivityItemFactoryCreator implements IItemFactoryCreator {
protected static final URL PLOT_ICON = HTSActivityItemFactory.class
.getResource("/org/caleydo/view/relationshipexplorer/icons/hbar.png");
public static class HTSActivityItemFactory implements IItemFactory {
protected static final URL ACTIVATION_ICON = AEntityColumn.class
.getResource("/org/caleydo/view/relationshipexplorer/icons/arrow_right_up.png");
protected static final URL INHIBITION_ICON = AEntityColumn.class
.getResource("/org/caleydo/view/relationshipexplorer/icons/arrow_right_down.png");
protected static final URL BIND_ICON = AEntityColumn.class
.getResource("/org/caleydo/view/relationshipexplorer/icons/arrow_bidirectional.png");
protected final TabularDataColumn column;
public HTSActivityItemFactory(TabularDataColumn column) {
this.column = column;
}
@Override
public GLElement createItem(Object elementID) {
TabularDataCollection collection = (TabularDataCollection) column.getCollection();
ATableBasedDataDomain dataDomain = collection.getDataDomain();
Perspective dimensionPerspective = collection.getDimensionPerspective();
IDType recordIDType = dataDomain.getOppositeIDType(collection.getDimensionPerspective().getIdType());
SimpleBarRenderer ic50Renderer = null;
PickableGLElement interactionTypeRenderer = new PickableGLElement();
interactionTypeRenderer.setSize(16, 16);
interactionTypeRenderer.setMinSizeProvider(GLMinSizeProviders.createDefaultMinSizeProvider(16, 16));
for (int dimensionID : dimensionPerspective.getVirtualArray()) {
Object dataClassDesc = dataDomain.getDataClassSpecificDescription(recordIDType,
(Integer) elementID, dimensionPerspective.getIdType(), dimensionID);
if (dataClassDesc instanceof NumericalProperties) {
NumericalProperties p = (NumericalProperties) dataClassDesc;
// TODO: use correct data center
ic50Renderer = new SimpleBarRenderer();
ic50Renderer.setHorizontal(true);
// ic50Renderer.setShowTooltip(true);
ic50Renderer.setBarWidth(ColumnTreeRenderStyle.COLUMN_SUMMARY_BAR_HEIGHT - 4);
float rawValue = (float) dataDomain.getRaw(recordIDType, (int) elementID,
dimensionPerspective.getIdType(), dimensionID);
ic50Renderer.setValue(rawValue);
ic50Renderer.setTooltip("" + rawValue);
if (p.getMax() != null) {
ic50Renderer.setColor(rawValue > p.getMax() ? dataDomain.getColor().darker().darker()
: dataDomain.getColor());
} else {
ic50Renderer.setColor(dataDomain.getColor());
}
float normalizedValue = dataDomain.getNormalizedValue(recordIDType, (int) elementID,
dimensionPerspective.getIdType(), dimensionID);
ic50Renderer.setNormalizedValue(normalizedValue);
ic50Renderer.setMinSize(new Vec2f(50, 16));
} else {
CategoryProperty<?> property = ((CategoricalClassDescription<?>) dataClassDesc)
.getCategoryProperty(dataDomain.getRaw(recordIDType, (int) elementID,
dimensionPerspective.getIdType(), dimensionID));
if (property != null) {
if (property.getCategoryName().equalsIgnoreCase("activation")) {
interactionTypeRenderer.setRenderer(GLRenderers.fillImage(ACTIVATION_ICON));
interactionTypeRenderer.setTooltip("Activation");
} else if (property.getCategoryName().equalsIgnoreCase("inhibition")) {
interactionTypeRenderer.setRenderer(GLRenderers.fillImage(INHIBITION_ICON));
interactionTypeRenderer.setTooltip("Inhibition");
} else if (property.getCategoryName().equalsIgnoreCase("binding")) {
interactionTypeRenderer.setRenderer(GLRenderers.fillImage(BIND_ICON));
interactionTypeRenderer.setTooltip("Binding");
}
}
}
}
GLElementContainer container = new GLElementContainer(new GLSizeRestrictiveFlowLayout2(true, 2,
GLPadding.ZERO));
container.setMinSizeProvider(GLMinSizeProviders.createHorizontalFlowMinSizeProvider(container, 2,
GLPadding.ZERO));
container.add(interactionTypeRenderer);
container.add(ic50Renderer);
return container;
}
@Override
public GLElement createHeaderExtension() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean needsUpdate(EUpdateCause cause) {
// TODO Auto-generated method stub
return false;
}
@Override
public void update() {
// TODO Auto-generated method stub
}
}
@Override
public IItemFactory create(IEntityCollection collection, IColumnModel column, ConTourElement contour) {
return new HTSActivityItemFactory((TabularDataColumn) column);
}
@Override
public URL getIconURL() {
return PLOT_ICON;
}
}
@Override
public boolean accepts(IEntityCollection collection) {
if (!(collection instanceof TabularDataCollection))
return false;
TabularDataCollection coll = (TabularDataCollection) collection;
ATableBasedDataDomain dataDomain = coll.getDataDomain();
Perspective dimensionPerspective = coll.getDimensionPerspective();
if (dimensionPerspective.getVirtualArray().size() != 2)
return false;
Object elementID = coll.getAllElementIDs().iterator().next();
IDType recordIDType = dataDomain.getOppositeIDType(dimensionPerspective.getIdType());
boolean numericalAttributeExists = false;
boolean categoricalAttributeExists = false;
for (int dimensionID : dimensionPerspective.getVirtualArray()) {
Object dataClassDesc = dataDomain.getDataClassSpecificDescription(recordIDType, (Integer) elementID,
dimensionPerspective.getIdType(), dimensionID);
if (dataClassDesc instanceof NumericalProperties || dataClassDesc == null) {
numericalAttributeExists = true;
} else {
categoricalAttributeExists = true;
}
}
return numericalAttributeExists && categoricalAttributeExists;
}
@Override
public void configure(ICallback<IItemFactoryCreator> callback) {
callback.on(new HTSActivityItemFactoryCreator());
}
@Override
public String getLabel() {
return "HTS Activity";
}
@Override
public Class<? extends IItemFactoryCreator> getConfigObjectClass() {
return HTSActivityItemFactoryCreator.class;
}
}
|
package org.labkey.wnprc_billing.dataentry;
import org.labkey.api.ehr.dataentry.AnimalDetailsFormSection;
import org.labkey.api.ehr.dataentry.DataEntryFormContext;
import org.labkey.api.ehr.dataentry.FormSection;
import org.labkey.api.ehr.dataentry.TaskForm;
import org.labkey.api.ehr.dataentry.TaskFormSection;
import org.labkey.api.module.Module;
import org.labkey.api.view.template.ClientDependency;
import org.labkey.api.ehr_billing.security.EHR_BillingAdminPermission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ChargesFormType extends TaskForm
{
public static final String NAME = "Charges";
public ChargesFormType(DataEntryFormContext ctx, Module owner)
{
super(ctx, owner, NAME, "Charges", "Billing", Arrays.asList(
new TaskFormSection(),
new AnimalDetailsFormSection(),
new ChargesFormSection()
));
addClientDependency(ClientDependency.fromPath("ehr_billing/model/sources/Charges.js"));
addClientDependency(ClientDependency.fromPath("ehr_billing/buttons/financeButtons.js"));
addClientDependency(ClientDependency.fromPath("ehr_billing/DataEntryUtils.js"));
addClientDependency(ClientDependency.fromPath("ehr/DataEntryUtils.js"));
addClientDependency(ClientDependency.fromPath("ehr_billing/form/field/EHRBillingProjectField.js"));
addClientDependency(ClientDependency.fromPath("ehr_billing/form/field/EHRBillingProjectEntryField.js"));
addClientDependency(ClientDependency.fromPath("ehr_billing/form/field/EHRBillingRowObserverEntryField.js"));
addClientDependency(ClientDependency.fromPath("ehr_billing/form/field/EHRBillingChargeIdEntryField.js"));
for (FormSection s : getFormSections())
{
s.addConfigSource("Charges");
}
}
@Override
public boolean isVisible()
{
return false;
}
// @Override
// protected List<String> getMoreActionButtonConfigs()
// List<String> defaultButtons = super.getMoreActionButtonConfigs();
// defaultButtons.add("FINANCESUBMIT");
// return defaultButtons;
// @Override
// protected List<String> getButtonConfigs()
// List<String> defaultButtons = new ArrayList<String>();
// defaultButtons.add("FINANCESUBMIT");
// return defaultButtons;
// @Override
// protected List<String> getMoreActionButtonConfigs()
// return Collections.emptyList();
@Override
public boolean canInsert()
{
if (!getCtx().getContainer().hasPermission(getCtx().getUser(), EHR_BillingAdminPermission.class))
return false;
return super.canInsert();
}
@Override
public boolean canRead()
{
if (!getCtx().getContainer().hasPermission(getCtx().getUser(), EHR_BillingAdminPermission.class))
return false;
return super.canRead();
}
}
|
package better.jsonrpc.websocket;
import java.io.IOException;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocket.OnTextMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import better.jsonrpc.core.JsonRpcConnection;
public class JsonRpcWsConnection extends JsonRpcConnection
implements WebSocket, OnTextMessage {
/** Currently active websocket connection */
private Connection mConnection;
public JsonRpcWsConnection(ObjectMapper mapper) {
super(mapper);
}
@Override
public boolean isConnected() {
return mConnection != null && mConnection.isOpen();
}
public void disconnect() {
if(mConnection != null && mConnection.isOpen()) {
mConnection.close();
}
}
public void transmit(String data) {
log.info("[" + mConnectionId + "] connection transmitting \"" + data + "\"");
if(mConnection != null && mConnection.isOpen()) {
try {
mConnection.sendMessage(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onOpen(Connection connection) {
log.info("[" + mConnectionId + "] connection open");
super.onOpen();
mConnection = connection;
}
@Override
public void onClose(int closeCode, String message) {
log.info("[" + mConnectionId + "] connection close " + closeCode + "/" + message);
super.onClose();
mConnection = null;
}
@Override
public void onMessage(String data) {
log.info("[" + mConnectionId + "] connection received message \"" + data + "\"");
try {
JsonNode message = mMapper.readTree(data);
if(message.isObject()) {
ObjectNode messageObj = ObjectNode.class.cast(message);
// requests and notifications
if(messageObj.has("method") && messageObj.has("params")) {
if(messageObj.has("id")) {
handleRequest(messageObj);
} else {
handleNotification(messageObj);
}
}
// responses
if(messageObj.has("result") || messageObj.has("error")) {
if(messageObj.has("id")) {
handleResponse(messageObj);
}
}
}
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
}
@Override
public void sendRequest(ObjectNode request) {
transmit(request.toString());
}
@Override
public void sendResponse(ObjectNode response) {
transmit(response.toString());
}
@Override
public void sendNotification(ObjectNode notification) {
transmit(notification.toString());
}
}
|
package org.jboss.as.test.integration.security.common.negotiation;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.auth.AUTH;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.InvalidCredentialsException;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.impl.auth.AuthSchemeBase;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BufferedHeader;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.CharArrayBuffer;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.Oid;
import org.jboss.logging.Logger;
public class JBossNegotiateScheme extends AuthSchemeBase {
private static final Logger LOGGER = Logger.getLogger(JBossNegotiateScheme.class);
/** The DEFAULT_LIFETIME */
private static final int DEFAULT_LIFETIME = 60;
private static final String SPNEGO_OID = "1.3.6.1.5.5.2";
enum State {
UNINITIATED, CHALLENGE_RECEIVED, TOKEN_GENERATED, FAILED,
}
private final boolean stripPort;
/** Authentication process state */
private State state;
/** base64 decoded challenge **/
private byte[] token;
private final Base64 base64codec;
/**
* Default constructor for the Negotiate authentication scheme.
*/
public JBossNegotiateScheme(boolean stripPort) {
super();
this.state = State.UNINITIATED;
this.stripPort = stripPort;
this.base64codec = new Base64(0);
}
/**
* Tests if the Negotiate authentication process has been completed.
*
* @return <tt>true</tt> if authorization has been processed, <tt>false</tt> otherwise.
*/
public boolean isComplete() {
return this.state == State.TOKEN_GENERATED || this.state == State.FAILED;
}
/**
* Returns textual designation of the Negotiate authentication scheme.
*
* @return <code>Negotiate</code>
*/
public String getSchemeName() {
return "Negotiate";
}
@Deprecated
public Header authenticate(final Credentials credentials, final HttpRequest request) throws AuthenticationException {
return authenticate(credentials, request, null);
}
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
throws AuthenticationException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (state == State.TOKEN_GENERATED) {
// hack for auto redirects
return new BasicHeader("X-dummy", "Token already generated");
}
if (state != State.CHALLENGE_RECEIVED) {
throw new IllegalStateException("Negotiation authentication process has not been initiated");
}
try {
String key = null;
if (isProxy()) {
key = ExecutionContext.HTTP_PROXY_HOST;
} else {
key = ExecutionContext.HTTP_TARGET_HOST;
}
HttpHost host = (HttpHost) context.getAttribute(key);
if (host == null) {
throw new AuthenticationException("Authentication host is not set " + "in the execution context");
}
String authServer;
if (!this.stripPort && host.getPort() > 0) {
authServer = host.toHostString();
} else {
authServer = host.getHostName();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("init " + authServer);
}
final Oid negotiationOid = new Oid(SPNEGO_OID);
final GSSManager manager = GSSManager.getInstance();
final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null,
DEFAULT_LIFETIME);
gssContext.requestMutualAuth(true);
gssContext.requestCredDeleg(true);
if (token == null) {
token = new byte[0];
}
token = gssContext.initSecContext(token, 0, token.length);
if (token == null) {
state = State.FAILED;
throw new AuthenticationException("GSS security context initialization failed");
}
state = State.TOKEN_GENERATED;
String tokenstr = new String(base64codec.encode(token));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sending response '" + tokenstr + "' back to the auth server");
}
CharArrayBuffer buffer = new CharArrayBuffer(32);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Negotiate ");
buffer.append(tokenstr);
return new BufferedHeader(buffer);
} catch (GSSException gsse) {
state = State.FAILED;
if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.NO_CRED)
throw new InvalidCredentialsException(gsse.getMessage(), gsse);
if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
|| gsse.getMajor() == GSSException.OLD_TOKEN)
throw new AuthenticationException(gsse.getMessage(), gsse);
// other error
throw new AuthenticationException(gsse.getMessage());
}
}
/**
* Returns the authentication parameter with the given name, if available.
*
* <p>
* There are no valid parameters for Negotiate authentication so this method always returns <tt>null</tt>.
* </p>
*
* @param name The name of the parameter to be returned
*
* @return the parameter with the given name
*/
public String getParameter(String name) {
if (name == null) {
throw new IllegalArgumentException("Parameter name may not be null");
}
return null;
}
/**
* The concept of an authentication realm is not supported by the Negotiate authentication scheme. Always returns
* <code>null</code>.
*
* @return <code>null</code>
*/
public String getRealm() {
return null;
}
/**
* Returns <tt>true</tt>. Negotiate authentication scheme is connection based.
*
* @return <tt>true</tt>.
*/
public boolean isConnectionBased() {
return true;
}
@Override
protected void parseChallenge(final CharArrayBuffer buffer, int beginIndex, int endIndex)
throws MalformedChallengeException {
String challenge = buffer.substringTrimmed(beginIndex, endIndex);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Received challenge '" + challenge + "' from the auth server");
}
if (state == State.UNINITIATED) {
token = new Base64().decode(challenge.getBytes());
state = State.CHALLENGE_RECEIVED;
} else {
LOGGER.debug("Authentication already attempted");
state = State.FAILED;
}
}
}
|
package com.xpn.xwiki.store;
import com.xpn.xwiki.test.AbstractBridgedComponentTestCase;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.jmock.Expectations;
import org.junit.Assert;
import java.sql.SQLException;
/**
* Unit tests for the {@link XWikiHibernateStore} class.
*
* @version $Id$
*/
public class XWikiHibernateStoreTest extends AbstractBridgedComponentTestCase
{
@org.junit.Test
public void testGetColumnsForSelectStatement()
{
XWikiHibernateStore store = new XWikiHibernateStore("whatever");
Assert.assertEquals(", doc.date", store.getColumnsForSelectStatement("where 1=1 order by doc.date desc"));
Assert.assertEquals(", doc.date", store.getColumnsForSelectStatement("where 1=1 order by doc.date asc"));
Assert.assertEquals(", doc.date", store.getColumnsForSelectStatement("where 1=1 order by doc.date"));
Assert.assertEquals(", description", store.getColumnsForSelectStatement("where 1=1 order by description desc"));
Assert.assertEquals(", ascendent", store.getColumnsForSelectStatement("where 1=1 order by ascendent asc"));
Assert.assertEquals(", doc.date, doc.name",
store.getColumnsForSelectStatement("where 1=1 order by doc.date, doc.name"));
Assert.assertEquals(", doc.date, doc.name",
store.getColumnsForSelectStatement("where 1=1 order by doc.date ASC, doc.name DESC"));
Assert.assertEquals("", store.getColumnsForSelectStatement(", BaseObject as obj where obj.name=doc.fullName"));
}
@org.junit.Test
public void testCreateSQLQuery()
{
XWikiHibernateStore store = new XWikiHibernateStore("whatever");
Assert.assertEquals(
"select distinct doc.space, doc.name from XWikiDocument as doc where (doc.hidden <> true or doc.hidden is null)",
store.createSQLQuery("select distinct doc.space, doc.name", ""));
Assert.assertEquals("select distinct doc.space, doc.name, doc.date from XWikiDocument as doc "
+ "where (doc.hidden <> true or doc.hidden is null) and 1=1 order by doc.date desc", store.createSQLQuery(
"select distinct doc.space, doc.name", "where 1=1 order by doc.date desc"));
}
@org.junit.Test
public void testEndTransactionWhenSQLBatchUpdateExceptionThrown() throws Exception
{
XWikiHibernateStore store = new XWikiHibernateStore("whatever");
final Transaction mockTransaction = getMockery().mock(Transaction.class);
SQLException sqlException2 = new SQLException("sqlexception2");
sqlException2.setNextException(new SQLException("nextexception2"));
final SQLException sqlException1 = new SQLException("sqlexception1");
sqlException1.initCause(sqlException2);
sqlException1.setNextException(new SQLException("nextexception1"));
getMockery().checking(new Expectations() {{
oneOf(mockTransaction).commit(); will(throwException(new HibernateException("exception1", sqlException1)));
}});
store.setTransaction(mockTransaction, getContext());
try {
store.endTransaction(getContext(), true);
Assert.fail("Should have thrown an exception here");
} catch (HibernateException e) {
Assert.assertEquals("Failed to commit or rollback transaction. Root cause [\n"
+ "SQL next exception = [java.sql.SQLException: nextexception1]\n"
+ "SQL next exception = [java.sql.SQLException: nextexception2]]", e.getMessage());
}
}
}
|
package org.zanata.webtrans.client.keys;
import java.util.Set;
import org.zanata.webtrans.client.events.KeyShortcutEventHandler;
import org.zanata.webtrans.client.presenter.KeyShortcutPresenter;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
/**
* Represents a key shortcut for registration with {@link KeyShortcutPresenter}.
*
* @author David Mason, <a
* href="mailto:damason@redhat.com">damason@redhat.com</a>
*
*/
public class KeyShortcut implements Comparable<KeyShortcut>
{
public enum KeyEvent {
KEY_UP ("keyup"),
KEY_DOWN ("keydown"),
KEY_PRESS ("keypress");
public final String nativeEventType;
KeyEvent(String nativeType)
{
this.nativeEventType = nativeType;
}
}
public static final String DO_NOT_DISPLAY_DESCRIPTION = "";
private final Set<Keys> keys;
private final Set<Keys> attentionKeys;
private final ShortcutContext context;
private String description;
private final KeyShortcutEventHandler handler;
private final KeyEvent keyEvent;
private final boolean stopPropagation;
private final boolean preventDefault;
/**
* Construct a KeyShortcut.
*
* @param builder key shortcut builder
*/
public KeyShortcut(Builder builder)
{
this.keys = builder.keys;
this.attentionKeys = builder.attentionKeys;
this.context = builder.context;
this.description = builder.description;
this.handler = builder.handler;
this.keyEvent = builder.keyEvent;
this.stopPropagation = builder.stopPropagation;
this.preventDefault = builder.preventDefault;
}
public Set<Keys> getAllKeys()
{
return keys;
}
public Set<Keys> getAllAttentionKeys()
{
return attentionKeys;
}
public ShortcutContext getContext()
{
return context;
}
public String getDescription()
{
return description;
}
public KeyShortcutEventHandler getHandler()
{
return handler;
}
public KeyEvent getKeyEvent()
{
return keyEvent;
}
public boolean isDisplayInView()
{
return !DO_NOT_DISPLAY_DESCRIPTION.equals(description);
}
public boolean isStopPropagation()
{
return stopPropagation;
}
public boolean isPreventDefault()
{
return preventDefault;
}
@Override
public int hashCode()
{
int hash = context.ordinal();
for (Keys singleKey : keys)
{
hash *= 2048;
hash += singleKey.hashCode();
}
for (Keys singleKey : attentionKeys)
{
hash *= 2048;
hash += singleKey.hashCode();
}
return hash;
}
/**
* Two {@link KeyShortcut} objects are equal if they have the same key combinations and context.
*/
@Override
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if (!(obj instanceof KeyShortcut))
{
return false;
}
KeyShortcut other = (KeyShortcut) obj;
return keys.equals(other.keys) && attentionKeys.equals(other.attentionKeys)
&& context == other.context;
}
/**
* Used for sorting shortcuts in summary in UI
*
* The decision to sort regular keys before attention keys is arbitrary
*/
@Override
public int compareTo(KeyShortcut o)
{
// assertion: keys and attentionKeys cannot both be empty
if (context.ordinal() != o.context.ordinal())
{
return context.ordinal() - o.context.ordinal();
}
if (keys.isEmpty())
{
if (o.keys.isEmpty())
{
return attentionKeys.iterator().next().compareTo(o.attentionKeys.iterator().next());
}
return 1;
}
else
{
if (o.keys.isEmpty())
{
return -1;
}
return keys.iterator().next().compareTo(o.keys.iterator().next());
}
}
public void setDescription(String description)
{
this.description = description;
}
public static class Builder
{
private Set<Keys> keys = Sets.newHashSet();
private Set<Keys> attentionKeys = Sets.newHashSet();
private ShortcutContext context;
private String description;
private KeyShortcutEventHandler handler;
private KeyEvent keyEvent = KeyEvent.KEY_DOWN;
private boolean stopPropagation = false;
private boolean preventDefault = false;
private Builder(KeyShortcut shortcut)
{
this.keys = shortcut.getAllKeys();
this.attentionKeys = shortcut.getAllAttentionKeys();
this.context = shortcut.getContext();
this.description = shortcut.getDescription();
this.handler = shortcut.getHandler();
this.keyEvent = shortcut.getKeyEvent();
this.stopPropagation = shortcut.isStopPropagation();
this.preventDefault = shortcut.isPreventDefault();
}
private Builder()
{
}
public static Builder builder()
{
return new Builder();
}
public KeyShortcut build()
{
Preconditions.checkNotNull(keys);
Preconditions.checkNotNull(attentionKeys);
if (keys.isEmpty() && attentionKeys.isEmpty())
{
throw new IllegalStateException("At least one key combination must be specified, none registered");
}
Preconditions.checkNotNull(context);
Preconditions.checkNotNull(handler);
Preconditions.checkNotNull(keyEvent);
return new KeyShortcut(this);
}
public Builder addKey(Keys key)
{
keys.add(key);
return this;
}
public Builder addAttentionKey(Keys key)
{
attentionKeys.add(key);
return this;
}
/**
* @param context see {@link KeyShortcutPresenter#setContextActive(ShortcutContext, boolean)}
* @return builder itself
*/
public Builder setContext(ShortcutContext context)
{
this.context = context;
return this;
}
/**
* @param description shown to the user in the key shortcut summary pane.
* Use {@link #DO_NOT_DISPLAY_DESCRIPTION} to prevent shortcut being
* @return builder itself
*/
public Builder setDescription(String description)
{
this.description = description;
return this;
}
/**
* @param handler activated for a registered {@link KeyShortcut} when context is active and a
* user inputs the correct key combination
* @return builder itself
*/
public Builder setHandler(KeyShortcutEventHandler handler)
{
this.handler = handler;
return this;
}
/**
* @param keyEvent determines which type of key event will trigger this shortcut.
* @return builder itself
*/
public Builder setKeyEvent(KeyEvent keyEvent)
{
this.keyEvent = keyEvent;
return this;
}
/**
* @param stopPropagation {@see NativeEvent#stopPropagation()}
* @return builder itself
*/
public Builder setStopPropagation(boolean stopPropagation)
{
this.stopPropagation = stopPropagation;
return this;
}
/**
* @param preventDefault {@see NativeEvent#preventDefault()}
* @return builder itself
*/
public Builder setPreventDefault(boolean preventDefault)
{
this.preventDefault = preventDefault;
return this;
}
}
}
|
package org.valkyriercp.application.exceptionhandling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.springframework.core.ErrorCoded;
import java.sql.SQLException;
/**
* Superclass of logging exception handlers.
* It handles a throwable by logging it and notify it to the user.
* Subclasses determine how it's notified to the user.
*
* @author Geoffrey De Smet
* @since 0.3
*/
public abstract class AbstractLoggingExceptionHandler extends AbstractRegisterableExceptionHandler {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
protected ExceptionPurger exceptionPurger = null;
private final ThreadLocal<Boolean> alreadyHandlingExceptionOnThisThread = new ThreadLocal<Boolean>();
private LoggingLevel level = LoggingLevel.ERROR;
private Marker marker;
public static enum LoggingLevel {
TRACE,
DEBUG,
INFO,
WARN,
ERROR
}
/**
* If set the throwable will first be purged before handling it.
*
* @param exceptionPurger
*/
public void setExceptionPurger(ExceptionPurger exceptionPurger) {
this.exceptionPurger = exceptionPurger;
}
/**
* Logs an exception and shows it to the user.
* <p/>
* Has infinite loop detection due to exception handling throwing an exception.
* An infinite loop can occur in different cases:
* <ul>
* <li>
* Case 1: The ExceptionHandler throws an exception, which is handled by the ExceptionHandler,
* which throws an exception, ...
* </li>
* <li>
* Case 2: notifyUserAboutException uses a modal dialog that triggers the event queue to do a focus lost
* That focus lost throws a new exception, catched by the event queue, which delegates it to the ExceptionHandler,
* which still hasn't returned from handling the original exception!
* Then the ExceptionHandler uses a modal dialog again, focus lost, throws exception, ...
* This causes a StackOverflowError or a hang-application-by-starvation due to too many dialogs.</li>
* </ul>
*/
public final void uncaughtException(Thread thread, Throwable throwable) {
Boolean infiniteLoopDetected = alreadyHandlingExceptionOnThisThread.get();
if (infiniteLoopDetected != null && infiniteLoopDetected.booleanValue()) {
// Preventing infinite loop case 2 (see javadoc)
// The original uncaughtException method has not yet returned
String detectionLogMessage = "Infinite exception handling loop detected. "
+ "The ExceptionHandler has probably thrown the following exception itself:";
try {
logger.error(detectionLogMessage, throwable);
} catch (Throwable ignoredThrowable) {
System.err.println(detectionLogMessage);
throwable.printStackTrace();
}
// Reset of alreadyHandlingExceptionOnThisThread not needed:
// the original uncaughtException method will return and reset it.
// Reset not wanted either: even if it's still looping, it is better to be able
// to report the first exception and lose performance due to an infinite event loop
// than to crash by hang-application-by-starvation due to too many dialogs.
return; // Ignore the throwable
}
alreadyHandlingExceptionOnThisThread.set(Boolean.TRUE);
try {
processUncaughtException(thread, throwable);
} catch (Throwable detectionThrowable) {
// Preventing infinite loop case 1 (see javadoc)
String detectionLogMessage = "The ExceptionHandler has thrown the following exception itself:";
try {
logger.error(detectionLogMessage, detectionThrowable);
} catch (Throwable ignoredThrowable) {
System.err.println(detectionLogMessage);
detectionThrowable.printStackTrace();
}
} finally {
alreadyHandlingExceptionOnThisThread.set(null);
}
}
/**
* Logs an exception and shows it to the user.
*/
private void processUncaughtException(Thread thread, Throwable throwable) {
if (exceptionPurger != null) {
throwable = exceptionPurger.purge(throwable);
}
logException(thread, throwable);
notifyUserAboutException(thread, throwable);
}
protected String extractErrorCode(Throwable throwable) {
if (throwable instanceof ErrorCoded) {
return ((ErrorCoded) throwable).getErrorCode();
} else if (throwable instanceof SQLException) {
return Integer.toString(((SQLException) throwable).getErrorCode());
} else {
return null;
}
}
/**
* Log an exception
*/
public void logException(Thread thread, Throwable throwable) {
String logMessage;
String errorCode = extractErrorCode(throwable);
if (errorCode != null) {
logMessage = "Uncaught throwable handled with errorCode (" + errorCode + ").";
} else {
logMessage = "Uncaught throwable handled.";
}
doLogException(logMessage, throwable);
}
private void doLogException(String logMessage, Throwable throwable) {
switch (level) {
case TRACE:
logger.trace(marker, logMessage, throwable);
break;
case DEBUG:
logger.debug(marker, logMessage, throwable);
break;
case INFO:
logger.info(marker, logMessage, throwable);
break;
case WARN:
logger.warn(marker, logMessage, throwable);
break;
case ERROR:
logger.error(marker, logMessage, throwable);
break;
}
}
/**
* Notify user about an exception
*/
public abstract void notifyUserAboutException(Thread thread, Throwable throwable);
public void setLevel(LoggingLevel level) {
this.level = level;
}
public Marker getMarker() {
return marker;
}
public void setMarker(Marker marker) {
this.marker = marker;
}
}
|
package edu.northwestern.bioinformatics.studycalendar.web.template;
import edu.northwestern.bioinformatics.studycalendar.core.Fixtures;
import edu.northwestern.bioinformatics.studycalendar.dao.StudySegmentDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySegment;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment;
import edu.northwestern.bioinformatics.studycalendar.service.DeltaService;
import edu.northwestern.bioinformatics.studycalendar.service.TestingTemplateService;
import edu.northwestern.bioinformatics.studycalendar.web.ControllerTestCase;
import static org.easymock.classextension.EasyMock.expect;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Rhett Sutphin
*/
public class SelectStudySegmentControllerTest extends ControllerTestCase {
private static final int STUDY_SEGMENT_ID = 90;
private SelectStudySegmentController controller;
private StudySegmentDao studySegmentDao;
private DeltaService deltaService;
private StudySegment studySegment;
private Study study;
@Override
protected void setUp() throws Exception {
super.setUp();
study = Fixtures.createBasicTemplate();
Fixtures.assignIds(study);
studySegment = study.getPlannedCalendar().getEpochs().get(0).getStudySegments().get(1);
studySegment.setId(STUDY_SEGMENT_ID);
controller = new SelectStudySegmentController();
studySegmentDao = registerDaoMockFor(StudySegmentDao.class);
deltaService = registerMockFor(DeltaService.class);
controller.setStudySegmentDao(studySegmentDao);
controller.setControllerTools(controllerTools);
controller.setDeltaService(deltaService);
controller.setTemplateService(new TestingTemplateService());
expect(studySegmentDao.getById(STUDY_SEGMENT_ID)).andReturn(studySegment).anyTimes();
request.setParameter("studySegment", Integer.toString(STUDY_SEGMENT_ID));
request.setMethod("GET");
}
// TODO: test the inclusion of the plan tree hierarchy
public void testRequest() throws Exception {
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
verifyMocks();
assertEquals("template/ajax/selectStudySegment", mv.getViewName());
Object actualStudySegment = mv.getModel().get("studySegment");
assertNotNull("study segment missing", actualStudySegment);
assertTrue("study segment is not wrapped", actualStudySegment instanceof StudySegmentTemplate);
System.out.println("mv.getModel " + mv.getModel());
assertEquals("Wrong model: " + mv.getModel(), 5, mv.getModel().size());
}
public void testRequestWhenAmended() throws Exception {
request.setParameter("developmentRevision", "true");
study.setDevelopmentAmendment(new Amendment("dev"));
expect(deltaService.revise(studySegment)).andReturn((StudySegment) studySegment.transientClone());
expect(deltaService.revise(study, study.getDevelopmentAmendment())).andReturn(study);
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
verifyMocks();
Object actualStudySegment = mv.getModel().get("studySegment");
assertNotNull("study segment missing", actualStudySegment);
assertTrue("study segment is not wrapped", actualStudySegment instanceof StudySegmentTemplate);
assertNotNull("dev revision missing", mv.getModel().get("developmentRevision"));
assertEquals("Wrong model: " + mv.getModel(), 6, mv.getModel().size());
}
public void testRequestWhenReleasedTemplateIsSelected() throws Exception {
study.setDevelopmentAmendment(new Amendment("dev"));
replayMocks();
ModelAndView mv = controller.handleRequest(request, response);
verifyMocks();
Object actualStudySegment = mv.getModel().get("studySegment");
assertNotNull("study segment missing", actualStudySegment);
assertTrue("study segment is not wrapped", actualStudySegment instanceof StudySegmentTemplate);
assertNull("must not revise study", mv.getModel().get("developmentRevision"));
assertEquals("Wrong model: " + mv.getModel(), 5, mv.getModel().size());
}
}
|
package com.xpn.xwiki.store.hibernate.query;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.NamedQueryDefinition;
import org.hibernate.engine.NamedSQLQueryDefinition;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.context.Execution;
import org.xwiki.job.event.status.JobProgressManager;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryExecutor;
import org.xwiki.query.QueryFilter;
import org.xwiki.query.QueryParameter;
import org.xwiki.query.SecureQuery;
import org.xwiki.query.WrappingQuery;
import org.xwiki.security.authorization.ContextualAuthorizationManager;
import org.xwiki.security.authorization.Right;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.internal.store.hibernate.query.HqlQueryUtils;
import com.xpn.xwiki.store.XWikiHibernateBaseStore.HibernateCallback;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.store.hibernate.HibernateSessionFactory;
import com.xpn.xwiki.util.Util;
/**
* QueryExecutor implementation for Hibernate Store.
*
* @version $Id$
* @since 1.6M1
*/
@Component
@Named("hql")
@Singleton
public class HqlQueryExecutor implements QueryExecutor, Initializable
{
/**
* Path to Hibernate mapping with named queries. Configured via component manager.
*/
private static final String MAPPING_PATH = "queries.hbm.xml";
private static final String ESCAPE_LIKE_PARAMETERS_FILTER = "escapeLikeParameters";
/**
* Session factory needed for register named queries mapping.
*/
@Inject
private HibernateSessionFactory sessionFactory;
/**
* Used for access to XWikiContext.
*/
@Inject
private Execution execution;
@Inject
private ContextualAuthorizationManager authorization;
@Inject
private JobProgressManager progress;
@Inject
@Named("context")
private Provider<ComponentManager> componentManagerProvider;
private volatile Set<String> allowedNamedQueries;
@Override
public void initialize() throws InitializationException
{
Configuration configuration = this.sessionFactory.getConfiguration();
configuration.addInputStream(Util.getResourceAsStream(MAPPING_PATH));
}
private Set<String> getAllowedNamedQueries()
{
if (this.allowedNamedQueries == null) {
synchronized (this) {
if (this.allowedNamedQueries == null) {
this.allowedNamedQueries = new HashSet<>();
Configuration configuration = this.sessionFactory.getConfiguration();
// Gather the list of allowed named queries
Map<String, NamedQueryDefinition> namedQueries = configuration.getNamedQueries();
for (Map.Entry<String, NamedQueryDefinition> query : namedQueries.entrySet()) {
if (HqlQueryUtils.isSafe(query.getValue().getQuery())) {
this.allowedNamedQueries.add(query.getKey());
}
}
}
}
}
return this.allowedNamedQueries;
}
/**
* @param statementString the statement to evaluate
* @return true if the select is allowed for user without PR
*/
protected static boolean isSafeSelect(String statementString)
{
return HqlQueryUtils.isShortFormStatement(statementString) || HqlQueryUtils.isSafe(statementString);
}
protected void checkAllowed(final Query query) throws QueryException
{
if (query instanceof SecureQuery && ((SecureQuery) query).isCurrentAuthorChecked()) {
if (!this.authorization.hasAccess(Right.PROGRAM)) {
if (query.isNamed() && !getAllowedNamedQueries().contains(query.getStatement())) {
throw new QueryException("Named queries requires programming right", query, null);
}
if (!isSafeSelect(query.getStatement())) {
throw new QueryException("The query requires programming right", query, null);
}
}
}
}
@Override
public <T> List<T> execute(final Query query) throws QueryException
{
// Make sure the query is allowed in the current context
checkAllowed(query);
String oldDatabase = getContext().getWikiId();
try {
this.progress.startStep(query, "query.hql.progress.execute", "Execute HQL query [{}]",
query);
if (query.getWiki() != null) {
getContext().setWikiId(query.getWiki());
}
return getStore().executeRead(getContext(), new HibernateCallback<List<T>>()
{
@SuppressWarnings("unchecked")
@Override
public List<T> doInHibernate(Session session)
{
org.hibernate.Query hquery = createHibernateQuery(session, query);
List<T> results = hquery.list();
if (query.getFilters() != null && !query.getFilters().isEmpty()) {
for (QueryFilter filter : query.getFilters()) {
results = filter.filterResults(results);
}
}
return results;
}
});
} catch (XWikiException e) {
throw new QueryException("Exception while executing query", query, e);
} finally {
getContext().setWikiId(oldDatabase);
this.progress.endStep(query);
}
}
protected org.hibernate.Query createHibernateQuery(Session session, Query query)
{
org.hibernate.Query hquery;
Query filteredQuery = query;
if (!filteredQuery.isNamed()) {
// For non-named queries, convert the short form into long form before we apply the filters.
filteredQuery = new WrappingQuery(filteredQuery)
{
@Override
public String getStatement()
{
// handle short queries
return completeShortFormStatement(getWrappedQuery().getStatement());
}
};
filteredQuery = filterQuery(filteredQuery, Query.HQL);
hquery = session.createQuery(filteredQuery.getStatement());
populateParameters(hquery, filteredQuery);
} else {
hquery = createNamedHibernateQuery(session, filteredQuery);
}
return hquery;
}
private Query filterQuery(Query query, String language)
{
Query filteredQuery = query;
// If there are Query parameters of type QueryParameter then, for convenience, automatically add the
// "escapeLikeParameters" filter (if not already there)
addEscapeLikeParametersFilter(query);
if (query.getFilters() != null && !query.getFilters().isEmpty()) {
for (QueryFilter filter : query.getFilters()) {
// Step 1: For backward-compatibility reasons call #filterStatement() first
String filteredStatement = filter.filterStatement(filteredQuery.getStatement(), language);
// Prevent unnecessary creation of WrappingQuery objects when the QueryFilter doesn't modify the
// statement.
if (!filteredStatement.equals(filteredQuery.getStatement())) {
filteredQuery = new WrappingQuery(filteredQuery) {
@Override
public String getStatement()
{
return filteredStatement;
}
};
}
// Step 2: Run #filterQuery()
filteredQuery = filter.filterQuery(filteredQuery);
}
}
return filteredQuery;
}
private void addEscapeLikeParametersFilter(Query query)
{
if (!hasQueryParametersType(query)) {
return;
}
// Find the component class for the "escapeLikeParameters" filter
QueryFilter escapeFilter;
try {
escapeFilter =
this.componentManagerProvider.get().getInstance(QueryFilter.class, ESCAPE_LIKE_PARAMETERS_FILTER);
} catch (ComponentLookupException e) {
// Shouldn't happen!
throw new RuntimeException(
String.format("Failed to locate [%s] Query Filter", ESCAPE_LIKE_PARAMETERS_FILTER), e);
}
boolean found = false;
for (QueryFilter filter : query.getFilters()) {
if (escapeFilter.getClass().getName().equals(filter.getClass().getName())) {
found = true;
break;
}
}
if (!found) {
query.addFilter(escapeFilter);
}
}
private boolean hasQueryParametersType(Query query)
{
boolean found = false;
for (Object value : query.getNamedParameters().values()) {
if (value instanceof QueryParameter) {
found = true;
break;
}
}
if (!found) {
for (Object value : query.getPositionalParameters().values()) {
if (value instanceof QueryParameter) {
found = true;
break;
}
}
}
return found;
}
/**
* Append the required select clause to HQL short query statements. Short statements are the only way for users
* without programming rights to perform queries. Such statements can be for example:
* <ul>
* <li>{@code , BaseObject obj where doc.fullName=obj.name and obj.className='XWiki.MyClass'}</li>
* <li>{@code where doc.creationDate > '2008-01-01'}</li>
* </ul>
*
* @param statement the statement to complete if required.
* @return the complete statement if it had to be completed, the original one otherwise.
*/
protected String completeShortFormStatement(String statement)
{
String lcStatement = statement.toLowerCase().trim();
if (lcStatement.isEmpty() || lcStatement.startsWith(",") || lcStatement.startsWith("where ")
|| lcStatement.startsWith("order by ")) {
return "select doc.fullName from XWikiDocument doc " + statement.trim();
}
return statement;
}
private org.hibernate.Query createNamedHibernateQuery(Session session, Query query)
{
org.hibernate.Query hQuery = session.getNamedQuery(query.getStatement());
Query filteredQuery = query;
if (filteredQuery.getFilters() != null && !filteredQuery.getFilters().isEmpty()) {
// Since we can't modify the Hibernate query statement at this point we need to create a new one to apply
// the query filter. This comes with a performance cost, we could fix it by handling named queries ourselves
// and not delegate them to Hibernate. This way we would always get a statement that we can transform before
// the execution.
boolean isNative = hQuery instanceof SQLQuery;
String language = isNative ? "sql" : Query.HQL;
final String statement = hQuery.getQueryString();
// Run filters
filteredQuery = filterQuery(new WrappingQuery(filteredQuery) {
@Override
public String getStatement()
{
return statement;
}
}, language);
if (isNative) {
hQuery = session.createSQLQuery(filteredQuery.getStatement());
// Copy the information about the return column types, if possible.
NamedSQLQueryDefinition definition = (NamedSQLQueryDefinition) this.sessionFactory.getConfiguration()
.getNamedSQLQueries().get(query.getStatement());
if (!StringUtils.isEmpty(definition.getResultSetRef())) {
((SQLQuery) hQuery).setResultSetMapping(definition.getResultSetRef());
}
} else {
hQuery = session.createQuery(filteredQuery.getStatement());
}
}
populateParameters(hQuery, filteredQuery);
return hQuery;
}
/**
* @param hquery query to populate parameters
* @param query query from to populate.
*/
protected void populateParameters(org.hibernate.Query hquery, Query query)
{
if (query.getOffset() > 0) {
hquery.setFirstResult(query.getOffset());
}
if (query.getLimit() > 0) {
hquery.setMaxResults(query.getLimit());
}
for (Entry<String, Object> e : query.getNamedParameters().entrySet()) {
setNamedParameter(hquery, e.getKey(), e.getValue());
}
Map<Integer, Object> positionalParameters = query.getPositionalParameters();
if (positionalParameters.size() > 0) {
int start = Collections.min(positionalParameters.keySet());
if (start == 0) {
// jdbc-style positional parameters. "?"
for (Entry<Integer, Object> e : positionalParameters.entrySet()) {
hquery.setParameter(e.getKey(), e.getValue());
}
} else {
// jpql-style. "?index"
for (Entry<Integer, Object> e : positionalParameters.entrySet()) {
// hack. hibernate assume "?1" is named parameter, so use string "1".
setNamedParameter(hquery, String.valueOf(e.getKey()), e.getValue());
}
}
}
}
/**
* Sets the value of the specified named parameter, taking into account the type of the given value.
*
* @param query the query to set the parameter for
* @param name the parameter name
* @param value the non-null parameter value
*/
protected void setNamedParameter(org.hibernate.Query query, String name, Object value)
{
if (value instanceof Collection) {
query.setParameterList(name, (Collection<?>) value);
} else if (value.getClass().isArray()) {
query.setParameterList(name, (Object[]) value);
} else {
query.setParameter(name, value);
}
}
/**
* @return Store component
*/
protected XWikiHibernateStore getStore()
{
return getContext().getWiki().getHibernateStore();
}
/**
* @return XWiki Context
*/
protected XWikiContext getContext()
{
return (XWikiContext) this.execution.getContext().getProperty(XWikiContext.EXECUTIONCONTEXT_KEY);
}
}
|
package org.eclipse.birt.report.designer.internal.ui.dnd;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.core.model.schematic.HandleAdapterFactory;
import org.eclipse.birt.report.designer.core.model.schematic.ListBandProxy;
import org.eclipse.birt.report.designer.core.model.schematic.TableHandleAdapter;
import org.eclipse.birt.report.designer.data.ui.dataset.DataSetUIUtil;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportElementEditPart;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.designer.util.DNDUtil;
import org.eclipse.birt.report.designer.util.IVirtualValidator;
import org.eclipse.birt.report.model.api.CachedMetaDataHandle;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.ColumnHintHandle;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.FreeFormHandle;
import org.eclipse.birt.report.model.api.GridHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.JointDataSetHandle;
import org.eclipse.birt.report.model.api.LabelHandle;
import org.eclipse.birt.report.model.api.ListHandle;
import org.eclipse.birt.report.model.api.ListingHandle;
import org.eclipse.birt.report.model.api.MasterPageHandle;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.TableGroupHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;
import org.eclipse.birt.report.model.api.olap.DimensionHandle;
import org.eclipse.birt.report.model.api.olap.MeasureHandle;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gef.EditPart;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
/**
* Utility for creation from data view to layout
*/
public class InsertInLayoutUtil
{
/**
* Rule interface for defining insertion rule
*/
abstract static interface InsertInLayoutRule
{
public boolean canInsert( );
public Object getInsertPosition( );
public void insert( Object object ) throws SemanticException;
}
/**
*
* Rule for inserting label after inserting data set column
*/
static class LabelAddRule implements InsertInLayoutRule
{
private Object container;
private CellHandle newTarget;
public LabelAddRule( Object container )
{
this.container = container;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.views.actions.InsertInLayoutAction.InsertInLayoutRule#canInsert()
*/
public boolean canInsert( )
{
if ( container instanceof SlotHandle )
{
container = ( (SlotHandle) container ).getElementHandle( );
}
if ( !( container instanceof CellHandle ) )
return false;
CellHandle cell = (CellHandle) container;
// Validates source position of data item
boolean canInsert = false;
if ( cell.getContainer( ).getContainer( ) instanceof TableGroupHandle )
{
canInsert = true;
}
else
{
if ( cell.getContainer( ).getContainerSlotHandle( ).getSlotID( ) == TableHandle.DETAIL_SLOT )
{
canInsert = true;
}
}
// Validates column count and gets the target
if ( canInsert )
{
TableHandle table = null;
if ( cell.getContainer( ).getContainer( ) instanceof TableHandle )
{
table = (TableHandle) cell.getContainer( ).getContainer( );
}
else
{
table = (TableHandle) cell.getContainer( )
.getContainer( )
.getContainer( );
}
SlotHandle header = table.getHeader( );
if ( header != null && header.getCount( ) > 0 )
{
int columnNum = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( cell )
.getColumnNumber( );
newTarget = (CellHandle) HandleAdapterFactory.getInstance( )
.getTableHandleAdapter( table )
.getCell( 1, columnNum, false );
return newTarget != null
&& newTarget.getContent( ).getCount( ) == 0;
}
}
return false;
}
/**
* Returns new Label insert position in form of <code>CellHandle</code>
*/
public Object getInsertPosition( )
{
return newTarget;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil.InsertInLayoutRule#insert()
*/
public void insert( Object object ) throws SemanticException
{
Assert.isTrue( object instanceof DesignElementHandle );
newTarget.addElement( (DesignElementHandle) object,
CellHandle.CONTENT_SLOT );
}
}
/**
*
* Rule for inserting multiple data into table, and populating adjacent
* cells
*/
static class MultiItemsExpandRule implements InsertInLayoutRule
{
private Object[] items;
private Object target;
private int focusIndex = 0;
public MultiItemsExpandRule( Object[] items, Object target )
{
this.items = items;
this.target = target;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.views.actions.InsertInLayoutAction.InsertInLayoutRule#canInsert()
*/
public boolean canInsert( )
{
return items != null
&& items.length > 1
&& target != null
&& ( target instanceof DesignElementHandle || target instanceof ListBandProxy );
}
/**
*
* Returns multiple insert positions in form of array
*/
public Object getInsertPosition( )
{
Object[] positions = new Object[items.length];
if ( target instanceof CellHandle )
{
CellHandle firstCell = (CellHandle) target;
TableHandleAdapter tableAdapter = HandleAdapterFactory.getInstance( )
.getTableHandleAdapter( getTableHandle( firstCell ) );
int currentColumn = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( firstCell )
.getColumnNumber( );
int currentRow = HandleAdapterFactory.getInstance( )
.getCellHandleAdapter( firstCell )
.getRowNumber( );
int columnDiff = currentColumn
+ items.length
- tableAdapter.getColumnCount( )
- 1;
// Insert columns if table can not contain all items
if ( columnDiff > 0 )
{
int insertColumn = tableAdapter.getColumnCount( );
try
{
tableAdapter.insertColumns( columnDiff, insertColumn );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
return null;
}
}
for ( int i = 0; i < positions.length; i++ )
{
positions[i] = tableAdapter.getCell( currentRow,
currentColumn++ );
}
focusIndex = 0;
}
else
{
for ( int i = 0; i < positions.length; i++ )
{
positions[i] = target;
}
focusIndex = items.length - 1;
}
return positions;
}
protected TableHandle getTableHandle( CellHandle firstCell )
{
DesignElementHandle tableContainer = firstCell.getContainer( )
.getContainer( );
if ( tableContainer instanceof TableHandle )
{
return (TableHandle) tableContainer;
}
return (TableHandle) tableContainer.getContainer( );
}
/**
* Returns the index of the focus element in the items
*/
public int getFocusIndex( )
{
return focusIndex;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil.InsertInLayoutRule#insert()
*/
public void insert( Object object ) throws SemanticException
{
// TODO Auto-generated method stub
}
}
/**
*
* Rule for setting key when inserting data set column to group handle
*/
static class GroupKeySetRule implements InsertInLayoutRule
{
private Object container;
private ResultSetColumnHandle dataSetColumn;
public GroupKeySetRule( Object container,
ResultSetColumnHandle dataSetColumn )
{
this.container = container;
this.dataSetColumn = dataSetColumn;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil.InsertInLayoutRule#canInsert()
*/
public boolean canInsert( )
{
return getGroupContainer( container ) != null
&& getGroupHandle( container ).getKeyExpr( ) == null
&& ( getGroupContainer( container ).getDataSet( ) == getDataSetHandle( dataSetColumn ) || getGroupContainer( container ).getDataSet( ) == null );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil.InsertInLayoutRule#getInsertPosition()
*/
public Object getInsertPosition( )
{
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil.InsertInLayoutRule#insert(java.lang.Object)
*/
public void insert( Object object ) throws SemanticException
{
Assert.isTrue( object instanceof ResultSetColumnHandle );
Assert.isTrue( object == dataSetColumn || object == null );
ReportItemHandle groupContainer = getGroupContainer( container );
DataSetHandle dataSetHandle = null;
if ( groupContainer instanceof ReportItemHandle )
{
dataSetHandle = ( (ReportItemHandle) groupContainer ).getDataSet( );
}
if ( dataSetHandle == null )
{
for ( DesignElementHandle elementHandle = groupContainer; elementHandle != null; elementHandle = elementHandle.getContainer( ) )
{
if ( elementHandle instanceof ListingHandle
&& ( dataSetHandle = ( (ListingHandle) elementHandle ).getDataSet( ) ) != null
&& ( dataSetHandle == getDataSetHandle( dataSetColumn ) ) )
{
break;
}
}
}
if ( dataSetHandle == null
|| dataSetHandle != getDataSetHandle( dataSetColumn ) )
{
getGroupContainer( container ).setDataSet( getDataSetHandle( dataSetColumn ) );
}
getGroupHandle( container ).setKeyExpr( DEUtil.getColumnExpression( dataSetColumn.getColumnName( ) ) );
}
protected DataSetHandle getDataSetHandle( ResultSetColumnHandle model )
{
return (DataSetHandle) model.getElementHandle( );
}
protected GroupHandle getGroupHandle( Object target )
{
DesignElementHandle handle = null;
if ( target instanceof CellHandle )
{
handle = ( (CellHandle) target ).getContainer( ).getContainer( );
}
else if ( target instanceof ListBandProxy )
{
handle = ( (ListBandProxy) target ).getElemtHandle( );
}
if ( handle instanceof GroupHandle )
{
return (GroupHandle) handle;
}
return null;
}
protected ReportItemHandle getGroupContainer( Object target )
{
GroupHandle group = getGroupHandle( target );
if ( group != null
&& group.getContainer( ) instanceof ReportItemHandle )
return (ReportItemHandle) group.getContainer( );
return null;
}
}
/**
* Creates a object to insert.
*
* @param insertObj
* object insert to layout
* @param target
* insert target, like cell or ListBandProxy
* @param targetParent
* insert target's non-dummy container, like table or list
* @return new object in layout
* @throws SemanticException
*/
public static DesignElementHandle performInsert( Object insertObj,
Object target, Object targetParent ) throws SemanticException
{
Assert.isNotNull( insertObj );
Assert.isNotNull( target );
if ( insertObj instanceof DataSetHandle )
{
return performInsertDataSet( (DataSetHandle) insertObj );
}
else if ( insertObj instanceof ResultSetColumnHandle )
{
return performInsertDataSetColumn( (ResultSetColumnHandle) insertObj,
target,
targetParent );
}
else if ( insertObj instanceof ScalarParameterHandle )
{
return performInsertParameter( (ScalarParameterHandle) insertObj );
}
else if ( insertObj instanceof String )
{
// Such as invalid group key
return performInsertString( (String) insertObj, target );
}
else if ( insertObj instanceof Object[] )
{
return performMultiInsert( (Object[]) insertObj,
target,
targetParent );
}
else if ( insertObj instanceof IStructuredSelection )
{
return performMultiInsert( ( (IStructuredSelection) insertObj ).toArray( ),
target,
targetParent );
}
return null;
}
public static DesignElementHandle performInsert( Object insertObj,
EditPart editPart ) throws SemanticException
{
Assert.isNotNull( insertObj );
Assert.isNotNull( editPart );
return performInsert( insertObj,
editPart.getModel( ),
editPart.getParent( ).getModel( ) );
}
/**
* Creates multiple objects
*
* @param array
* multiple creation source
* @param target
* @param targetParent
* @return first creation in layout
* @throws SemanticException
*/
protected static DesignElementHandle performMultiInsert( Object[] array,
Object target, Object targetParent ) throws SemanticException
{
DesignElementHandle result = null;
MultiItemsExpandRule rule = new MultiItemsExpandRule( array, target );
if ( rule.canInsert( ) )
{
Object[] positions = (Object[]) rule.getInsertPosition( );
if ( positions != null )
{
for ( int i = 0; i < array.length; i++ )
{
DesignElementHandle newObj = performInsert( array[i],
positions[i],
targetParent );
if ( i == rule.getFocusIndex( ) )
{
result = newObj;
}
else
{
DNDUtil.addElementHandle( positions[i], newObj );
}
}
}
}
else if ( array.length != 0 )
{
result = performInsert( array[0], target, targetParent );
}
return result;
}
protected static DataItemHandle performInsertParameter(
ScalarParameterHandle model ) throws SemanticException
{
// DataItemHandle dataHandle = SessionHandleAdapter.getInstance( )
// .getReportDesignHandle( )
// .getElementFactory( )
// .newDataItem( null );
DataItemHandle dataHandle = DesignElementFactory.getInstance( )
.newDataItem( null );
ComputedColumn bindingColumn = StructureFactory.newComputedColumn( dataHandle,
model.getName( ) );
bindingColumn.setExpression( DEUtil.getExpression( model ) );
// hardcode
// parameter's type datatime is not equals data's.
String paramType = model.getDataType( );
if ( "dateTime".equals( paramType ) )
paramType = "date-time";
bindingColumn.setDataType( paramType );
dataHandle.addColumnBinding( bindingColumn, false );
dataHandle.setResultSetColumn( bindingColumn.getName( ) );
return dataHandle;
}
/**
* Inserts dataset column into the target. Add label or group key if
* possible
*
* @param model
* column item
* @param target
* insert target like cell or ListBandProxy
* @param targetParent
* target container like table or list
* @return to be inserted data item
* @throws SemanticException
*/
protected static DataItemHandle performInsertDataSetColumn(
ResultSetColumnHandle model, Object target, Object targetParent )
throws SemanticException
{
/*
* search the target container, if container has the same dataset, add
* the column binding if it does not exist in the container. If the
* container's dataset is not the dragged dataset column's dataset,
* column binding will be added to the new dataitem, and set dataitem's
* dataset with the dragged dataset column's dataset.
*/
DataItemHandle dataHandle = DesignElementFactory.getInstance( )
.newDataItem( null );
DataSetHandle dataSet = (DataSetHandle) model.getElementHandle( );
dataHandle.setResultSetColumn( model.getColumnName( ) );
if ( targetParent instanceof ReportItemHandle )
{
ReportItemHandle container = (ReportItemHandle) targetParent;
ComputedColumn bindingColumn = StructureFactory.newComputedColumn( dataHandle,
model.getColumnName( ) );
bindingColumn.setDataType( model.getDataType( ) );
bindingColumn.setExpression( DEUtil.getExpression( model ) );
bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) );
if ( target instanceof DesignElementHandle )
{
if ( ExpressionUtil.hasAggregation( bindingColumn.getExpression( ) ) )
{
String groupType = DEUtil.getGroupControlType( (DesignElementHandle) target );
if ( groupType.equals( DEUtil.TYPE_GROUP_GROUP ) )
bindingColumn.setAggregateOn( ( (GroupHandle) DEUtil.getGroups( (DesignElementHandle) target )
.get( 0 ) ).getName( ) );
else if ( groupType.equals( DEUtil.TYPE_GROUP_LISTING ) )
bindingColumn.setAggregateOn( null );
}
}
DataSetHandle containerDataSet = DEUtil.getFirstDataSet( container );
container = DEUtil.getListingContainer( container );
if ( containerDataSet == null && container != null )
{
container.setDataSet( dataSet );
containerDataSet = dataSet;
}
if ( dataSet.equals( containerDataSet ) && container != null )
{
if ( container.getDataBindingReference( ) != null )
container.getDataBindingReference( )
.addColumnBinding( bindingColumn, false );
else
container.addColumnBinding( bindingColumn, false );
}
else
{
// should not happen
dataHandle.setDataSet( dataSet );
dataHandle.addColumnBinding( bindingColumn, false );
}
// GroupHandle groupHandle = getGroupHandle( target );
// if ( groupHandle != null )
// ComputedColumn bindingColumn =
// StructureFactory.newComputedColumn( groupHandle,
// model.getColumnName( ) );
// // bindingColumn.setColumnName( model.getColumnName( ) );
// bindingColumn.setDataType( model.getDataType( ) );
// bindingColumn.setExpression( DEUtil.getExpression( model ) );
// groupHandle.addColumnBinding( bindingColumn, false );
// else
// ComputedColumn bindingColumn =
// StructureFactory.newComputedColumn( container,
// model.getColumnName( ) );
// bindingColumn.setDataType( model.getDataType( ) );
// bindingColumn.setExpression( DEUtil.getExpression( model ) );
// container.addColumnBinding( bindingColumn, false );
// ComputedColumn bindingColumn =
// StructureFactory.createComputedColumn( );
// bindingColumn.setName( model.getColumnName( ) );
// bindingColumn.setDataType( model.getDataType( ) );
// bindingColumn.setExpression( DEUtil.getExpression( model ) );
// GroupHandle groupHandle = getGroupHandle( target );
// if ( groupHandle != null )
// for ( Iterator iter = groupHandle.getColumnBindings( )
// .iterator( ); iter.hasNext( ); )
// ComputedColumnHandle element = (ComputedColumnHandle) iter.next(
// if ( element.getStructure( ).equals( bindingColumn ) )
// bindingExist = true;
// break;
// else
// for ( Iterator iter = container.getColumnBindings( ).iterator( );
// iter.hasNext( ); )
// ComputedColumnHandle element = (ComputedColumnHandle) iter.next(
// if ( element.getStructure( ).equals( bindingColumn ) )
// bindingExist = true;
// break;
}
else
{
ComputedColumn bindingColumn = StructureFactory.newComputedColumn( dataHandle,
model.getColumnName( ) );
bindingColumn.setDataType( model.getDataType( ) );
bindingColumn.setExpression( DEUtil.getExpression( model ) );
bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) );
if ( target instanceof DesignElementHandle )
{
if ( ExpressionUtil.hasAggregation( bindingColumn.getExpression( ) ) )
{
String groupType = DEUtil.getGroupControlType( (DesignElementHandle) target );
if ( groupType.equals( DEUtil.TYPE_GROUP_GROUP ) )
bindingColumn.setAggregateOn( ( (GroupHandle) DEUtil.getGroups( (DesignElementHandle) target )
.get( 0 ) ).getName( ) );
else if ( groupType.equals( DEUtil.TYPE_GROUP_LISTING ) )
bindingColumn.setAggregateOn( null );
}
}
dataHandle.addColumnBinding( bindingColumn, false );
dataHandle.setDataSet( dataSet );
}
// if ( !bindingExist )
// ComputedColumn bindingColumn = StructureFactory.newComputedColumn(
// dataHandle,
// model.getColumnName( ) );
// bindingColumn.setDataType( model.getDataType( ) );
// bindingColumn.setExpression( DEUtil.getExpression( model ) );
// dataHandle.addColumnBinding( bindingColumn, false );
// dataHandle.setDataSet( dataSet );
InsertInLayoutRule rule = new LabelAddRule( target );
if ( rule.canInsert( ) )
{
// LabelHandle label = SessionHandleAdapter.getInstance( )
// .getReportDesignHandle( )
// .getElementFactory( )
// .newLabel( null );
LabelHandle label = DesignElementFactory.getInstance( )
.newLabel( null );
label.setText( UIUtil.getColumnDisplayName( model ) );
rule.insert( label );
}
rule = new GroupKeySetRule( target, model );
if ( rule.canInsert( ) )
{
rule.insert( model );
}
return dataHandle;
}
// private static GroupHandle getGroupHandle( Object target )
// DesignElementHandle handle = null;
// if ( target instanceof CellHandle )
// handle = ( (CellHandle) target ).getContainer( ).getContainer( );
// else if ( target instanceof ListBandProxy )
// handle = ( (ListBandProxy) target ).getElemtHandle( );
// if ( handle instanceof GroupHandle )
// return (GroupHandle) handle;
// return null;
/**
* Inserts invalid column string into the target. Add label if possible
*
* @param expression
* invalid column or other expression
* @param target
* insert target like cell or ListBandProxy
* @return to be inserted data item
* @throws SemanticException
*/
protected static DesignElementHandle performInsertString(
String expression, Object target ) throws SemanticException
{
// DataItemHandle dataHandle = SessionHandleAdapter.getInstance( )
// .getReportDesignHandle( )
// .getElementFactory( )
// .newDataItem( null );
DataItemHandle dataHandle = DesignElementFactory.getInstance( )
.newDataItem( null );
dataHandle.setResultSetColumn( expression );
InsertInLayoutRule rule = new LabelAddRule( target );
if ( rule.canInsert( ) )
{
// LabelHandle label = SessionHandleAdapter.getInstance( )
// .getReportDesignHandle( )
// .getElementFactory( )
// .newLabel( null );
LabelHandle label = DesignElementFactory.getInstance( )
.newLabel( null );
label.setText( expression );
rule.insert( label );
}
return dataHandle;
}
protected static TableHandle performInsertDataSet( DataSetHandle model )
throws SemanticException
{
// DataSetItemModel[] columns = DataSetManager.getCurrentInstance( )
// .getColumns( model, false );
// if ( columns == null || columns.length == 0 )
// return null;
// // TableHandle tableHandle = SessionHandleAdapter.getInstance( )
// // .getReportDesignHandle( )
// // .getElementFactory( )
// // .newTableItem( null, columns.length );
CachedMetaDataHandle cachedMetadata = DataSetUIUtil.getCachedMetaDataHandle( model );
List columList = new ArrayList( );
for ( Iterator iter = cachedMetadata.getResultSet( ).iterator( ); iter.hasNext( ); )
{
ResultSetColumnHandle element = (ResultSetColumnHandle) iter.next( );
columList.add( element );
}
ResultSetColumnHandle[] columns = (ResultSetColumnHandle[]) columList.toArray( new ResultSetColumnHandle[columList.size( )] );
TableHandle tableHandle = DesignElementFactory.getInstance( )
.newTableItem( null, columns.length );
setInitWidth( tableHandle );
insertToCell( model,
tableHandle,
tableHandle.getHeader( ),
columns,
true );
insertToCell( model,
tableHandle,
tableHandle.getDetail( ),
columns,
false );
tableHandle.setDataSet( model );
return tableHandle;
}
/**
* Validates object can be inserted to layout. Support the multiple.
*
* @param insertObj
* single inserted object or multi-objects
* @param targetPart
* @return if can be inserted to layout
*/
public static boolean handleValidateInsertToLayout( Object insertObj,
EditPart targetPart )
{
if ( targetPart == null )
{
return false;
}
if ( insertObj instanceof Object[] )
{
Object[] array = (Object[]) insertObj;
if ( !checkSameDataSetInMultiColumns( array ) )
{
return false;
}
if ( !checkContainContainMulitItem( array, targetPart.getModel( ) ) )
{
return false;
}
for ( int i = 0; i < array.length; i++ )
{
if ( !handleValidateInsertToLayout( array[i], targetPart ) )
{
return false;
}
}
return true;
}
else if ( insertObj instanceof IStructuredSelection )
{
return handleValidateInsertToLayout( ( (IStructuredSelection) insertObj ).toArray( ),
targetPart );
}
else if ( insertObj instanceof DataSetHandle )
{
return isHandleValid( (DataSetHandle) insertObj )
&& handleValidateDataSet( targetPart );
}
else if ( insertObj instanceof ResultSetColumnHandle )
{
return handleValidateDataSetColumn( (ResultSetColumnHandle) insertObj,
targetPart );
}
// else if ( insertObj instanceof DimensionHandle )
// return handleValidateDimension( (DimensionHandle) insertObj,
// targetPart );
// else if ( insertObj instanceof MeasureHandle )
// return handleValidateMeasure( (MeasureHandle) insertObj,
// targetPart );
else if ( insertObj instanceof LabelHandle )
{
return handleValidateLabel( (LabelHandle) insertObj, targetPart );
}
else if ( insertObj instanceof ResultSetColumnHandle )
{
return handleValidateDataSetColumn( (ResultSetColumnHandle) insertObj,
targetPart );
}
else if ( insertObj instanceof ScalarParameterHandle )
{
return isHandleValid( (ScalarParameterHandle) insertObj )
&& handleValidateParameter( targetPart );
}
return false;
}
private static boolean handleValidateLabel( LabelHandle handle,
EditPart targetPart )
{
if ( targetPart.getModel( ) instanceof IAdaptable )
{
Object obj = ( (IAdaptable) targetPart.getModel( ) ).getAdapter( DesignElementHandle.class );
if ( obj instanceof ExtendedItemHandle )
{
return ( (ExtendedItemHandle) obj ).canContain( DEUtil.getDefaultContentName( obj ),
handle );
}
}
return false;
}
private static boolean checkContainContainMulitItem( Object[] objects,
Object slotHandle )
{
SlotHandle handle = null;
// if ( slotHandle instanceof ReportElementModel )
// handle = ( (ReportElementModel) slotHandle ).getSlotHandle( );
// else
if ( slotHandle instanceof SlotHandle )
{
handle = (SlotHandle) slotHandle;
}
if ( handle != null && objects != null && objects.length > 1 )
{
if ( !handle.getDefn( ).isMultipleCardinality( ) )
{
return false;
}
}
return true;
}
/**
* Checks if all the DataSetColumn has the same DataSet.
*
* @param array
* all elements
* @return false if not same; true if every column has the same DataSet or
* the element is not an instance of DataSetColumn
*/
protected static boolean checkSameDataSetInMultiColumns( Object[] array )
{
if ( array == null )
return false;
Object dataSet = null;
for ( int i = 0; i < array.length; i++ )
{
if ( array[i] instanceof ResultSetColumnHandle )
{
Object currDataSet = ( (ResultSetColumnHandle) array[i] ).getElementHandle( );
if ( currDataSet == null )
{
return false;
}
if ( dataSet == null )
{
dataSet = currDataSet;
}
else
{
if ( dataSet != currDataSet )
{
return false;
}
}
}
}
return true;
}
/**
* Validates container of drop target from data set in data view
*
* @param dropPart
* @return validate result
*/
protected static boolean handleValidateDataSetDropContainer(
EditPart dropPart )
{
if ( dropPart.getParent( ) == null )
{
return false;
}
Object container = dropPart.getParent( ).getModel( );
return ( container instanceof GridHandle
|| container instanceof TableHandle
|| container instanceof FreeFormHandle
|| container instanceof ListHandle || dropPart.getModel( ) instanceof ModuleHandle );
}
/**
* Validates container of drop target from data set column in data view
*
* @param dropPart
* @return validate result
*/
protected static boolean handleValidateDataSetColumnDropContainer(
EditPart dropPart )
{
if ( dropPart.getParent( ) == null )
{
return false;
}
Object container = dropPart.getParent( ).getModel( );
return ( container instanceof GridHandle
|| container instanceof TableHandle
|| container instanceof FreeFormHandle
|| container instanceof ListHandle
|| container instanceof MasterPageHandle || dropPart.getModel( ) instanceof ModuleHandle );
}
protected static boolean handleValidateMeasureDropContainer(
MeasureHandle measure, EditPart dropPart )
{
if ( dropPart.getModel( ) instanceof IVirtualValidator )
{
return ( (IVirtualValidator) dropPart.getModel( ) ).handleValidate( measure );
}
return false;
}
protected static boolean handleValidateDimensionDropContainer(
DimensionHandle dimension, EditPart dropPart )
{
if ( dropPart.getModel( ) instanceof IVirtualValidator )
{
return ( (IVirtualValidator) dropPart.getModel( ) ).handleValidate( dimension );
}
return false;
}
/**
* Validates container of drop target from scalar parameter in data view
*
* @param dropPart
* @return validate result
*/
protected static boolean handleValidateParameterDropContainer(
EditPart dropPart )
{
if ( dropPart.getParent( ) == null )
{
return false;
}
Object container = dropPart.getParent( ).getModel( );
return ( container instanceof GridHandle
|| container instanceof TableHandle
|| container instanceof FreeFormHandle
|| container instanceof ListHandle || dropPart.getModel( ) instanceof ModuleHandle );
}
/**
* Validates drop target from data set in data view.
*
* @return validate result
*/
protected static boolean handleValidateDataSet( EditPart target )
{
return handleValidateDataSetDropContainer( target )
&& DNDUtil.handleValidateTargetCanContainType( target.getModel( ),
ReportDesignConstants.TABLE_ITEM );
}
protected static boolean handleValidateDimension(
DimensionHandle insertObj, EditPart target )
{
return handleValidateDimensionDropContainer( insertObj, target );
}
protected static boolean handleValidateMeasure( MeasureHandle insertObj,
EditPart target )
{
return handleValidateMeasureDropContainer( insertObj, target );
}
/**
* Validates drop target from data set column in data view.
*
* @return validate result
*/
protected static boolean handleValidateDataSetColumn(
ResultSetColumnHandle insertObj, EditPart target )
{
if ( handleValidateDataSetColumnDropContainer( target )
&& DNDUtil.handleValidateTargetCanContainType( target.getModel( ),
ReportDesignConstants.DATA_ITEM ) )
{
// Validates target is report root
if ( target.getModel( ) instanceof ModuleHandle
|| isMasterPageHeaderOrFooter( target.getModel( ) ) )
{
return true;
}
// Validates target's dataset is null or the same with the inserted
DesignElementHandle handle = (DesignElementHandle) target.getParent( )
.getModel( );
if ( handle instanceof ReportItemHandle )
{
ReportItemHandle bindingHolder = DEUtil.getListingContainer( handle );
DataSetHandle dataSet = DEUtil.getFirstDataSet( handle );
return dataSet == null
&& ( bindingHolder == null || !bindingHolder.getColumnBindings( )
.iterator( )
.hasNext( ) )
|| insertObj.getElementHandle( ).equals( dataSet );
}
}
return false;
}
private static boolean isMasterPageHeaderOrFooter( Object obj )
{
if ( !( obj instanceof SlotHandle ) )
{
return false;
}
if ( ( (SlotHandle) obj ).getElementHandle( ) instanceof MasterPageHandle )
{
return true;
}
return false;
}
/**
* Validates drop target from scalar parameter in data view.
*
* @return validate result
*/
protected static boolean handleValidateParameter( EditPart target )
{
return handleValidateParameterDropContainer( target )
&& DNDUtil.handleValidateTargetCanContainType( target.getModel( ),
ReportDesignConstants.DATA_ITEM );
}
/**
* Validates drag source from data view to layout. Support the multiple.
*
* @return validate result
*/
public static boolean handleValidateInsert( Object insertObj )
{
if ( insertObj instanceof Object[] )
{
Object[] array = (Object[]) insertObj;
if ( array.length == 0 )
{
return false;
}
for ( int i = 0; i < array.length; i++ )
{
if ( !handleValidateInsert( array[i] ) )
return false;
}
return true;
}
else if ( insertObj instanceof IStructuredSelection )
{
return handleValidateInsert( ( (IStructuredSelection) insertObj ).toArray( ) );
}
// else if ( insertObj instanceof ParameterHandle )
// if ( ( (ParameterHandle) insertObj ).getRoot( ) instanceof
// LibraryHandle )
// return false;
if ( insertObj instanceof DataSetHandle )
{
return DataSetUIUtil.hasMetaData( (DataSetHandle) insertObj );
}
return insertObj instanceof ResultSetColumnHandle
|| insertObj instanceof ScalarParameterHandle
|| insertObj instanceof DimensionHandle
|| insertObj instanceof MeasureHandle;
}
protected static void insertToCell( DataSetHandle model,
TableHandle tableHandle, SlotHandle slot,
ResultSetColumnHandle[] columns, boolean isLabel )
{
for ( int i = 0; i < slot.getCount( ); i++ )
{
SlotHandle cells = ( (RowHandle) slot.get( i ) ).getCells( );
for ( int j = 0; j < cells.getCount( ); j++ )
{
CellHandle cell = (CellHandle) cells.get( j );
try
{
if ( isLabel )
{
LabelHandle labelItemHandle = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.getElementFactory( )
.newLabel( null );
// LabelHandle labelItemHandle =
// DesignElementFactory.getInstance( )
// .newLabel( null );
String labelText = UIUtil.getColumnDisplayName( columns[j] );
if ( labelText != null )
{
labelItemHandle.setText( labelText );
}
String displayKey = getDisplayKey( columns[j] );
if ( displayKey != null )
{
labelItemHandle.setTextKey( displayKey );
}
cell.addElement( labelItemHandle, cells.getSlotID( ) );
}
else
{
DataItemHandle dataHandle = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.getElementFactory( )
.newDataItem( null );
// DataItemHandle dataHandle =
// DesignElementFactory.getInstance( )
// .newDataItem( null );
dataHandle.setResultSetColumn( columns[j].getColumnName( ) );
cell.addElement( dataHandle, cells.getSlotID( ) );
// add data binding to table.
ComputedColumn bindingColumn = StructureFactory.newComputedColumn( tableHandle,
columns[j].getColumnName( ) );
bindingColumn.setDataType( columns[j].getDataType( ) );
bindingColumn.setExpression( DEUtil.getExpression( columns[j] ) );
bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( columns[j] ) );
tableHandle.addColumnBinding( bindingColumn, false );
}
}
catch ( Exception e )
{
ExceptionHandler.handle( e );
}
}
}
}
private static String getDisplayKey( ResultSetColumnHandle column )
{
DataSetHandle dataset = (DataSetHandle) column.getElementHandle( );
for ( Iterator iter = dataset.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP )
.iterator( ); iter.hasNext( ); )
{
ColumnHintHandle element = (ColumnHintHandle) iter.next( );
if ( element.getColumnName( ).equals( column.getColumnName( ) )
|| column.getColumnName( ).equals( element.getAlias( ) ) )
{
return element.getDisplayNameKey( );
}
}
return null;
}
/**
* Sets initial width to new object
*
* @param object
* new object
*/
public static void setInitWidth( Object object )
{
int percentAll = 100;
try
{
if ( object instanceof TableHandle )
{
TableHandle table = (TableHandle) object;
table.setWidth( percentAll
+ DesignChoiceConstants.UNITS_PERCENTAGE );
}
else if ( object instanceof GridHandle )
{
GridHandle grid = (GridHandle) object;
grid.setWidth( percentAll
+ DesignChoiceConstants.UNITS_PERCENTAGE );
}
else
return;
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
protected static boolean isHandleValid( DesignElementHandle handle )
{
if ( handle instanceof DataSetHandle )
{
if ( ( !( handle instanceof JointDataSetHandle ) && ( (DataSetHandle) handle ).getDataSource( ) == null )
|| !DataSetUIUtil.hasMetaData( (DataSetHandle) handle ) )
{
return false;
}
}
return handle.isValid( ) && handle.getSemanticErrors( ).isEmpty( );
}
/**
* Converts edit part selection into model selection.
*
* @param selection
* edit part
* @return model, return Collections.EMPTY_LIST if selection is null or
* empty.
*/
public static IStructuredSelection editPart2Model( ISelection selection )
{
if ( selection == null || !( selection instanceof IStructuredSelection ) )
return new StructuredSelection( Collections.EMPTY_LIST );
List list = ( (IStructuredSelection) selection ).toList( );
List resultList = new ArrayList( );
for ( int i = 0; i < list.size( ); i++ )
{
Object obj = list.get( i );
if ( obj instanceof ReportElementEditPart )
{
Object model = ( (ReportElementEditPart) obj ).getModel( );
if ( model instanceof ListBandProxy )
{
model = ( (ListBandProxy) model ).getSlotHandle( );
}
resultList.add( model );
}
}
return new StructuredSelection( resultList );
}
/**
* Converts edit part selection into model selection.
*
* @param selection
* edit part
* @return model, return Collections.EMPTY_LIST if selection is null or
* empty.
*/
public static IStructuredSelection editPart2Model( List selection )
{
if ( selection == null || ( selection.size( ) == 0 ) )
return new StructuredSelection( Collections.EMPTY_LIST );
List list = selection;
List resultList = new ArrayList( );
for ( int i = 0; i < list.size( ); i++ )
{
Object obj = list.get( i );
if ( obj instanceof ReportElementEditPart )
{
Object model = ( (ReportElementEditPart) obj ).getModel( );
if ( model instanceof ListBandProxy )
{
model = ( (ListBandProxy) model ).getSlotHandle( );
}
resultList.add( model );
}
}
return new StructuredSelection( resultList );
}
}
|
package org.mti.hip.utils;
import android.util.Log;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class HttpClient {
private HttpClient instance;
private OkHttpClient client;
public static final String tallyEndpoint = "/visits/upload";
public static final String visitEndpoint = "/facilities/11/visits";
public static final String facilitiesEndpoint = "/facilities";
public static final String diagnosisEndpoint = "/diagnosis";
public static final String supplementalEndpoint = "/supplementals";
public static final String settlementEndpoint = "/settlements";
public static final String categoriesEndpoint = "/categories";
public static final String injuryLocationsEndpoint = "/injurylocations";
public static final String post = "POST";
public static final String get = "GET";
// TODO add constant for facility ID (this will be SET when it is selected
// from the Facility Selection screen)
/*
Default Show/Hide List Operations Expand Operations
GET /facilities/{facilityId}/visits Get facility visits
POST /facilities/{facilityId}/visits Add visit
POST /facilities/{facilityId}/visits/upload Upload visits
GET /facilities
GET /facilities/{facilityId}
GET /citizenships Citizenship Lookup List
GET /diagnosis Diagnosis Lookup List
GET /supplementals
*/
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public HttpClient() {
client = new OkHttpClient();
}
public String post(final String endpoint, final String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url("http://clinicwebapp.azurewebsites.net/hip" + endpoint)
.post(body)
.build();
Response response;
String responseString = null;
response = client.newCall(request).execute();
responseString = parseResponse(response);
return responseString;
}
public String get(final String endpoint) throws IOException {
Request request = new Request.Builder()
.url("http://clinicwebapp.azurewebsites.net/hip" + endpoint)
.build();
Response response;
String responseString = null;
response = client.newCall(request).execute();
responseString = parseResponse(response);
return responseString;
}
private String parseResponse(Response response) throws IOException {
String responseString = response.body().string();
if (!response.isSuccessful()) {
Log.e("parsed response error", response.code() + " " + responseString);
throw new IOException("There was an issue with the network request");
}
return responseString;
}
}
|
package org.zoneproject.extractor.plugin.spotlight;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.zoneproject.extractor.utils.Config;
import org.zoneproject.extractor.utils.Database;
import org.zoneproject.extractor.utils.Item;
import org.zoneproject.extractor.utils.Prop;
import org.zoneproject.extractor.utils.ZoneOntology;
/**
*
* @author Desclaux Christophe <christophe@zouig.org>
*/
public class SpotlightRequest {
private final static int NUMBER_OF_ANNOTATIONS = 10;
public enum Endpoints {
EN(Config.getVar("Spotlight-EN")),
FR(Config.getVar("Spotlight-FR"));
private final String value;
Endpoints(String value) {this.value = value;}
public String getValue() {return this.value;}
}
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(SpotlightRequest.class);
public static ArrayList<Prop> getProperties(Item item){
String endpoint="";
try {
ArrayList<Prop> result = new ArrayList<Prop>();
String itemLang = item.getElements(ZoneOntology.PLUGIN_LANG)[0].toUpperCase();
try{
endpoint = Endpoints.valueOf(itemLang).getValue();
}catch(java.lang.IllegalArgumentException ex){
endpoint = Endpoints.valueOf("EN").getValue();
}
if(item.concat().equals("")){
return result;
}
String contentString = item.concat();
if(contentString.length()> 100000) {
contentString = item.concat().substring(0,100000);
}
String json = getResponse(contentString, endpoint);
Annotation[] entities = SpotlightRequest.getNamedEntities(json);
Arrays.sort(entities);
for(int i=0; i < entities.length && i < NUMBER_OF_ANNOTATIONS; i++){
Annotation e = entities[i];
Prop p = new Prop(ZoneOntology.PLUGIN_SPOTLIGHT_ENTITIES, e.getUri(), false,true);
result.add(p);
}
return result;
} catch (IOException ex) {
logger.warn("The server "+ endpoint + " is not responding"+ ex);
return null;
} catch (java.lang.ArrayIndexOutOfBoundsException ex) {
logger.warn("Not lang property for item "+item.getUri());
return null;
}
}
public static String getResponse(String text,String endPoint) throws IOException {
URL dbpedia;
HttpURLConnection dbpedia_connection;
dbpedia = new URL(endPoint+"/annotate");
dbpedia_connection = (HttpURLConnection) dbpedia.openConnection();
dbpedia_connection.setDoOutput(true);
dbpedia_connection.setRequestMethod("GET");
dbpedia_connection.setRequestProperty("Accept", "application/json");
String urlParameters = "confidance=0.5&support=80&text=";
urlParameters = urlParameters.concat(URLEncoder.encode(text));
dbpedia_connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(dbpedia_connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
dbpedia_connection.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(
dbpedia_connection.getInputStream()));
String inputLine;
String output = "";
while ((inputLine = in.readLine()) != null) {
output += inputLine;
}
in.close();
return output;
}
public static Annotation[] getNamedEntities(String f){
ObjectMapper mapper = new ObjectMapper();
HashMap<String,Annotation> result = new HashMap<String,Annotation>();
try {
//first need to allow non-standard json
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
mapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
Map<String,Object> map = mapper.readValue(f, Map.class);
ArrayList<LinkedHashMap> documentElems = (ArrayList<LinkedHashMap>)map.get("Resources");
if(documentElems != null){
for(int i=0; i < documentElems.size();i++){
LinkedHashMap cur = (LinkedHashMap) documentElems.get(i);
Annotation a = new Annotation(cur.get("@URI").toString(),Double.parseDouble(cur.get("@similarityScore").toString()),cur.get("@types").toString(),Integer.parseInt(cur.get("@offset").toString()));
if(!result.containsKey(a.getUri())){
result.put(a.getUri(),a);
}else{
result.get(a.getUri()).addScore(a.getScore());
}
}
}
} catch (Exception ex) {
Logger.getLogger(SpotlightRequest.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
return result.values().toArray(new Annotation[result.size()]);
}
public static void main(String[] args) throws IOException {
String text = "Un nouveau portail pour notre documentation en ligne.\\n Antidot met à disposition de l’ensemble de ses clients et partenaires un nouveau portail pour l’accès en ligne à la documentation de ses produits. Ce portail documentaire a pour ambition de faciliter vos recherches et de simplifier votre navigation au sein de près de 2000 pages de Guides, Notes techniques et Notes de version : […]. Antidot met à disposition de l’ensemble de ses clients et partenaires un nouveau portail pour l’accès en ligne à la documentation de ses produits .Ce portail documentaire a pour ambition de faciliter vos recherches et de simplifier votre navigation au sein de près de 2000 pages de Guides, Notes techniques et Notes de version :Ce service vous est aujourd’hui ouvert en version beta. N’hésitez pas à nous faire part de vos retours : tous les commentaires et suggestions que nous recueillerons seront étudiés avec la plus grande attention.Pour la petite histoire, ce portail documentaire est réalisé intégralement à partir de nos solutions dont il exploite les fonctionnalités avancées :AIF – Information Factory : pour la recomposition et l’analyse des unités documentaires fines,AFS – Finder Suite : pour le moteur de recherche et la lecture dynamique et continue.Il sera bientôt enrichi des fonctions d’alertes et d’annotation apportées par notre produit ACS – Collaboration Services .Nous vous remercions de votre confiance.Partagez";
text = "Réserve parlementaire: Chevènement et Hue demandent à Fabius des explications sur des fuites dans \"Le Monde\".\n Dépêche AFP, mardi 10 septembre 2013, 17h46. Les sénateurs Jean-Pierre Chevènement et Robert Hue ont demandé lundi au ministre des Affaires étrangères Laurent Fabius, dans une lettre commune, des explications sur un \"fichier\" que le Quai d'Orsay aurait communiqué au journal Le Monde concernant l'usage par des élus de leur réserve parlementaire. Dans son édition datée de dimanche-lundi, Le Monde affirmait s'être vu communiquer par le ministère des Affaires étrangères un fichier détaillant les versements de députés et sénateurs en faveur de programmes de développement ou relatifs à l'action extérieure de la France. Pointant du doigt l'utilisation par certains élus de leur réserve parlementaire 2011 ou 2012 pour financer leurs propres associations, le journal citait MM. Hue, président du Mouvement unitaire progressiste (MUP), Chevènement, président d'honneur du Mouvement républicain et citoyen (MRC), et l'ancien président Valéry Giscard d'Estaing. \"J'observe que M. Giscard d'Estaing,";
text = "la\",Syrie";
String itemId = "https://twitter.com/phdossmann/status/393016902722674689";
itemId = "https://twitter.com/hay_out/status/393292223259086848";
itemId = "http://rue89.feedsportal.com/c/33822/f/608948/s/33028bdf/sc/23/l/0L0Srue890N0C20A130C10A0C280Cpetit0Eprobleme0Edamazon0Eresume0Egraphique0E2470A14/story01.htm";
Item item = Database.getOneItemByURI(itemId);
Database.addAnnotations(itemId,getProperties(item));
//getNamedEntities(json);
}
}
|
package com.github.shynixn.astraledit.bukkit.logic.business.command;
import com.github.shynixn.astraledit.api.bukkit.business.command.PlayerCommand;
import com.github.shynixn.astraledit.api.bukkit.business.controller.SelectionController;
import com.github.shynixn.astraledit.bukkit.AstralEditPlugin;
import com.github.shynixn.astraledit.bukkit.Permission;
import com.github.shynixn.astraledit.bukkit.logic.business.Operation;
import com.github.shynixn.astraledit.bukkit.logic.business.OperationType;
import com.github.shynixn.astraledit.bukkit.logic.business.SelectionManager;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class JoinCommand implements PlayerCommand {
private final SelectionManager manager;
private final Plugin plugin;
/**
* Creates a new instance of the JoinCommand with SelectionController as dependency.
*
* @param manager dependency.
*/
public JoinCommand(SelectionManager manager, Plugin plugin) {
this.manager = manager;
this.plugin = plugin;
}
/**
* Executes the given command if the arguments match.
*
* @param player executing the command.
* @param args arguments.
* @return True if this command was executed. False if the arguments do not match.
*/
@Override
public boolean onPlayerExecuteCommand(Player player, String[] args) {
if (args.length != 1 && !args[0].equalsIgnoreCase("join") && !Permission.JOIN.hasPermission(player)) {
return false;
}
this.plugin.getServer().getScheduler().runTaskAsynchronously(this.plugin, () -> {
if (!this.manager.hasSelection(player)) {
player.sendMessage(AstralEditPlugin.PREFIX_ERROR + "You don't have a valid render.");
} else if (!this.manager.getSelection(player).isJoined()) {
this.manager.getSelection(player).join();
this.manager.addOperation(player, new Operation(OperationType.COMBINE));
}
});
return true;
}
}
|
package org.ovirt.engine.api.restapi.types;
import org.junit.Test;
import org.ovirt.engine.api.model.StorageDomain;
import org.ovirt.engine.api.model.StorageDomainStatus;
import org.ovirt.engine.api.model.StorageDomainType;
import org.ovirt.engine.api.restapi.model.StorageFormat;
import org.ovirt.engine.api.model.StorageType;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.storage_domain_static;
public class StorageDomainMapperTest extends
AbstractInvertibleMappingTest<StorageDomain, storage_domain_static, storage_domains> {
protected StorageDomainMapperTest() {
super(StorageDomain.class, storage_domain_static.class, storage_domains.class);
}
@Override
protected StorageDomain postPopulate(StorageDomain model) {
model.setType(MappingTestHelper.shuffle(StorageDomainType.class).value());
model.getStorage().setType(MappingTestHelper.shuffle(StorageType.class).value());
model.setStorageFormat(MappingTestHelper.shuffle(StorageFormat.class).value());
return model;
}
@Override
protected storage_domains getInverse(storage_domain_static to) {
storage_domains inverse = new storage_domains();
inverse.setid(to.getId());
inverse.setstorage_name(to.getstorage_name());
inverse.setstorage_domain_type(to.getstorage_domain_type());
inverse.setstorage_type(to.getstorage_type());
inverse.setStorageFormat(to.getStorageFormat());
return inverse;
}
@Override
protected void verify(StorageDomain model, StorageDomain transform) {
assertNotNull(transform);
assertEquals(model.getName(), transform.getName());
assertEquals(model.getId(), transform.getId());
// REVIST No descriptions for storage domains
// assertEquals(model.getDescription(), transform.getDescription());
assertEquals(model.getType(), transform.getType());
assertNotNull(transform.getStorage());
assertEquals(model.getStorage().getType(), transform.getStorage().getType());
assertEquals(model.getStorageFormat(), transform.getStorageFormat());
}
@Test
public void testMemory() {
storage_domains entity = new storage_domains();
entity.setavailable_disk_size(3);
entity.setused_disk_size(4);
entity.setcommitted_disk_size(5);
StorageDomain model = StorageDomainMapper.map(entity, (StorageDomain)null);
assertEquals(model.getAvailable(), Long.valueOf(3221225472L));
assertEquals(model.getUsed(), Long.valueOf(4294967296L));
assertEquals(model.getCommitted(), Long.valueOf(5368709120L));
}
@Test
public void storageDomainMappings() {
assertEquals(StorageDomainStatus.ACTIVE, StorageDomainMapper.map(org.ovirt.engine.core.common
.businessentities.StorageDomainStatus.Active, null));
assertEquals(StorageDomainStatus.INACTIVE, StorageDomainMapper.map(org.ovirt.engine.core.common
.businessentities.StorageDomainStatus.InActive, null));
assertEquals(StorageDomainStatus.LOCKED, StorageDomainMapper.map(org.ovirt.engine.core.common
.businessentities.StorageDomainStatus.Locked, null));
assertEquals(StorageDomainStatus.UNATTACHED, StorageDomainMapper.map(org.ovirt.engine.core.common
.businessentities.StorageDomainStatus.Unattached, null));
assertEquals(StorageDomainStatus.UNKNOWN, StorageDomainMapper.map(org.ovirt.engine.core.common
.businessentities.StorageDomainStatus.Unknown, null));
assertTrue(StorageDomainMapper.map(org.ovirt.engine.core.common
.businessentities.StorageDomainStatus.Uninitialized, null) == null);
assertTrue(StorageDomainMapper.map(org.ovirt.engine.core.common
.businessentities.StorageDomainStatus.Maintenance, null) == null);
}
}
|
package org.ovirt.engine.core.vdsbroker.attestation;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.ovirt.engine.core.common.businessentities.AttestationResultEnum;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
import org.ovirt.engine.core.utils.ssl.AuthSSLProtocolSocketFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
public class AttestationService {
private static final String HEADER_HOSTS = "hosts";
private static final String HEADER_HOST_NAME = "host_name";
private static final String HEADER_RESULT = "trust_lvl";
private static final String HEADER_VTIME = "vtime";
private static final String CONTENT_TYPE = "application/json";
private static final AttestationService instance = new AttestationService();
private static final Log log = LogFactory.getLog(AttestationService.class);
public static HttpClient getClient() {
HttpClient httpClient = new HttpClient();
if (Config
.<Boolean> GetValue(ConfigValues.SecureConnectionWithOATServers)) {
URL trustStoreUrl;
try {
int port = Config
.<Integer> GetValue(ConfigValues.AttestationPort);
trustStoreUrl = new URL("file:
+ Config.resolveAttestationTrustStorePath());
String truststorePassword = Config
.<String> GetValue(ConfigValues.AttestationTruststorePass);
String attestationServer = Config
.<String> GetValue(ConfigValues.AttestationServer);
// registering the https protocol with a socket factory that
// provides client authentication.
ProtocolSocketFactory factory = new AuthSSLProtocolSocketFactory(getTrustStore(trustStoreUrl.getPath(),
truststorePassword));
Protocol clientAuthHTTPS = new Protocol("https", factory, port);
httpClient.getHostConfiguration().setHost(attestationServer,
port, clientAuthHTTPS);
} catch (Exception e) {
log.fatal(
"Failed to init AuthSSLProtocolSocketFactory. SSL connections will not work",
e);
}
}
return httpClient;
}
private static KeyStore getTrustStore(String filePath, String password) throws IOException,
KeyStoreException, CertificateException, NoSuchAlgorithmException {
KeyStore ks;
try (InputStream in = new FileInputStream(filePath)) {
ks = KeyStore.getInstance("JKS");
ks.load(in, password.toCharArray());
}
return ks;
}
public static AttestationService getInstance() {
return instance;
}
private AttestationService() {
}
public List<AttestationValue> attestHosts(List<String> hosts) {
String pollURI = Config.<String> GetValue(ConfigValues.PollUri);
List<AttestationValue> values = new ArrayList<AttestationValue>();
PostMethod postMethod = new PostMethod("/" + pollURI);
try {
postMethod.setRequestEntity(new StringRequestEntity(
writeListJson(hosts)));
postMethod.addRequestHeader("Accept", CONTENT_TYPE);
postMethod.addRequestHeader("Content-type", CONTENT_TYPE);
HttpClient httpClient = getClient();
int statusCode = httpClient.executeMethod(postMethod);
String strResponse = postMethod.getResponseBodyAsString();
log.debug("return attested result:" + strResponse);
if (statusCode == 200) {
values = parsePostedResp(strResponse);
} else {
log.error("attestation error:" + strResponse);
}
} catch (JsonParseException e) {
log.error(
String.format("Failed to parse result: [%s]",
e.getMessage()), e);
} catch (IOException e) {
log.error(
String.format(
"Failed to attest hosts: [%s], make sure hosts are up and reachable",
e.getMessage()), e);
} finally {
postMethod.releaseConnection();
}
return values;
}
public List<AttestationValue> parsePostedResp(String str)
throws JsonParseException, IOException {
JsonFactory jfactory = new JsonFactory();
List<AttestationValue> values = new ArrayList<AttestationValue>();
JsonParser jParser = jfactory.createJsonParser(str);
try {
jParser.nextToken();
while (jParser.nextToken() != JsonToken.END_OBJECT) {
if (jParser.getCurrentName().equalsIgnoreCase(HEADER_HOSTS)) {
while (jParser.nextToken() != JsonToken.END_ARRAY
&& jParser.getCurrentToken() != JsonToken.END_OBJECT) {
AttestationValue value = new AttestationValue();
if (jParser.getCurrentName().equalsIgnoreCase(
HEADER_HOST_NAME)) {
jParser.nextToken();
value.setHostName(jParser.getText());
jParser.nextToken();
}
if (jParser.getCurrentName().equalsIgnoreCase(
HEADER_RESULT)) {
jParser.nextToken();
value.setTrustLevel(AttestationResultEnum
.valueOf(jParser.getText().toUpperCase()));
jParser.nextToken();
}
if (jParser.getCurrentName().equalsIgnoreCase(
HEADER_VTIME)) {
jParser.nextToken();
jParser.nextToken();
}
if (value.getHostName() != null) {
log.debug("host_name:" + value.getHostName()
+ ", trustLevel:" + value.getTrustLevel());
values.add(value);
}
jParser.nextToken();
}
break;
}
}
} finally {
jParser.close();
}
return values;
}
public String writeListJson(List<String> hosts) {
StringBuilder sb = new StringBuilder("{\"").append(HEADER_HOSTS)
.append("\":[");
for (String host : hosts) {
sb = sb.append("\"").append(host).append("\",");
}
String jsonString = sb.substring(0, sb.length() - 1) + "]}";
return jsonString;
}
}
|
package io.flutter.actions;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import io.flutter.FlutterBundle;
import io.flutter.FlutterMessages;
@SuppressWarnings("ComponentNotRegistered")
public class OpenSimulatorAction extends AnAction {
final boolean enabled;
public OpenSimulatorAction(boolean enabled) {
super("Open iOS Simulator");
this.enabled = enabled;
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(enabled);
}
@Override
public void actionPerformed(AnActionEvent event) {
try {
final GeneralCommandLine cmd = new GeneralCommandLine().withExePath("open").withParameters("-a", "Simulator.app");
final OSProcessHandler handler = new OSProcessHandler(cmd);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(final ProcessEvent event) {
if (event.getExitCode() != 0) {
final String msg = event.getText() != null ? event.getText() : "Process error - exit code: (" + event.getExitCode() + ")";
FlutterMessages.showError("Error Opening Simulator", msg);
}
}
});
handler.startNotify();
}
catch (ExecutionException e) {
FlutterMessages.showError(
"Error Opening Simulator",
FlutterBundle.message("flutter.command.exception.message", e.getMessage()));
}
}
}
|
package org.jboss.hal.testsuite.test.configuration.messaging.connections;
import org.apache.commons.lang.RandomStringUtils;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.hal.testsuite.category.Shared;
import org.jboss.hal.testsuite.creaper.ResourceVerifier;
import org.jboss.hal.testsuite.page.config.MessagingPage;
import org.jboss.hal.testsuite.test.configuration.messaging.AbstractMessagingTestCase;
import org.jboss.hal.testsuite.util.ConfigChecker;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.core.online.operations.Address;
import org.wildfly.extras.creaper.core.online.operations.OperationException;
import org.wildfly.extras.creaper.core.online.operations.Values;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertTrue;
@Ignore("JBEAP-4467")
@RunWith(Arquillian.class)
@Category(Shared.class)
public class ConnectorServicesTestCase extends AbstractMessagingTestCase {
private static final String CONNECTOR_SERVICE = "connector-service_" + RandomStringUtils.randomAlphanumeric(5);
private static final String CONNECTOR_SERVICE_TBA = "connector-service-TBA_" + RandomStringUtils.randomAlphanumeric(5);
private static final String CONNECTOR_SERVICE_TBR = "connector-service-TBR_" + RandomStringUtils.randomAlphanumeric(5);
private static final Address CONNECTOR_SERVICE_ADDRESS = DEFAULT_MESSAGING_SERVER.and("connector-service", CONNECTOR_SERVICE);
private static final Address CONNECTOR_SERVICE_ADDRESS_TBR = DEFAULT_MESSAGING_SERVER.and("connector-service", CONNECTOR_SERVICE_TBR);
private static final Address CONNECTOR_SERVICE_ADDRESS_TBA = DEFAULT_MESSAGING_SERVER.and("connector-service", CONNECTOR_SERVICE_TBA);
private static final String PROPERTY_TBR_KEY = "key4";
/* No implementation of org.apache.activemq.artemis.core.server.ConnectorServiceFactory is currently present in
* ActiveMQ module so filling value is used instead. This value should be only used to verify if value is correctly
* propagated to model from web console configuration.*/
private static final String FACTORY_CLASS = "clazz";
@BeforeClass
public static void setUp() throws Exception {
operations.add(CONNECTOR_SERVICE_ADDRESS, Values.of("factory-class", FACTORY_CLASS)).assertSuccess();
PropertiesOps.addProperty(CONNECTOR_SERVICE_ADDRESS, client, PROPERTY_TBR_KEY, "test");
new ResourceVerifier(CONNECTOR_SERVICE_ADDRESS, client).verifyExists();
operations.add(CONNECTOR_SERVICE_ADDRESS_TBR, Values.of("factory-class", FACTORY_CLASS));
new ResourceVerifier(CONNECTOR_SERVICE_ADDRESS_TBR, client).verifyExists();
}
@AfterClass
public static void tearDown() throws InterruptedException, TimeoutException, IOException, OperationException {
operations.removeIfExists(CONNECTOR_SERVICE_ADDRESS);
operations.removeIfExists(CONNECTOR_SERVICE_ADDRESS_TBA);
operations.removeIfExists(CONNECTOR_SERVICE_ADDRESS_TBR);
}
@Page
private MessagingPage page;
@Before
public void before() {
page.navigateToMessaging();
page.selectConnectionsView();
page.switchToConnectorServices();
page.selectInTable(CONNECTOR_SERVICE);
}
@Test
public void addConnectorServices() throws Exception {
page.addConnetorServices(CONNECTOR_SERVICE_TBA, FACTORY_CLASS);
new ResourceVerifier(CONNECTOR_SERVICE_ADDRESS_TBA, client).verifyExists();
}
@Test
public void updateConnectorServicesServicesFactoryClass() throws Exception {
new ConfigChecker.Builder(client, CONNECTOR_SERVICE_ADDRESS)
.configFragment(page.getConfigFragment())
.editAndSave(ConfigChecker.InputType.TEXT, "factoryClass", FACTORY_CLASS)
.verifyFormSaved()
.verifyAttribute("factory-class", FACTORY_CLASS);
}
@Test
public void addConnectorServicesProperty() throws Exception {
boolean isClosed = page.addProperty("prop", "test");
assertTrue("Property should be added and wizard closed.", isClosed);
Assert.assertTrue(PropertiesOps.isPropertyPresentInParams(CONNECTOR_SERVICE_ADDRESS, client, "prop"));
}
@Test
public void removeConnectorServicesProperties() throws Exception {
page.removeProperty(PROPERTY_TBR_KEY);
Assert.assertFalse(PropertiesOps.isPropertyPresentInParams(CONNECTOR_SERVICE_ADDRESS, client, PROPERTY_TBR_KEY));
}
@Test
public void removeConnectorServices() throws Exception {
page.selectInTable(CONNECTOR_SERVICE_TBR, 0);
page.remove();
new ResourceVerifier(CONNECTOR_SERVICE_ADDRESS_TBR, client).verifyDoesNotExist();
}
}
|
/**
* @brief Package for manipulation with XML and parsers
*/
package com.rehivetech.beeeon.network.xml;
import android.util.Xml;
import com.rehivetech.beeeon.Constants;
import com.rehivetech.beeeon.household.device.Device;
import com.rehivetech.beeeon.household.device.Device.SaveDevice;
import com.rehivetech.beeeon.household.device.Facility;
import com.rehivetech.beeeon.household.location.Location;
import com.rehivetech.beeeon.exception.AppException;
import com.rehivetech.beeeon.exception.NetworkError;
import com.rehivetech.beeeon.household.user.User;
import com.rehivetech.beeeon.network.INetwork.NetworkAction;
import com.rehivetech.beeeon.network.authentication.IAuthProvider;
import com.rehivetech.beeeon.network.xml.action.Action;
import com.rehivetech.beeeon.network.xml.condition.BetweenFunc;
import com.rehivetech.beeeon.network.xml.condition.ConditionFunction;
import com.rehivetech.beeeon.network.xml.condition.DewPointFunc;
import com.rehivetech.beeeon.network.xml.condition.EqualFunc;
import com.rehivetech.beeeon.network.xml.condition.GreaterEqualFunc;
import com.rehivetech.beeeon.network.xml.condition.GreaterThanFunc;
import com.rehivetech.beeeon.network.xml.condition.LesserEqualFunc;
import com.rehivetech.beeeon.network.xml.condition.LesserThanFunc;
import com.rehivetech.beeeon.network.xml.condition.TimeFunc;
import org.xmlpull.v1.XmlSerializer;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
/**
* Class for creating XML messages
*
* @author ThinkDeep
*
*/
public class XmlCreator {
private static final String ns = null;
private static final String COM_VER = Constants.COM_VER;
// states
public static final String PASSBORDER = "passborder";
public static final String SIGNIN = "signin";
public static final String SIGNUP = "signup";
public static final String GETUSERINFO ="getuserinfo";
public static final String JOINACCOUNT = "joinaccount";
public static final String CUTACCOUNT = "cutaccount";
public static final String ADDADAPTER = "addadapter";
public static final String REINITADAPTER = "reinitadapter";
public static final String GETADAPTERS = "getadapters";
public static final String ADDACCOUNTS = "addaccs";
public static final String DELACCOUNTS = "delaccs";
public static final String GETACCOUNTS = "getaccs";
public static final String SETCCOUNTS = "setaccs";
public static final String SCANMODE = "scanmode";
public static final String SETDEVS = "setdevs";
public static final String GETDEVICES = "getdevs";
public static final String GETALLDEVICES = "getalldevs";
public static final String DELDEVICE = "deldev";
public static final String SWITCH = "switch";
public static final String GETLOG = "getlog";
public static final String ADDVIEW = "addview";
public static final String DELVIEW = "delview";
public static final String SETVIEW = "setview";
public static final String GETVIEWS = "getviews";
public static final String GETNEWDEVICES = "getnewdevs";
public static final String SETTIMEZONE = "settimezone";
public static final String GETTIMEZONE = "gettimezone";
public static final String GETROOMS = "getrooms";
public static final String SETROOMS = "setrooms";
public static final String ADDROOM = "addroom";
public static final String DELROOM = "delroom";
public static final String DELGCMID = "delgcmid";
public static final String SETGCMID = "setgcmid";
public static final String GETNOTIFICATIONS = "getnotifs";
public static final String NOTIFICATIONREAD = "notifread";
public static final String SETCONDITION = "setcond";
public static final String SETLOCALE = "setlocale";
public static final String CONDITIONPLUSACTION = "condacition";
public static final String GETCONDITION = "getcond";
public static final String GETCONDITIONS = "getconds";
public static final String ADDCONDITION = "addcond";
public static final String DELCONDITION = "delcond";
public static final String SETACTION = "setact";
public static final String GETACTIONS = "getacts";
public static final String GETACTION = "getact";
public static final String ADDACTION = "addact";
public static final String DELACTION = "delact";
public static final String ADDALG = "addalg";
public static final String GETALLALGS = "getallalgs";
public static final String GETALGS = "getlags";
public static final String SETALG = "setalg";
public static final String DELALG = "delalg";
// end of states
/**
* Type of condition
*
* @author ThinkDeep
*
*/
public enum ConditionType {
AND("and"), OR("or");
private final String mValue;
private ConditionType(String value) {
mValue = value;
}
public String getValue() {
return mValue;
}
public static ConditionType fromValue(String value) {
for (ConditionType item : values()) {
if (value.equalsIgnoreCase(item.getValue()))
return item;
}
throw new IllegalArgumentException("Invalid ConditionType value");
}
}
// /////////////////////////////////////SIGNIN,SIGNUP,ADAPTERS/////////////////////////////////////
/**
* Method create message for registration of new user
* @param authProvider provider of authentication with parameters to send
* @return
*/
public static String createSignUp(IAuthProvider authProvider) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.VERSION, COM_VER); // every time use version
serializer.attribute(ns, Xconstants.STATE, SIGNUP);
// NOTE: Ok, i did it like that, but i do not like it
serializer.attribute(ns, Xconstants.SERVICE, authProvider.getProviderName());
serializer.startTag(ns, Xconstants.PARAM);
for (Map.Entry<String, String> entry : authProvider.getParameters().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null)
serializer.attribute(ns, key, value);
}
serializer.endTag(ns, Xconstants.PARAM);
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create message for login
* @param locale localization of phone
* @param pid unique id of phone
* @param authProvider provider of authentication with parameters to send
* @return
*/
public static String createSignIn(String locale, String pid, IAuthProvider authProvider) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.VERSION, COM_VER); // every time use version
serializer.attribute(ns, Xconstants.STATE, SIGNIN);
serializer.attribute(ns, Xconstants.LOCALE, locale);
serializer.attribute(ns, Xconstants.PID, pid);
// NOTE: Ok, i did it like that, but i do not like it
serializer.attribute(ns, Xconstants.SERVICE, authProvider.getProviderName());
serializer.startTag(ns, Xconstants.PARAM);
for (Map.Entry<String, String> entry : authProvider.getParameters().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null)
serializer.attribute(ns, key, value);
}
serializer.endTag(ns, Xconstants.PARAM);
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create message for joining new provider to actual user
* @param authProvider provider of authentication with parameters to send
*
* @return
*/
public static String createJoinAccount(String bt, IAuthProvider authProvider) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.VERSION, COM_VER); // every time use version
serializer.attribute(ns, Xconstants.STATE, JOINACCOUNT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.SERVICE, authProvider.getProviderName());
serializer.startTag(ns, Xconstants.PARAM);
for (Map.Entry<String, String> entry : authProvider.getParameters().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null)
serializer.attribute(ns, key, value);
}
serializer.endTag(ns, Xconstants.PARAM);
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create message for removing part of account (or whole account)
* @param bt
* @param providerName name of service (beeeon, google, facebook, ...)
* @return
*/
public static String createCutAccount(String bt, String providerName){
return createComAttribsVariant(Xconstants.STATE, CUTACCOUNT, Xconstants.BT, bt, Xconstants.SERVICE, providerName);
}
public static String createGetUserInfo(String bt){
return createComAttribsVariant(Xconstants.STATE, GETUSERINFO, Xconstants.BT, bt);
}
/**
* Method create XML for AddAdapter message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param adapterName
* name of adapter
* @return AddAdapter message
* @since 2.2
*/
public static String createAddAdapter(String bt, String aid, String adapterName) {
return createComAttribsVariant(Xconstants.STATE, ADDADAPTER, Xconstants.BT, bt, Xconstants.AID, aid, Xconstants.ANAME, adapterName);
}
/**
* Method create XML of GetAdapters message
*
* @param bt
* userID of user
* @return GetAdapters message
* @since 2.2
*/
public static String createGetAdapters(String bt) {
return createComAttribsVariant(Xconstants.STATE, GETADAPTERS, Xconstants.BT, bt);
}
/**
* Method create XML for ReInit message
*
* @param bt
* userID of user
* @param adapterIdOld
* old id of adapter
* @param adapterIdNew
* new id of adapter
* @return ReInit message
* @since 2.2
*/
public static String createReInitAdapter(String bt, String adapterIdOld, String adapterIdNew) {
return createComAttribsVariant(Xconstants.STATE, REINITADAPTER, Xconstants.BT, bt, Xconstants.OLDID, adapterIdOld, Xconstants.NEWID, adapterIdNew);
}
// /////////////////////////////////////DEVICES,LOGS///////////////////////////////////////////////
/**
* Method create XML for AdapterListen message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @return XML of AdapterListen message
* @since 2.2
*/
public static String createAdapterScanMode(String bt, String aid) {
return createComAttribsVariant(Xconstants.STATE, SCANMODE, Xconstants.BT, bt, Xconstants.AID, aid);
}
/**
* Method create XML for GetAllDevices message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @return XML of GetAllDevices message
* @since 2.2
*/
public static String createGetAllDevices(String bt, String aid) {
return createComAttribsVariant(Xconstants.STATE, GETALLDEVICES, Xconstants.BT, bt, Xconstants.AID, aid);
}
/**
* Method create XML for getting uninitialized devices
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @return XML of GetNewDevices message
* @since 2.2
*/
public static String createGetNewDevices(String bt, String aid) {
return createComAttribsVariant(Xconstants.STATE, GETNEWDEVICES, Xconstants.BT, bt, Xconstants.AID, aid);
}
/**
* Method create XML of GetDevices message
*
* @param bt
* userID of user
* @param facilities
* facilities with devices to update
* @return update message
* @since 2.2
*/
public static String createGetDevices(String bt, List<Facility> facilities) {
if(facilities.size() < 1)
throw new IllegalArgumentException("Expected more than zero facilities");
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, GETDEVICES);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
// sort by adapter address
Collections.sort(facilities, new Comparator<Facility>() {
@Override
public int compare(Facility left, Facility right) {
return Integer.valueOf(left.getAdapterId()).compareTo(Integer.valueOf(right.getAdapterId()));
}
});
String aid = "";
for (Facility facility : facilities) {
boolean isSameAdapter = aid.equals(facility.getAdapterId());
if (!isSameAdapter) { // new adapter
if (aid.length() > 0)
serializer.endTag(ns, Xconstants.ADAPTER);
aid = facility.getAdapterId();
serializer.startTag(ns, Xconstants.ADAPTER);
serializer.attribute(ns, Xconstants.ID, aid);
}
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, facility.getAddress());
for (Device device : facility.getDevices()) {
serializer.startTag(ns, Xconstants.PART);
serializer.attribute(ns, Xconstants.TYPE, device.getRawTypeId());
serializer.endTag(ns, Xconstants.PART);
}
serializer.endTag(ns, Xconstants.DEVICE);
}
serializer.endTag(ns, Xconstants.ADAPTER);
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create XML for GetLog message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param did
* deviceID of wanted device
* @param deviceType
* is type of sensor
* @param from
* date in unix timestamp
* @param to
* date in unix timestamp
* @param funcType
* is aggregation function type {avg, median, ...}
* @param interval
* is time value in seconds that represents nicely e.g. month, week, day, 10 hours, 1 hour, ...
* @return GetLog message
* @since 2.2
*/
public static String createGetLog(String bt, String aid, String did, String deviceType, String from, String to, String funcType, int interval) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, GETLOG);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.FROM, from);
serializer.attribute(ns, Xconstants.TO, to);
serializer.attribute(ns, Xconstants.FTYPE, funcType);
serializer.attribute(ns, Xconstants.INTERVAL, String.valueOf(interval));
serializer.attribute(ns, Xconstants.AID, aid);
serializer.attribute(ns, Xconstants.DID, did);
serializer.attribute(ns, Xconstants.DTYPE, deviceType);
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create XML of SetDevs message. Almost all fields are optional
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param facilities
* with changed fields
* @return Partial message
* @since 2.2
*/
public static String createSetDevs(String bt, String aid, List<Facility> facilities, EnumSet<SaveDevice> toSave) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, SETDEVS);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.AID, aid);
for (Facility facility : facilities) {
serializer.startTag(ns, Xconstants.DEVICE);
if (toSave.contains(SaveDevice.SAVE_INITIALIZED))
serializer.attribute(ns, Xconstants.INITIALIZED, (facility.isInitialized()) ? Xconstants.ONE : Xconstants.ZERO);
serializer.attribute(ns, Xconstants.DID, facility.getAddress());
if (toSave.contains(SaveDevice.SAVE_LOCATION))
serializer.attribute(ns, Xconstants.LID, facility.getLocationId());
if (toSave.contains(SaveDevice.SAVE_REFRESH))
serializer.attribute(ns, Xconstants.REFRESH, Integer.toString(facility.getRefresh().getInterval()));
for (Device device : facility.getDevices()) {
serializer.startTag(ns, Xconstants.PART);
serializer.attribute(ns, Xconstants.TYPE, device.getRawTypeId());
if (toSave.contains(SaveDevice.SAVE_VISIBILITY))
serializer.attribute(ns, Xconstants.VISIBILITY, (device.isVisible()) ? Xconstants.ONE : Xconstants.ZERO);
if (toSave.contains(SaveDevice.SAVE_NAME))
serializer.attribute(ns, Xconstants.NAME, device.getName());
// if (toSave.contains(SaveDevice.SAVE_VALUE))
// serializer.attribute(ns, Xconstants.VALUE, String.valueOf(device.getValue().getDoubleValue()));
serializer.endTag(ns, Xconstants.PART);
}
serializer.endTag(ns, Xconstants.DEVICE);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* New method create XML of SetDevs message with only one device in it. toSave parameter must by set properly.
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param device
* to save
* @param toSave
* ECO mode to save only wanted fields
* @return SetDevs message
* @since 2.2
*/
public static String createSetDev(String bt, String aid, Device device, EnumSet<SaveDevice> toSave) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
Facility facility = device.getFacility();
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, SETDEVS);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.AID, aid);
serializer.startTag(ns, Xconstants.DEVICE);
if (toSave.contains(SaveDevice.SAVE_INITIALIZED))
serializer.attribute(ns, Xconstants.INITIALIZED, (facility.isInitialized()) ? Xconstants.ONE : Xconstants.ZERO);
// send always
serializer.attribute(ns, Xconstants.DID, facility.getAddress());
if (toSave.contains(SaveDevice.SAVE_LOCATION))
serializer.attribute(ns, Xconstants.LID, facility.getLocationId());
if (toSave.contains(SaveDevice.SAVE_REFRESH))
serializer.attribute(ns, Xconstants.REFRESH, Integer.toString(facility.getRefresh().getInterval()));
if (toSave.contains(SaveDevice.SAVE_NAME) || toSave.contains(SaveDevice.SAVE_VALUE)) {
serializer.startTag(ns, Xconstants.PART);
// send always if sensor changed
serializer.attribute(ns, Xconstants.TYPE, device.getRawTypeId());
// if (toSave.contains(SaveDevice.SAVE_VISIBILITY))
// serializer.attribute(ns, Xconstants.VISIBILITY, (device.getVisibility()) ? Xconstants.ONE : Xconstants.ZERO);
if (toSave.contains(SaveDevice.SAVE_NAME))
serializer.attribute(ns, Xconstants.NAME, device.getName());
if (toSave.contains(SaveDevice.SAVE_VALUE))
serializer.attribute(ns, Xconstants.VALUE, String.valueOf(device.getValue().getDoubleValue()));
serializer.endTag(ns, Xconstants.PART);
}
serializer.endTag(ns, Xconstants.DEVICE);
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create XML for Switch message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param device
* to switch value
* @return XML of Switch message
* @since 2.2
*/
public static String createSwitch(String bt, String aid, Device device) {
return createComAttribsVariant(Xconstants.STATE, SWITCH, Xconstants.BT, bt, Xconstants.AID, aid, Xconstants.DID, device.getFacility().getAddress(), Xconstants.DTYPE,
device.getRawTypeId(), Xconstants.VALUE, String.valueOf(device.getValue().getDoubleValue()));
}
/**
* Method create XML of DelDevice message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param facility
* to be removed
* @return XML of DelDevice message
* @since 2.2
*/
public static String createDeleteDevice(String bt, String aid, Facility facility) {
return createComAttribsVariant(Xconstants.STATE, DELDEVICE, Xconstants.BT, bt, Xconstants.AID, aid, Xconstants.DID, facility.getAddress());
}
// /////////////////////////////////////ROOMS//////////////////////////////////////////////////////
/**
* Method create XML of AddRoom message
*
* @param bt
* userID of user
* @param location
* to create
* @return created message
* @since 2.2
*/
public static String createAddRoom(String bt, Location location) {
return createComAttribsVariant(Xconstants.STATE, ADDROOM, Xconstants.BT, bt, Xconstants.AID, location.getAdapterId(), Xconstants.LTYPE, Integer.toString(location.getType()), Xconstants.LNAME,
location.getName());
}
/**
* Method create XML of SetRooms message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param locations
* list of location object to update
* @return message SetRooms
* @since 2.2
*/
public static String createSetRooms(String bt, String aid, List<Location> locations) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, SETROOMS);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.AID, aid);
for (Location location : locations) {
serializer.startTag(ns, Xconstants.LOCATION);
serializer.attribute(ns, Xconstants.ID, location.getId());
serializer.attribute(ns, Xconstants.TYPE, Integer.toString(location.getType()));
serializer.attribute(ns, Xconstants.NAME, location.getName());
serializer.endTag(ns, Xconstants.LOCATION);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create XML of DelRoom message
*
* @param bt
* userID of user
* @param lid
* locationID of location to delete
* @return DelRoom message
* @since 2.2
*/
public static String createDeleteRoom(String bt, Location location) {
return createComAttribsVariant(Xconstants.STATE, DELROOM, Xconstants.BT, bt, Xconstants.AID, location.getAdapterId(), Xconstants.LID, location.getId());
}
/**
* Method create XML of GetRooms message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @return message GetRooms
* @since 2.2
*/
public static String createGetRooms(String bt, String aid) {
return createComAttribsVariant(Xconstants.STATE, GETROOMS, Xconstants.BT, bt, Xconstants.AID, aid);
}
// /////////////////////////////////////VIEWS//////////////////////////////////////////////////////
/**
* Method create XML of AddView message
*
* @param bt
* userID of user
* @param viewName
* name of custom view (also used as ID)
* @param iconNum
* type of icon
* @param devices
* list of devices in view
* @return addView message
* @since 2.2
*/
public static String createAddView(String bt, String viewName, int iconNum, List<Device> devices) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, ADDVIEW);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.NAME, viewName);
serializer.attribute(ns, Xconstants.ICON, Integer.toString(iconNum));
for (Device device : devices) {
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.AID, device.getFacility().getAdapterId());
serializer.attribute(ns, Xconstants.DID, device.getId());
serializer.attribute(ns, Xconstants.TYPE, device.getRawTypeId());
serializer.endTag(ns, Xconstants.DEVICE);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create one view to update message
*
* @param bt
* userID of user
* @param viewName
* name of view and also ID
* @param iconNum
* type of icon
* @param device
* device to be updated
* @param action
* type of manipulation, add or remove
* @return updateView message
* @since 2.2
*/
public static String createSetView(String bt, String viewName, int iconNum, Device device, NetworkAction action) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, SETVIEW);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.NAME, viewName);
serializer.attribute(ns, Xconstants.ICON, Integer.toString(iconNum));
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.AID, device.getFacility().getAdapterId());
serializer.attribute(ns, Xconstants.DID, device.getId());
serializer.attribute(ns, Xconstants.ACTION, action.getValue());
serializer.endTag(ns, Xconstants.DEVICE);
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create XML of DelVIew message
*
* @param bt
* userID of user
* @param viewName
* name of view and also ID
* @return DelVIew message
* @since 2.2
*/
public static String createDelView(String bt, String viewName) {
return createComAttribsVariant(Xconstants.STATE, DELVIEW, Xconstants.BT, bt, Xconstants.NAME, viewName);
}
/**
* Method create XML of GetViews message (method added in 1.6 version)
*
* @param bt
* userID of user
* @return getViews message
* @since 2.2
*/
public static String createGetViews(String bt) {
return createComAttribsVariant(Xconstants.STATE, GETVIEWS, Xconstants.BT, bt);
}
// /////////////////////////////////////ACCOUNTS///////////////////////////////////////////////////
/**
* Method create XML for AddAcount message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param users
* map with User object and User.Role
* @return AddAcc message
* @since 2.2
*/
public static String createAddAccounts(String bt, String aid, ArrayList<User> users) {
return createAddSeTAcc(ADDACCOUNTS, bt, aid, users);
}
/**
* Method create XML for SetAcount message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param users
* map with User object and User.Role
* @return SetAcc message
* @since 2.2
*/
public static String createSetAccounts(String bt, String aid, ArrayList<User> users) {
return createAddSeTAcc(SETCCOUNTS, bt, aid, users);
}
/**
* Method create XML for DelAcc message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param users
* list with Users
* @return dellAcc message
* @since 2.2
*/
public static String createDelAccounts(String bt, String aid, List<User> users) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, DELACCOUNTS);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.AID, aid);
for (User user : users) {
serializer.startTag(ns, Xconstants.USER);
serializer.attribute(ns, Xconstants.EMAIL, user.getEmail());
serializer.endTag(ns, Xconstants.USER);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create XML for GetAccs message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @return GetAcc message
* @since 2.2
*/
public static String createGetAccounts(String bt, String aid) {
return createComAttribsVariant(Xconstants.STATE, GETACCOUNTS, Xconstants.BT, bt, Xconstants.AID, aid);
}
// /////////////////////////////////////TIME///////////////////////////////////////////////////////
/**
* Method create XML of SetTimeZone message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @param diffToGMT
* difference to GMT (Xconstants.UTC+0)
* @return SetTimeZone message
* @since 2.2
*/
public static String createSetTimeZone(String bt, String aid, int diffToGMT) {
return createComAttribsVariant(Xconstants.STATE, SETTIMEZONE, Xconstants.BT, bt, Xconstants.AID, aid, Xconstants.UTC, Integer.toString(diffToGMT));
}
/**
* Method create XML of GetTimeZone message
*
* @param bt
* userID of user
* @param aid
* adapterID of actual adapter
* @return GetTimeZone message
* @since 2.2
*/
public static String createGetTimeZone(String bt, String aid) {
return createComAttribsVariant(Xconstants.STATE, GETTIMEZONE, Xconstants.BT, bt, Xconstants.AID, aid);
}
// /////////////////////////////////////OTHERS/////////////////////////////////////////////////////
/**
* Method create XML of SetLocale message
*
* @param bt
* userID of user
* @param locale
* of phone
* @return message SetLocale
* @since 2.2
*/
public static String createSetLocale(String bt, String locale) {
return createComAttribsVariant(Xconstants.STATE, SETLOCALE, Xconstants.BT, bt, Xconstants.LOCALE, locale);
}
// /////////////////////////////////////CONDITIONS,ACTIONS/////////////////////////////////////////
/**
* Method create XML of AddCond message
*
* @param bt
* userID of actual user
* @param name
* name of condition
* @param type
* type of condition
* @param condFuncs
* list of conditions
* @return AddCond message
* @since 2.2
*/
public static String createAddCondition(String bt, String name, ConditionType type, ArrayList<ConditionFunction> condFuncs) {
return createAddSetCond(ADDCONDITION, bt, name, type, condFuncs, "");
}
/**
* Method crate XMl of SetCond message
*
* @param bt
* userID of actual user
* @param name
* name of condition
* @param type
* type of condition
* @param cid
* conditionID to be update
* @param condFuncs
* list of conditions
* @return SetCond message
* @since 2.2
*/
public static String createSetCondition(String bt, String name, ConditionType type, String cid, ArrayList<ConditionFunction> condFuncs) {
return createAddSetCond(SETCONDITION, bt, name, type, condFuncs, cid);
}
/**
* Method create XML of DelCond message
*
* @param bt
* userID of actual user
* @param cid
* conditionID to be delete
* @return DelCond message
* @since 2.2
*/
public static String createDelCondition(String bt, String cid) {
return createComAttribsVariant(Xconstants.STATE, DELCONDITION, Xconstants.BT, bt, Xconstants.CID, cid);
}
/**
* Method create XML of GetCond message
*
* @param bt
* userID of actual user
* @param cid
* conditionID
* @return GetCond message
* @since 2.2
*/
public static String createGetCondition(String bt, String cid) {
return createComAttribsVariant(Xconstants.STATE, GETCONDITION, Xconstants.BT, bt, Xconstants.CID, cid);
}
/**
* Method create XML of GetConds message
*
* @param bt
* userID of actual user
* @return GetConds message
* @since 2.2
*/
public static String createGetConditions(String bt) {
return createComAttribsVariant(Xconstants.STATE, GETCONDITIONS, Xconstants.BT, bt);
}
/**
* Method create XML of AddAct message
*
* @param bt
* userID of actual user
* @param name
* name of new action
* @param actions
* list of action to add
* @return AddAct message
* @since 2.2
*/
public static String createAddAction(String bt, String name, List<Action> actions) {
return createAddSetAct(ADDACTION, bt, name, "", actions);
}
/**
* Method create XML of SetAct message
*
* @param bt
* userID of actual user
* @param name
* name of new action
* @param acid
* actionID to be updated
* @param actions
* list of action to update
* @return SetAct message
* @since 2.2
*/
public static String createSetAction(String bt, String name, String acid, List<Action> actions) {
return createAddSetAct(SETACTION, bt, name, acid, actions);
}
/**
* Method create XML of DelAct
*
* @param bt
* userID of actual user
* @param acid
* actionID to be removed
* @return DelAct message
* @since 2.2
*/
public static String createDelAction(String bt, String acid) {
return createComAttribsVariant(Xconstants.STATE, DELACTION, Xconstants.BT, bt, Xconstants.ACID, acid);
}
/**
* Method create XML of GetActs message
*
* @param bt
* userID of actual user
* @return GetActs message
* @since 2.2
*/
public static String createGetActions(String bt) {
return createComAttribsVariant(Xconstants.STATE, GETACTIONS, Xconstants.BT, bt);
}
/**
* Method create XML of GetAct message
*
* @param bt
* userID of actual user
* @param acid
* actionID
* @return GetAct message
* @since 2.2
*/
public static String createGetAction(String bt, String acid) {
return createComAttribsVariant(Xconstants.STATE, GETACTION, Xconstants.BT, bt, Xconstants.ACID, acid);
}
/**
* Method create XML of CondAction message
*
* @param bt
* userID of user
* @param cid
* conditionID
* @param acid
* actionID
* @return CondAction message
* @since 2.2
*/
public static String createConditionPlusAction(String bt, String cid, String acid) {
return createComAttribsVariant(Xconstants.STATE, CONDITIONPLUSACTION, Xconstants.BT, bt, Xconstants.CID, cid, Xconstants.ACID, acid);
}
// /////////////////////////////////////NOTIFICATIONS//////////////////////////////////////////////
/**
* Method create XML of DelXconstants.GCMID message (delete google cloud message id)
*
* @param userId
* of last logged user
* @param gcmid
* id of google messaging
* @return message DelXconstants.GCMID
* @since 2.2
*/
public static String createDeLGCMID(String userId, String gcmid) {
return createComAttribsVariant(Xconstants.STATE, DELGCMID, Xconstants.UID, userId, Xconstants.GCMID, gcmid);
}
/**
* Method create XML of SetXconstants.GCMID message
*
* @param bt
* userID of user logged in now
* @param gcmid
* id of google messaging
* @return message SetXconstants.GCMID
* @since 2.2
*/
public static String createSetGCMID(String bt, String gcmid) {
return createComAttribsVariant(Xconstants.STATE, SETGCMID, Xconstants.BT, bt, Xconstants.GCMID, gcmid);
}
/**
* Method create XML of GetNotifs message
*
* @param bt
* SessionID of user
* @return message GetNotifs
* @since 2.2
*/
public static String createGetNotifications(String bt) {
return createComAttribsVariant(Xconstants.STATE, GETNOTIFICATIONS, Xconstants.BT, bt);
}
/**
* Method create XML of NotifRead message
*
* @param bt
* userID of user
* @param mids
* list of gcmID of read notification
* @return message NotifRead
* @since 2.2
*/
public static String createNotificaionRead(String bt, List<String> mids) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, NOTIFICATIONREAD);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
for (String mid : mids) {
serializer.startTag(ns, Xconstants.NOTIFICAION);
serializer.attribute(ns, Xconstants.MSGID, mid);
serializer.endTag(ns, Xconstants.NOTIFICAION);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method create message for creating new rule or editing the old one
* @param bt
* @param name
* @param aid
* @param type
* @param devices
* list of devices in right position for algorithm
* @param params
* list of strings with additional params for new rule
* @return
*/
public static String createAddSetAlgor(String bt, String name, String algId, String aid, int type, List<String> devices, List<String> params, String regionId, String geoType, Boolean state){
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
if(state == null)
serializer.attribute(ns, Xconstants.STATE, ADDALG);
else {
serializer.attribute(ns, Xconstants.STATE, SETALG);
serializer.attribute(ns, Xconstants.ENABLE, (state.booleanValue()) ? "1" : "0");
serializer.attribute(ns, Xconstants.ALGID, algId);
}
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.ALGNAME, name);
serializer.attribute(ns, Xconstants.AID, aid);
serializer.attribute(ns, Xconstants.ATYPE, Integer.toString(type));
int i = 1;
for(String device : devices){
serializer.startTag(ns, Xconstants.DEVICE);
String[] id_type = device.split(Device.ID_SEPARATOR);
serializer.attribute(ns, Xconstants.ID, id_type[0]);
serializer.attribute(ns, Xconstants.TYPE, id_type[1]);
serializer.attribute(ns, Xconstants.POSITION, Integer.toString(i++));
serializer.endTag(ns, Xconstants.DEVICE);
}
i=1;
for(String param : params) {
serializer.startTag(ns, Xconstants.PARAM);
serializer.attribute(ns, Xconstants.POSITION, Integer.toString(i++));
serializer.text(param);
serializer.endTag(ns, Xconstants.PARAM);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
public static String createAddAlgor(String bt, String name, String aid, int type, List<String> devices, List<String> params, String regionId, String geoType){
return createAddSetAlgor(bt, name, null, aid, type, devices, params, regionId, geoType, null);
}
public static String createSetAlgor(String bt, String name, String algId, String aid, int type, boolean enable, List<String> devices, List<String>params, String regionId, String geoType){
return createAddSetAlgor(bt, name, algId, aid, type, devices, params, regionId, geoType, enable);
}
/**
* Method return message with demands for specific rules
* @param bt
* @param aid
* @param algids
* @return
*/
public static String createGetAlgs(String bt, String aid, ArrayList<String> algids){
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, GETALGS);
serializer.attribute(ns, Xconstants.AID, aid);
for(String algId : algids){
serializer.startTag(ns, Xconstants.ALGORITHM);
serializer.attribute(ns, Xconstants.ID, algId);
serializer.endTag(ns, Xconstants.ALGORITHM);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
/**
* Method returns message with demands for all rules of user on specific adapter
* @param bt
* @return
*/
public static String createGetAllAlgs(String bt, String aid){
return createComAttribsVariant(Xconstants.STATE, GETALLALGS, Xconstants.BT, bt, Xconstants.AID, aid);
}
/**
* Method returns message with demands for delete specific rule
* @param bt
* @param algid
* @return
*/
public static String createDelAlg(String bt, String algid){
return createComAttribsVariant(Xconstants.STATE, DELALG, Xconstants.BT, bt, Xconstants.ALGID, algid);
}
/**
* Method create message for PassBorder event
* @param bt
* @param rid
* @param type
* @return
*/
public static String createPassBorder(String bt, String rid, String type){
return createComAttribsVariant(Xconstants.STATE, PASSBORDER, Xconstants.BT, bt, Xconstants.RID, rid, Xconstants.TYPE, type);
}
private static String createComAttribsVariant(String... args) {
if (0 != (args.length % 2)) { // odd
throw new RuntimeException("Bad params count");
}
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.VERSION, COM_VER); // every time use version
for (int i = 0; i < args.length; i += 2) { // take pair of args
serializer.attribute(ns, args[i], args[i + 1]);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
private static String createAddSeTAcc(String state, String bt, String aid, ArrayList<User> users) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, state);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.AID, aid);
for (User user : users) {
serializer.startTag(ns, Xconstants.USER);
serializer.attribute(ns, Xconstants.EMAIL, user.getEmail());
serializer.attribute(ns, Xconstants.ROLE, user.getRole().getValue());
serializer.endTag(ns, Xconstants.USER);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
private static String createAddSetCond(String state, String bt, String name, ConditionType type, ArrayList<ConditionFunction> condFuncs, String cid) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, state);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.CNAME, name);
serializer.attribute(ns, Xconstants.CTYPE, type.getValue());
if (state.equals(SETCONDITION))
serializer.attribute(ns, Xconstants.ID, cid);
for (ConditionFunction func : condFuncs) {
serializer.startTag(ns, Xconstants.FUNC);
serializer.attribute(ns, Xconstants.TYPE, func.getFuncType().getValue());
switch (func.getFuncType()) {
case EQ:
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, ((EqualFunc) func).getDevice().getId());
serializer.attribute(ns, Xconstants.TYPE, ((EqualFunc) func).getDevice().getRawTypeId());
serializer.endTag(ns, Xconstants.DEVICE);
serializer.startTag(ns, Xconstants.VALUE);
serializer.text(((EqualFunc) func).getValue());
serializer.endTag(ns, Xconstants.VALUE);
break;
case GT:
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, ((GreaterThanFunc) func).getDevice().getId());
serializer.attribute(ns, Xconstants.TYPE, ((GreaterThanFunc) func).getDevice().getRawTypeId());
serializer.endTag(ns, Xconstants.DEVICE);
serializer.startTag(ns, Xconstants.VALUE);
serializer.text(((GreaterThanFunc) func).getValue());
serializer.endTag(ns, Xconstants.VALUE);
break;
case GE:
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, ((GreaterEqualFunc) func).getDevice().getId());
serializer.attribute(ns, Xconstants.TYPE, ((GreaterEqualFunc) func).getDevice().getRawTypeId());
serializer.endTag(ns, Xconstants.DEVICE);
serializer.startTag(ns, Xconstants.VALUE);
serializer.text(((GreaterEqualFunc) func).getValue());
serializer.endTag(ns, Xconstants.VALUE);
break;
case LT:
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, ((LesserThanFunc) func).getDevice().getId());
serializer.attribute(ns, Xconstants.TYPE, ((LesserThanFunc) func).getDevice().getRawTypeId());
serializer.endTag(ns, Xconstants.DEVICE);
serializer.startTag(ns, Xconstants.VALUE);
serializer.text(((LesserThanFunc) func).getValue());
serializer.endTag(ns, Xconstants.VALUE);
break;
case LE:
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, ((LesserEqualFunc) func).getDevice().getId());
serializer.attribute(ns, Xconstants.TYPE, ((LesserEqualFunc) func).getDevice().getRawTypeId());
serializer.endTag(ns, Xconstants.DEVICE);
serializer.startTag(ns, Xconstants.VALUE);
serializer.text(((LesserEqualFunc) func).getValue());
serializer.endTag(ns, Xconstants.VALUE);
break;
case BTW:
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, ((BetweenFunc) func).getDevice().getId());
serializer.attribute(ns, Xconstants.TYPE, ((BetweenFunc) func).getDevice().getRawTypeId());
serializer.endTag(ns, Xconstants.DEVICE);
serializer.startTag(ns, Xconstants.VALUE);
serializer.text(((BetweenFunc) func).getMinValue());
serializer.endTag(ns, Xconstants.VALUE);
serializer.startTag(ns, Xconstants.VALUE);
serializer.text(((BetweenFunc) func).getMaxValue());
serializer.endTag(ns, Xconstants.VALUE);
break;
case DP:
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, ((DewPointFunc) func).getTempDevice().getId());
serializer.attribute(ns, Xconstants.TYPE, ((DewPointFunc) func).getTempDevice().getType() + "");
serializer.endTag(ns, Xconstants.DEVICE);
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, ((DewPointFunc) func).getHumiDevice().getId());
serializer.attribute(ns, Xconstants.TYPE, ((DewPointFunc) func).getHumiDevice().getRawTypeId());
serializer.endTag(ns, Xconstants.DEVICE);
break;
case TIME:
serializer.startTag(ns, Xconstants.VALUE);
serializer.text(((TimeFunc) func).getTime());
serializer.endTag(ns, Xconstants.VALUE);
break;
case GEO:
serializer.startTag(ns, Xconstants.VALUE);
// FIXME: wait for martin
serializer.text("TODO");
serializer.endTag(ns, Xconstants.VALUE);
break;
default:
break;
}
serializer.endTag(ns, Xconstants.FUNC);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
private static String createAddSetAct(String state, String bt, String name, String actid, List<Action> actions) {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", null);
serializer.startTag(ns, Xconstants.COM_ROOT);
serializer.attribute(ns, Xconstants.BT, bt);
serializer.attribute(ns, Xconstants.STATE, state);
serializer.attribute(ns, Xconstants.VERSION, COM_VER);
serializer.attribute(ns, Xconstants.ACNAME, name);
if (state.equals(SETACTION))
serializer.attribute(ns, Xconstants.ACID, actid);
for (Action action : actions) {
serializer.startTag(ns, Xconstants.ACTION);
serializer.attribute(ns, Xconstants.TYPE, action.getType().getValue());
if (action.getType() == Action.ActionType.ACTOR) {
serializer.startTag(ns, Xconstants.DEVICE);
serializer.attribute(ns, Xconstants.ID, action.getDevice().getId());
serializer.attribute(ns, Xconstants.TYPE, action.getDevice().getRawTypeId());
serializer.attribute(ns, Xconstants.VALUE, action.getValue());
serializer.endTag(ns, Xconstants.DEVICE);
}
serializer.endTag(ns, Xconstants.ACTION);
}
serializer.endTag(ns, Xconstants.COM_ROOT);
serializer.endDocument();
return writer.toString();
} catch (Exception e) {
throw AppException.wrap(e, NetworkError.XML);
}
}
}
|
package ViewManager;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.cassandra.cql3.UpdateParameters;
import org.apache.cassandra.db.marshal.ColumnToCollectionType;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.json.simple.JSONObject;
import client.client.XmlHandler;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ColumnDefinitions;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
import com.datastax.driver.core.policies.DefaultRetryPolicy;
import com.datastax.driver.core.policies.TokenAwarePolicy;
import com.datastax.driver.core.utils.Bytes;
public class ViewManagerController {
Cluster currentCluster = null;
ViewManager vm = null;
private static XMLConfiguration baseTableKeysConfig;
List<String> baseTableName;
List<String> pkName;
List<String> deltaTableName;
List<String> reverseTablesNames_Join;
List<String> reverseTablesNames_AggJoin;
List<String> reverseTablesNames_AggJoinGroupBy;
List<String> preaggTableNames;
List<String> preaggJoinTableNames;
List<String> rj_joinTables;
List<String> rj_joinKeys;
List<String> rj_joinKeyTypes;
List<String> rj_nrDelta;
int rjoins;
List<String> pkType;
Stream stream = null;
public ViewManagerController() {
connectToCluster();
retrieveLoadXmlHandlers();
parseXmlMapping();
stream = new Stream();
vm = new ViewManager(currentCluster);
}
private void retrieveLoadXmlHandlers() {
baseTableKeysConfig = new XMLConfiguration();
baseTableKeysConfig.setDelimiterParsingDisabled(true);
try {
baseTableKeysConfig
.load("ViewManager/properties/baseTableKeys.xml");
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
public void parseXmlMapping() {
baseTableName = baseTableKeysConfig.getList("tableSchema.table.name");
pkName = baseTableKeysConfig.getList("tableSchema.table.pkName");
pkType = baseTableKeysConfig.getList("tableSchema.table.pkType");
deltaTableName = VmXmlHandler.getInstance().getDeltaPreaggMapping()
.getList("mapping.unit.deltaTable");
reverseTablesNames_Join = VmXmlHandler.getInstance().getRjJoinMapping()
.getList("mapping.unit.reverseJoin");
reverseTablesNames_AggJoin = VmXmlHandler.getInstance()
.getRjJoinMapping().getList("mapping.unit.reverseJoin");
reverseTablesNames_AggJoinGroupBy = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping()
.getList("mapping.unit.reverseJoin");
rj_joinTables = VmXmlHandler.getInstance().getDeltaReverseJoinMapping()
.getList("mapping.unit.Join.name");
rj_joinKeys = VmXmlHandler.getInstance().getDeltaReverseJoinMapping()
.getList("mapping.unit.Join.JoinKey");
rj_joinKeyTypes = VmXmlHandler.getInstance()
.getDeltaReverseJoinMapping().getList("mapping.unit.Join.type");
rj_nrDelta = VmXmlHandler.getInstance().getDeltaReverseJoinMapping()
.getList("mapping.unit.nrDelta");
rjoins = VmXmlHandler.getInstance().getDeltaReverseJoinMapping()
.getInt("mapping.nrUnit");
preaggTableNames = VmXmlHandler.getInstance().getHavingPreAggMapping()
.getList("mapping.unit.preaggTable");
preaggJoinTableNames = VmXmlHandler.getInstance()
.getHavingJoinAggMapping().getList("mapping.unit.preaggTable");
}
private void connectToCluster() {
currentCluster = Cluster
.builder()
.addContactPoint(
XmlHandler.getInstance().getClusterConfig()
.getString("config.host.localhost"))
.withRetryPolicy(DefaultRetryPolicy.INSTANCE)
.withLoadBalancingPolicy(
new TokenAwarePolicy(new DCAwareRoundRobinPolicy()))
.build();
}
public void update(JSONObject json) {
// get position of basetable from xml list
// retrieve pk of basetable and delta from XML mapping file
int indexBaseTableName = baseTableName.indexOf((String) json.get("table"));
String baseTablePrimaryKey = pkName.get(indexBaseTableName);
String baseTablePrimaryKeyType = pkType.get(indexBaseTableName);
stream = new Stream();
stream.setBaseTable((String) json.get("table"));
CustomizedRow deltaUpdatedRow = null;
// 1. update Delta Table
// 1.a If successful, retrieve entire updated Row from Delta to pass on
// as streams
if (vm.updateDelta(stream,json, indexBaseTableName, baseTablePrimaryKey)) {
deltaUpdatedRow = stream.getDeltaUpdatedRow();
}
// update selection view
// for each delta, loop on all selection views possible
// check if selection condition is met based on selection key
// if yes then update selection, if not ignore
// also compare old values of selection condition, if they have changed
// then delete row from table
int position1 = deltaTableName.indexOf("delta_" + (String) json.get("table"));
if (position1 != -1) {
String temp4 = "mapping.unit(";
temp4 += Integer.toString(position1);
temp4 += ")";
int nrConditions = VmXmlHandler.getInstance()
.getDeltaSelectionMapping().getInt(temp4 + ".nrCond");
for (int i = 0; i < nrConditions; i++) {
String s = temp4 + ".Cond(" + Integer.toString(i) + ")";
String selecTable = VmXmlHandler.getInstance()
.getDeltaSelectionMapping().getString(s + ".name");
String nrAnd = VmXmlHandler.getInstance()
.getDeltaSelectionMapping().getString(s + ".nrAnd");
boolean myEval = true;
boolean myEval_old = true;
for (int j = 0; j < Integer.parseInt(nrAnd); j++) {
String s11 = s + ".And(";
s11 += Integer.toString(j);
s11 += ")";
String operation = VmXmlHandler.getInstance()
.getDeltaSelectionMapping()
.getString(s11 + ".operation");
String value = VmXmlHandler.getInstance()
.getDeltaSelectionMapping()
.getString(s11 + ".value");
String type = VmXmlHandler.getInstance()
.getDeltaSelectionMapping()
.getString(s11 + ".type");
String selColName = VmXmlHandler.getInstance()
.getDeltaSelectionMapping()
.getString(s11 + ".selectionCol");
myEval &= Utils.evaluateCondition(stream.getDeltaUpdatedRow(), operation, value, type, selColName+"_new");
myEval_old &= Utils.evaluateCondition(stream.getDeltaUpdatedRow(), operation, value, type, selColName+"_old");
}
// if condition matching now & matched before
if (myEval && myEval_old) {
vm.updateSelection(stream.getDeltaUpdatedRow(),
(String) json.get("keyspace"), selecTable,
baseTablePrimaryKey);
// if matching now & not matching before
} else if (myEval && !myEval_old) {
vm.updateSelection(stream.getDeltaUpdatedRow(),
(String) json.get("keyspace"), selecTable,
baseTablePrimaryKey);
// if not matching now & matching before
} else if (!myEval && myEval_old) {
vm.deleteRowSelection((String) json.get("keyspace"), selecTable,
baseTablePrimaryKey, json);
// if not matching now & not before, ignore
}
}
}
// 2. for the delta table updated, get the depending preaggregation/agg
// tables
// preagg tables hold all column values, hence they have to be updated
int position = deltaTableName.indexOf("delta_"
+ (String) json.get("table"));
if (position != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(position);
temp += ")";
int nrPreagg = VmXmlHandler.getInstance().getDeltaPreaggMapping()
.getInt(temp + ".nrPreagg");
for (int i = 0; i < nrPreagg; i++) {
String s = temp + ".Preagg(" + Integer.toString(i) + ")";
String AggKey = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".AggKey");
String AggKeyType = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".AggKeyType");
String preaggTable = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".name");
String AggCol = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".AggCol");
String AggColType = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".AggColType");
// 2.a after getting the preagg table name & neccessary
// parameters,
// check if aggKey in delta (_old & _new ) is null
// if null then dont update, else update
boolean isNull = checkIfAggIsNull(AggKey, deltaUpdatedRow);
if (!isNull) {
// WHERE clause condition evaluation
String condName = VmXmlHandler.getInstance()
.getDeltaPreaggMapping()
.getString(s + ".Cond.name");
if (!condName.equals("none")) {
String nrAnd = VmXmlHandler.getInstance()
.getDeltaPreaggMapping()
.getString(s + ".Cond.nrAnd");
boolean eval = true;
String operation = "";
String value = "";
String type = "";
String colName = "";
for (int j = 0; j < Integer.parseInt(nrAnd); j++) {
String s11 = s + ".Cond.And(";
s11 += Integer.toString(j);
s11 += ")";
operation = VmXmlHandler.getInstance()
.getDeltaPreaggMapping()
.getString(s11 + ".operation");
value = VmXmlHandler.getInstance()
.getDeltaPreaggMapping()
.getString(s11 + ".value");
type = VmXmlHandler.getInstance()
.getDeltaPreaggMapping()
.getString(s11 + ".type");
colName = VmXmlHandler.getInstance()
.getDeltaPreaggMapping()
.getString(s11 + ".selectionCol");
eval &= Utils.evaluateCondition(deltaUpdatedRow,
operation, value, type, colName + "_new");
}
System.out.println((String) json.get("table")
+ " condition is " + eval);
// condition fulfilled
if (eval) {
// by passing the whole delta Row, we have agg key
// value
// even if it is not in json
vm.updatePreaggregation(stream, AggKey,
AggKeyType, json, preaggTable,
baseTablePrimaryKey, AggCol, AggColType,
false, false);
} else {
// cascade delete
String pkVAlue = Utils.getColumnValueFromDeltaStream(deltaUpdatedRow, baseTablePrimaryKey, baseTablePrimaryKeyType, "");
boolean eval_old = Utils.evaluateCondition(deltaUpdatedRow, operation, value, type,colName + "_old");
if (eval_old) {
cascadeDeleteHavingTables(json,preaggTable,AggKey,AggKeyType,pkVAlue,AggCol,AggColType);
}
// continue
continue;
}
} else {
// by passing the whole delta Row, we have agg key value
// even if it is not in json
vm.updatePreaggregation(stream, AggKey,
AggKeyType, json, preaggTable,
baseTablePrimaryKey, AggCol, AggColType, false,
false);
}
}
}
}
// End of updating preagg with having clause
else {
System.out.println("No Preaggregation table for this delta table "
+ " delta_" + (String) json.get("table") + " available");
}
stream.resetPreaggregationRows();
// 3. for the delta table updated, get update depending reverse join
// tables
int cursor = 0;
for (int j = 0; j < rjoins; j++) {
// basetables
int nrOfTables = Integer.parseInt(rj_nrDelta.get(j));
String joinTable = rj_joinTables.get(j);
// include only indices from 1 to nrOfTables
// get basetables from name of rj table
List<String> baseTables = Arrays.asList(
rj_joinTables.get(j).split("_")).subList(1, nrOfTables + 1);
String tableName = (String) json.get("table");
String keyspace = (String) json.get("keyspace");
int column = baseTables.indexOf(tableName) + 1;
String joinKeyName = rj_joinKeys.get(cursor + column - 1);
String joinKeyType = rj_joinKeyTypes.get(j);
if (column == 0) {
System.out.println("No ReverseJoin for this delta update");
continue;
}
// Check on where clause for join
// WHERE clause condition evaluation
position = VmXmlHandler.getInstance().getDeltaReverseJoinMapping()
.getList("mapping.unit.Join.name").indexOf(joinTable);
if (position != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(position);
temp += ").Join";
String condName = VmXmlHandler.getInstance()
.getDeltaReverseJoinMapping()
.getString(temp + ".Cond.name");
List<String> baseTableNames = new ArrayList<>();
String otherTable = "";
if (!condName.equals("none")) {
baseTableNames = VmXmlHandler.getInstance()
.getDeltaReverseJoinMapping()
.getList(temp + ".Cond.table.name");
otherTable = VmXmlHandler.getInstance()
.getDeltaReverseJoinMapping()
.getString(temp + ".Cond.otherTable");
if (!baseTableNames.contains((String) json.get("table"))
&& !otherTable.equals((String) json.get("table"))) {
continue;
}
}
// to override the next if condition,to update the reverse join
if (otherTable.equals((String) json.get("table"))) {
condName = "none";
}
if (!condName.equals("none")) {
String nrAnd = VmXmlHandler.getInstance()
.getDeltaReverseJoinMapping()
.getString(temp + ".Cond.nrAnd");
boolean eval = true;
String operation = "";
String value = "";
String type = "";
String colName = "";
for (int jj = 0; jj < Integer.parseInt(nrAnd); jj++) {
String s11 = temp + ".Cond.And(";
s11 += Integer.toString(jj);
s11 += ")";
operation = VmXmlHandler.getInstance()
.getDeltaReverseJoinMapping()
.getString(s11 + ".operation");
value = VmXmlHandler.getInstance()
.getDeltaReverseJoinMapping()
.getString(s11 + ".value");
type = VmXmlHandler.getInstance()
.getDeltaReverseJoinMapping()
.getString(s11 + ".type");
colName = VmXmlHandler.getInstance()
.getDeltaReverseJoinMapping()
.getString(s11 + ".selectionCol");
eval &= Utils.evaluateCondition(deltaUpdatedRow, operation,
value, type, colName + "_new");
}
System.out.println((String) json.get("table")
+ " condition is " + eval);
// condition fulfilled
if (eval) {
// by passing the whole delta Row, we have agg key
// value
// even if it is not in json
vm.updateReverseJoin(stream,json, cursor, nrOfTables,
joinTable, baseTables, joinKeyName, tableName,
keyspace, joinKeyType, column);
} else {
String pkVAlue = Utils.getColumnValueFromDeltaStream(deltaUpdatedRow, baseTablePrimaryKey, baseTablePrimaryKeyType, "");
boolean eval_old = Utils.evaluateCondition(deltaUpdatedRow,
operation, value, type, colName + "_old");
if (eval_old) {
// 1. retrieve the row to be deleted from delta
// table
StringBuilder selectQuery = new StringBuilder(
"SELECT *");
selectQuery.append(" FROM ")
.append(json.get("keyspace")).append(".")
.append("delta_" + json.get("table"))
.append(" WHERE ")
.append(baseTablePrimaryKey).append(" = ")
.append(pkVAlue).append(";");
System.out.println(selectQuery);
ResultSet selectionResult;
try {
Session session = currentCluster.connect();
selectionResult = session.execute(selectQuery
.toString());
} catch (Exception e) {
e.printStackTrace();
return;
}
// 2. set DeltaDeletedRow variable for streaming
//vm.setDeltaDeletedRow(selectionResult.one());
CustomizedRow crow = new CustomizedRow(selectionResult.one());
stream.setDeltaDeletedRow(crow);
cascadeDeleteReverseJoin( json, j, cursor);
stream.setDeltaDeletedRow(null);
//cascadeDelete(json, false);
}
// continue
continue;
}
} else {
// by passing the whole delta Row, we have agg key value
// even if it is not in json
vm.updateReverseJoin(stream,json, cursor, nrOfTables, joinTable,
baseTables, joinKeyName, tableName, keyspace,
joinKeyType, column);
}
}
// END OF UPDATE JoinPreag
stream.resetReverseJoinRows();
cursor += nrOfTables;
}
stream.resetDeltaRows();
}
private void cascadeDeleteHavingTables(JSONObject json,String preaggTable,String aggKey, String aggKeyType, String pkVAlue, String aggCol, String aggColType) {
int position1 = preaggTableNames.indexOf(preaggTable);
if (position1 != -1) {
String temp4 = "mapping.unit(";
temp4 += Integer.toString(position1);
temp4 += ")";
int nrConditions = VmXmlHandler.getInstance()
.getHavingPreAggMapping().getInt(temp4 + ".nrCond");
for (int m = 0; m < nrConditions; m++) {
String s1 = temp4 + ".Cond(" + Integer.toString(m)
+ ")";
String havingTable = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s1 + ".name");
vm.deleteElementFromHaving(stream,json,havingTable,aggKey,aggKeyType,pkVAlue,aggCol,aggColType);
}
}
}
private void evaluateLeftorRightJoinAggHaving(String temp, String aggColPosition,
int e, JSONObject json, String leftOrRight) {
Integer nrHaving = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getInt(temp + "." +aggColPosition+".c(" + e
+ ")."+leftOrRight+".nrHaving");
if(nrHaving!=0){
List<String> havingTableName = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ")."+leftOrRight+".Having.name");
List<String> aggFct = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ")."+leftOrRight+".Having.And.aggFct");
List<String> havingType = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ")."+leftOrRight+".Having.And.type");
List<String> operation = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ")."+leftOrRight+".Having.And.operation");
List<String> value = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ")."+leftOrRight+".Having.And.value");
for(int j=0;j<nrHaving;j++){
if(stream.getLeftOrRightJoinAggDeleteRow()!=null){
//boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggDeleteRow(), aggFct.get(j), operation.get(j), value.get(j));
//if(result){
String pkName = stream.getLeftOrRightJoinAggDeleteRow().getName(0);
String pkType = stream.getLeftOrRightJoinAggDeleteRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getLeftOrRightJoinAggDeleteRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), havingTableName.get(j), pkName,pkValue);
}
if(stream.getLeftOrRightJoinAggUpdatedOldRow()!=null){
boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggUpdatedOldRow(), aggFct.get(j), operation.get(j), value.get(j));
if(result){
JoinAggregationHelper.insertStatement(json, havingTableName.get(j), stream.getLeftOrRightJoinAggUpdatedOldRow());
}else{
String pkName = stream.getLeftOrRightJoinAggUpdatedOldRow().getName(0);
String pkType = stream.getLeftOrRightJoinAggUpdatedOldRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getLeftOrRightJoinAggUpdatedOldRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), havingTableName.get(j), pkName,pkValue);
}
}
if(stream.getLeftOrRightJoinAggNewRow()!=null){
boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggNewRow(), aggFct.get(j), operation.get(j), value.get(j));
if(result){
JoinAggregationHelper.insertStatement(json, havingTableName.get(j), stream.getLeftOrRightJoinAggNewRow());
}else{
String pkName = stream.getLeftOrRightJoinAggNewRow().getName(0);
String pkType = stream.getLeftOrRightJoinAggNewRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getLeftOrRightJoinAggNewRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), havingTableName.get(j), pkName,pkValue);
}
}
}
}
}
private void evaluateInnerJoinAggHaving(String temp,String aggColPosition,int e,JSONObject json){
Integer nrHaving = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getInt(temp + "." +aggColPosition+".c(" + e
+ ").inner.nrHaving");
if(nrHaving!=0){
List<String> innerHaving = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").inner.Having.name");
List<String> aggFct = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").inner.Having.And.aggFct");
List<String> innerHavingType = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").inner.Having.And.type");
List<String> operation = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").inner.Having.And.operation");
List<String> value = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").inner.Having.And.value");
for(int j=0;j<nrHaving;j++){
if(stream.getInnerJoinAggDeleteRow()!=null){
//boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggDeleteRow(), aggFct.get(j), operation.get(j), value.get(j));
//if(result){
String pkName = stream.getInnerJoinAggDeleteRow().getName(0);
String pkType = stream.getInnerJoinAggDeleteRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getInnerJoinAggDeleteRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), innerHaving.get(j), pkName,pkValue);
}
if(stream.getInnerJoinAggUpdatedOldRow()!=null){
boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggUpdatedOldRow(), aggFct.get(j), operation.get(j), value.get(j));
if(result){
JoinAggregationHelper.insertStatement(json, innerHaving.get(j), stream.getInnerJoinAggUpdatedOldRow());
}else{
String pkName = stream.getInnerJoinAggUpdatedOldRow().getName(0);
String pkType = stream.getInnerJoinAggUpdatedOldRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getInnerJoinAggUpdatedOldRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), innerHaving.get(j), pkName,pkValue);
}
}
if(stream.getInnerJoinAggNewRow()!=null){
boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggNewRow(), aggFct.get(j), operation.get(j), value.get(j));
if(result){
JoinAggregationHelper.insertStatement(json, innerHaving.get(j), stream.getInnerJoinAggNewRow());
}else{
String pkName = stream.getInnerJoinAggNewRow().getName(0);
String pkType = stream.getInnerJoinAggNewRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getInnerJoinAggNewRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), innerHaving.get(j), pkName,pkValue);
}
}
}
}
}
private void evaluateInnerJoinAggGroupByHaving(int i, int e, String temp,JSONObject json,String aggColPosition) {
Integer nrHaving = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getInt(temp + "." +aggColPosition+".c(" + e
+ ").Agg(" + i + ").inner.nrHaving");
if(nrHaving!=0){
List<String> innerHaving = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").Agg(" + i + ").inner.Having.name");
List<String> aggFct = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").Agg(" + i + ").inner.Having.And.aggFct");
List<String> innerHavingType = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").Agg(" + i + ").inner.Having.And.type");
List<String> operation = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").Agg(" + i + ").inner.Having.And.operation");
List<String> value = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e
+ ").Agg(" + i + ").inner.Having.And.value");
for(int j=0;j<nrHaving;j++){
if(stream.getInnerJoinAggGroupByDeleteOldRow()!=null){
//boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggGroupByDeleteOldRow(), aggFct.get(j), operation.get(j), value.get(j));
//if(result){
String pkName = stream.getInnerJoinAggGroupByDeleteOldRow().getName(0);
String pkType = stream.getInnerJoinAggGroupByDeleteOldRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getInnerJoinAggGroupByDeleteOldRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), innerHaving.get(j), pkName,pkValue);
}
if(stream.getInnerJoinAggGroupByUpdatedOldRow()!=null){
boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggGroupByUpdatedOldRow(), aggFct.get(j), operation.get(j), value.get(j));
if(result){
JoinAggGroupByHelper.insertStatement(json, innerHaving.get(j), stream.getInnerJoinAggGroupByUpdatedOldRow());
}else{
String pkName = stream.getInnerJoinAggGroupByUpdatedOldRow().getName(0);
String pkType = stream.getInnerJoinAggGroupByUpdatedOldRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getInnerJoinAggGroupByUpdatedOldRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), innerHaving.get(j), pkName,pkValue);
}
}
if(stream.getInnerJoinAggGroupByNewRow()!=null){
boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggGroupByNewRow(), aggFct.get(j), operation.get(j), value.get(j));
if(result){
JoinAggGroupByHelper.insertStatement(json, innerHaving.get(j), stream.getInnerJoinAggGroupByNewRow());
}else{
String pkName = stream.getInnerJoinAggGroupByNewRow().getName(0);
String pkType = stream.getInnerJoinAggGroupByNewRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getInnerJoinAggGroupByNewRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), innerHaving.get(j), pkName,pkValue);
}
}
}
}
}
private void evaluateLeftorRightJoinAggGroupByHaving(int i, int e, String temp,JSONObject json,String position) {
Integer nrHaving = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getInt(temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ")."+position+".nrHaving");
if(nrHaving!=0){
List<String> leftHaving = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ")."+position+".Having.name");
List<String> aggFct = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ")."+position+".Having.And.aggFct");
List<String> leftHavingType = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ")."+position+".Having.And.type");
List<String> operation = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ")."+position+".Having.And.operation");
List<String> value = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ")."+position+".Having.And.value");
for(int j=0;j<nrHaving;j++){
if(stream.getLeftOrRightJoinAggGroupByDeleteRow()!=null){
//boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggGroupByDeleteRow(), aggFct.get(j), operation.get(j), value.get(j));
//if(result){
String pkName = stream.getLeftOrRightJoinAggGroupByDeleteRow().getName(0);
String pkType = stream.getLeftOrRightJoinAggGroupByDeleteRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getLeftOrRightJoinAggGroupByDeleteRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), leftHaving.get(j), pkName,pkValue);
}
if(stream.getLeftOrRightJoinAggGroupByUpdatedOldRow()!=null){
boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggGroupByUpdatedOldRow(), aggFct.get(j), operation.get(j), value.get(j));
if(result){
JoinAggGroupByHelper.insertStatement(json, leftHaving.get(j), stream.getLeftOrRightJoinAggGroupByUpdatedOldRow());
}else{
String pkName = stream.getLeftOrRightJoinAggGroupByUpdatedOldRow().getName(0);
String pkType = stream.getLeftOrRightJoinAggGroupByUpdatedOldRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getLeftOrRightJoinAggGroupByUpdatedOldRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), leftHaving.get(j), pkName,pkValue);
}
}
if(stream.getLeftOrRightJoinAggGroupByNewRow()!=null){
boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggGroupByNewRow(), aggFct.get(j), operation.get(j), value.get(j));
if(result){
JoinAggGroupByHelper.insertStatement(json, leftHaving.get(j), stream.getLeftOrRightJoinAggGroupByNewRow());
}else{
String pkName = stream.getLeftOrRightJoinAggGroupByNewRow().getName(0);
String pkType = stream.getLeftOrRightJoinAggGroupByNewRow().getType(0);
String pkValue = Utils.getColumnValueFromDeltaStream(stream.getLeftOrRightJoinAggGroupByNewRow(), pkName, pkType, "");
Utils.deleteEntireRowWithPK((String)json.get("keyspace"), leftHaving.get(j), pkName,pkValue);
}
}
}
}
}
private boolean checkIfAggIsNull(String aggKey, CustomizedRow deltaUpdatedRow) {
if (deltaUpdatedRow != null) {
if (deltaUpdatedRow.isNull(aggKey + "_new") && deltaUpdatedRow.isNull(aggKey + "_old")) {
return true;
}
}
return false;
}
public void cascadeDelete(JSONObject json, boolean deleteOperation) {
// boolean deleteOperation is set to false if this method is called from
// the update method
// i.e WHERE clause condition evaluates to fasle
// get position of basetable from xml list
// retrieve pk of basetable and delta from XML mapping file
int indexBaseTableName = baseTableName.indexOf((String) json
.get("table"));
String baseTablePrimaryKey = pkName.get(indexBaseTableName);
stream = new Stream();
stream.setBaseTable((String) json.get("table"));
CustomizedRow deltaDeletedRow = null;
// 1. delete from Delta Table
// 1.a If successful, retrieve entire delta Row from Delta to pass on as
// streams
if (deleteOperation) {
if (vm.deleteRowDelta(stream,json)) {
deltaDeletedRow = stream.getDeltaDeletedRow();
}
} else
deltaDeletedRow = stream.getDeltaDeletedRow();
// 2. for the delta table updated, get the depending preaggregation/agg
// tables
// preagg tables hold all column values, hence they have to be updated
int position = deltaTableName.indexOf("delta_"
+ (String) json.get("table"));
if (position != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(position);
temp += ")";
int nrPreagg = VmXmlHandler.getInstance().getDeltaPreaggMapping()
.getInt(temp + ".nrPreagg");
for (int i = 0; i < nrPreagg; i++) {
String s = temp + ".Preagg(" + Integer.toString(i) + ")";
String AggKey = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".AggKey");
String AggKeyType = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".AggKeyType");
String preaggTable = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".name");
String AggCol = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".AggCol");
String AggColType = VmXmlHandler.getInstance()
.getDeltaPreaggMapping().getString(s + ".AggColType");
// by passing the whole delta Row, we have agg key value even if
// it is not in json
vm.deleteRowPreaggAgg(stream, baseTablePrimaryKey,
json, preaggTable, AggKey, AggKeyType, AggCol,
AggColType);
}
} else {
System.out.println("No Preaggregation table for this delta table "
+ " delta_" + (String) json.get("table") + " available");
}
stream.resetPreaggregationRows();
// 3. for the delta table updated, get the depending selection tables
// tables
// check if condition is true based on selection true
// if true, delete row from selection table
int position1 = deltaTableName.indexOf("delta_"
+ (String) json.get("table"));
if (deleteOperation && position1 != -1) {
String temp4 = "mapping.unit(";
temp4 += Integer.toString(position1);
temp4 += ")";
int nrConditions = VmXmlHandler.getInstance()
.getDeltaSelectionMapping().getInt(temp4 + ".nrCond");
for (int i = 0; i < nrConditions; i++) {
String s = temp4 + ".Cond(" + Integer.toString(i) + ")";
String selecTable = VmXmlHandler.getInstance()
.getDeltaSelectionMapping().getString(s + ".name");
String nrAnd = VmXmlHandler.getInstance()
.getDeltaSelectionMapping().getString(s + ".nrAnd");
boolean eval = true;
for (int j = 0; j < Integer.parseInt(nrAnd); j++) {
String s11 = s + ".And(";
s11 += Integer.toString(j);
s11 += ")";
String operation = VmXmlHandler.getInstance()
.getDeltaSelectionMapping()
.getString(s11 + ".operation");
String value = VmXmlHandler.getInstance()
.getDeltaSelectionMapping()
.getString(s11 + ".value");
String type = VmXmlHandler.getInstance()
.getDeltaSelectionMapping()
.getString(s11 + ".type");
String selColName = VmXmlHandler.getInstance()
.getDeltaSelectionMapping()
.getString(s11 + ".selectionCol");
eval&= Utils.evaluateCondition(stream.getDeltaDeletedRow(), operation, value, type, selColName+"_new");
}
if (eval){
vm.deleteRowSelection(
(String) json.get("keyspace"), selecTable,
baseTablePrimaryKey, json);
}
}
}
// 4. reverse joins
if (deleteOperation) {
// check for rj mappings after updating delta
int cursor = 0;
// for each join
for (int j = 0; j < rjoins; j++) {
// basetables
int nrOfTables = Integer.parseInt(rj_nrDelta.get(j));
String joinTable = rj_joinTables.get(j);
// include only indices from 1 to nrOfTables
// get basetables from name of rj table
List<String> baseTables = Arrays.asList(
rj_joinTables.get(j).split("_")).subList(1,
nrOfTables + 1);
String tableName = (String) json.get("table");
String keyspace = (String) json.get("keyspace");
int column = baseTables.indexOf(tableName) + 1;
String joinKeyName = rj_joinKeys.get(cursor + column - 1);
String aggKeyType = rj_joinKeyTypes.get(j);
vm.deleteReverseJoin(stream,json, cursor, nrOfTables, joinTable,
baseTables, joinKeyName, tableName, keyspace,
aggKeyType, column);
// HERE DELETE FROM JOIN TABLES
String updatedReverseJoin = vm.getReverseJoinTableName();
position = reverseTablesNames_Join.indexOf(updatedReverseJoin);
if (position != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(position);
temp += ")";
int nrJoin = VmXmlHandler.getInstance().getRjJoinMapping()
.getInt(temp + ".nrJoin");
for (int i = 0; i < nrJoin; i++) {
String s = temp + ".join(" + Integer.toString(i) + ")";
String innerJoinTableName = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".innerJoin");
String leftJoinTableName = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".leftJoin");
String rightJoinTableName = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".rightJoin");
String leftJoinTable = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".LeftTable");
String rightJoinTable = VmXmlHandler.getInstance()
.getRjJoinMapping()
.getString(s + ".RightTable");
tableName = (String) json.get("table");
Boolean updateLeft = false;
Boolean updateRight = false;
if (tableName.equals(leftJoinTable)) {
updateLeft = true;
} else {
updateRight = true;
}
vm.deleteJoinController(stream,stream.getDeltaDeletedRow(),
innerJoinTableName, leftJoinTableName,
rightJoinTableName, json, updateLeft,
updateRight);
}
} else {
System.out
.println("No join table for this reverse join table "
+ updatedReverseJoin + " available");
}
// END OF DELETE FROM JOIN TABLES
// UPDATE join aggregation
int positionAgg = reverseTablesNames_AggJoin.indexOf(joinTable);
String joinKeyType = rj_joinKeyTypes.get(j);
if (positionAgg != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(positionAgg);
temp += ")";
Boolean updateLeft = false;
Boolean updateRight = false;
String leftJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getString(temp + ".LeftTable");
String rightJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getString(temp + ".RightTable");
tableName = (String) json.get("table");
if (tableName.equals(leftJoinTable)) {
updateLeft = true;
} else {
updateRight = true;
}
int nrLeftAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getInt(temp + ".leftAggColumns.nr");
for (int e = 0; e < nrLeftAggColumns; e++) {
String aggColName = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").type");
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").inner.name");
String leftJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").left.name");
int index = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getInt(temp + ".leftAggColumns.c(" + e + ").index");
if (updateLeft) {
vm.deleteJoinAgg_DeleteLeft_AggColLeftSide(stream,
innerJoinAggTable, leftJoinAggTable, json,
joinKeyType, joinKeyName, aggColName,
aggColType);
} else {
vm.deleteJoinAgg_DeleteRight_AggColLeftSide(stream,leftJoinAggTable,
innerJoinAggTable, json, joinKeyType,
joinKeyName, aggColName, aggColType);
}
if(!leftJoinAggTable.equals("false")){
evaluateLeftorRightJoinAggHaving(temp,"leftAggColumns", e, json,"left");
}
if(!innerJoinAggTable.equals("false")){
evaluateInnerJoinAggHaving(temp, "leftAggColumns", e, json);
}
stream.resetJoinAggRows();
}
int nrRightAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getInt(temp + ".rightAggColumns.nr");
for (int e = 0; e < nrRightAggColumns; e++) {
String aggColName = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e + ").type");
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").inner.name");
String rightJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").right.name");
int index = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getInt(temp + ".rightAggColumns.c(" + e
+ ").index");
if (updateLeft) {
vm.deleteJoinAgg_DeleteLeft_AggColRightSide(stream,rightJoinAggTable,
innerJoinAggTable, json, joinKeyType,
joinKeyName, aggColName, aggColType);
} else {
vm.deleteJoinAgg_DeleteRight_AggColRightSide(stream,
innerJoinAggTable, rightJoinAggTable, json,
joinKeyType, joinKeyName, aggColName,
aggColType);
}
if(!rightJoinAggTable.equals("false")){
evaluateLeftorRightJoinAggHaving(temp,"rightAggColumns", e, json,"right");
}
if(!innerJoinAggTable.equals("false")){
evaluateInnerJoinAggHaving(temp, "rightAggColumns", e, json);
}
stream.resetJoinAggRows();
}
}
int positionAggGroupBy = reverseTablesNames_AggJoinGroupBy
.indexOf(joinTable);
if (positionAggGroupBy != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(positionAggGroupBy);
temp += ")";
Boolean updateLeft = false;
Boolean updateRight = false;
String leftJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping()
.getString(temp + ".LeftTable");
String rightJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping()
.getString(temp + ".RightTable");
tableName = (String) json.get("table");
if (tableName.equals(leftJoinTable)) {
updateLeft = true;
} else {
updateRight = true;
}
int nrLeftAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".leftAggColumns.nr");
for (int e = 0; e < nrLeftAggColumns; e++) {
String aggColName = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").type");
int nrAgg = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".leftAggColumns.c(" + e + ").nrAgg");
for (int i = 0; i < nrAgg; i++) {
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").inner.name");
String leftJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").left.name");
String aggKey = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").Key");
aggKeyType = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").KeyType");
int index = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".leftAggColumns.c(" + e
+ ").index");
int AggKeyIndex = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").aggKeyIndex");
if (updateLeft) {
vm.deleteJoinAgg_DeleteLeft_AggColLeftSide_GroupBy(stream,
innerJoinAggTable, leftJoinAggTable,
json, aggKeyType, aggKey, aggColName,
aggColType,index);
} else {
vm.deleteJoinAgg_DeleteRight_AggColLeftSide_GroupBy(stream,
innerJoinAggTable, leftJoinAggTable,
json, aggKeyType, aggKey, aggColName,
aggColType, AggKeyIndex, index);
}
//evalute Left Having
if(!leftJoinAggTable.equals("false")){
evaluateLeftorRightJoinAggGroupByHaving(i,e,temp,json,"left");
}
//evalute Inner Having
if(!innerJoinAggTable.equals("false")){
evaluateInnerJoinAggGroupByHaving(i,e,temp,json,"leftAggColumns");
}
stream.resetJoinAggGroupByUpRows();
}
}
int nrRightAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".rightAggColumns.nr");
for (int e = 0; e < nrRightAggColumns; e++) {
String aggColName = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e + ").type");
int nrAgg = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".rightAggColumns.c(" + e
+ ").nrAgg");
for (int i = 0; i < nrAgg; i++) {
String aggKey = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").Key");
aggKeyType = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").KeyType");
int index = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".rightAggColumns.c(" + e
+ ").index");
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").inner");
String rightJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").right");
int AggKeyIndex = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").aggKeyIndex");
if (updateLeft) {
vm.deleteJoinAgg_DeleteLeft_AggColRightSide_GroupBy(stream,
innerJoinAggTable, rightJoinAggTable,
json, aggKeyType, aggKey, aggColName,
aggColType, AggKeyIndex, index);
} else {
vm.deleteJoinAgg_DeleteRight_AggColRightSide_GroupBy(stream,
innerJoinAggTable, rightJoinAggTable,
json, aggKeyType, aggKey, aggColName,
aggColType,index);
}
//evalute Left Having
if(!rightJoinAggTable.equals("false")){
evaluateLeftorRightJoinAggGroupByHaving(i,e,temp,json,"right");
}
//evalute Inner Having
if(!innerJoinAggTable.equals("false")){
evaluateInnerJoinAggGroupByHaving(i,e,temp,json,"rightAggColumns");
}
stream.resetJoinAggGroupByUpRows();
}
}
}
stream.resetReverseJoinRows();
cursor += nrOfTables;
}
stream.resetDeltaRows();
}
}
public boolean cascadeDeleteReverseJoin(JSONObject json, int j, int cursor){
// basetables
int nrOfTables = Integer.parseInt(rj_nrDelta.get(j));
String joinTable = rj_joinTables.get(j);
// include only indices from 1 to nrOfTables
// get basetables from name of rj table
List<String> baseTables = Arrays.asList(
rj_joinTables.get(j).split("_")).subList(1,
nrOfTables + 1);
String tableName = (String) json.get("table");
String keyspace = (String) json.get("keyspace");
int column = baseTables.indexOf(tableName) + 1;
String joinKeyName = rj_joinKeys.get(cursor + column - 1);
String aggKeyType = rj_joinKeyTypes.get(j);
vm.deleteReverseJoin(stream,json, cursor, nrOfTables, joinTable,
baseTables, joinKeyName, tableName, keyspace,
aggKeyType, column);
// HERE DELETE FROM JOIN TABLES
//String updatedReverseJoin = vm.getReverseJoinTableName();
int position = reverseTablesNames_Join.indexOf(joinTable);
if (position != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(position);
temp += ")";
int nrJoin = VmXmlHandler.getInstance().getRjJoinMapping()
.getInt(temp + ".nrJoin");
for (int i = 0; i < nrJoin; i++) {
String s = temp + ".join(" + Integer.toString(i) + ")";
String innerJoinTableName = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".innerJoin");
String leftJoinTableName = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".leftJoin");
String rightJoinTableName = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".rightJoin");
String leftJoinTable = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".LeftTable");
String rightJoinTable = VmXmlHandler.getInstance()
.getRjJoinMapping()
.getString(s + ".RightTable");
tableName = (String) json.get("table");
Boolean updateLeft = false;
Boolean updateRight = false;
if (tableName.equals(leftJoinTable)) {
updateLeft = true;
} else {
updateRight = true;
}
vm.deleteJoinController(stream,stream.getDeltaDeletedRow(),
innerJoinTableName, leftJoinTableName,
rightJoinTableName, json, updateLeft,
updateRight);
}
} else {
System.out
.println("No join table for this reverse join table "
+ joinTable + " available");
}
// END OF DELETE FROM JOIN TABLES
// UPDATE join aggregation
int positionAgg = reverseTablesNames_AggJoin.indexOf(joinTable);
String joinKeyType = rj_joinKeyTypes.get(j);
if (positionAgg != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(positionAgg);
temp += ")";
Boolean updateLeft = false;
Boolean updateRight = false;
String leftJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getString(temp + ".LeftTable");
String rightJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getString(temp + ".RightTable");
tableName = (String) json.get("table");
if (tableName.equals(leftJoinTable)) {
updateLeft = true;
} else {
updateRight = true;
}
int nrLeftAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getInt(temp + ".leftAggColumns.nr");
for (int e = 0; e < nrLeftAggColumns; e++) {
String aggColName = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").type");
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").inner.name");
String leftJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").left.name");
int index = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getInt(temp + ".leftAggColumns.c(" + e + ").index");
if (updateLeft) {
vm.deleteJoinAgg_DeleteLeft_AggColLeftSide(stream,
innerJoinAggTable, leftJoinAggTable, json,
joinKeyType, joinKeyName, aggColName,
aggColType);
} else {
vm.deleteJoinAgg_DeleteRight_AggColLeftSide(stream,leftJoinAggTable,
innerJoinAggTable, json, joinKeyType,
joinKeyName, aggColName, aggColType);
}
if(!leftJoinAggTable.equals("false")){
evaluateLeftorRightJoinAggHaving(temp,"leftAggColumns", e, json,"left");
}
if(!innerJoinAggTable.equals("false")){
evaluateInnerJoinAggHaving(temp, "leftAggColumns", e, json);
}
stream.resetJoinAggRows();
}
int nrRightAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getInt(temp + ".rightAggColumns.nr");
for (int e = 0; e < nrRightAggColumns; e++) {
String aggColName = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e + ").type");
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").inner.name");
String rightJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").right.name");
int index = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getInt(temp + ".rightAggColumns.c(" + e
+ ").index");
if (updateLeft) {
vm.deleteJoinAgg_DeleteLeft_AggColRightSide(stream,rightJoinAggTable,
innerJoinAggTable, json, joinKeyType,
joinKeyName, aggColName, aggColType);
} else {
vm.deleteJoinAgg_DeleteRight_AggColRightSide(stream,
innerJoinAggTable, rightJoinAggTable, json,
joinKeyType, joinKeyName, aggColName,
aggColType);
}
if(!rightJoinAggTable.equals("false")){
evaluateLeftorRightJoinAggHaving(temp,"rightAggColumns", e, json,"right");
}
if(!innerJoinAggTable.equals("false")){
evaluateInnerJoinAggHaving(temp, "rightAggColumns", e, json);
}
stream.resetJoinAggRows();
}
}
int positionAggGroupBy = reverseTablesNames_AggJoinGroupBy
.indexOf(joinTable);
if (positionAggGroupBy != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(positionAggGroupBy);
temp += ")";
Boolean updateLeft = false;
Boolean updateRight = false;
String leftJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping()
.getString(temp + ".LeftTable");
String rightJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping()
.getString(temp + ".RightTable");
tableName = (String) json.get("table");
if (tableName.equals(leftJoinTable)) {
updateLeft = true;
} else {
updateRight = true;
}
int nrLeftAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".leftAggColumns.nr");
for (int e = 0; e < nrLeftAggColumns; e++) {
String aggColName = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").type");
int nrAgg = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".leftAggColumns.c(" + e + ").nrAgg");
for (int i = 0; i < nrAgg; i++) {
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").inner.name");
String leftJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").left.name");
String aggKey = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").Key");
aggKeyType = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").KeyType");
int index = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".leftAggColumns.c(" + e
+ ").index");
int AggKeyIndex = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".leftAggColumns.c(" + e
+ ").Agg(" + i + ").aggKeyIndex");
if (updateLeft) {
vm.deleteJoinAgg_DeleteLeft_AggColLeftSide_GroupBy(stream,
innerJoinAggTable, leftJoinAggTable,
json, aggKeyType, aggKey, aggColName,
aggColType,index);
} else {
vm.deleteJoinAgg_DeleteRight_AggColLeftSide_GroupBy(stream,
innerJoinAggTable, leftJoinAggTable,
json, aggKeyType, aggKey, aggColName,
aggColType, AggKeyIndex, index);
}
//evalute Left Having
if(!leftJoinAggTable.equals("false")){
evaluateLeftorRightJoinAggGroupByHaving(i,e,temp,json,"left");
}
//evalute Inner Having
if(!innerJoinAggTable.equals("false")){
evaluateInnerJoinAggGroupByHaving(i,e,temp,json,"leftAggColumns");
}
stream.resetJoinAggGroupByUpRows();
}
}
int nrRightAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".rightAggColumns.nr");
for (int e = 0; e < nrRightAggColumns; e++) {
String aggColName = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e + ").type");
int nrAgg = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".rightAggColumns.c(" + e
+ ").nrAgg");
for (int i = 0; i < nrAgg; i++) {
String aggKey = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").Key");
aggKeyType = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").KeyType");
int index = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".rightAggColumns.c(" + e
+ ").index");
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").inner");
String rightJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").right");
int AggKeyIndex = VmXmlHandler
.getInstance()
.getRJAggJoinGroupByMapping()
.getInt(temp + ".rightAggColumns.c(" + e
+ ").Agg(" + i + ").aggKeyIndex");
if (updateLeft) {
vm.deleteJoinAgg_DeleteLeft_AggColRightSide_GroupBy(stream,
innerJoinAggTable, rightJoinAggTable,
json, aggKeyType, aggKey, aggColName,
aggColType, AggKeyIndex, index);
} else {
vm.deleteJoinAgg_DeleteRight_AggColRightSide_GroupBy(stream,
innerJoinAggTable, rightJoinAggTable,
json, aggKeyType, aggKey, aggColName,
aggColType,index);
}
//evalute Left Having
if(!rightJoinAggTable.equals("false")){
evaluateLeftorRightJoinAggGroupByHaving(i,e,temp,json,"right");
}
//evalute Inner Having
if(!innerJoinAggTable.equals("false")){
evaluateInnerJoinAggGroupByHaving(i,e,temp,json,"rightAggColumns");
}
stream.resetJoinAggGroupByUpRows();
}
}
}
stream.resetReverseJoinRows();
return true;
}
public void propagatePreaggUpdate(JSONObject json) {
String preaggTable = json.get("table").toString();
// 2.1 update preaggregations with having clause
// check if preagg has some having clauses or not
int position1 = preaggTableNames.indexOf(preaggTable);
if (position1 != -1) {
String temp4 = "mapping.unit(";
temp4 += Integer.toString(position1);
temp4 += ")";
int nrConditions = VmXmlHandler.getInstance()
.getHavingPreAggMapping().getInt(temp4 + ".nrCond");
for (int m = 0; m < nrConditions; m++) {
String s1 = temp4 + ".Cond(" + Integer.toString(m)
+ ")";
String havingTable = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s1 + ".name");
String nrAnd = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s1 + ".nrAnd");
boolean eval1 = true;
for (int n = 0; n < Integer.parseInt(nrAnd); n++) {
String s11 = s1 + ".And(";
s11 += Integer.toString(n);
s11 += ")";
String aggFct = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s11 + ".aggFct");
String operation = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s11 + ".operation");
String value = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s11 + ".value");
CustomizedRow PreagRow = stream.getUpdatedPreaggRow();
eval1&= Utils.evalueJoinAggConditions(PreagRow, aggFct, operation, value);
}
CustomizedRow PreagRow = stream.getUpdatedPreaggRow();
// if matching now & not matching before
// if condition matching now & matched before
if (eval1) {
vm.updateHaving(stream.getDeltaUpdatedRow(),
json,havingTable, PreagRow);
// if not matching now
} else if (!eval1) {
vm.deleteRowHaving((String) json.get("keyspace"),
havingTable, PreagRow);
// if not matching now & not before, ignore
}
CustomizedRow deletedRow = stream.getUpdatedPreaggRowDeleted();
if (deletedRow != null) {
vm.deleteRowHaving((String) json.get("keyspace"),
havingTable, deletedRow);
}
}
} else {
System.out
.println("No Having table for this joinpreaggregation Table "
+ preaggTable + " available");
}
}
public boolean propagateRJ(JSONObject json) {
JSONObject data = (JSONObject) json.get("data");
String bufferString = data.get("stream").toString();
stream = Serialize.deserializeStream(bufferString);
System.out.println("++++++++ "+stream.getBaseTable());
String tableName = stream.getBaseTable();
int indexBaseTableName = baseTableName.indexOf(stream.getBaseTable());
String baseTablePrimaryKey = pkName.get(indexBaseTableName);
String baseTablePrimaryKeyType = pkType.get(indexBaseTableName);
// String tableName = (String) json.get("table");
String keyspace = (String) json.get("keyspace");
String joinTable = json.get("table").toString();
int indexOfRJ = rj_joinTables.indexOf(joinTable);
// basetables
int nrOfTables = Integer.parseInt(rj_nrDelta.get(indexOfRJ));
List<String> baseTables = Arrays.asList(joinTable.split("_")).subList(
1, nrOfTables + 1);
int column = baseTables.indexOf(tableName) + 1;
String joinKeyName = rj_joinKeys.get(indexOfRJ * 2 + column - 1);
String joinKeyType = rj_joinKeyTypes.get(indexOfRJ);
int position = reverseTablesNames_Join.indexOf(joinTable);
if (position != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(position);
temp += ")";
int nrJoin = VmXmlHandler.getInstance().getRjJoinMapping()
.getInt(temp + ".nrJoin");
for (int i = 0; i < nrJoin; i++) {
String s = temp + ".join(" + Integer.toString(i) + ")";
String innerJoinTableName = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".innerJoin");
String leftJoinTableName = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".leftJoin");
String rightJoinTableName = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".rightJoin");
String leftJoinTable = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".LeftTable");
String rightJoinTable = VmXmlHandler.getInstance()
.getRjJoinMapping().getString(s + ".RightTable");
Boolean updateLeft = false;
Boolean updateRight = false;
if (tableName.equals(leftJoinTable)) {
updateLeft = true;
} else {
updateRight = true;
}
vm.updateJoinController(stream, innerJoinTableName,
leftJoinTableName, rightJoinTableName, json,
updateLeft, updateRight, joinKeyType, joinKeyName,
baseTablePrimaryKey);
}
} else {
System.out.println("No join table for this reverse join table "
+ joinTable + " available");
}
// UPDATE join agg
int positionAgg = reverseTablesNames_AggJoin.indexOf(joinTable);
if (positionAgg != -1) {
String temp = "mapping.unit(";
temp += Integer.toString(positionAgg);
temp += ")";
Boolean updateLeft = false;
Boolean updateRight = false;
String leftJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getString(temp + ".LeftTable");
String rightJoinTable = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getString(temp + ".RightTable");
if (tableName.equals(leftJoinTable)) {
updateLeft = true;
} else {
updateRight = true;
}
int nrLeftAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getInt(temp + ".leftAggColumns.nr");
for (int e = 0; e < nrLeftAggColumns; e++) {
String aggColName = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getString(temp + ".leftAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getString(temp + ".leftAggColumns.c(" + e + ").type");
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e
+ ").inner.name");
String leftJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".leftAggColumns.c(" + e + ").left.name");
int index = VmXmlHandler.getInstance().getRJAggJoinMapping()
.getInt(temp + ".leftAggColumns.c(" + e + ").index");
if (updateLeft) {
vm.updateJoinAgg_UpdateLeft_AggColLeftSide(stream,
innerJoinAggTable, leftJoinAggTable, json,
joinKeyType, joinKeyName, aggColName, aggColType);
} else {
vm.updateJoinAgg_UpdateRight_AggColLeftSide(stream,
innerJoinAggTable, leftJoinAggTable, json,
joinKeyType, joinKeyName, aggColName, aggColType,
index);
}
if (!leftJoinAggTable.equals("false")) {
evaluateLeftorRightJoinAggHaving(temp, "leftAggColumns", e,
json, "left");
}
if (!innerJoinAggTable.equals("false")) {
evaluateInnerJoinAggHaving(temp, "leftAggColumns", e, json);
}
stream.resetJoinAggRows();
}
int nrRightAggColumns = VmXmlHandler.getInstance()
.getRJAggJoinMapping().getInt(temp + ".rightAggColumns.nr");
for (int e = 0; e < nrRightAggColumns; e++) {
String aggColName = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getString(temp + ".rightAggColumns.c(" + e + ").name");
String aggColType = VmXmlHandler.getInstance()
.getRJAggJoinMapping()
.getString(temp + ".rightAggColumns.c(" + e + ").type");
String innerJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").inner.name");
String rightJoinAggTable = VmXmlHandler
.getInstance()
.getRJAggJoinMapping()
.getString(
temp + ".rightAggColumns.c(" + e
+ ").right.name");
int index = VmXmlHandler.getInstance().getRJAggJoinMapping()
.getInt(temp + ".rightAggColumns.c(" + e + ").index");
if (updateLeft) {
vm.updateJoinAgg_UpdateLeft_AggColRightSide(stream,
innerJoinAggTable, rightJoinAggTable, json,
joinKeyType, joinKeyName, aggColName, aggColType,
index);
} else {
vm.updateJoinAgg_UpdateRight_AggColRightSide(stream,
innerJoinAggTable, rightJoinAggTable, json,
joinKeyType, joinKeyName, aggColName, aggColType);
}
if (!rightJoinAggTable.equals("false")) {
evaluateLeftorRightJoinAggHaving(temp, "rightAggColumns",
e, json, "right");
}
if (!innerJoinAggTable.equals("false")) {
evaluateInnerJoinAggHaving(temp, "rightAggColumns", e, json);
}
stream.resetJoinAggRows();
}
}
return true;
}
public void decidePreagg(JSONObject json) {
JSONObject data = (JSONObject) json.get("data");
String bufferString = data.get("stream").toString();
stream = Serialize.deserializeStream(bufferString);
JSONObject deltaJSON = stream.getDeltaJSON();
if(!stream.isDeleteOperation()){
propagatePreaggUpdate(deltaJSON);
}else{
propagatePreaggDelete(deltaJSON);
}
}
private void propagatePreaggDelete(JSONObject json) {
// update the corresponding preagg wih having clause
String preaggTable = json.get("table").toString();
int position = preaggTableNames.indexOf(preaggTable);
if (position != -1) {
String temp4 = "mapping.unit(";
temp4 += Integer.toString(position);
temp4 += ")";
int nrConditions = VmXmlHandler.getInstance()
.getHavingPreAggMapping().getInt(temp4 + ".nrCond");
for (int r = 0; r < nrConditions; r++) {
String s1 = temp4 + ".Cond(" + Integer.toString(r)
+ ")";
String havingTable = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s1 + ".name");
String nrAnd = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s1 + ".nrAnd");
boolean eval1 = true;
for (int j = 0; j < Integer.parseInt(nrAnd); j++) {
String s11 = s1 + ".And(";
s11 += Integer.toString(j);
s11 += ")";
String aggFct = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s11 + ".aggFct");
String operation = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s11 + ".operation");
String value = VmXmlHandler.getInstance()
.getHavingPreAggMapping()
.getString(s11 + ".value");
eval1&= Utils.evalueJoinAggConditions(stream.getDeletePreaggRow(), aggFct, operation, value);
}
CustomizedRow DeletedPreagRowMapSize1 = stream.getDeletePreaggRowDeleted();
if (stream.getDeletePreaggRow() != null) {
if (eval1) {
vm.updateHaving(stream.getDeltaDeletedRow(),
json,havingTable, stream.getDeletePreaggRow());
} else {
vm.deleteRowHaving((String) json.get("keyspace"),
havingTable, stream.getDeletePreaggRow());
}
} else if (DeletedPreagRowMapSize1 != null) {
vm.deleteRowHaving((String) json.get("keyspace"),
havingTable, DeletedPreagRowMapSize1);
}
}
}
}
}
|
package de.uka.ipd.sdq.beagle.core.timeout;
import org.apache.commons.lang3.Validate;
import java.util.Arrays;
/**
* Implements an adaptive timeout. This means that later calls to {@link #isReached()}
* will return {@code false} if the previous calls took a long time, too.
*
* @author Christoph Michelbach
*/
public class AdaptiveTimeout extends Timeout {
/**
* How much additional time is always tolerated. Stated in milliseconds.
*/
private static final long ADDITIONAL_TIME_TOLEARANCE = 5 * 60 * 1000;
/**
* How far the adaptive timeout looks back to the past (calls to {@link #isReached()})
* before forgetting about events. This is also how often {@link #isReached()} will
* return {@code true} for sure because this much data has to be collected before
* enabling the timeout to make a sensible decision.
*/
private static final int RANGE = 10;
/**
* Whether the timeout has been reached in the past. {@code true} if it did;
* {@code false} otherwise.
*/
private boolean reachedTimeoutInThePast;
/**
* When {@link #isReached()} has been called the last time. Stated in milliseconds.
*/
private long timeOfPreviousCall;
/**
* How often {@link #isReached()} has been called in the past.
*/
private int numberOfPreviousCalls;
/**
* Contains the telling times of the previous calls to {@link #isReached()}.
*/
private long[] previousTellingTimes = new long[RANGE];
/**
* The current regression line.
*/
private RegressionLine regressionLine;
@Override
public void init() {
Validate.isTrue(!this.initilised);
super.init();
this.timeOfPreviousCall = System.currentTimeMillis();
}
@Override
public void reportOneStepProgress() {
Validate.isTrue(this.initilised);
if (this.reachedTimeoutInThePast) {
return;
}
final long currentTime = System.currentTimeMillis();
this.regressionLine = new RegressionLine(this.previousTellingTimes);
this.regressionLine.init();
final long predictedValue = (long) this.regressionLine.getValueFor(RANGE);
final long maximallyTolerableTime = predictedValue + ADDITIONAL_TIME_TOLEARANCE;
final boolean reachedTimeout = (currentTime - this.timeOfPreviousCall) > maximallyTolerableTime;
this.reachedTimeoutInThePast = reachedTimeout;
// Prepare everything for the next call to this method.
this.addTellingTimeToPreviousTellingTimes(currentTime - this.timeOfPreviousCall);
this.timeOfPreviousCall = currentTime;
this.numberOfPreviousCalls++;
}
@Override
public boolean isReached() {
Validate.isTrue(this.initilised);
if (this.reachedTimeoutInThePast) {
return true;
}
final long currentTime = System.currentTimeMillis();
final long predictedValue = (long) this.regressionLine.getValueFor(RANGE);
final long maximallyTolerableTime = predictedValue + ADDITIONAL_TIME_TOLEARANCE;
final boolean returnValue = (currentTime - this.timeOfPreviousCall) > maximallyTolerableTime;
this.reachedTimeoutInThePast = returnValue;
return returnValue;
}
/**
* Shifts the contents of {@link #previousTimes} one down and adds {@code} time to the
* highest element.
*
*
* @param time The telling time to add.
*/
private void addTellingTimeToPreviousTellingTimes(final long time) {
for (int i = 1; i < RANGE; i++) {
this.previousTellingTimes[i - 1] = this.previousTellingTimes[i];
}
this.previousTellingTimes[RANGE - 1] = time;
}
/**
* A regression line with data points of equal distance on the x-axis.
*
* @author Christoph Michelbach
*/
private class RegressionLine {
/**
* The data to determine the regression line for.
*/
private long[] data;
/**
* Whether the regression line has been initialised since its data has been
* updated the last time.
*/
private boolean initialised;
/**
* The offset of the regression line.
*/
private double offset;
/**
* The slope of the regression line.
*/
private double slope;
/**
* Constructs a new {@link RegressionLine} object.
*
* @param data The data to determine the regression line for.
*/
RegressionLine(final long[] data) {
this.data = data.clone();
this.initialised = false;
}
/**
* Calculates the offset and slope of the regression line.
*/
public void init() {
final double averageTime = Arrays.stream(this.data).average().getAsDouble();
double sum1 = 0;
for (int i = 0; i < this.data.length; i++) {
final long time = this.data[i];
sum1 += (i - this.data.length / 2d) * (time - averageTime);
}
/*
* If you have equal distances between the x-coordinates of data and start
* counting with 0, the divisor sum of the slope of the regression line can be
* simplified to this. Go grab a pencil and a peace of paper and try it
* yourself. :)
*/
final double sum2 = 1 / 12d * this.data.length * (-1 + Math.pow(this.data.length, 2));
this.slope = sum1 / sum2;
this.offset = averageTime - this.slope * (1 / 2d * (this.data.length - 1) * this.data.length);
this.initialised = true;
}
/**
* Returns the offset of the regression line.
*
* @return The offset.
*/
public double getOffset() {
Validate.validState(this.initialised);
return this.offset;
}
/**
* Returns the slope of the regression line.
*
* @return The slope.
*/
public double getSlope() {
Validate.validState(this.initialised);
return this.slope;
}
/**
* Returns the function value for {@code xValue}.
*
* @param xValue The value on the x-axis.
* @return The function value for {@code xValue}.
*/
public double getValueFor(final double xValue) {
Validate.validState(this.initialised);
return this.offset + xValue * this.slope;
}
}
}
|
// $Id: MisoUtil.java,v 1.20 2003/04/18 22:59:04 mdb Exp $
package com.threerings.miso.util;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import com.samskivert.swing.SmartPolygon;
import com.threerings.media.sprite.Sprite;
import com.threerings.media.util.MathUtil;
import com.threerings.util.DirectionCodes;
import com.threerings.util.DirectionUtil;
import com.threerings.miso.Log;
/**
* Miscellaneous isometric-display-related utility routines.
*/
public class MisoUtil
implements DirectionCodes
{
/**
* Given two points in screen pixel coordinates, return the
* compass direction that point B lies in from point A from an
* isometric perspective.
*
* @param ax the x-position of point A.
* @param ay the y-position of point A.
* @param bx the x-position of point B.
* @param by the y-position of point B.
*
* @return the direction specified as one of the <code>Sprite</code>
* class's direction constants.
*/
public static int getDirection (
MisoSceneMetrics metrics, int ax, int ay, int bx, int by)
{
Point afpos = new Point(), bfpos = new Point();
// convert screen coordinates to full coordinates to get both
// tile coordinates and fine coordinates
screenToFull(metrics, ax, ay, afpos);
screenToFull(metrics, bx, by, bfpos);
// pull out the tile coordinates for each point
int tax = afpos.x / FULL_TILE_FACTOR;
int tay = afpos.y / FULL_TILE_FACTOR;
int tbx = bfpos.x / FULL_TILE_FACTOR;
int tby = bfpos.y / FULL_TILE_FACTOR;
// compare tile coordinates to determine direction
int dir = getIsoDirection(tax, tay, tbx, tby);
if (dir != DirectionCodes.NONE) {
return dir;
}
// destination point is in the same tile as the
// origination point, so consider fine coordinates
// pull out the fine coordinates for each point
int fax = afpos.x - (tax * FULL_TILE_FACTOR);
int fay = afpos.y - (tay * FULL_TILE_FACTOR);
int fbx = bfpos.x - (tbx * FULL_TILE_FACTOR);
int fby = bfpos.y - (tby * FULL_TILE_FACTOR);
// compare fine coordinates to determine direction
dir = getIsoDirection(fax, fay, fbx, fby);
// arbitrarily return southwest if fine coords were also equivalent
return (dir == -1) ? SOUTHWEST : dir;
}
/**
* Given two points in an isometric coordinate system (in which {@link
* #NORTH} is in the direction of the negative x-axis and {@link
* #WEST} in the direction of the negative y-axis), return the compass
* direction that point B lies in from point A. This method is used
* to determine direction for both tile coordinates and fine
* coordinates within a tile, since the coordinate systems are the
* same.
*
* @param ax the x-position of point A.
* @param ay the y-position of point A.
* @param bx the x-position of point B.
* @param by the y-position of point B.
*
* @return the direction specified as one of the <code>Sprite</code>
* class's direction constants, or <code>DirectionCodes.NONE</code> if
* point B is equivalent to point A.
*/
public static int getIsoDirection (int ax, int ay, int bx, int by)
{
// head off a div by 0 at the pass..
if (bx == ax) {
if (by == ay) {
return DirectionCodes.NONE;
}
return (by < ay) ? EAST : WEST;
}
// figure direction base on the slope of the line
float slope = ((float) (ay - by)) / ((float) Math.abs(ax - bx));
if (slope > 2f) {
return EAST;
}
if (slope > .5f) {
return (bx < ax) ? NORTHEAST : SOUTHEAST;
}
if (slope > -.5f) {
return (bx < ax) ? NORTH : SOUTH;
}
if (slope > -2f) {
return (bx < ax) ? NORTHWEST : SOUTHWEST;
}
return WEST;
}
/**
* Given two points in screen coordinates, return the isometrically
* projected compass direction that point B lies in from point A.
*
* @param ax the x-position of point A.
* @param ay the y-position of point A.
* @param bx the x-position of point B.
* @param by the y-position of point B.
*
* @return the direction specified as one of the <code>Sprite</code>
* class's direction constants, or <code>DirectionCodes.NONE</code> if
* point B is equivalent to point A.
*/
public static int getProjectedIsoDirection (int ax, int ay, int bx, int by)
{
return toIsoDirection(DirectionUtil.getDirection(ax, ay, bx, by));
}
/**
* Converts a non-isometric orientation (where north points toward the
* top of the screen) to an isometric orientation where north points
* toward the upper-left corner of the screen.
*/
public static int toIsoDirection (int dir)
{
if (dir != DirectionCodes.NONE) {
// rotate the direction clockwise (ie. change SOUTHEAST to
// SOUTH)
dir = DirectionUtil.rotateCW(dir, 2);
}
return dir;
}
/**
* Returns the tile coordinate of the given full coordinate.
*/
public static int fullToTile (int val)
{
return (val / FULL_TILE_FACTOR);
}
/**
* Returns the fine coordinate of the given full coordinate.
*/
public static int fullToFine (int val)
{
return (val - ((val / FULL_TILE_FACTOR) * FULL_TILE_FACTOR));
}
/**
* Convert the given screen-based pixel coordinates to their
* corresponding tile-based coordinates. Converted coordinates
* are placed in the given point object.
*
* @param sx the screen x-position pixel coordinate.
* @param sy the screen y-position pixel coordinate.
* @param tpos the point object to place coordinates in.
*
* @return the point instance supplied via the <code>tpos</code>
* parameter.
*/
public static Point screenToTile (
MisoSceneMetrics metrics, int sx, int sy, Point tpos)
{
// determine the upper-left of the quadrant that contains our
// point
int zx = (int)Math.floor((float)(sx - metrics.origin.x) /
metrics.tilewid);
int zy = (int)Math.floor((float)(sy - metrics.origin.y) /
metrics.tilehei);
// these are the screen coordinates of the tile's top
int ox = (zx * metrics.tilewid + metrics.origin.x),
oy = (zy * metrics.tilehei + metrics.origin.y);
// these are the tile coordinates
tpos.x = zy + zx; tpos.y = zy - zx;
// now determine which of the four tiles our point occupies
int dx = sx - ox, dy = sy - oy;
if (Math.round(metrics.slopeY * dx + metrics.tilehei) <= dy) {
tpos.x += 1;
}
if (Math.round(metrics.slopeX * dx) > dy) {
tpos.y -= 1;
}
// Log.info("Converted [sx=" + sx + ", sy=" + sy +
// ", zx=" + zx + ", zy=" + zy +
// ", ox=" + ox + ", oy=" + oy +
// ", dx=" + dx + ", dy=" + dy +
// ", tpos.x=" + tpos.x + ", tpos.y=" + tpos.y + "].");
return tpos;
}
/**
* Convert the given tile-based coordinates to their corresponding
* screen-based pixel coordinates. The screen coordinate for a tile is
* the upper-left coordinate of the rectangle that bounds the tile
* polygon. Converted coordinates are placed in the given point
* object.
*
* @param x the tile x-position coordinate.
* @param y the tile y-position coordinate.
* @param spos the point object to place coordinates in.
*
* @return the point instance supplied via the <code>spos</code>
* parameter.
*/
public static Point tileToScreen (
MisoSceneMetrics metrics, int x, int y, Point spos)
{
spos.x = metrics.origin.x + ((x - y - 1) * metrics.tilehwid);
spos.y = metrics.origin.y + ((x + y) * metrics.tilehhei);
return spos;
}
/**
* Convert the given fine coordinates to pixel coordinates within
* the containing tile. Converted coordinates are placed in the
* given point object.
*
* @param x the x-position fine coordinate.
* @param y the y-position fine coordinate.
* @param ppos the point object to place coordinates in.
*/
public static void fineToPixel (
MisoSceneMetrics metrics, int x, int y, Point ppos)
{
ppos.x = metrics.tilehwid + ((x - y) * metrics.finehwid);
ppos.y = (x + y) * metrics.finehhei;
}
/**
* Convert the given pixel coordinates, whose origin is at the
* top-left of a tile's containing rectangle, to fine coordinates
* within that tile. Converted coordinates are placed in the
* given point object.
*
* @param x the x-position pixel coordinate.
* @param y the y-position pixel coordinate.
* @param fpos the point object to place coordinates in.
*/
public static void pixelToFine (
MisoSceneMetrics metrics, int x, int y, Point fpos)
{
// calculate line parallel to the y-axis (from the given
// x/y-pos to the x-axis)
float bY = y - (metrics.fineSlopeY * x);
// determine intersection of x- and y-axis lines
int crossx = (int)((bY - metrics.fineBX) /
(metrics.fineSlopeX - metrics.fineSlopeY));
int crossy = (int)((metrics.fineSlopeY * crossx) + bY);
// TODO: final position should check distance between our
// position and the surrounding fine coords and return the
// actual closest fine coord, rather than just dividing.
// determine distance along the x-axis
float xdist = MathUtil.distance(metrics.tilehwid, 0, crossx, crossy);
fpos.x = (int)(xdist / metrics.finelen);
// determine distance along the y-axis
float ydist = MathUtil.distance(x, y, crossx, crossy);
fpos.y = (int)(ydist / metrics.finelen);
}
/**
* Convert the given screen-based pixel coordinates to full
* scene-based coordinates that include both the tile coordinates
* and the fine coordinates in each dimension. Converted
* coordinates are placed in the given point object.
*
* @param sx the screen x-position pixel coordinate.
* @param sy the screen y-position pixel coordinate.
* @param fpos the point object to place coordinates in.
*
* @return the point passed in to receive the coordinates.
*/
public static Point screenToFull (
MisoSceneMetrics metrics, int sx, int sy, Point fpos)
{
// get the tile coordinates
Point tpos = new Point();
screenToTile(metrics, sx, sy, tpos);
// get the screen coordinates for the containing tile
Point spos = tileToScreen(metrics, tpos.x, tpos.y, new Point());
// get the fine coordinates within the containing tile
pixelToFine(metrics, sx - spos.x, sy - spos.y, fpos);
// toss in the tile coordinates for good measure
fpos.x += (tpos.x * FULL_TILE_FACTOR);
fpos.y += (tpos.y * FULL_TILE_FACTOR);
return fpos;
}
/**
* Convert the given full coordinates to screen-based pixel
* coordinates. Converted coordinates are placed in the given
* point object.
*
* @param x the x-position full coordinate.
* @param y the y-position full coordinate.
* @param spos the point object to place coordinates in.
*
* @return the point passed in to receive the coordinates.
*/
public static Point fullToScreen (
MisoSceneMetrics metrics, int x, int y, Point spos)
{
// get the tile screen position
int tx = x / FULL_TILE_FACTOR, ty = y / FULL_TILE_FACTOR;
Point tspos = tileToScreen(metrics, tx, ty, new Point());
// get the pixel position of the fine coords within the tile
Point ppos = new Point();
int fx = x - (tx * FULL_TILE_FACTOR), fy = y - (ty * FULL_TILE_FACTOR);
fineToPixel(metrics, fx, fy, ppos);
// final position is tile position offset by fine position
spos.x = tspos.x + ppos.x;
spos.y = tspos.y + ppos.y;
return spos;
}
/**
* Converts the given fine coordinate to a full coordinate (a tile
* coordinate plus a fine coordinate remainder). The fine coordinate
* is assumed to be relative to tile <code>(0, 0)</code>.
*/
public static int fineToFull (MisoSceneMetrics metrics, int fine)
{
return toFull(fine / metrics.finegran, fine % metrics.finegran);
}
/**
* Composes the supplied tile coordinate and fine coordinate offset
* into a full coordinate.
*/
public static int toFull (int tile, int fine)
{
return tile * FULL_TILE_FACTOR + fine;
}
/**
* Return a polygon framing the specified tile.
*
* @param x the tile x-position coordinate.
* @param y the tile y-position coordinate.
*/
public static Polygon getTilePolygon (
MisoSceneMetrics metrics, int x, int y)
{
return getFootprintPolygon(metrics, x, y, 1, 1);
}
/**
* Return a screen-coordinates polygon framing the two specified
* tile-coordinate points.
*/
public static Polygon getMultiTilePolygon (MisoSceneMetrics metrics,
Point sp1, Point sp2)
{
int x = Math.min(sp1.x, sp2.x), y = Math.min(sp1.y, sp2.y);
int width = Math.abs(sp1.x-sp2.x)+1, height = Math.abs(sp1.y-sp2.y)+1;
return getFootprintPolygon(metrics, x, y, width, height);
}
/**
* Returns a polygon framing the specified scene footprint.
*
* @param x the x tile coordinate of the "upper-left" of the footprint.
* @param y the y tile coordinate of the "upper-left" of the footprint.
* @param width the width in tiles of the footprint.
* @param height the height in tiles of the footprint.
*/
public static Polygon getFootprintPolygon (
MisoSceneMetrics metrics, int x, int y, int width, int height)
{
SmartPolygon footprint = new SmartPolygon();
Point tpos = MisoUtil.tileToScreen(metrics, x, y, new Point());
// start with top-center point
int rx = tpos.x + metrics.tilehwid, ry = tpos.y;
footprint.addPoint(rx, ry);
// right point
rx += width * metrics.tilehwid;
ry += width * metrics.tilehhei;
footprint.addPoint(rx, ry);
// bottom-center point
rx -= height * metrics.tilehwid;
ry += height * metrics.tilehhei;
footprint.addPoint(rx, ry);
// left point
rx -= width * metrics.tilehwid;
ry -= width * metrics.tilehhei;
footprint.addPoint(rx, ry);
// end with top-center point
rx += height * metrics.tilehwid;
ry -= height * metrics.tilehhei;
footprint.addPoint(rx, ry);
return footprint;
}
/**
* Adds the supplied fine coordinates to the supplied tile coordinates
* to compute full coordinates.
*
* @retun the point object supplied as <code>full</code>.
*/
public static Point tilePlusFineToFull (MisoSceneMetrics metrics,
int tileX, int tileY,
int fineX, int fineY,
Point full)
{
int dtx = fineX / metrics.finegran;
int dty = fineY / metrics.finegran;
int fx = fineX - dtx * metrics.finegran;
if (fx < 0) {
dtx
fx += metrics.finegran;
}
int fy = fineY - dty * metrics.finegran;
if (fy < 0) {
dty
fy += metrics.finegran;
}
full.x = toFull(tileX + dtx, fx);
full.y = toFull(tileY + dty, fy);
return full;
}
/**
* Turns x and y scene coordinates into an integer key.
*
* @return the hash key, given x and y.
*/
public static final int coordsToKey (int x, int y)
{
return ((y << 16) & (0xFFFF0000)) | (x & 0xFFFF);
}
/**
* Gets the x coordinate from an integer hash key.
*
* @return the x coordinate.
*/
public static final int xCoordFromKey (int key)
{
return (key & 0xFFFF);
}
/**
* Gets the y coordinate from an integer hash key.
*
* @return the y coordinate from the hash key.
*/
public static final int yCoordFromKey (int key)
{
return ((key >> 16) & 0xFFFF);
}
/** Multiplication factor to embed tile coords in full coords. */
protected static final int FULL_TILE_FACTOR = 100;
}
|
package fr.nicolaspomepuy.discreetapprate;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.lang.reflect.Field;
import java.util.Date;
public class Utils {
private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height";
private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width";
private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar";
/**
* Convert a size in dp to a size in pixels
*
* @param context the {@link android.content.Context} to be used
* @param dpi size in dp
* @return the size in pixels
*/
public static int convertDPItoPixels(Context context, int dpi) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpi * scale + 0.5f);
}
public static boolean isPowerOfTwo(int x) {
return (x & (x - 1)) == 0;
}
public static Date installTimeFromPackageManager(
PackageManager packageManager, String packageName) {
// API level 9 and above have the "firstInstallTime" field.
// Check for it with reflection and return if present.
try {
PackageInfo info = packageManager.getPackageInfo(packageName, 0);
Field field = PackageInfo.class.getField("firstInstallTime");
long timestamp = field.getLong(info);
return new Date(timestamp);
} catch (PackageManager.NameNotFoundException e) {
return null; // package not found
} catch (IllegalAccessException e) {
} catch (NoSuchFieldException e) {
} catch (IllegalArgumentException e) {
} catch (SecurityException e) {
}
// field wasn't found
return null;
}
public static boolean isGooglePlayInstalled(Context context) {
PackageManager pm = context.getPackageManager();
boolean app_installed = false;
try {
PackageInfo info = pm.getPackageInfo("com.android.vending", PackageManager.GET_ACTIVITIES);
String label = (String) info.applicationInfo.loadLabel(pm);
app_installed = (label != null && !label.equals("Market"));
} catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
public static boolean isOnline(Context context) {
int res = context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE);
if (res == PackageManager.PERMISSION_GRANTED) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
return true;
}
@SuppressLint("NewApi")
public static int getSoftbuttonsbarHeight(Activity activity) {
if (getInternalBoolean(activity.getResources(), SHOW_NAV_BAR_RES_NAME)) {
return 0;
}
return getInternalDimensionSize(activity.getResources(), NAV_BAR_HEIGHT_RES_NAME);
}
@SuppressLint("NewApi")
public static int getSoftbuttonsbarWidth(Activity activity) {
if (getInternalBoolean(activity.getResources(), SHOW_NAV_BAR_RES_NAME)) {
return 0;
}
return getInternalDimensionSize(activity.getResources(), NAV_BAR_WIDTH_RES_NAME);
}
@SuppressLint("NewApi")
public static int getStatusBarHeight(Activity activity) {
return getInternalDimensionSize(activity.getResources(), STATUS_BAR_HEIGHT_RES_NAME);
}
public static int getInternalDimensionSize(Resources res, String key) {
int result = 0;
int resourceId = res.getIdentifier(key, "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
return result;
}
private static boolean getInternalBoolean(Resources res, String key) {
int resourceId = res.getIdentifier(key, "bool", "android");
return (resourceId > 0) ? res.getBoolean(resourceId) : false;
}
public static boolean hasFlag(int flags, int flag) {
return (flags & flag) == flag;
}
}
|
package org.collectionspace.chain.csp.persistence.services;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.collectionspace.chain.util.jtmpl.InvalidJTmplException;
import org.collectionspace.chain.util.jxj.InvalidJXJException;
import org.collectionspace.chain.util.jxj.JXJFile;
import org.collectionspace.chain.util.jxj.JXJTransformer;
import org.collectionspace.chain.util.xtmpl.InvalidXTmplException;
import org.collectionspace.csp.api.persistence.ExistException;
import org.collectionspace.csp.api.persistence.Storage;
import org.collectionspace.csp.api.persistence.UnderlyingStorageException;
import org.collectionspace.csp.api.persistence.UnimplementedException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* This class is a bag of hacks and tricks re Services/API integration. As they get fixed, this class should shrink.
*
* And spite of Pride, in erring Reason's spite,
* One truth is clear, Whatever is, is right.
* - Alexander Pope
*/
/**
* ServicesCollectionObjectStorage implements storage for collection object, and will
* probably be supplemented by similar classes for other services. However, as we add these, common factors will emerge
* which will allow them to be refactored into a common base class (or similar), meaning that
* ServicesCollectionObjectStorage and similar just end up with special code for a particular interface.
*/
class ServicesCollectionObjectStorage implements Storage {
private ServicesConnection conn;
private JXJTransformer jxj;
private ServicesIdentifierMap cspace_264_hack;
private static Logger log=LoggerFactory.getLogger(ServicesCollectionObjectStorage.class);
// XXX refactor into util
private Document getDocument(String in) throws DocumentException, IOException {
String path=getClass().getPackage().getName().replaceAll("\\.","/");
InputStream stream=Thread.currentThread().getContextClassLoader().getResourceAsStream(path+"/"+in);
SAXReader reader=new SAXReader();
Document doc=reader.read(stream);
stream.close();
return doc;
}
public ServicesCollectionObjectStorage(ServicesConnection conn) throws InvalidJXJException, DocumentException, IOException {
this.conn=conn;
cspace_264_hack=new ServicesIdentifierMap(conn,
"collectionobjects",
"collection-object-list/collection-object-list-item",
"collection-object/objectNumber");
JXJFile jxj_file=JXJFile.compile(getDocument("collectionobject.jxj"));
jxj=jxj_file.getTransformer("collection-object");
if(jxj==null)
throw new InvalidJXJException("Missing collection-object transform.");
}
private JSONObject cspace264Hack_unmunge(JSONObject in) {
// 1. Extract accession number from other numbers
try {
JSONArray ons=in.getJSONArray("objectNumber");
String accnum=null;
JSONArray new_ons=new JSONArray();
for(int i=0;i<ons.length();i++) {
String v=ons.getString(i);
if(v.startsWith("_accnum:")) {
accnum=v.substring("_accnum:".length());
} else {
new_ons.put(v);
}
}
in.remove("objectNumber");
in.put("objectNumber",new_ons);
if(accnum!=null) {
in.remove("accessionNumber");
in.put("accessionNumber",accnum);
}
} catch (JSONException e) {}
return in;
}
private JSONObject cspace264Hack_munge(JSONObject in,String path) {
// 1. Copy accession number into other number
JSONArray ons=new JSONArray();
String accnum;
try {
accnum = in.getString("accessionNumber");
} catch (JSONException e1) {
accnum = "";
}
try {
ons=in.getJSONArray("objectNumber");
} catch (JSONException e) {}
ons.put("_accnum:"+accnum);
in.remove("objectNumber");
try {
in.put("objectNumber",ons);
} catch (JSONException e) {
log.error("CSPACE-264 hack workaround failed: json exception writing objectNumber",e);
}
// 2. Copy path into accession number
in.remove("accessionNumber");
try {
in.put("accessionNumber","_path:"+path);
} catch (JSONException e) {
log.error("CSPACE-264 hack workaround failed: json exception writing accessionNumber",e);
}
return in;
}
// XXX
@SuppressWarnings("unchecked")
private Document cspace266Hack_munge(Document in) {
StringBuffer out=new StringBuffer();
for(Node n : (List<Node>)(in.selectNodes("collection-object/otherNumber"))) {
out.append(n.getText());
out.append(' ');
n.detach();
}
Node n=((Element)in.selectSingleNode("collection-object")).addElement("otherNumber");
n.setText(out.toString());
in.selectNodes("collection-object").add(n);
return in;
}
private Document cspace266Hack_unmunge(Document in) {
Node n=in.selectSingleNode("collection-object/otherNumber");
if(n==null)
return in;
String value=n.getText();
n.detach();
if(value==null || "".equals(value))
return in;
for(String v : value.split(" ")) {
Node nw=((Element)in.selectSingleNode("collection-object")).addElement("otherNumber");
nw.setText(v);
}
return in;
}
public void createJSON(String filePath, JSONObject jsonObject) throws ExistException, UnimplementedException, UnderlyingStorageException {
// XXX Here's what we do because of CSPACE-264
autocreateJSON(filePath,jsonObject);
// XXX End of here's what we do because of CSPACE-264
// Here's what we should do ->
// throw new UnimplementedException("Cannot create collectionobject at known path, use autocreateJSON");
}
@SuppressWarnings("unchecked")
public String[] getPaths(String subdir) throws UnderlyingStorageException {
try {
List<String> out=new ArrayList<String>();
ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET,"collectionobjects/");
if(all.getStatus()!=200)
throw new ConnectionException("Bad request during identifier cache map update: status not 200");
List<Node> objects=all.getDocument().selectNodes("collection-object-list/collection-object-list-item");
for(Node object : objects) {
String csid=object.selectSingleNode("csid").getText();
int idx=csid.lastIndexOf("/");
if(idx!=-1)
csid=csid.substring(idx+1);
String mid=cspace_264_hack.fromCSID(csid);
if(mid.startsWith("_path:")) {
out.add(mid.substring("_path:".length()));
} else {
out.add(csid);
}
}
return out.toArray(new String[0]);
} catch (ConnectionException e) {
throw new UnderlyingStorageException("Service layer exception",e);
}
}
private boolean cspace268Hack_empty(Document doc) {
|
package alma.acs.nc;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.omg.CORBA.BAD_PARAM;
import org.omg.CORBA.IntHolder;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;
import org.omg.CosNotification.Property;
import org.omg.CosNotification.PropertyError;
import org.omg.CosNotification.UnsupportedAdmin;
import org.omg.CosNotification.UnsupportedQoS;
import org.omg.CosNotifyChannelAdmin.ChannelNotFound;
import com.cosylab.CDB.DAO;
import com.cosylab.cdb.client.CDBAccess;
import com.cosylab.cdb.client.DAOProxy;
import com.cosylab.util.WildcharMatcher;
import gov.sandia.NotifyMonitoringExt.EventChannel;
import gov.sandia.NotifyMonitoringExt.EventChannelFactory;
import gov.sandia.NotifyMonitoringExt.EventChannelFactoryHelper;
import gov.sandia.NotifyMonitoringExt.EventChannelHelper;
import gov.sandia.NotifyMonitoringExt.NameAlreadyUsed;
import gov.sandia.NotifyMonitoringExt.NameMapError;
import alma.ACSErrTypeCORBA.wrappers.AcsJNarrowFailedEx;
import alma.ACSErrTypeCommon.wrappers.AcsJBadParameterEx;
import alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx;
import alma.ACSErrTypeCommon.wrappers.AcsJGenericErrorEx;
import alma.ACSErrTypeCommon.wrappers.AcsJUnexpectedExceptionEx;
import alma.AcsNCTraceLog.LOG_NC_ChannelCreatedRaw_OK;
import alma.AcsNCTraceLog.LOG_NC_ChannelCreated_ATTEMPT;
import alma.AcsNCTraceLog.LOG_NC_ChannelCreated_OK;
import alma.AcsNCTraceLog.LOG_NC_ChannelDestroyed_OK;
import alma.AcsNCTraceLog.LOG_NC_TaoExtensionsSubtypeMissing;
import alma.acs.container.AdvancedContainerServices;
import alma.acs.container.ContainerServicesBase;
import alma.acs.exceptions.AcsJException;
import alma.acs.logging.AcsLogLevel;
import alma.acs.util.StopWatch;
/**
* This class provides methods useful to both supplier and consumer objects.
*/
public class Helper {
/**
* In a running system, there can be only one reference to the Naming Service.
*/
private final NamingContext m_nContext;
/**
* Java property name for the CORBA Naming Service corbaloc.
* This property is set in the acsstartup :: acsStartJava.
* <p>
* @TODO: Check if we can eliminate this property if we use something similar as in
* jmanager's {@link com.cosylab.acs.maci.plug.NamingServiceRemoteDirectory}.
*/
private static final String m_nameJavaProp = "ORBInitRef.NameService";
// / Access to the component's name along with the logging service.
private final ContainerServicesBase m_services;
// / Our own personal logger
protected final Logger m_logger;
protected final Random random = new Random(System.currentTimeMillis());
// / Provides access to channel's quality of service properties
private final ChannelProperties m_channelProperties;
// CDB access helper (factory)
private final CDBAccess m_cdbAccess;
// cached MACI/Channels DAO
private DAOProxy channelsDAO;
// channelId is used to reconnect to channel in case that Notify Server crashes
private int channelId;
private EventChannelFactory notifyFactory;
/**
* Map that's used similar to a log repeat guard, because the OMC was flooded with NC config problem logs
* (as of 2008-03-06).
* <p>
* key = channel name; value = timestamp in ms when config error was found for the given channel.
*/
private final Map<String, Long> channelConfigProblems = new HashMap<String, Long>();
/**
* Creates a new instance of Helper, which includes resolving the naming service.
* @param services A reference to the ContainerServices
* @throws AcsJException Generic ACS exception will be thrown if anything in this class is broken.
*/
public Helper(ContainerServicesBase services) throws AcsJException {
this(services, getNamingServiceInitial(services));
}
/**
* Creates a new instance of Helper.
* This constructor is preferred, because it makes dependencies explicit.
* @param services A reference to the ContainerServices
* @param namingService Reference to the naming service.
* @throws AcsJException Generic ACS exception will be thrown if anything in this class is broken.
*/
public Helper(ContainerServicesBase services, NamingContext namingService) throws AcsJException {
if (services == null) {
AcsJBadParameterEx ex = new AcsJBadParameterEx();
ex.setReason("Null reference obtained for the ContainerServices!");
throw ex;
}
// save a local reference to the container services
m_services = services;
// immediately grab a logger
m_logger = m_services.getLogger();
// create a helper object used to retrieve channel properties
m_channelProperties = new ChannelProperties(services);
m_nContext = namingService;
// create CDB access
m_cdbAccess = new CDBAccess(getContainerServices().getAdvancedContainerServices().getORB(), m_logger);
m_cdbAccess.setDAL(getContainerServices().getCDB());
}
/**
* Returns a reference to the Container Services which are provided by a
* container or client.
*
* @return A valid reference to the ContainerServices instance.
*/
public ContainerServicesBase getContainerServices() {
return m_services;
}
/**
* Retrieves and returns a reference to the Naming Service.
* This code belongs to the constructor and should only be called from there.
* <p>
* This method is <code>protected </code> to support unit tests, otherwise it would be <code>private</code>.
* <p>
* @TODO: The dependence of NC libs on the NamingService should be expressed in a less hidden form
* than using a property, which leads to dangerous runtime-only failures if missing.
* It would already be an improvement if we would obtain the NamingService reference
* from {@link AdvancedContainerServices#getORB()}.
* A more radical change would be to integrate the NC classes into the ContainerServices.
*
* @return Valid reference to the Naming Service.
* @throws AcsJException
* Thrown when there's a bad corbaloc given for the Naming Service
* or the reference cannot be narrowed.
* @see #getNamingService()
*/
protected static NamingContext getNamingServiceInitial(ContainerServicesBase cs) throws AcsJException {
// acsStartJava always adds this Java property for us
String nameCorbaloc = System.getProperty(m_nameJavaProp);
// make sure the end-user is using acsStartJava
if (nameCorbaloc == null || nameCorbaloc.trim().isEmpty()) {
AcsJBadParameterEx ex = new AcsJBadParameterEx();
ex.setReason("Missing Java property '" + m_nameJavaProp + "' for the Naming Service corbaloc!");
throw ex;
}
// get the unnarrowed reference to the Naming Service
org.omg.CORBA.Object tempCorbaObject = cs.getAdvancedContainerServices().corbaObjectFromString(nameCorbaloc);
if (tempCorbaObject == null) {
// very bad situation. without the naming service we cannot do anything.
Throwable cause = new Throwable("Null reference obtained for the Naming Service, corbaloc=" + nameCorbaloc);
//AcsJFailedToResolveServiceEx ex = new AcsJFailedToResolveServiceEx();
// @TODO add parameter "service" and "reason" to definition of AcsJFailedToResolveServiceEx
// ex.setReason("Null reference obtained for the Naming Service, corbaloc=" + nameCorbaloc);
throw new alma.ACSErrTypeCORBA.wrappers.AcsJFailedToResolveServiceEx(cause);
}
NamingContext ret = NamingContextHelper.narrow(tempCorbaObject);
if (ret == null) {
// very bad situation. without the naming service we cannot do anything.
Throwable cause = new Throwable("Unable to narrow Naming Service reference to the correct type!");
throw new alma.ACSErrTypeCommon.wrappers.AcsJTypeNotSupportedEx(cause);
}
return ret;
}
/**
* Returns a reference to the Naming Service.
* <p>
* @return Valid reference to the Naming Service.
*/
public NamingContext getNamingService() {
return m_nContext;
}
public EventChannel getNotificationChannel(EventChannelFactory ecf)
{
EventChannel ec = null;
try {
ec = EventChannelHelper.narrow( ecf.get_event_channel(channelId) ); // @TODO HSO: Shouldn't this be "ec = ..." ?
} catch (ChannelNotFound e) {
// I cannot recover the channel using the ID
}
return ec;
}
/**
* This method gets a reference to the event channel. If it is not already
* registered with the naming service, it is created.
*
* @TODO Make "protected" again once we no longer have NC classes in separate subpackge "refactored".
*
* @return Reference to the event channel specified by channelName. Never null.
* @param channelName
* Name of the event channel registered with the CORBA Naming
* Service
* @param channelKind
* Kind of the channel as registered with the CORBA naming service ("channels").
* @param notifyFactoryName
* Name of the notification service as registered with the CORBA
* naming service.
* @throws AcsJException
* Standard ACS Java exception.
*/
public EventChannel getNotificationChannel(String channelName, String channelKind, String notifyFactoryName)
throws AcsJException
{
// return value
EventChannel retValue = null;
NameComponent[] t_NameSequence = { new NameComponent(channelName, channelKind) };
// (retryNumberAttempts * retrySleepSec) = the time before we give up to get a reference or create the channel if
// a channel of the given name supposedly gets created already (due to race conditions with other clients).
int retryNumberAttempts = 20;
int retrySleepSec = 2;
do {
try {
// @TODO move the check for existing channel from naming service to the NC factory,
// now that we use the TAO extension with named NCs.
// The only advantage of still using the naming service is that the naming service is a real system-wide singleton
// and can return also channels that were by mistake created from a different notify service factory than the one configured in the CDB.
initializeNotifyFactory(notifyFactoryName);
retValue = EventChannelHelper.narrow(getNamingService().resolve(t_NameSequence));
}
catch (org.omg.CosNaming.NamingContextPackage.NotFound e) {
// No other consumers or suppliers have registered the channel yet...
// This can mean that the channel has never been created, or that it is currently being created but has not yet been registered.
}
catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e) {
// Think there is virtually no chance of this every happening but...
throw new AcsJUnexpectedExceptionEx(e);
}
catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) {
// Think there is virtually no chance of this every happening but...
throw new AcsJUnexpectedExceptionEx(e);
}
if (retValue == null) {
// Couldn't get the channel object from the naming service.
// Let's try to create it, which may fail if some other consumer or supplier is currently doing the same,
// but only because we use the TAO extensions that support named NCs.
try {
retValue = createNotificationChannel(channelName, channelKind, notifyFactoryName);
} catch (NameAlreadyUsed ex) {
m_logger.log(Level.INFO, "NC '" + channelName + "' seems to be getting created. Will wait and try again in " + retrySleepSec + " seconds.", ex);
try {
Thread.sleep(retrySleepSec*1000);
} catch (InterruptedException ex1) {
// too bad
}
}
}
} while (retValue == null && --retryNumberAttempts >= 0);
if (retValue == null) {
AcsJGenericErrorEx ex = new AcsJGenericErrorEx();
ex.setErrorDesc("Giving up to get reference to channel " + channelName);
throw ex;
}
return retValue;
}
/**
* @param notifyFactoryName
* @throws AcsJException AcsJCORBAProblemEx if the NotifyService reference cannot be retrieved from the NamingService;
* AcsJNarrowFailedEx if the NotifyService is not of the required TAO extension type.
*/
protected void initializeNotifyFactory(String notifyFactoryName)
throws AcsJException
{
if (notifyFactory == null){
final String standardEventFactoryId = org.omg.CosNotifyChannelAdmin.EventChannelFactoryHelper.id();
final String specialEventFactoryId = gov.sandia.NotifyMonitoringExt.EventChannelFactoryHelper.id();
// get the Notification Factory first.
NameComponent[] t_NameFactory = { new NameComponent(notifyFactoryName, "") };
org.omg.CORBA.Object notifyFactoryObj = null;
//notifyFactory = null;
try {
notifyFactoryObj = getNamingService().resolve(t_NameFactory);
}
catch (org.omg.CosNaming.NamingContextPackage.NotFound ex) {
String reason = "The CORBA Notification Service '" + notifyFactoryName +
"' is not registered in the Naming Service: " + ex.why.toString();
AcsJCORBAProblemEx ex2 = new AcsJCORBAProblemEx();
ex2.setInfo(reason);
throw ex2;
}catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e) {
// Think there is virtually no chance of this every happening but...
Throwable cause = new Throwable(e.getMessage());
throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause);
} catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) {
// Think there is virtually no chance of this every happening but...
Throwable cause = new Throwable(e.getMessage());
throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause);
}
// narrow the notification factory to the TAO extension subtype
try {
notifyFactory = EventChannelFactoryHelper.narrow(notifyFactoryObj);
} catch (BAD_PARAM ex) {
if (notifyFactoryObj._is_a(standardEventFactoryId)) {
LOG_NC_TaoExtensionsSubtypeMissing.log(m_logger, notifyFactoryName, specialEventFactoryId, standardEventFactoryId);
}
else {
LOG_NC_TaoExtensionsSubtypeMissing.log(m_logger, notifyFactoryName, specialEventFactoryId, "???");
}
AcsJNarrowFailedEx ex2 = new AcsJNarrowFailedEx(ex);
ex2.setNarrowType(specialEventFactoryId);
throw ex2;
}
}
}
protected EventChannel createNotificationChannel(String channelName, String channelKind, String notifyFactoryName)
throws AcsJException, NameAlreadyUsed
{
LOG_NC_ChannelCreated_ATTEMPT.log(m_logger, channelName, notifyFactoryName);
// return value
EventChannel retValue = null;
channelId = -1; // to be assigned by factory
StopWatch stopwatch = new StopWatch();
try {
initializeNotifyFactory(notifyFactoryName);
// create the channel
// here we use the channel properties taken directly from our channel properties helper object.
// presumably these values come from the ACS configuration database.
IntHolder channelIdHolder = new IntHolder();
retValue = createNotifyChannel_internal(
m_channelProperties.configQofS(channelName),
m_channelProperties.configAdminProps(channelName),
channelName,
channelIdHolder);
// The fact that we got here without exception means that the channel name was not used yet.
// sanity check
if (retValue == null) {
// a null reference implies we cannot go any further
Throwable cause = new Throwable("Null reference obtained for the '" + channelName + "' channel!");
throw new alma.ACSErrTypeJavaNative.wrappers.AcsJJavaLangEx(cause); // TODO: more specific ex type
}
channelId = channelIdHolder.value;
// register our new channel with the naming service
try {
NameComponent[] t_NameChannel = { new NameComponent(channelName, channelKind) };
getNamingService().rebind(t_NameChannel, retValue);
}
catch (org.omg.CosNaming.NamingContextPackage.NotFound ex) {
// Corba spec: "If already bound, the previous binding must be of type nobject;
// otherwise, a NotFound exception with a why reason of not_object is raised."
String reason = "Failed to register the new channel '" + channelName +
"' with the Naming Service: " + ex.why.toString();
AcsJCORBAProblemEx ex2 = new AcsJCORBAProblemEx(ex);
ex2.setInfo(reason);
throw ex2;
}
} catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e) {
// Think there is virtually no chance of this every happening but...
Throwable cause = new Throwable(e.getMessage());
throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause);
} catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) {
// Think there is virtually no chance of this every happening but...
Throwable cause = new Throwable(e.getMessage());
throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause);
} catch (org.omg.CosNotification.UnsupportedQoS e) {
Throwable cause = new Throwable("The quality of service properties specified for the '" + channelName
+ "' channel are unsupported: " + e.getMessage());
throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause);
}
LOG_NC_ChannelCreated_OK.log(m_logger, channelName, channelId, notifyFactoryName, stopwatch.getLapTimeMillis());
return retValue;
}
/**
* Broken out from {@link #createNotificationChannel(String, String, String)}
* to give tests better control about the timing when this call to the event factory is made.
* @throws NameAlreadyUsed if the call to NotifyFactory#create_named_channel fails with this exception.
* @throws AcsJCORBAProblemEx if the TAO extension throws a NameMapError or if the QoS attributes cause a UnsupportedAdmin.
*/
protected EventChannel createNotifyChannel_internal(Property[] initial_qos, Property[] initial_admin, String channelName, IntHolder channelIdHolder)
throws NameAlreadyUsed, UnsupportedQoS, AcsJNarrowFailedEx, AcsJCORBAProblemEx {
EventChannel ret = null;
StopWatch stopwatch = new StopWatch();
try {
// The TAO extension of the notify factory that we use declares only the plain EventChannel type,
// even though it creates the TAO-extension subtype.
org.omg.CosNotifyChannelAdmin.EventChannel eventChannelBaseType = notifyFactory.create_named_channel(
initial_qos,
initial_admin,
channelIdHolder,
channelName);
LOG_NC_ChannelCreatedRaw_OK.log(m_logger, channelName, channelIdHolder.value, stopwatch.getLapTimeMillis());
// re-create the client side corba stub, to get the extension subtype
ret = gov.sandia.NotifyMonitoringExt.EventChannelHelper.narrow(eventChannelBaseType);
} catch (BAD_PARAM ex) {
LOG_NC_TaoExtensionsSubtypeMissing.log(m_logger, channelName, EventChannel.class.getName(), org.omg.CosNotifyChannelAdmin.EventChannelHelper.id());
AcsJNarrowFailedEx ex2 = new AcsJNarrowFailedEx(ex);
ex2.setNarrowType(EventChannelHelper.id());
throw ex2;
} catch (NameMapError ex) {
String msg = "Got a TAO extension-specific NameMapError exception that means the TAO NC extension is not usable. Bailing out since we need the extension.";
m_logger.log(AcsLogLevel.ERROR, msg, ex);
AcsJCORBAProblemEx ex2 = new AcsJCORBAProblemEx(ex);
ex2.setInfo(msg);
throw ex2;
} catch (UnsupportedAdmin ex) {
AcsJCORBAProblemEx ex2 = new AcsJCORBAProblemEx(ex);
ex2.setInfo(createUnsupportedAdminLogMessage(ex, channelName));
throw ex2;
}
return ret;
}
/**
* <b>Destroys the channel and unregisters it from the naming service. ONLY
* USE THIS METHOD IF YOU KNOW FOR CERTAIN THERE IS ONLY ONE SUPPLIER FOR THE
* CHANNEL!!! Use this method with extreme caution as it's likely to become
* deprecated in future versions of ACS!</b>
*
* @param channelName
* name of the channel as registered int the CORBA notification
* service
* @param channelKind
* Kind of the channel as registered with the CORBA naming service.
* @param channelRef
* reference to the channel being destroyed.
* Here we use the plain OMG type instead of the TAO extension subtype, because the extensions are
* not used for channel destruction.
* @throws AcsJException
* Thrown when the channel isn't registered with the Naming
* Service.
* @warning this method assumes
*/
protected void destroyNotificationChannel(String channelName, String channelKind, org.omg.CosNotifyChannelAdmin.EventChannel channelRef)
throws AcsJException
{
try {
// destroy the remote CORBA object
channelRef.destroy();
// unregister our channel with the naming service
NameComponent[] t_NameChannel = { new NameComponent(channelName, channelKind) };
getNamingService().unbind(t_NameChannel);
} catch (org.omg.CosNaming.NamingContextPackage.NotFound e) {
// Think there is virtually no chance of this every happening but...
String msg = "Cannot unbind the '" + channelName + "' channel from the Naming Service!";
m_logger.severe(msg);
} catch (org.omg.CosNaming.NamingContextPackage.CannotProceed e) {
// Think there is virtually no chance of this every happening but...
Throwable cause = new Throwable(e.getMessage());
throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause);
} catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) {
// Think there is virtually no chance of this every happening but...
Throwable cause = new Throwable(e.getMessage());
throw new alma.ACSErrTypeCommon.wrappers.AcsJCORBAProblemEx(cause);
}
LOG_NC_ChannelDestroyed_OK.log(m_logger, channelName, ""); // TODO use notif.service name
}
/**
* Provides access to the information about the channel contained within the
* ACS CDB
*
* @return This class's channel properties member.
*/
public ChannelProperties getChannelProperties() {
return m_channelProperties;
}
/**
* Get notification channel factory name for given channel.
* @param channelName name of the channel.
* @return notification channel factory name.
*/
public String getNotificationFactoryNameForChannel(String channelName)
{
return getNotificationFactoryNameForChannel(channelName, null);
}
/**
* Gets the notification channel factory name for the given channel/domain.
* <p>
* Tries to use the optional mapping from the CDB, otherwise uses <code>"NotifyEventChannelFactory"</code>.
* @param channelName name of the channel.
* @param domainName name of the domain, <code>null</code> if undefined.
* @return notification channel factory name.
*/
public String getNotificationFactoryNameForChannel(String channelName, String domainName)
{
// lazy initialization
if (channelsDAO == null)
{
try {
channelsDAO = m_cdbAccess.createDAO("MACI/Channels");
} catch (Throwable th) {
// keep track of when this occurs
Long timeLastError = channelConfigProblems.get(channelName);
channelConfigProblems.put(channelName, System.currentTimeMillis());
// don't log this too often (currently only once)
if (timeLastError == null) {
m_logger.log(AcsLogLevel.CONFIG, "Config issue for channel '" + channelName + "'. " +
"Failed to get MACI/Channels DAO from CDB. Will use default notification service.");
}
}
}
// query CDB...
if (channelsDAO != null)
{
// if channel mapping exists take it, wildchars are also supported
try {
String[] channelNameList = channelsDAO.get_string_seq("NotificationServiceMapping/Channels_");
for (String pattern : channelNameList) {
String regExpStr = WildcharMatcher.simpleWildcardToRegex(pattern);
if (Pattern.matches(regExpStr, channelName))
return channelsDAO.get_string("NotificationServiceMapping/Channels_/" + pattern + "/NotificationService");
}
} catch (Throwable th) {
m_logger.finer("No Channel to NotificationService mapping found for channel: " + channelName);
}
// try domain mapping, if given
if (domainName != null)
{
try {
return channelsDAO.get_string("NotificationServiceMapping/Domains/" + domainName + "/NotificationService");
} catch (Throwable th) {
m_logger.finer("No Domain to NotificationService mapping found for domain/channel: " + domainName + "/" + channelName);
}
}
// return default
try {
return channelsDAO.get_string("NotificationServiceMapping/DefaultNotificationService");
} catch (Throwable th) {
m_logger.finer("No NotificationServiceMapping/DefaultNotificationService attribute found, returning hardcoded default.");
}
}
// return default
return alma.acscommon.NOTIFICATION_FACTORY_NAME.value;
}
/**
* The following returns a map where each key is the name of an event and the
* value is the maximum amount of time (in floating point seconds) an event receiver has
* to process the event before a warning message is logged.
*
* @param channelName name of the channel
* @return HashMap described above
*/
public HashMap<String, Double> getEventHandlerTimeoutMap(String channelName) {
// initialize the return value
HashMap<String, Double> retVal = new HashMap<String, Double>();
// data access object to traverse the ACS CDB
DAO dao = null;
// keys into the DAO
String[] keys = null;
// get the dao for the channel...
// ...if this fails, just return.
try {
dao = m_services.getCDB().get_DAO_Servant(
"MACI/Channels/" + channelName);
} catch (Exception e) {
m_logger.finer("No CDB entry found for '" + channelName + "' channel");
return retVal;
}
// names of all the events
try {
keys = dao.get_string_seq("Events");
} catch (Exception e) {
m_logger.finer("CDB entry found for '" + channelName
+ "' but no Events element.");
return retVal;
}
// sanity check on the number of events
if (keys.length == 0) {
m_logger.finer("No event definitions found for the '" + channelName
+ "' within the CDB.");
return retVal;
}
// populate the hashmap
for (int i = 0; i < keys.length; i++) {
// determine the value location
String timeoutLocation = "Events/" + keys[i] + "/MaxProcessTime";
// get the value (floating point seconds)
try {
double value = dao.get_double(timeoutLocation);
retVal.put(keys[i], new Double(value));
} catch (Exception e) {
e.printStackTrace();
m_logger
.severe("Could not convert 'MaxProcessTime' to floating "
+ "point seconds for the '"
+ channelName
+ "' channel and '" + keys[i] + "' event type.");
}
}
return retVal;
}
public EventChannelFactory getNotifyFactory() {
return notifyFactory;
}
/**
* Corba spec: If the implementation of the target object is not capable of supporting
* any of the requested administrative property settings, the UnsupportedAdmin exception is raised.
* This exception has associated with it a list of name-value pairs of which each name
* identifies an administrative property whose requested setting could not be satisfied,
* and each associated value the closest setting for that property that could be satisfied.
* @param ex
* @param channelName
* @return a String that contains the information from UnsupportedAdmin
*/
public String createUnsupportedAdminLogMessage(UnsupportedAdmin ex, String channelName) {
StringBuilder sb = new StringBuilder();
sb.append("Caught " + ex.getMessage() + ": The administrative properties specified for the '" + channelName
+ "' channel are not supported: ");
for (PropertyError propertyError : ex.admin_err) {
sb.append("code=" + propertyError.code.toString()).append("; ");
sb.append("name=" + propertyError.name);
// TODO: Figure out what type (inside the Any) the range values are and add something like the following
// sb.append("available_low=" + propertyError.available_range.low_val.extract_long());
}
return sb.toString();
}
/**
* Appends a random number to the given client name.
* <p>
* This is used when setting names on NC proxy objects via the TAO extension API.
* It reduces the risk of creating a new object with an existing name,
* because TAO has memory bug and will not delete the badly named object
* even if it throws the correct NameAlreadyUsed exception.
* @param clientName
* @return "clientName-randomNumber"
*/
public String createRandomizedClientName(String clientName) {
StringBuffer clientNameSB = new StringBuffer(clientName);
clientNameSB.append('-');
clientNameSB.append(String.format("%05d", Math.abs(random.nextInt())));
return clientNameSB.toString();
}
}
|
package org.jetel.component;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.StringTokenizer;
import java.util.Scanner;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.channels.Channels;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.GraphConfigurationException;
import org.jetel.exception.JetelException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.graph.runtime.GraphExecutor;
import org.jetel.graph.runtime.GraphRuntimeContext;
import org.jetel.graph.runtime.WatchDog;
import org.jetel.main.runGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.file.FileUtils;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
public class RunGraph extends Node{
private static final String XML_OUTPUT_FILE_ATTRIBUTE = "logFile";
private static final String XML_APPEND_ATTRIBUTE = "logAppend";
private static final String XML_GRAPH_NAME_ATTRIBUTE = "graphName";
private static final String XML_SAME_INSTANCE_ATTRIBUTE = "sameInstance";
private static final String XML_ALTERNATIVE_JVM = "alternativeJavaCmdLine";
private static final String XML_GRAPH_EXEC_CLASS = "graphExecClass";
private static final String XML_CLOVER_CMD_LINE = "cloverCmdLineArgs";
private final static String JAVA_CMD_LINE = "java -cp";
private final static String CLOVER_CMD_LINE = "";
private final static String CLOVER_RUN_CLASS = "org.jetel.main.runGraph";
private final static String ERROR_COMPONENT_REGEX = ".*Node ([A-Z](\\w)+) finished with status: ERROR.*";
private final static String ERROR_LAST_MSG_REGEX = "ERROR\\s*\\[main\\]\\s*-\\s*(.*)";
public static String COMPONENT_TYPE = "RUN_GRAPH";
private final static int INPUT_PORT = 0;
private final static int OK_OUTPUT_PORT = 0;
private final static int ERR_OUTPUT_PORT = 1;
private final static int ERROR_LINES=100;
public final static long KILL_PROCESS_WAIT_TIME = 1000;
private String graphName = null;
private String classPath;
private String javaCmdLine;
private String cloverCmdLineArgs;
private String cloverRunClass;
private FileWriter outputFile = null;
/* this indicates the mode in which a dummy record is sent to port 0 in case of successful termination of the
* graph specified as graphName OR to the port 1 of it terminated with an error
*/
private boolean pipelineMode = false;
// whether to run the graph using another instance of JVM and clover (default: use this instance)
private boolean sameInstance = true;
private boolean append;
private boolean outputStatusMsg = false;
private int exitValue;
private String outputFileName;
static Log logger = LogFactory.getLog(RunGraph.class);
private void setCloverCmdLineArgs(String cloverCmdLineArgs) {
this.cloverCmdLineArgs = cloverCmdLineArgs;
}
public String getCloverCmdLine() {
return javaCmdLine;
}
public void setJavaCmdLine(String javaCmdLine) {
this.javaCmdLine = javaCmdLine;
}
public String getCloverRunClass() {
return cloverRunClass;
}
public void setCloverRunClass(String cloverRunClass) {
this.cloverRunClass = cloverRunClass;
}
/**
* @param id of component
* @param errorLinesNumber number of error lines which will be logged
*/
public RunGraph(String id) {
super(id);
this.append = false;
if(!this.sameInstance) {
this.classPath = System.getProperty("java.class.path");
}
}
/**
* @param id of component
* @param graphName name of the file containing graph definition
* @param errorLinesNumber number of error lines which will be logged
* @param append whether to append to the output file
* @param sameInst whether to run the graph in this instance of clover or run it over.
*/
public RunGraph(String id, boolean append, boolean sameInst) {
super(id);
this.append = append;
this.sameInstance = sameInst;
if(!this.sameInstance) {
this.classPath = System.getProperty("java.class.path");
}
}
/**
* this method interrupts thread
*
* @param thread to be killed
* @param millisec time to wait
* @return true if process has been interrupted in given time, false in another
* case
*/
static boolean kill(Thread thread, long millisec){
if (!thread.isAlive()){
return true;
}
thread.interrupt();
try {
Thread.sleep(millisec);
}catch(InterruptedException ex){
}
return !thread.isAlive();
}
/**
* This method interrupts process if it is alive after given time
*
* @param thread to be killed
* @param millisec time to wait before interrupting
*/
static void waitKill(Thread thread, long millisec){
if (!thread.isAlive()){
return;
}
try{
Thread.sleep(millisec);
thread.interrupt();
}catch(InterruptedException ex){
//do nothing, just leave
}
}
/**
* run graphs whose filenames are determined by input port or an attribute
*
* @return FINISHED_OK if all the graphs were processed succesfully, ERROR otherwise
* @throws Exception
*/
@Override
public Result execute() throws Exception {
//Creating and initializing record from input port
boolean success;
DataRecord inRecord=null;
InputPort inPort = getInputPort(INPUT_PORT);
//If there is input port read metadata, initialize inRecord and create data formater
if (inPort!=null) {
DataRecordMetadata meta=inPort.getMetadata();
inRecord = new DataRecord(meta);
inRecord.init();
}
// Creating and initializing record to output port
DataRecord outRec=null;
OutputPort outPort, outPortErr;
outPort=getOutputPort(OK_OUTPUT_PORT);
//If there is output port read metadadata, initialize succOutRecord and create proper data parser
if (outPort!=null) {
DataRecordMetadata meta=outPort.getMetadata();
outRec = new DataRecord(meta);
outRec.init();
}
outPortErr=getOutputPort(ERR_OUTPUT_PORT);
if(outRec==null && outPortErr!=null) {
outRec = new DataRecord(outPortErr.getMetadata());
outRec.init();
}
// if the second output port is connected, let's switch to the 'pipeline' mode
if(pipelineMode) {
// if(outPortErr!=null && outPort!=null) {
if(inRecord != null) {
inRecord = readRecord(INPUT_PORT, inRecord);
// if no record was received
if(inRecord == null) {
broadcastEOF();
if (outputFile!=null) {
outputFile.close();
}
return Result.FINISHED_OK;
}
}
if (runSingleGraph(graphName, outRec)) {
if(outPort!=null) {
outPort.writeRecord(outRec);
}
} else if(outPortErr!=null) {
outPortErr.writeRecord(outRec);
}
broadcastEOF();
if (outputFile!=null) {
outputFile.close();
}
return Result.FINISHED_OK;
}
success = false;
while(inRecord != null && runIt) {
inRecord = readRecord(INPUT_PORT, inRecord);
if(inRecord == null) break;
DataField field = inRecord.getField(0);
Object val = field.getValue();
if(val == null) continue;
String fname = val.toString();
try{
success = runSingleGraph(fname, outRec);
} catch (Exception e) {
logger.error("Exception while processing " + fname + ": "+ e.getMessage());
}
outPort.writeRecord(outRec);
}
broadcastEOF();
if (outputFile!=null) {
outputFile.close();
}
if (success) return Result.FINISHED_OK;
else return Result.ERROR;
}
private boolean runSingleGraph(String graphName, DataRecord output) throws Exception {
boolean ok = true;
Process process;
String status = null;
int duration = 0;
String errComp = null;
String lastErrMsg = null;
if(sameInstance) {
logger.info("********Running graph " + graphName + " in the same instance.");
if(runGraphThisInstance(graphName, output)) return true;
else return false;
}
logger.info("Running graph " + graphName + " in separate instance of clover.");
String commandLine = javaCmdLine + " " + classPath + " " + cloverRunClass + " " + cloverCmdLineArgs + " " + graphName;
logger.info("Executing command: \"" + commandLine + "\"");
process = Runtime.getRuntime().exec(commandLine);
//get process input and output streams
BufferedInputStream process_out = new BufferedInputStream(process.getInputStream());
BufferedInputStream process_err = new BufferedInputStream(process.getErrorStream());
// If there is input port read records and write them to input stream of the process
//if output is not sent to file log process error stream
BufferedReader err=new BufferedReader(new InputStreamReader(process_err));
BufferedReader out=new BufferedReader(new InputStreamReader(process_out));
String line;
int i=0;
while ((line=err.readLine())!=null){
if (i<=ERROR_LINES) {
logger.warn("Processing " + graphName + ": " + line);
// errmes.append(line+"\n");
}
/*
if(line.compareTo(summaryBegin) == 0) {
line=err.readLine();
if(line==null) {
}
line=err.readLine();
for (Result res: Result.values()) {
}
}
*/
if(outputFile != null) outputFile.write(line + "\n");
}
Pattern patErr = Pattern.compile(ERROR_LAST_MSG_REGEX);
Pattern pt = Pattern.compile(ERROR_COMPONENT_REGEX);
while ((line=out.readLine())!=null){
int pos;
if(line.compareTo("Phase# Finished Status RunTime") == 0) {
if ((line=out.readLine())==null) break;
if(outputFile != null) outputFile.write(line);
StringTokenizer tk = new StringTokenizer(line);
for(int j=0; j<4 && tk.hasMoreTokens(); j++) tk.nextToken();
if(i==4) {
status = tk.nextToken();
}
// TODO
}
// "finished with status: ERROR"
Matcher match = pt.matcher(line);
if(match.matches() && errComp==null) errComp = match.group(1);
if((pos=line.indexOf("WatchDog thread finished - total execution time")) != -1) { //TODO
Scanner sc = new Scanner(line.substring(pos));
while(sc.hasNext() && !sc.hasNextInt()) sc.next();
if(sc.hasNextInt()) duration = sc.nextInt();
}
Matcher matchErr = patErr.matcher(line);
if(matchErr.matches()) lastErrMsg = matchErr.group(1);
if(outputFile != null) outputFile.write(line + "\n");
}
err.close();
out.close();
process_err.close();
process_out.close();
// wait for executed process to finish
// wait for SendData and/or GetData threads to finish work
try {
exitValue=process.waitFor();
} catch(InterruptedException ex){
logger.error("InterruptedException in "+this.getId(),ex);
process.destroy();
//interrupt threads if they run still
}
String resultMsg = null;
if(output != null) {
// if(status == null) status="*Finished OK";
output.getField(0).setValue(graphName);
if(status!=null) output.getField(1).setValue(status);
output.getField(3).setValue(errComp);
output.getField(4).setValue(duration);
}
if (!runIt) {
resultMsg = (resultMsg == null ? "" : resultMsg) + "\n" + "STOPPED";
if(output != null) {
if(status == null) output.getField(1).setValue("Aborted");
output.getField(2).setValue((lastErrMsg!=null) ? lastErrMsg : resultMsg);
}
return false;
}
if (exitValue!=0){
resultMsg = (resultMsg == null ? "" : resultMsg) + "\n" + graphName + ": Process exit value not 0";
if(output != null) {
if(status == null) output.getField(1).setValue("Error");
output.getField(2).setValue((lastErrMsg != null) ? lastErrMsg : resultMsg);
}
logger.info(graphName + ": Processing with an ERROR: " + resultMsg);
return false;
/*
resultMsg = "Process exit value not 0";
ok = false;;
throw new JetelException(resultMsg);
*/
}
if (ok) {
logger.info(graphName + ": Processing finished successfully");
if(status == null && output != null) output.getField(1).setValue("Finished successfully");
return true;
} else {
logger.info(graphName + ": Processing with an ERROR: " + resultMsg);
if(output!=null) output.getField(2).setValue((lastErrMsg != null) ? lastErrMsg : resultMsg);
throw new JetelException(resultMsg);
}
}
private boolean runGraphThisInstance(String graphFileName, DataRecord output) {
InputStream in = null;
WatchDog watchdog;
output.getField(0).setValue(graphFileName);
output.getField(1).setValue("Error");
output.getField(3).setValue("");
output.getField(4).setValue(0);
try {
in = Channels.newInputStream(FileUtils.getReadableChannel(null, graphFileName));
} catch (IOException e) {
output.getField(2).setValue("Error - graph definition file can't be read: " + e.getMessage());
return false;
}
GraphRuntimeContext runtimeContext = new GraphRuntimeContext();
GraphExecutor graphExecutor = new GraphExecutor();
Future<Result> futureResult = null;
String password = null; // TODO
try {
futureResult = graphExecutor.runGraph(in, runtimeContext, password);
watchdog = graphExecutor.getWatchDog();
} catch (XMLConfigurationException e) {
output.getField(2).setValue("Error in reading graph from XML: " + e.getMessage());
return false;
} catch (GraphConfigurationException e) {
output.getField(2).setValue("Error - graph's configuration invalid: " + e.getMessage());
return false;
} catch (ComponentNotReadyException e) {
output.getField(2).setValue("Error during graph initialization: " + e.getMessage());
return false;
} catch (RuntimeException e) {
output.getField(2).setValue("Error during graph initialization: " + e.getMessage());
return false;
}
Result result = Result.N_A;
try {
result = futureResult.get();
} catch (InterruptedException e) {
output.getField(2).setValue("Graph was unexpectedly interrupted !" + e.getMessage());
return false;
} catch (ExecutionException e) {
output.getField(2).setValue("Error during graph processing !" + e.getMessage());
return false;
}
switch (result) {
case FINISHED_OK:
output.getField(1).setValue("Finished OK");
output.getField(2).setValue("");
output.getField(3).setValue("");
if(watchdog != null) output.getField(4).setValue(watchdog.getTotalRunTime());
return true;
case ABORTED:
output.getField(1).setValue("Aborted");
output.getField(2).setValue("Graph execution aborted. ");
if(watchdog != null) {
output.getField(3).setValue(watchdog.getFatalErrorSourceID());
output.getField(4).setValue(watchdog.getTotalRunTime());
}
System.err.println(graphFileName + ": " + "Execution of graph aborted !");
return false;
default:
output.getField(1).setValue(result.message());
output.getField(2).setValue("Execution of graph failed !");
if(watchdog!=null) {
output.getField(3).setValue(watchdog.getFatalErrorSourceID());
output.getField(4).setValue(watchdog.getTotalRunTime());
}
System.err.println(graphFileName + ": " + "Execution of graph failed !");
return false;
}
}
@Override
public void free() {
if(!isInitialized()) return;
super.free();
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#init()
*/
@Override public void init() throws ComponentNotReadyException {
if(isInitialized()) return;
super.init();
if(graphName!=null) {
pipelineMode = true;
}
//prepare output file
// if (getOutPorts().size()==0 && outputFileName!=null){
if (outputFileName!=null){
File outFile= new File(outputFileName);
try{
outFile.createNewFile();
this.outputFile = new FileWriter(outFile,append);
}catch(IOException ex){
throw new ComponentNotReadyException(ex);
}
}
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#getType()
*/
@Override public String getType(){
return COMPONENT_TYPE;
}
/**
* this method checks the metadata
*
* @param meta metadata to be checked
* @return true if the metadata is OK, false otherwise
*
*/
boolean checkMetadata(DataRecordMetadata meta)
{
if(meta.getFields().length < 5) return false;
for(int i=0;i<4;i++) {
if(meta.getFieldType(i) != DataFieldMetadata.STRING_FIELD) {
return false;
}
}
if(meta.getFieldType(4) != DataFieldMetadata.DECIMAL_FIELD) return false;
return true;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#checkConfig()
*/
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
checkInputPorts(status, 0, 1);
checkOutputPorts(status, 0, 2);
DataRecordMetadata inMetadata=null;
if(graphName!=null) pipelineMode=true;
OutputPort outPort1, outPort2;
outPort1=getOutputPort(OK_OUTPUT_PORT);
outPort2=getOutputPort(ERR_OUTPUT_PORT);
InputPort inPort1=getInputPort(INPUT_PORT);
if(outPort1!=null && !checkMetadata(outPort1.getMetadata()) ||
outPort2!=null && !checkMetadata(outPort2.getMetadata())) {
ConfigurationProblem problem = new ConfigurationProblem("Wrong output metadata", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL);
status.add(problem);
return status;
}
if(inPort1!=null) {
inMetadata=inPort1.getMetadata();
if(pipelineMode) {
if(!checkMetadata(inMetadata)) {
ConfigurationProblem problem = new ConfigurationProblem("Wrong input metadata", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL);
status.add(problem);
return status;
}
} else {
if(inMetadata.getFieldType(0) != DataFieldMetadata.STRING_FIELD) {
ConfigurationProblem problem = new ConfigurationProblem("Wrong input metadata - first field should be string", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL);
status.add(problem);
return status;
}
}
} else if(!pipelineMode) {
ConfigurationProblem problem = new ConfigurationProblem("If no graph is specified as an attribute, the input port must be connected", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL);
status.add(problem);
return status;
}
if(!sameInstance && (cloverCmdLineArgs == null || cloverCmdLineArgs.equals(""))) {
ConfigurationProblem problem = new ConfigurationProblem("If the graph is executed in separate instance of clover, supplying the command line for clover is necessary (at least the -plugins argument)" ,
ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL);
status.add(problem);
return status;
}
try {
init();
} catch (ComponentNotReadyException e) {
ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL);
if(!StringUtils.isEmpty(e.getAttributeName())) {
problem.setAttributeName(e.getAttributeName());
}
status.add(problem);
} finally {
free();
}
return status;
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#fromXML(org.jetel.graph.TransformationGraph, org.w3c.dom.Element)
*/
public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
RunGraph runG;
try {
runG = new RunGraph(xattribs.getString(XML_ID_ATTRIBUTE),
xattribs.getBoolean(XML_APPEND_ATTRIBUTE,false),
xattribs.getBoolean(XML_SAME_INSTANCE_ATTRIBUTE, true));
runG.setJavaCmdLine(JAVA_CMD_LINE);
runG.setCloverRunClass(CLOVER_RUN_CLASS);
runG.setCloverCmdLineArgs(CLOVER_CMD_LINE);
if (xattribs.exists(XML_OUTPUT_FILE_ATTRIBUTE)){
runG.setOutputFile(xattribs.getString(XML_OUTPUT_FILE_ATTRIBUTE));
}
if (xattribs.exists(XML_GRAPH_NAME_ATTRIBUTE)) {
runG.setGraphName(xattribs.getString(XML_GRAPH_NAME_ATTRIBUTE));
}
if (xattribs.exists(XML_ALTERNATIVE_JVM)) {
runG.setJavaCmdLine(xattribs.getString(XML_ALTERNATIVE_JVM));
}
if (xattribs.exists(XML_GRAPH_EXEC_CLASS)) {
runG.setCloverRunClass(xattribs.getString(XML_GRAPH_EXEC_CLASS));
}
if (xattribs.exists(XML_CLOVER_CMD_LINE)) {
runG.setCloverCmdLineArgs(xattribs.getString(XML_CLOVER_CMD_LINE));
}
return runG;
} catch (Exception ex) {
throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex);
}
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#toXML(org.w3c.dom.Element)
*/
@Override public void toXML(Element xmlElement) {
super.toXML(xmlElement);
xmlElement.setAttribute(XML_GRAPH_NAME_ATTRIBUTE, graphName);
xmlElement.setAttribute(XML_APPEND_ATTRIBUTE, String.valueOf(append));
xmlElement.setAttribute(XML_SAME_INSTANCE_ATTRIBUTE, String.valueOf(append));
if (outputFile!=null){
xmlElement.setAttribute(XML_OUTPUT_FILE_ATTRIBUTE,outputFileName);
}
if (javaCmdLine.compareTo(JAVA_CMD_LINE) != 0) {
xmlElement.setAttribute(XML_ALTERNATIVE_JVM, javaCmdLine);
}
if (cloverRunClass.compareTo(CLOVER_RUN_CLASS) != 0) {
xmlElement.setAttribute(XML_GRAPH_EXEC_CLASS, cloverRunClass);
}
if (cloverCmdLineArgs.compareTo(CLOVER_CMD_LINE) != 0) {
xmlElement.setAttribute(XML_CLOVER_CMD_LINE, cloverCmdLineArgs);
}
}
/**
* Sets output file
*
* @param outputFile
*/
protected void setOutputFile(String outputFile){
this.outputFileName = outputFile;
}
protected void setGraphName(String graphName) {
this.graphName = graphName;
}
private static class SendDataToFile extends Thread {
BufferedInputStream process_out;
FileWriter outFile;
String resultMsg=null;
Result resultCode;
volatile boolean runIt;
Thread parentThread;
Throwable resultException;
/**
* Constructor for SendDataToFile object
*
* @param parentThread thread which creates this object
* @param outFile output file
* @param process_out input stream, where are data read from
*/
SendDataToFile(Thread parentThread,FileWriter outFile,
BufferedInputStream process_out){
super(parentThread.getName()+".SendDataToFile");
this.outFile = outFile;
this.process_out = process_out;
this.runIt=true;
this.parentThread = parentThread;
}
public void stop_it(){
runIt=false;
}
public void run() {
resultCode=Result.RUNNING;
BufferedReader out = new BufferedReader(new InputStreamReader(process_out));
String line = null;
try{
while (runIt && ((line=out.readLine())!=null)){
synchronized (outFile) {
outFile.write(line+"\n");
}
}
}catch(IOException ex){
resultMsg = ex.getMessage();
resultCode = Result.ERROR;
resultException = ex;
waitKill(parentThread,KILL_PROCESS_WAIT_TIME);
}catch(Exception ex){
resultMsg = ex.getMessage();
resultCode = Result.ERROR;
resultException = ex;
waitKill(parentThread,KILL_PROCESS_WAIT_TIME);
}
finally{
try{
out.close();
}catch(IOException e){
//do nothing, out closed
}
}
if (resultCode==Result.RUNNING){
if (runIt){
resultCode=Result.FINISHED_OK;
}else{
resultCode = Result.ABORTED;
}
}
}
/**
* @return Returns the resultCode.
*/
public Result getResultCode() {
return resultCode;
}
public String getResultMsg() {
return resultMsg;
}
public Throwable getResultException() {
return resultException;
}
}
}
/**
* This is class for reading records from input port and writing them to Formatter
*
* @author avackova
*
*/
|
//$HeadURL$
package org.deegree.services.wms;
import static org.deegree.commons.utils.io.Utils.determineSimilarity;
import static org.deegree.commons.utils.net.HttpUtils.STREAM;
import static org.deegree.commons.utils.net.HttpUtils.retrieve;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import javax.imageio.ImageIO;
import org.apache.commons.io.IOUtils;
import org.deegree.commons.utils.test.IntegrationTestUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class WMSSimilarityIntegrationTest {
private String request;
private byte[] response;
public WMSSimilarityIntegrationTest( Object wasXml, String request, byte[] response ) {
// we only use .kvp for WMS
this.request = (String) request;
if ( !this.request.startsWith( "?" ) ) {
this.request = "?" + this.request;
}
this.response = (byte[]) response;
}
@Parameters
public static Collection<Object[]> getParameters() {
return IntegrationTestUtils.getTestRequests();
}
@Test
public void testSimilarity()
throws IOException {
String base = "http://localhost:" + System.getProperty( "portnumber" );
base += "/deegree-wms-similarity-tests/services" + request;
InputStream in = retrieve( STREAM, base );
try {
BufferedImage img2 = ImageIO.read( new ByteArrayInputStream( response ) );
byte[] bs = IOUtils.toByteArray( in );
BufferedImage img1 = ImageIO.read( new ByteArrayInputStream( bs ) );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write( img1, "tif", bos );
bos.close();
in = new ByteArrayInputStream( bos.toByteArray() );
bos = new ByteArrayOutputStream();
bos.close();
ImageIO.write( img2, "tif", bos );
this.response = bos.toByteArray();
} catch ( Throwable t ) {
t.printStackTrace();
// just compare initial byte arrays
}
double sim = determineSimilarity( in, new ByteArrayInputStream( response ) );
Assert.assertEquals( "Images are not similar enough.", 1.0, sim, 0.01 );
}
}
|
package com.robodoot.dr.RoboApp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import org.pololu.maestro.*;
import java.io.Serializable;
public class PololuHandler implements Serializable {
public MaestroSSC maestro;
public static final int NECK_YAW_SERVO = 10;
public static final int NECK_PITCH_SERVO = 9;
private boolean isConnected=false;
public enum Motor{
HEAD_YAW (9, "Head Yaw",1600,0,0),
HEAD_PITCH (10, "Head Pitch",2200,0,0);
public final int number;
public final int homePos;
public final int min;
public final int max;
public final String name;
Motor(int num, String str, int h, int mi, int ma)
{
number = num;
name = str;
homePos = h;
min = mi;
max = ma;
}
}
public float speedConst = 90f;
public int yaw=1600;
public int pitch=2200;
public void setTarget(int ID, int target)
{
if(isConnected)
{
maestro.setTarget(ID, target);
}
}
public PololuHandler()
{
maestro = new MaestroSSC();
}
public boolean isOpen()
{
return isConnected;
}
public void home()
{
maestro.setTarget(9,2200);
maestro.setTarget(10,1600);
yaw = 1600;
pitch = 2200;
}
public void setSpeedConst(float newConst)
{
speedConst=newConst;
}
public void onResume(Intent intent,Activity parent ){
String action = intent.getAction();
isConnected = false;
if (action.equals("android.hardware.usb.action.USB_DEVICE_ATTACHED")) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
UsbManager usbManager = (UsbManager) parent.getSystemService(Context.USB_SERVICE);
maestro.setDevice(usbManager, device);
isConnected = true;
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
maestro.setDevice(null, null);
} else {
}
}
}
public void stopNeckMotors()
{
// maestro.setSpeed(NECK_YAW_SERVO,0);
// maestro.setSpeed(NECK_PITCH_SERVO,0);
}
public void cameraYawSpeed(float speedPercent)
{
int addToYaw = (int)(speedPercent*speedConst);
yaw+=addToYaw;
maestro.setTarget(NECK_YAW_SERVO, yaw);
}
public void cameraPitchSpeed(float speedPercent)
{
int addToPitch = (int)(speedPercent*speedConst);
pitch+=addToPitch;
maestro.setTarget(NECK_PITCH_SERVO, pitch);
}
}
|
package org.jetel.ctl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import junit.framework.AssertionFailedError;
import org.jetel.component.CTLRecordTransform;
import org.jetel.component.RecordTransform;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.SetVal;
import org.jetel.data.lookup.LookupTable;
import org.jetel.data.lookup.LookupTableFactory;
import org.jetel.data.primitive.Decimal;
import org.jetel.data.sequence.Sequence;
import org.jetel.data.sequence.SequenceFactory;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.TransformException;
import org.jetel.graph.ContextProvider;
import org.jetel.graph.ContextProvider.Context;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataFieldContainerType;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataFieldType;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.test.CloverTestCase;
import org.jetel.util.MiscUtils;
import org.jetel.util.bytes.PackedDecimal;
import org.jetel.util.crypto.Base64;
import org.jetel.util.crypto.Digest;
import org.jetel.util.crypto.Digest.DigestType;
import org.jetel.util.primitive.TypedProperties;
import org.jetel.util.string.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Years;
import sun.misc.Cleaner;
public abstract class CompilerTestCase extends CloverTestCase {
protected static final String INPUT_1 = "firstInput";
protected static final String INPUT_2 = "secondInput";
protected static final String INPUT_3 = "thirdInput";
protected static final String INPUT_4 = "multivalueInput";
protected static final String OUTPUT_1 = "firstOutput";
protected static final String OUTPUT_2 = "secondOutput";
protected static final String OUTPUT_3 = "thirdOutput";
protected static final String OUTPUT_4 = "fourthOutput";
protected static final String OUTPUT_5 = "firstMultivalueOutput";
protected static final String OUTPUT_6 = "secondMultivalueOutput";
protected static final String OUTPUT_7 = "thirdMultivalueOutput";
protected static final String LOOKUP = "lookupMetadata";
protected static final String NAME_VALUE = " HELLO ";
protected static final Double AGE_VALUE = 20.25;
protected static final String CITY_VALUE = "Chong'La";
protected static final Date BORN_VALUE;
protected static final Long BORN_MILLISEC_VALUE;
static {
Calendar c = Calendar.getInstance();
c.set(2008, 12, 25, 13, 25, 55);
c.set(Calendar.MILLISECOND, 333);
BORN_VALUE = c.getTime();
BORN_MILLISEC_VALUE = c.getTimeInMillis();
}
protected static final Integer VALUE_VALUE = Integer.MAX_VALUE - 10;
protected static final Boolean FLAG_VALUE = true;
protected static final byte[] BYTEARRAY_VALUE = "Abeceda zedla deda".getBytes();
protected static final BigDecimal CURRENCY_VALUE = new BigDecimal("133.525");
protected static final int DECIMAL_PRECISION = 7;
protected static final int DECIMAL_SCALE = 3;
protected static final int NORMALIZE_RETURN_OK = 0;
public static final int DECIMAL_MAX_PRECISION = 32;
public static final MathContext MAX_PRECISION = new MathContext(DECIMAL_MAX_PRECISION,RoundingMode.DOWN);
/** Flag to trigger Java compilation */
private boolean compileToJava;
protected DataRecord[] inputRecords;
protected DataRecord[] outputRecords;
protected TransformationGraph graph;
public CompilerTestCase(boolean compileToJava) {
this.compileToJava = compileToJava;
}
/**
* Method to execute tested CTL code in a way specific to testing scenario.
*
* Assumes that
* {@link #graph}, {@link #inputRecords} and {@link #outputRecords}
* have already been set.
*
* @param compiler
*/
public abstract void executeCode(ITLCompiler compiler);
/**
* Method which provides access to specified global variable
*
* @param varName
* global variable to be accessed
* @return
*
*/
protected abstract Object getVariable(String varName);
protected void check(String varName, Object expectedResult) {
assertEquals(varName, expectedResult, getVariable(varName));
}
protected void checkEquals(String varName1, String varName2) {
assertEquals("Comparing " + varName1 + " and " + varName2 + " : ", getVariable(varName1), getVariable(varName2));
}
protected void checkNull(String varName) {
assertNull(getVariable(varName));
}
private void checkArray(String varName, byte[] expected) {
byte[] actual = (byte[]) getVariable(varName);
assertTrue("Arrays do not match; expected: " + byteArrayAsString(expected) + " but was " + byteArrayAsString(actual), Arrays.equals(actual, expected));
}
private static String byteArrayAsString(byte[] array) {
final StringBuilder sb = new StringBuilder("[");
for (final byte b : array) {
sb.append(b);
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
sb.append(']');
return sb.toString();
}
@Override
protected void setUp() {
// set default locale to English to prevent various parsing errors
Locale.setDefault(Locale.ENGLISH);
initEngine();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
inputRecords = null;
outputRecords = null;
graph = null;
}
protected TransformationGraph createEmptyGraph() {
return new TransformationGraph();
}
protected TransformationGraph createDefaultGraph() {
TransformationGraph g = createEmptyGraph();
// set the context URL, so that imports can be used
g.getRuntimeContext().setContextURL(CompilerTestCase.class.getResource("."));
final HashMap<String, DataRecordMetadata> metadataMap = new HashMap<String, DataRecordMetadata>();
metadataMap.put(INPUT_1, createDefaultMetadata(INPUT_1));
metadataMap.put(INPUT_2, createDefaultMetadata(INPUT_2));
metadataMap.put(INPUT_3, createDefaultMetadata(INPUT_3));
metadataMap.put(INPUT_4, createDefaultMultivalueMetadata(INPUT_4));
metadataMap.put(OUTPUT_1, createDefaultMetadata(OUTPUT_1));
metadataMap.put(OUTPUT_2, createDefaultMetadata(OUTPUT_2));
metadataMap.put(OUTPUT_3, createDefaultMetadata(OUTPUT_3));
metadataMap.put(OUTPUT_4, createDefault1Metadata(OUTPUT_4));
metadataMap.put(OUTPUT_5, createDefaultMultivalueMetadata(OUTPUT_5));
metadataMap.put(OUTPUT_6, createDefaultMultivalueMetadata(OUTPUT_6));
metadataMap.put(OUTPUT_7, createDefaultMultivalueMetadata(OUTPUT_7));
metadataMap.put(LOOKUP, createDefaultMetadata(LOOKUP));
g.addDataRecordMetadata(metadataMap);
g.addSequence(createDefaultSequence(g, "TestSequence"));
g.addLookupTable(createDefaultLookup(g, "TestLookup"));
Properties properties = new Properties();
properties.put("PROJECT", ".");
properties.put("DATAIN_DIR", "${PROJECT}/data-in");
properties.put("COUNT", "`1+2`");
properties.put("NEWLINE", "\\n");
g.setGraphProperties(properties);
initDefaultDictionary(g);
return g;
}
private void initDefaultDictionary(TransformationGraph g) {
try {
g.getDictionary().init();
g.getDictionary().setValue("s", "string", null);
g.getDictionary().setValue("i", "integer", null);
g.getDictionary().setValue("l", "long", null);
g.getDictionary().setValue("d", "decimal", null);
g.getDictionary().setValue("n", "number", null);
g.getDictionary().setValue("a", "date", null);
g.getDictionary().setValue("b", "boolean", null);
g.getDictionary().setValue("y", "byte", null);
g.getDictionary().setValue("i211", "integer", new Integer(211));
g.getDictionary().setValue("sVerdon", "string", "Verdon");
g.getDictionary().setValue("l452", "long", new Long(452));
g.getDictionary().setValue("d621", "decimal", new BigDecimal(621));
g.getDictionary().setValue("n9342", "number", new Double(934.2));
g.getDictionary().setValue("a1992", "date", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime());
g.getDictionary().setValue("bTrue", "boolean", Boolean.TRUE);
g.getDictionary().setValue("yFib", "byte", new byte[]{1,2,3,5,8,13,21,34,55,89} );
g.getDictionary().setValue("stringList", "list", Arrays.asList("aa", "bb", null, "cc"));
g.getDictionary().setContentType("stringList", "string");
g.getDictionary().setValue("dateList", "list", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000)));
g.getDictionary().setContentType("dateList", "date");
g.getDictionary().setValue("byteList", "list", Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78}));
g.getDictionary().setContentType("byteList", "byte");
} catch (ComponentNotReadyException e) {
throw new RuntimeException("Error init default dictionary", e);
}
}
protected Sequence createDefaultSequence(TransformationGraph graph, String name) {
Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE", new Object[] { "Sequence0", graph, name }, new Class[] { String.class, TransformationGraph.class, String.class });
try {
seq.checkConfig(new ConfigurationStatus());
seq.init();
} catch (ComponentNotReadyException e) {
throw new RuntimeException(e);
}
return seq;
}
/**
* Creates default lookup table of type SimpleLookupTable with 4 records using default metadata and a composite
* lookup key Name+Value. Use field City for testing response.
*
* @param graph
* @param name
* @return
*/
protected LookupTable createDefaultLookup(TransformationGraph graph, String name) {
final TypedProperties props = new TypedProperties();
props.setProperty("id", "LookupTable0");
props.setProperty("type", "simpleLookup");
props.setProperty("metadata", LOOKUP);
props.setProperty("key", "Name;Value");
props.setProperty("name", name);
props.setProperty("keyDuplicates", "true");
/*
* The test lookup table is populated from file TestLookup.dat. Alternatively uncomment the populating code
* below, however this will most probably break down test_lookup() because free() will wipe away all data and
* noone will restore them
*/
URL dataFile = getClass().getSuperclass().getResource("TestLookup.dat");
if (dataFile == null) {
throw new RuntimeException("Unable to populate testing lookup table. File 'TestLookup.dat' not found by classloader");
}
props.setProperty("fileURL", dataFile.getFile());
LookupTableFactory.init();
LookupTable lkp = LookupTableFactory.createLookupTable(props);
lkp.setGraph(graph);
try {
lkp.checkConfig(new ConfigurationStatus());
lkp.init();
lkp.preExecute();
} catch (ComponentNotReadyException ex) {
throw new RuntimeException(ex);
}
/*DataRecord lkpRecord = createEmptyRecord(createDefaultMetadata("lookupResponse"));
lkpRecord.getField("Name").setValue("Alpha");
lkpRecord.getField("Value").setValue(1);
lkpRecord.getField("City").setValue("Andorra la Vella");
lkp.put(lkpRecord);
lkpRecord.getField("Name").setValue("Bravo");
lkpRecord.getField("Value").setValue(2);
lkpRecord.getField("City").setValue("Bruxelles");
lkp.put(lkpRecord);
// duplicate entry
lkpRecord.getField("Name").setValue("Charlie");
lkpRecord.getField("Value").setValue(3);
lkpRecord.getField("City").setValue("Chamonix");
lkp.put(lkpRecord);
lkpRecord.getField("Name").setValue("Charlie");
lkpRecord.getField("Value").setValue(3);
lkpRecord.getField("City").setValue("Chomutov");
lkp.put(lkpRecord);*/
return lkp;
}
/**
* Creates records with default structure
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefaultMetadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
ret.addField(new DataFieldMetadata("Name", DataFieldType.STRING, "|"));
ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|"));
ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|"));
DataFieldMetadata dateField = new DataFieldMetadata("Born", DataFieldType.DATE, "|");
dateField.setFormatStr("yyyy-MM-dd HH:mm:ss");
ret.addField(dateField);
ret.addField(new DataFieldMetadata("BornMillisec", DataFieldType.LONG, "|"));
ret.addField(new DataFieldMetadata("Value", DataFieldType.INTEGER, "|"));
ret.addField(new DataFieldMetadata("Flag", DataFieldType.BOOLEAN, "|"));
ret.addField(new DataFieldMetadata("ByteArray", DataFieldType.BYTE, "|"));
DataFieldMetadata decimalField = new DataFieldMetadata("Currency", DataFieldType.DECIMAL, "\n");
decimalField.setProperty(DataFieldMetadata.LENGTH_ATTR, String.valueOf(DECIMAL_PRECISION));
decimalField.setProperty(DataFieldMetadata.SCALE_ATTR, String.valueOf(DECIMAL_SCALE));
ret.addField(decimalField);
return ret;
}
/**
* Creates records with default structure
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefault1Metadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
ret.addField(new DataFieldMetadata("Field1", DataFieldType.STRING, "|"));
ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|"));
ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|"));
return ret;
}
/**
* Creates records with default structure
* containing multivalue fields.
*
* @param name
* name for the record to use
* @return metadata with default structure
*/
protected DataRecordMetadata createDefaultMultivalueMetadata(String name) {
DataRecordMetadata ret = new DataRecordMetadata(name);
DataFieldMetadata stringListField = new DataFieldMetadata("stringListField", DataFieldType.STRING, "|");
stringListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(stringListField);
DataFieldMetadata dateField = new DataFieldMetadata("dateField", DataFieldType.DATE, "|");
ret.addField(dateField);
DataFieldMetadata byteField = new DataFieldMetadata("byteField", DataFieldType.BYTE, "|");
ret.addField(byteField);
DataFieldMetadata dateListField = new DataFieldMetadata("dateListField", DataFieldType.DATE, "|");
dateListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(dateListField);
DataFieldMetadata byteListField = new DataFieldMetadata("byteListField", DataFieldType.BYTE, "|");
byteListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(byteListField);
DataFieldMetadata stringField = new DataFieldMetadata("stringField", DataFieldType.STRING, "|");
ret.addField(stringField);
DataFieldMetadata integerMapField = new DataFieldMetadata("integerMapField", DataFieldType.INTEGER, "|");
integerMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(integerMapField);
DataFieldMetadata stringMapField = new DataFieldMetadata("stringMapField", DataFieldType.STRING, "|");
stringMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(stringMapField);
DataFieldMetadata dateMapField = new DataFieldMetadata("dateMapField", DataFieldType.DATE, "|");
dateMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(dateMapField);
DataFieldMetadata byteMapField = new DataFieldMetadata("byteMapField", DataFieldType.BYTE, "|");
byteMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(byteMapField);
DataFieldMetadata integerListField = new DataFieldMetadata("integerListField", DataFieldType.INTEGER, "|");
integerListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(integerListField);
DataFieldMetadata decimalListField = new DataFieldMetadata("decimalListField", DataFieldType.DECIMAL, "|");
decimalListField.setContainerType(DataFieldContainerType.LIST);
ret.addField(decimalListField);
DataFieldMetadata decimalMapField = new DataFieldMetadata("decimalMapField", DataFieldType.DECIMAL, "|");
decimalMapField.setContainerType(DataFieldContainerType.MAP);
ret.addField(decimalMapField);
return ret;
}
protected DataRecord createDefaultMultivalueRecord(DataRecordMetadata dataRecordMetadata) {
final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata);
ret.init();
for (int i = 0; i < ret.getNumFields(); i++) {
DataField field = ret.getField(i);
DataFieldMetadata fieldMetadata = field.getMetadata();
switch (fieldMetadata.getContainerType()) {
case SINGLE:
switch (fieldMetadata.getDataType()) {
case STRING:
field.setValue("John");
break;
case DATE:
field.setValue(new Date(10000));
break;
case BYTE:
field.setValue(new byte[] { 0x12, 0x34, 0x56, 0x78 } );
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
break;
case LIST:
{
List<Object> value = new ArrayList<Object>();
switch (fieldMetadata.getDataType()) {
case STRING:
value.addAll(Arrays.asList("John", "Doe", "Jersey"));
break;
case INTEGER:
value.addAll(Arrays.asList(123, 456, 789));
break;
case DATE:
value.addAll(Arrays.asList(new Date (12000), new Date(34000)));
break;
case BYTE:
value.addAll(Arrays.asList(new byte[] {0x12, 0x34}, new byte[] {0x56, 0x78}));
break;
case DECIMAL:
value.addAll(Arrays.asList(12.34, 56.78));
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
field.setValue(value);
}
break;
case MAP:
{
Map<String, Object> value = new HashMap<String, Object>();
switch (fieldMetadata.getDataType()) {
case STRING:
value.put("firstName", "John");
value.put("lastName", "Doe");
value.put("address", "Jersey");
break;
case INTEGER:
value.put("count", 123);
value.put("max", 456);
value.put("sum", 789);
break;
case DATE:
value.put("before", new Date (12000));
value.put("after", new Date(34000));
break;
case BYTE:
value.put("hash", new byte[] {0x12, 0x34});
value.put("checksum", new byte[] {0x56, 0x78});
break;
case DECIMAL:
value.put("asset", 12.34);
value.put("liability", 56.78);
break;
default:
throw new UnsupportedOperationException("Not implemented.");
}
field.setValue(value);
}
break;
default:
throw new IllegalArgumentException(fieldMetadata.getContainerType().toString());
}
}
return ret;
}
protected DataRecord createDefaultRecord(DataRecordMetadata dataRecordMetadata) {
final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata);
ret.init();
SetVal.setString(ret, "Name", NAME_VALUE);
SetVal.setDouble(ret, "Age", AGE_VALUE);
SetVal.setString(ret, "City", CITY_VALUE);
SetVal.setDate(ret, "Born", BORN_VALUE);
SetVal.setLong(ret, "BornMillisec", BORN_MILLISEC_VALUE);
SetVal.setInt(ret, "Value", VALUE_VALUE);
SetVal.setValue(ret, "Flag", FLAG_VALUE);
SetVal.setValue(ret, "ByteArray", BYTEARRAY_VALUE);
SetVal.setValue(ret, "Currency", CURRENCY_VALUE);
return ret;
}
/**
* Allocates new records with structure prescribed by metadata and sets all its fields to <code>null</code>
*
* @param metadata
* structure to use
* @return empty record
*/
protected DataRecord createEmptyRecord(DataRecordMetadata metadata) {
DataRecord ret = DataRecordFactory.newRecord(metadata);
ret.init();
for (int i = 0; i < ret.getNumFields(); i++) {
SetVal.setNull(ret, i);
}
return ret;
}
/**
* Executes the code using the default graph and records.
*/
protected void doCompile(String expStr, String testIdentifier) {
TransformationGraph graph = createDefaultGraph();
DataRecord[] inRecords = new DataRecord[] { createDefaultRecord(graph.getDataRecordMetadata(INPUT_1)), createDefaultRecord(graph.getDataRecordMetadata(INPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(INPUT_3)), createDefaultMultivalueRecord(graph.getDataRecordMetadata(INPUT_4)) };
DataRecord[] outRecords = new DataRecord[] { createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_1)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_3)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_4)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_5)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_6)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_7)) };
doCompile(expStr, testIdentifier, graph, inRecords, outRecords);
}
/**
* This method should be used to execute a test with a custom graph and custom input and output records.
*
* To execute a test with the default graph,
* use {@link #doCompile(String)}
* or {@link #doCompile(String, String)} instead.
*
* @param expStr
* @param testIdentifier
* @param graph
* @param inRecords
* @param outRecords
*/
protected void doCompile(String expStr, String testIdentifier, TransformationGraph graph, DataRecord[] inRecords, DataRecord[] outRecords) {
this.graph = graph;
this.inputRecords = inRecords;
this.outputRecords = outRecords;
// prepend the compilation mode prefix
if (compileToJava) {
expStr = "//#CTL2:COMPILE\n" + expStr;
}
print_code(expStr);
DataRecordMetadata[] inMetadata = new DataRecordMetadata[inRecords.length];
for (int i = 0; i < inRecords.length; i++) {
inMetadata[i] = inRecords[i].getMetadata();
}
DataRecordMetadata[] outMetadata = new DataRecordMetadata[outRecords.length];
for (int i = 0; i < outRecords.length; i++) {
outMetadata[i] = outRecords[i].getMetadata();
}
ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8");
// try {
// System.out.println(compiler.convertToJava(expStr, CTLRecordTransform.class, testIdentifier));
// } catch (ErrorMessageException e) {
// System.out.println("Error parsing CTL code. Unable to output Java translation.");
List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier);
printMessages(messages);
if (compiler.errorCount() > 0) {
throw new AssertionFailedError("Error in execution. Check standard output for details.");
}
// CLVFStart parseTree = compiler.getStart();
// parseTree.dump("");
executeCode(compiler);
}
protected void doCompileExpectError(String expStr, String testIdentifier, List<String> errCodes) {
graph = createDefaultGraph();
DataRecordMetadata[] inMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(INPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_3) };
DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(OUTPUT_2), graph.getDataRecordMetadata(OUTPUT_3), graph.getDataRecordMetadata(OUTPUT_4) };
// prepend the compilation mode prefix
if (compileToJava) {
expStr = "//#CTL2:COMPILE\n" + expStr;
}
print_code(expStr);
ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8");
List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier);
printMessages(messages);
if (compiler.errorCount() == 0) {
throw new AssertionFailedError("No errors in parsing. Expected " + errCodes.size() + " errors.");
}
if (compiler.errorCount() != errCodes.size()) {
throw new AssertionFailedError(compiler.errorCount() + " errors in code, but expected " + errCodes.size() + " errors.");
}
Iterator<String> it = errCodes.iterator();
for (ErrorMessage errorMessage : compiler.getDiagnosticMessages()) {
String expectedError = it.next();
if (!expectedError.equals(errorMessage.getErrorMessage())) {
throw new AssertionFailedError("Error : \'" + compiler.getDiagnosticMessages().get(0).getErrorMessage() + "\', but expected: \'" + expectedError + "\'");
}
}
// CLVFStart parseTree = compiler.getStart();
// parseTree.dump("");
// executeCode(compiler);
}
protected void doCompileExpectError(String testIdentifier, String errCode) {
doCompileExpectErrors(testIdentifier, Arrays.asList(errCode));
}
protected void doCompileExpectErrors(String testIdentifier, List<String> errCodes) {
URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl");
if (importLoc == null) {
throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found");
}
final StringBuilder sourceCode = new StringBuilder();
String line = null;
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream()));
while ((line = rd.readLine()) != null) {
sourceCode.append(line).append("\n");
}
rd.close();
} catch (IOException e) {
throw new RuntimeException("I/O error occured when reading source file", e);
}
doCompileExpectError(sourceCode.toString(), testIdentifier, errCodes);
}
/**
* Method loads tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should
* be stored in the same directory as this class.
*
* @param Test
* identifier defining CTL file to load code from
*/
protected String loadSourceCode(String testIdentifier) {
URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl");
if (importLoc == null) {
throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found");
}
final StringBuilder sourceCode = new StringBuilder();
String line = null;
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream()));
while ((line = rd.readLine()) != null) {
sourceCode.append(line).append("\n");
}
rd.close();
} catch (IOException e) {
throw new RuntimeException("I/O error occured when reading source file", e);
}
return sourceCode.toString();
}
/**
* Method loads and compiles tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should
* be stored in the same directory as this class.
*
* The default graph and records are used for the execution.
*
* @param Test
* identifier defining CTL file to load code from
*/
protected void doCompile(String testIdentifier) {
String sourceCode = loadSourceCode(testIdentifier);
doCompile(sourceCode, testIdentifier);
}
protected void printMessages(List<ErrorMessage> diagnosticMessages) {
for (ErrorMessage e : diagnosticMessages) {
System.out.println(e);
}
}
/**
* Compares two records if they have the same number of fields and identical values in their fields. Does not
* consider (or examine) metadata.
*
* @param lhs
* @param rhs
* @return true if records have the same number of fields and the same values in them
*/
protected static boolean recordEquals(DataRecord lhs, DataRecord rhs) {
if (lhs == rhs)
return true;
if (rhs == null)
return false;
if (lhs == null) {
return false;
}
if (lhs.getNumFields() != rhs.getNumFields()) {
return false;
}
for (int i = 0; i < lhs.getNumFields(); i++) {
if (lhs.getField(i).isNull()) {
if (!rhs.getField(i).isNull()) {
return false;
}
} else if (!lhs.getField(i).equals(rhs.getField(i))) {
return false;
}
}
return true;
}
public void print_code(String text) {
String[] lines = text.split("\n");
System.out.println("\t: 1 2 3 4 5 ");
System.out.println("\t:12345678901234567890123456789012345678901234567890123456789");
for (int i = 0; i < lines.length; i++) {
System.out.println((i + 1) + "\t:" + lines[i]);
}
}
@SuppressWarnings("unchecked")
public void test_operators_unary_record_allowed() {
doCompile("test_operators_unary_record_allowed");
check("value", Arrays.asList(14, 16, 16, 65, 63, 63));
check("bornMillisec", Arrays.asList(14L, 16L, 16L, 65L, 63L, 63L));
List<Double> actualAge = (List<Double>) getVariable("age");
double[] expectedAge = {14.123, 16.123, 16.123, 65.789, 63.789, 63.789};
for (int i = 0; i < actualAge.size(); i++) {
assertEquals("age[" + i + "]", expectedAge[i], actualAge.get(i), 0.0001);
}
check("currency", Arrays.asList(
new BigDecimal(BigInteger.valueOf(12500), 3),
new BigDecimal(BigInteger.valueOf(14500), 3),
new BigDecimal(BigInteger.valueOf(14500), 3),
new BigDecimal(BigInteger.valueOf(65432), 3),
new BigDecimal(BigInteger.valueOf(63432), 3),
new BigDecimal(BigInteger.valueOf(63432), 3)
));
}
@SuppressWarnings("unchecked")
public void test_dynamic_compare() {
doCompile("test_dynamic_compare");
String varName = "compare";
List<Integer> compareResult = (List<Integer>) getVariable(varName);
for (int i = 0; i < compareResult.size(); i++) {
if ((i % 3) == 0) {
assertTrue(varName + "[" + i + "]", compareResult.get(i) > 0);
} else if ((i % 3) == 1) {
assertEquals(varName + "[" + i + "]", Integer.valueOf(0), compareResult.get(i));
} else if ((i % 3) == 2) {
assertTrue(varName + "[" + i + "]", compareResult.get(i) < 0);
}
}
varName = "compareBooleans";
compareResult = (List<Integer>) getVariable(varName);
assertEquals(varName + "[0]", Integer.valueOf(0), compareResult.get(0));
assertTrue(varName + "[1]", compareResult.get(1) > 0);
assertTrue(varName + "[2]", compareResult.get(2) < 0);
assertEquals(varName + "[3]", Integer.valueOf(0), compareResult.get(3));
}
private void test_dynamic_get_set_loop(String testIdentifier) {
doCompile(testIdentifier);
check("recordLength", 9);
check("value", Arrays.asList(654321, 777777, 654321, 654323, 123456, 112567, 112233));
check("type", Arrays.asList("string", "number", "string", "date", "long", "integer", "boolean", "byte", "decimal"));
check("asString", Arrays.asList("1000", "1001.0", "1002", "Thu Jan 01 01:00:01 CET 1970", "1004", "1005", "true", null, "1008.000"));
check("isNull", Arrays.asList(false, false, false, false, false, false, false, true, false));
check("fieldName", Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency"));
Integer[] indices = new Integer[9];
for (int i = 0; i < indices.length; i++) {
indices[i] = i;
}
check("fieldIndex", Arrays.asList(indices));
// check dynamic write and read with all data types
check("booleanVar", true);
assertTrue("byteVar", Arrays.equals(new BigInteger("1234567890abcdef", 16).toByteArray(), (byte[]) getVariable("byteVar")));
check("decimalVar", new BigDecimal(BigInteger.valueOf(1000125), 3));
check("integerVar", 1000);
check("longVar", 1000000000000L);
check("numberVar", 1000.5);
check("stringVar", "hello");
check("dateVar", new Date(5000));
// null value
Boolean[] someValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(someValue, Boolean.FALSE);
check("someValue", Arrays.asList(someValue));
Boolean[] nullValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(nullValue, Boolean.TRUE);
check("nullValue", Arrays.asList(nullValue));
String[] asString2 = new String[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
check("asString2", Arrays.asList(asString2));
Boolean[] isNull2 = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()];
Arrays.fill(isNull2, Boolean.TRUE);
check("isNull2", Arrays.asList(isNull2));
}
public void test_dynamic_get_set_loop() {
test_dynamic_get_set_loop("test_dynamic_get_set_loop");
}
public void test_dynamic_get_set_loop_alternative() {
test_dynamic_get_set_loop("test_dynamic_get_set_loop_alternative");
}
public void test_dynamic_invalid() {
doCompileExpectErrors("test_dynamic_invalid", Arrays.asList(
"Input record cannot be assigned to",
"Input record cannot be assigned to"
));
}
public void test_return_constants() {
// test case for issue 2257
System.out.println("Return constants test:");
doCompile("test_return_constants");
check("skip", RecordTransform.SKIP);
check("all", RecordTransform.ALL);
check("ok", NORMALIZE_RETURN_OK);
check("stop", RecordTransform.STOP);
}
public void test_raise_error_terminal() {
// test case for issue 2337
doCompile("test_raise_error_terminal");
}
public void test_raise_error_nonliteral() {
// test case for issue CL-2071
doCompile("test_raise_error_nonliteral");
}
public void test_case_unique_check() {
// test case for issue 2515
doCompileExpectErrors("test_case_unique_check", Arrays.asList("Duplicate case", "Duplicate case"));
}
public void test_case_unique_check2() {
// test case for issue 2515
doCompileExpectErrors("test_case_unique_check2", Arrays.asList("Duplicate case", "Duplicate case"));
}
public void test_case_unique_check3() {
doCompileExpectError("test_case_unique_check3", "Default case is already defined");
}
public void test_rvalue_for_append() {
// test case for issue 3956
doCompile("test_rvalue_for_append");
check("a", Arrays.asList("1", "2"));
check("b", Arrays.asList("a", "b", "c"));
check("c", Arrays.asList("1", "2", "a", "b", "c"));
}
public void test_rvalue_for_map_append() {
// test case for issue 3960
doCompile("test_rvalue_for_map_append");
HashMap<Integer, String> map1instance = new HashMap<Integer, String>();
map1instance.put(1, "a");
map1instance.put(2, "b");
HashMap<Integer, String> map2instance = new HashMap<Integer, String>();
map2instance.put(3, "c");
map2instance.put(4, "d");
HashMap<Integer, String> map3instance = new HashMap<Integer, String>();
map3instance.put(1, "a");
map3instance.put(2, "b");
map3instance.put(3, "c");
map3instance.put(4, "d");
check("map1", map1instance);
check("map2", map2instance);
check("map3", map3instance);
}
public void test_global_field_access() {
// test case for issue 3957
doCompileExpectError("test_global_field_access", "Unable to access record field in global scope");
}
public void test_global_scope() {
// test case for issue 5006
doCompile("test_global_scope");
check("len", "Kokon".length());
}
//TODO Implement
/*public void test_new() {
doCompile("test_new");
}*/
public void test_parser() {
System.out.println("\nParser test:");
doCompile("test_parser");
}
public void test_ref_res_import() {
System.out.println("\nSpecial character resolving (import) test:");
URL importLoc = getClass().getSuperclass().getResource("test_ref_res.ctl");
String expStr = "import '" + importLoc + "';\n";
doCompile(expStr, "test_ref_res_import");
}
public void test_ref_res_noimport() {
System.out.println("\nSpecial character resolving (no import) test:");
doCompile("test_ref_res");
}
public void test_import() {
System.out.println("\nImport test:");
URL importLoc = getClass().getSuperclass().getResource("import.ctl");
String expStr = "import '" + importLoc + "';\n";
importLoc = getClass().getSuperclass().getResource("other.ctl");
expStr += "import '" + importLoc + "';\n" +
"integer sumInt;\n" +
"function integer transform() {\n" +
" if (a == 3) {\n" +
" otherImportVar++;\n" +
" }\n" +
" sumInt = sum(a, otherImportVar);\n" +
" return 0;\n" +
"}\n";
doCompile(expStr, "test_import");
}
public void test_scope() throws ComponentNotReadyException, TransformException {
System.out.println("\nMapping test:");
// String expStr =
// "function string computeSomething(int n) {\n" +
// " string s = '';\n" +
// " do {\n" +
// " int i = n--;\n" +
// " s = s + '-' + i;\n" +
// " } while (n > 0)\n" +
// " return s;" +
// "function int transform() {\n" +
// " printErr(computeSomething(10));\n" +
// " return 0;\n" +
URL importLoc = getClass().getSuperclass().getResource("samplecode.ctl");
String expStr = "import '" + importLoc + "';\n";
// "function int getIndexOfOffsetStart(string encodedDate) {\n" +
// "int offsetStart;\n" +
// "int actualLastMinus;\n" +
// "int lastMinus = -1;\n" +
// "if ( index_of(encodedDate, '+') != -1 )\n" +
// " return index_of(encodedDate, '+');\n" +
// "do {\n" +
// " actualLastMinus = index_of(encodedDate, '-', lastMinus+1);\n" +
// " if ( actualLastMinus != -1 )\n" +
// " lastMinus = actualLastMinus;\n" +
// "} while ( actualLastMinus != -1 )\n" +
// "return lastMinus;\n" +
// "function int transform() {\n" +
// " getIndexOfOffsetStart('2009-04-24T08:00:00-05:00');\n" +
// " return 0;\n" +
doCompile(expStr, "test_scope");
}
public void test_type_void() {
doCompileExpectErrors("test_type_void", Arrays.asList("Syntax error on token 'void'",
"Variable 'voidVar' is not declared",
"Variable 'voidVar' is not declared",
"Syntax error on token 'void'"));
}
public void test_type_integer() {
doCompile("test_type_integer");
check("i", 0);
check("j", -1);
check("field", VALUE_VALUE);
checkNull("nullValue");
check("varWithInitializer", 123);
checkNull("varWithNullInitializer");
}
public void test_type_integer_edge() {
String testExpression =
"integer minInt;\n"+
"integer maxInt;\n"+
"function integer transform() {\n" +
"minInt=" + Integer.MIN_VALUE + ";\n" +
"printErr(minInt, true);\n" +
"maxInt=" + Integer.MAX_VALUE + ";\n" +
"printErr(maxInt, true);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_int_edge");
check("minInt", Integer.MIN_VALUE);
check("maxInt", Integer.MAX_VALUE);
}
public void test_type_long() {
doCompile("test_type_long");
check("i", Long.valueOf(0));
check("j", Long.valueOf(-1));
check("field", BORN_MILLISEC_VALUE);
check("def", Long.valueOf(0));
checkNull("nullValue");
check("varWithInitializer", 123L);
checkNull("varWithNullInitializer");
}
public void test_type_long_edge() {
String expStr =
"long minLong;\n"+
"long maxLong;\n"+
"function integer transform() {\n" +
"minLong=" + (Long.MIN_VALUE) + "L;\n" +
"printErr(minLong);\n" +
"maxLong=" + (Long.MAX_VALUE) + "L;\n" +
"printErr(maxLong);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr,"test_long_edge");
check("minLong", Long.MIN_VALUE);
check("maxLong", Long.MAX_VALUE);
}
public void test_type_decimal() {
doCompile("test_type_decimal");
check("i", new BigDecimal(0, MAX_PRECISION));
check("j", new BigDecimal(-1, MAX_PRECISION));
check("field", CURRENCY_VALUE);
check("def", new BigDecimal(0, MAX_PRECISION));
checkNull("nullValue");
check("varWithInitializer", new BigDecimal("123.35", MAX_PRECISION));
checkNull("varWithNullInitializer");
check("varWithInitializerNoDist", new BigDecimal(123.35, MAX_PRECISION));
}
public void test_type_decimal_edge() {
String testExpression =
"decimal minLong;\n"+
"decimal maxLong;\n"+
"decimal minLongNoDist;\n"+
"decimal maxLongNoDist;\n"+
"decimal minDouble;\n"+
"decimal maxDouble;\n"+
"decimal minDoubleNoDist;\n"+
"decimal maxDoubleNoDist;\n"+
"function integer transform() {\n" +
"minLong=" + String.valueOf(Long.MIN_VALUE) + "d;\n" +
"printErr(minLong);\n" +
"maxLong=" + String.valueOf(Long.MAX_VALUE) + "d;\n" +
"printErr(maxLong);\n" +
"minLongNoDist=" + String.valueOf(Long.MIN_VALUE) + "L;\n" +
"printErr(minLongNoDist);\n" +
"maxLongNoDist=" + String.valueOf(Long.MAX_VALUE) + "L;\n" +
"printErr(maxLongNoDist);\n" +
// distincter will cause the double-string be parsed into exact representation within BigDecimal
"minDouble=" + String.valueOf(Double.MIN_VALUE) + "D;\n" +
"printErr(minDouble);\n" +
"maxDouble=" + String.valueOf(Double.MAX_VALUE) + "D;\n" +
"printErr(maxDouble);\n" +
// no distincter will cause the double-string to be parsed into inexact representation within double
// then to be assigned into BigDecimal (which will extract only MAX_PRECISION digits)
"minDoubleNoDist=" + String.valueOf(Double.MIN_VALUE) + ";\n" +
"printErr(minDoubleNoDist);\n" +
"maxDoubleNoDist=" + String.valueOf(Double.MAX_VALUE) + ";\n" +
"printErr(maxDoubleNoDist);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_decimal_edge");
check("minLong", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION));
check("maxLong", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION));
check("minLongNoDist", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION));
check("maxLongNoDist", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION));
// distincter will cause the MIN_VALUE to be parsed into exact representation (i.e. 4.9E-324)
check("minDouble", new BigDecimal(String.valueOf(Double.MIN_VALUE), MAX_PRECISION));
check("maxDouble", new BigDecimal(String.valueOf(Double.MAX_VALUE), MAX_PRECISION));
// no distincter will cause MIN_VALUE to be parsed into double inexact representation and extraction of
// MAX_PRECISION digits (i.e. 4.94065.....E-324)
check("minDoubleNoDist", new BigDecimal(Double.MIN_VALUE, MAX_PRECISION));
check("maxDoubleNoDist", new BigDecimal(Double.MAX_VALUE, MAX_PRECISION));
}
public void test_type_number() {
doCompile("test_type_number");
check("i", Double.valueOf(0));
check("j", Double.valueOf(-1));
check("field", AGE_VALUE);
check("def", Double.valueOf(0));
checkNull("nullValue");
checkNull("varWithNullInitializer");
}
public void test_type_number_edge() {
String testExpression =
"number minDouble;\n" +
"number maxDouble;\n"+
"function integer transform() {\n" +
"minDouble=" + Double.MIN_VALUE + ";\n" +
"printErr(minDouble);\n" +
"maxDouble=" + Double.MAX_VALUE + ";\n" +
"printErr(maxDouble);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_number_edge");
check("minDouble", Double.valueOf(Double.MIN_VALUE));
check("maxDouble", Double.valueOf(Double.MAX_VALUE));
}
public void test_type_string() {
doCompile("test_type_string");
check("i","0");
check("helloEscaped", "hello\\nworld");
check("helloExpanded", "hello\nworld");
check("fieldName", NAME_VALUE);
check("fieldCity", CITY_VALUE);
check("escapeChars", "a\u0101\u0102A");
check("doubleEscapeChars", "a\\u0101\\u0102A");
check("specialChars", "špeciálne značky s mäkčeňom môžu byť");
check("dQescapeChars", "a\u0101\u0102A");
//TODO:Is next test correct?
check("dQdoubleEscapeChars", "a\\u0101\\u0102A");
check("dQspecialChars", "špeciálne značky s mäkčeňom môžu byť");
check("empty", "");
check("def", "");
checkNull("varWithNullInitializer");
}
public void test_type_string_long() {
int length = 1000;
StringBuilder tmp = new StringBuilder(length);
for (int i = 0; i < length; i++) {
tmp.append(i % 10);
}
String testExpression =
"string longString;\n" +
"function integer transform() {\n" +
"longString=\"" + tmp + "\";\n" +
"printErr(longString);\n" +
"return 0;\n" +
"}\n";
doCompile(testExpression, "test_string_long");
check("longString", String.valueOf(tmp));
}
public void test_type_date() throws Exception {
doCompile("test_type_date");
check("d3", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 1).getTime());
check("d2", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3).getTime());
check("d1", new GregorianCalendar(2006, GregorianCalendar.JANUARY, 1, 1, 2, 3).getTime());
check("field", BORN_VALUE);
checkNull("nullValue");
check("minValue", new GregorianCalendar(1970, GregorianCalendar.JANUARY, 1, 1, 0, 0).getTime());
checkNull("varWithNullInitializer");
// test with a default time zone set on the GraphRuntimeContext
Context context = null;
try {
tearDown();
setUp();
TransformationGraph graph = new TransformationGraph();
graph.getRuntimeContext().setTimeZone("GMT+8");
context = ContextProvider.registerGraph(graph);
doCompile("test_type_date");
Calendar calendar = new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3);
calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
check("d2", calendar.getTime());
calendar.set(2006, 0, 1, 1, 2, 3);
check("d1", calendar.getTime());
} finally {
ContextProvider.unregister(context);
}
}
public void test_type_boolean() {
doCompile("test_type_boolean");
check("b1", true);
check("b2", false);
check("b3", false);
checkNull("nullValue");
checkNull("varWithNullInitializer");
}
public void test_type_boolean_compare() {
doCompileExpectErrors("test_type_boolean_compare", Arrays.asList(
"Operator '>' is not defined for types 'boolean' and 'boolean'",
"Operator '>=' is not defined for types 'boolean' and 'boolean'",
"Operator '<' is not defined for types 'boolean' and 'boolean'",
"Operator '<=' is not defined for types 'boolean' and 'boolean'",
"Operator '<' is not defined for types 'boolean' and 'boolean'",
"Operator '>' is not defined for types 'boolean' and 'boolean'",
"Operator '>=' is not defined for types 'boolean' and 'boolean'",
"Operator '<=' is not defined for types 'boolean' and 'boolean'"));
}
public void test_type_list() {
doCompile("test_type_list");
check("intList", Arrays.asList(1, 2, 3, 4, 5, 6));
check("intList2", Arrays.asList(1, 2, 3));
check("stringList", Arrays.asList(
"first", "replaced", "third", "fourth",
"fifth", "sixth", "extra"));
check("stringListCopy", Arrays.asList(
"first", "second", "third", "fourth",
"fifth", "seventh"));
check("stringListCopy2", Arrays.asList(
"first", "replaced", "third", "fourth",
"fifth", "sixth", "extra"));
assertTrue(getVariable("stringList") != getVariable("stringListCopy"));
assertEquals(getVariable("stringList"), getVariable("stringListCopy2"));
assertEquals(Arrays.asList(false, null, true), getVariable("booleanList"));
assertDeepEquals(Arrays.asList(new byte[] {(byte) 0xAB}, null), getVariable("byteList"));
assertDeepEquals(Arrays.asList(null, new byte[] {(byte) 0xCD}), getVariable("cbyteList"));
assertEquals(Arrays.asList(new Date(12000), null, new Date(34000)), getVariable("dateList"));
assertEquals(Arrays.asList(null, new BigDecimal(BigInteger.valueOf(1234), 2)), getVariable("decimalList"));
assertEquals(Arrays.asList(12, null, 34), getVariable("intList3"));
assertEquals(Arrays.asList(12l, null, 98l), getVariable("longList"));
assertEquals(Arrays.asList(12.34, null, 56.78), getVariable("numberList"));
assertEquals(Arrays.asList("aa", null, "bb"), getVariable("stringList2"));
List<?> decimalList2 = (List<?>) getVariable("decimalList2");
for (Object o: decimalList2) {
assertTrue(o instanceof BigDecimal);
}
List<?> intList4 = (List<?>) getVariable("intList4");
Set<Object> intList4Set = new HashSet<Object>(intList4);
assertEquals(3, intList4Set.size());
}
public void test_type_list_field() {
doCompile("test_type_list_field");
check("copyByValueTest1", "2");
check("copyByValueTest2", "test");
}
public void test_type_map_field() {
doCompile("test_type_map_field");
Integer copyByValueTest1 = (Integer) getVariable("copyByValueTest1");
assertEquals(new Integer(2), copyByValueTest1);
Integer copyByValueTest2 = (Integer) getVariable("copyByValueTest2");
assertEquals(new Integer(100), copyByValueTest2);
}
/**
* The structure of the objects must be exactly the same!
*
* @param o1
* @param o2
*/
private static void assertDeepCopy(Object o1, Object o2) {
if (o1 instanceof DataRecord) {
assertFalse(o1 == o2);
DataRecord r1 = (DataRecord) o1;
DataRecord r2 = (DataRecord) o2;
for (int i = 0; i < r1.getNumFields(); i++) {
assertDeepCopy(r1.getField(i).getValue(), r2.getField(i).getValue());
}
} else if (o1 instanceof Map) {
assertFalse(o1 == o2);
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
for (Object key: m1.keySet()) {
assertDeepCopy(m1.get(key), m2.get(key));
}
} else if (o1 instanceof List) {
assertFalse(o1 == o2);
List<?> l1 = (List<?>) o1;
List<?> l2 = (List<?>) o2;
for (int i = 0; i < l1.size(); i++) {
assertDeepCopy(l1.get(i), l2.get(i));
}
} else if (o1 instanceof Date) {
assertFalse(o1 == o2);
// } else if (o1 instanceof byte[]) { // not required anymore
// assertFalse(o1 == o2);
}
}
/**
* The structure of the objects must be exactly the same!
*
* @param o1
* @param o2
*/
private static void assertDeepEquals(Object o1, Object o2) {
if ((o1 == null) && (o2 == null)) {
return;
}
assertTrue((o1 == null) == (o2 == null));
if (o1 instanceof DataRecord) {
DataRecord r1 = (DataRecord) o1;
DataRecord r2 = (DataRecord) o2;
assertEquals(r1.getNumFields(), r2.getNumFields());
for (int i = 0; i < r1.getNumFields(); i++) {
assertDeepEquals(r1.getField(i).getValue(), r2.getField(i).getValue());
}
} else if (o1 instanceof Map) {
Map<?, ?> m1 = (Map<?, ?>) o1;
Map<?, ?> m2 = (Map<?, ?>) o2;
assertTrue(m1.keySet().equals(m2.keySet()));
for (Object key: m1.keySet()) {
assertDeepEquals(m1.get(key), m2.get(key));
}
} else if (o1 instanceof List) {
List<?> l1 = (List<?>) o1;
List<?> l2 = (List<?>) o2;
assertEquals("size", l1.size(), l2.size());
for (int i = 0; i < l1.size(); i++) {
assertDeepEquals(l1.get(i), l2.get(i));
}
} else if (o1 instanceof byte[]) {
byte[] b1 = (byte[]) o1;
byte[] b2 = (byte[]) o2;
if (b1 != b2) {
if (b1 == null || b2 == null) {
assertEquals(b1, b2);
}
assertEquals("length", b1.length, b2.length);
for (int i = 0; i < b1.length; i++) {
assertEquals(String.format("[%d]", i), b1[i], b2[i]);
}
}
} else if (o1 instanceof CharSequence) {
String s1 = ((CharSequence) o1).toString();
String s2 = ((CharSequence) o2).toString();
assertEquals(s1, s2);
} else if ((o1 instanceof Decimal) || (o1 instanceof BigDecimal)) {
BigDecimal d1 = o1 instanceof Decimal ? ((Decimal) o1).getBigDecimalOutput() : (BigDecimal) o1;
BigDecimal d2 = o2 instanceof Decimal ? ((Decimal) o2).getBigDecimalOutput() : (BigDecimal) o2;
assertEquals(d1, d2);
} else {
assertEquals(o1, o2);
}
}
private void check_assignment_deepcopy_variable_declaration() {
Date testVariableDeclarationDate1 = (Date) getVariable("testVariableDeclarationDate1");
Date testVariableDeclarationDate2 = (Date) getVariable("testVariableDeclarationDate2");
byte[] testVariableDeclarationByte1 = (byte[]) getVariable("testVariableDeclarationByte1");
byte[] testVariableDeclarationByte2 = (byte[]) getVariable("testVariableDeclarationByte2");
assertDeepEquals(testVariableDeclarationDate1, testVariableDeclarationDate2);
assertDeepEquals(testVariableDeclarationByte1, testVariableDeclarationByte2);
assertDeepCopy(testVariableDeclarationDate1, testVariableDeclarationDate2);
assertDeepCopy(testVariableDeclarationByte1, testVariableDeclarationByte2);
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_array_access_expression() {
{
// JJTARRAYACCESSEXPRESSION - List
List<String> stringListField1 = (List<String>) getVariable("stringListField1");
DataRecord recordInList1 = (DataRecord) getVariable("recordInList1");
List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1");
List<DataRecord> recordList2 = (List<DataRecord>) getVariable("recordList2");
assertDeepEquals(stringListField1, recordInList1.getField("stringListField").getValue());
assertDeepEquals(recordInList1, recordList1.get(0));
assertDeepEquals(recordList1, recordList2);
assertDeepCopy(stringListField1, recordInList1.getField("stringListField").getValue());
assertDeepCopy(recordInList1, recordList1.get(0));
assertDeepCopy(recordList1, recordList2);
}
{
// map of records
Date testDate1 = (Date) getVariable("testDate1");
Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1");
DataRecord recordInMap1 = (DataRecord) getVariable("recordInMap1");
DataRecord recordInMap2 = (DataRecord) getVariable("recordInMap2");
Map<Integer, DataRecord> recordMap2 = (Map<Integer, DataRecord>) getVariable("recordMap2");
assertDeepEquals(testDate1, recordInMap1.getField("dateField").getValue());
assertDeepEquals(recordInMap1, recordMap1.get(0));
assertDeepEquals(recordInMap2, recordMap1.get(0));
assertDeepEquals(recordMap1, recordMap2);
assertDeepCopy(testDate1, recordInMap1.getField("dateField").getValue());
assertDeepCopy(recordInMap1, recordMap1.get(0));
assertDeepCopy(recordInMap2, recordMap1.get(0));
assertDeepCopy(recordMap1, recordMap2);
}
{
// map of dates
Map<Integer, Date> dateMap1 = (Map<Integer, Date>) getVariable("dateMap1");
Date date1 = (Date) getVariable("date1");
Date date2 = (Date) getVariable("date2");
assertDeepCopy(date1, dateMap1.get(0));
assertDeepCopy(date2, dateMap1.get(1));
}
{
// map of byte arrays
Map<Integer, byte[]> byteMap1 = (Map<Integer, byte[]>) getVariable("byteMap1");
byte[] byte1 = (byte[]) getVariable("byte1");
byte[] byte2 = (byte[]) getVariable("byte2");
assertDeepCopy(byte1, byteMap1.get(0));
assertDeepCopy(byte2, byteMap1.get(1));
}
{
// JJTARRAYACCESSEXPRESSION - Function call
List<String> testArrayAccessFunctionCallStringList = (List<String>) getVariable("testArrayAccessFunctionCallStringList");
DataRecord testArrayAccessFunctionCall = (DataRecord) getVariable("testArrayAccessFunctionCall");
Map<String, DataRecord> function_call_original_map = (Map<String, DataRecord>) getVariable("function_call_original_map");
Map<String, DataRecord> function_call_copied_map = (Map<String, DataRecord>) getVariable("function_call_copied_map");
List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list");
List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list");
assertDeepEquals(testArrayAccessFunctionCallStringList, testArrayAccessFunctionCall.getField("stringListField").getValue());
assertEquals(1, function_call_original_map.size());
assertEquals(2, function_call_copied_map.size());
assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall), function_call_original_list);
assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall, testArrayAccessFunctionCall), function_call_copied_list);
assertDeepEquals(testArrayAccessFunctionCall, function_call_original_map.get("1"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("1"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("2"));
assertDeepEquals(testArrayAccessFunctionCall, function_call_original_list.get(1));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(1));
assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(2));
assertDeepCopy(testArrayAccessFunctionCall, function_call_original_map.get("1"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("1"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("2"));
assertDeepCopy(testArrayAccessFunctionCall, function_call_original_list.get(1));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(1));
assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(2));
}
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_field_access_expression() {
// field access
Date testFieldAccessDate1 = (Date) getVariable("testFieldAccessDate1");
String testFieldAccessString1 = (String) getVariable("testFieldAccessString1");
List<Date> testFieldAccessDateList1 = (List<Date>) getVariable("testFieldAccessDateList1");
List<String> testFieldAccessStringList1 = (List<String>) getVariable("testFieldAccessStringList1");
Map<String, Date> testFieldAccessDateMap1 = (Map<String, Date>) getVariable("testFieldAccessDateMap1");
Map<String, String> testFieldAccessStringMap1 = (Map<String, String>) getVariable("testFieldAccessStringMap1");
DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
assertDeepEquals(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue());
assertDeepEquals(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0));
assertDeepEquals(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0));
assertDeepEquals(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first"));
assertDeepEquals(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first"));
assertDeepEquals(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue());
assertDeepEquals(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue());
assertDeepEquals(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue());
assertDeepEquals(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue());
assertDeepEquals(testFieldAccessRecord1, thirdMultivalueOutput);
assertDeepCopy(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue());
assertDeepCopy(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0));
assertDeepCopy(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0));
assertDeepCopy(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first"));
assertDeepCopy(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first"));
assertDeepCopy(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue());
assertDeepCopy(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue());
assertDeepCopy(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue());
assertDeepCopy(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue());
assertDeepCopy(testFieldAccessRecord1, thirdMultivalueOutput);
}
@SuppressWarnings("unchecked")
private void check_assignment_deepcopy_member_access_expression() {
{
// member access - record
Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1");
byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1");
List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1");
List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1");
DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1");
DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
}
{
// member access - record
Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1");
byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1");
List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1");
List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1");
DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1");
DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2");
DataRecord testMemberAccessRecord3 = (DataRecord) getVariable("testMemberAccessRecord3");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecord3, testMemberAccessRecord2);
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecord3, testMemberAccessRecord2);
// dictionary
Date dictionaryDate = (Date) graph.getDictionary().getEntry("a").getValue();
byte[] dictionaryByte = (byte[]) graph.getDictionary().getEntry("y").getValue();
List<String> testMemberAccessStringList1 = (List<String>) getVariable("testMemberAccessStringList1");
List<Date> testMemberAccessDateList2 = (List<Date>) getVariable("testMemberAccessDateList2");
List<byte[]> testMemberAccessByteList2 = (List<byte[]>) getVariable("testMemberAccessByteList2");
List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList");
List<Date> dictionaryDateList = (List<Date>) graph.getDictionary().getValue("dateList");
List<byte[]> dictionaryByteList = (List<byte[]>) graph.getDictionary().getValue("byteList");
assertDeepEquals(dictionaryDate, testMemberAccessDate1);
assertDeepEquals(dictionaryByte, testMemberAccessByte1);
assertDeepEquals(dictionaryStringList, testMemberAccessStringList1);
assertDeepEquals(dictionaryDateList, testMemberAccessDateList2);
assertDeepEquals(dictionaryByteList, testMemberAccessByteList2);
assertDeepCopy(dictionaryDate, testMemberAccessDate1);
assertDeepCopy(dictionaryByte, testMemberAccessByte1);
assertDeepCopy(dictionaryStringList, testMemberAccessStringList1);
assertDeepCopy(dictionaryDateList, testMemberAccessDateList2);
assertDeepCopy(dictionaryByteList, testMemberAccessByteList2);
// member access - array of records
List<DataRecord> testMemberAccessRecordList1 = (List<DataRecord>) getVariable("testMemberAccessRecordList1");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2));
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2));
// member access - map of records
Map<Integer, DataRecord> testMemberAccessRecordMap1 = (Map<Integer, DataRecord>) getVariable("testMemberAccessRecordMap1");
assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue());
assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue());
assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0));
assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0));
assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue());
assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue());
assertDeepEquals(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2));
assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue());
assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue());
assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0));
assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0));
assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue());
assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue());
assertDeepCopy(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2));
}
}
@SuppressWarnings("unchecked")
public void test_assignment_deepcopy() {
doCompile("test_assignment_deepcopy");
List<DataRecord> secondRecordList = (List<DataRecord>) getVariable("secondRecordList");
assertEquals("before", secondRecordList.get(0).getField("Name").getValue().toString());
List<DataRecord> firstRecordList = (List<DataRecord>) getVariable("firstRecordList");
assertEquals("after", firstRecordList.get(0).getField("Name").getValue().toString());
check_assignment_deepcopy_variable_declaration();
check_assignment_deepcopy_array_access_expression();
check_assignment_deepcopy_field_access_expression();
check_assignment_deepcopy_member_access_expression();
}
public void test_assignment_deepcopy_field_access_expression() {
doCompile("test_assignment_deepcopy_field_access_expression");
DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
DataRecord multivalueInput = inputRecords[3];
assertDeepEquals(firstMultivalueOutput, testFieldAccessRecord1);
assertDeepEquals(secondMultivalueOutput, multivalueInput);
assertDeepEquals(thirdMultivalueOutput, secondMultivalueOutput);
assertDeepCopy(firstMultivalueOutput, testFieldAccessRecord1);
assertDeepCopy(secondMultivalueOutput, multivalueInput);
assertDeepCopy(thirdMultivalueOutput, secondMultivalueOutput);
}
public void test_assignment_array_access_function_call() {
doCompile("test_assignment_array_access_function_call");
Map<String, String> originalMap = new HashMap<String, String>();
originalMap.put("a", "b");
Map<String, String> copiedMap = new HashMap<String, String>(originalMap);
copiedMap.put("c", "d");
check("originalMap", originalMap);
check("copiedMap", copiedMap);
}
public void test_assignment_array_access_function_call_wrong_type() {
doCompileExpectErrors("test_assignment_array_access_function_call_wrong_type",
Arrays.asList(
"Expression is not a composite type but is resolved to 'string'",
"Type mismatch: cannot convert from 'integer' to 'string'",
"Cannot convert from 'integer' to string"
));
}
@SuppressWarnings("unchecked")
public void test_assignment_returnvalue() {
doCompile("test_assignment_returnvalue");
{
List<String> stringList1 = (List<String>) getVariable("stringList1");
List<String> stringList2 = (List<String>) getVariable("stringList2");
List<String> stringList3 = (List<String>) getVariable("stringList3");
List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1");
Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1");
List<String> stringList4 = (List<String>) getVariable("stringList4");
Map<String, Integer> integerMap1 = (Map<String, Integer>) getVariable("integerMap1");
DataRecord record1 = (DataRecord) getVariable("record1");
DataRecord record2 = (DataRecord) getVariable("record2");
DataRecord firstMultivalueOutput = outputRecords[4];
DataRecord secondMultivalueOutput = outputRecords[5];
DataRecord thirdMultivalueOutput = outputRecords[6];
Date dictionaryDate1 = (Date) getVariable("dictionaryDate1");
Date dictionaryDate = (Date) graph.getDictionary().getValue("a");
Date zeroDate = new Date(0);
List<String> testReturnValueDictionary2 = (List<String>) getVariable("testReturnValueDictionary2");
List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList");
List<String> testReturnValue10 = (List<String>) getVariable("testReturnValue10");
DataRecord testReturnValue11 = (DataRecord) getVariable("testReturnValue11");
List<String> testReturnValue12 = (List<String>) getVariable("testReturnValue12");
List<String> testReturnValue13 = (List<String>) getVariable("testReturnValue13");
Map<Integer, DataRecord> function_call_original_map = (Map<Integer, DataRecord>) getVariable("function_call_original_map");
Map<Integer, DataRecord> function_call_copied_map = (Map<Integer, DataRecord>) getVariable("function_call_copied_map");
DataRecord function_call_map_newrecord = (DataRecord) getVariable("function_call_map_newrecord");
List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list");
List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list");
DataRecord function_call_list_newrecord = (DataRecord) getVariable("function_call_list_newrecord");
// identifier
assertFalse(stringList1.isEmpty());
assertTrue(stringList2.isEmpty());
assertTrue(stringList3.isEmpty());
// array access expression - list
assertDeepEquals("unmodified", recordList1.get(0).getField("stringField").getValue());
assertDeepEquals("modified", recordList1.get(1).getField("stringField").getValue());
// array access expression - map
assertDeepEquals("unmodified", recordMap1.get(0).getField("stringField").getValue());
assertDeepEquals("modified", recordMap1.get(1).getField("stringField").getValue());
// array access expression - function call
assertDeepEquals(null, function_call_original_map.get(2));
assertDeepEquals("unmodified", function_call_map_newrecord.getField("stringField"));
assertDeepEquals("modified", function_call_copied_map.get(2).getField("stringField"));
assertDeepEquals(Arrays.asList(null, function_call_list_newrecord), function_call_original_list);
assertDeepEquals("unmodified", function_call_list_newrecord.getField("stringField"));
assertDeepEquals("modified", function_call_copied_list.get(2).getField("stringField"));
// field access expression
assertFalse(stringList4.isEmpty());
assertTrue(((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).isEmpty());
assertFalse(integerMap1.isEmpty());
assertTrue(((Map<?, ?>) firstMultivalueOutput.getField("integerMapField").getValue()).isEmpty());
assertDeepEquals("unmodified", record1.getField("stringField"));
assertDeepEquals("modified", secondMultivalueOutput.getField("stringField").getValue());
assertDeepEquals("unmodified", record2.getField("stringField"));
assertDeepEquals("modified", thirdMultivalueOutput.getField("stringField").getValue());
// member access expression - dictionary
// There is no function that could modify a date
// assertEquals(zeroDate, dictionaryDate);
// assertFalse(zeroDate.equals(testReturnValueDictionary1));
assertFalse(testReturnValueDictionary2.isEmpty());
assertTrue(dictionaryStringList.isEmpty());
// member access expression - record
assertFalse(testReturnValue10.isEmpty());
assertTrue(((List<?>) testReturnValue11.getField("stringListField").getValue()).isEmpty());
// member access expression - list of records
assertFalse(testReturnValue12.isEmpty());
assertTrue(((List<?>) recordList1.get(2).getField("stringListField").getValue()).isEmpty());
// member access expression - map of records
assertFalse(testReturnValue13.isEmpty());
assertTrue(((List<?>) recordMap1.get(2).getField("stringListField").getValue()).isEmpty());
}
}
@SuppressWarnings("unchecked")
public void test_type_map() {
doCompile("test_type_map");
Map<String, Integer> testMap = (Map<String, Integer>) getVariable("testMap");
assertEquals(Integer.valueOf(1), testMap.get("zero"));
assertEquals(Integer.valueOf(2), testMap.get("one"));
assertEquals(Integer.valueOf(3), testMap.get("two"));
assertEquals(Integer.valueOf(4), testMap.get("three"));
assertEquals(4, testMap.size());
Map<Date, String> dayInWeek = (Map<Date, String>) getVariable("dayInWeek");
Calendar c = Calendar.getInstance();
c.set(2009, Calendar.MARCH, 2, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Monday", dayInWeek.get(c.getTime()));
Map<Date, String> dayInWeekCopy = (Map<Date, String>) getVariable("dayInWeekCopy");
c.set(2009, Calendar.MARCH, 3, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Tuesday", ((Map<Date, String>) getVariable("tuesday")).get(c.getTime()));
assertEquals("Tuesday", dayInWeekCopy.get(c.getTime()));
c.set(2009, Calendar.MARCH, 4, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
assertEquals("Wednesday", ((Map<Date, String>) getVariable("wednesday")).get(c.getTime()));
assertEquals("Wednesday", dayInWeekCopy.get(c.getTime()));
assertFalse(dayInWeek.equals(dayInWeekCopy));
{
Map<?, ?> preservedOrder = (Map<?, ?>) getVariable("preservedOrder");
assertEquals(100, preservedOrder.size());
int i = 0;
for (Map.Entry<?, ?> entry: preservedOrder.entrySet()) {
assertEquals("key" + i, entry.getKey());
assertEquals("value" + i, entry.getValue());
i++;
}
}
}
public void test_type_record_list() {
doCompile("test_type_record_list");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_list_global() {
doCompile("test_type_record_list_global");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_map() {
doCompile("test_type_record_map");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record_map_global() {
doCompile("test_type_record_map_global");
check("resultInt", 6);
check("resultString", "string");
check("resultInt2", 10);
check("resultString2", "string2");
}
public void test_type_record() {
doCompile("test_type_record");
// expected result
DataRecord expected = createDefaultRecord(createDefaultMetadata("expected"));
// simple copy
assertTrue(recordEquals(expected, inputRecords[0]));
assertTrue(recordEquals(expected, (DataRecord) getVariable("copy")));
// copy and modify
expected.getField("Name").setValue("empty");
expected.getField("Value").setValue(321);
Calendar c = Calendar.getInstance();
c.set(1987, Calendar.NOVEMBER, 13, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
expected.getField("Born").setValue(c.getTime());
assertTrue(recordEquals(expected, (DataRecord) getVariable("modified")));
// 2x modified copy
expected.getField("Name").setValue("not empty");
assertTrue(recordEquals(expected, (DataRecord)getVariable("modified2")));
// no modification by reference is possible
assertTrue(recordEquals(expected, (DataRecord)getVariable("modified3")));
expected.getField("Value").setValue(654321);
assertTrue(recordEquals(expected, (DataRecord)getVariable("reference")));
assertTrue(getVariable("modified3") != getVariable("reference"));
// output record
assertTrue(recordEquals(expected, outputRecords[1]));
// null record
expected.setToNull();
assertTrue(recordEquals(expected, (DataRecord)getVariable("nullRecord")));
}
public void test_variables() {
doCompile("test_variables");
check("b1", true);
check("b2", true);
check("b4", "hi");
check("i", 2);
}
public void test_operator_plus() {
doCompile("test_operator_plus");
check("iplusj", 10 + 100);
check("lplusm", Long.valueOf(Integer.MAX_VALUE) + Long.valueOf(Integer.MAX_VALUE / 10));
check("mplusl", getVariable("lplusm"));
check("mplusi", Long.valueOf(Integer.MAX_VALUE) + 10);
check("iplusm", getVariable("mplusi"));
check("nplusm1", Double.valueOf(0.1D + 0.001D));
check("nplusj", Double.valueOf(100 + 0.1D));
check("jplusn", getVariable("nplusj"));
check("m1plusm", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) + 0.001d));
check("mplusm1", getVariable("m1plusm"));
check("dplusd1", new BigDecimal("0.1", MAX_PRECISION).add(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dplusj", new BigDecimal(100, MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("jplusd", getVariable("dplusj"));
check("dplusm", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("mplusd", getVariable("dplusm"));
check("dplusn", new BigDecimal("0.1").add(new BigDecimal(0.1D, MAX_PRECISION)));
check("nplusd", getVariable("dplusn"));
check("spluss1", "hello world");
check("splusj", "hello100");
check("jpluss", "100hello");
check("splusm", "hello" + Long.valueOf(Integer.MAX_VALUE));
check("mpluss", Long.valueOf(Integer.MAX_VALUE) + "hello");
check("splusm1", "hello" + Double.valueOf(0.001D));
check("m1pluss", Double.valueOf(0.001D) + "hello");
check("splusd1", "hello" + new BigDecimal("0.0001"));
check("d1pluss", new BigDecimal("0.0001", MAX_PRECISION) + "hello");
}
public void test_operator_minus() {
doCompile("test_operator_minus");
check("iminusj", 10 - 100);
check("lminusm", Long.valueOf(Integer.MAX_VALUE / 10) - Long.valueOf(Integer.MAX_VALUE));
check("mminusi", Long.valueOf(Integer.MAX_VALUE - 10));
check("iminusm", 10 - Long.valueOf(Integer.MAX_VALUE));
check("nminusm1", Double.valueOf(0.1D - 0.001D));
check("nminusj", Double.valueOf(0.1D - 100));
check("jminusn", Double.valueOf(100 - 0.1D));
check("m1minusm", Double.valueOf(0.001D - Long.valueOf(Integer.MAX_VALUE)));
check("mminusm1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) - 0.001D));
check("dminusd1", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dminusj", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jminusd", new BigDecimal(100, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dminusm", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mminusd", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dminusn", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("nminusd", new BigDecimal(0.1D, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operator_multiply() {
doCompile("test_operator_multiply");
check("itimesj", 10 * 100);
check("ltimesm", Long.valueOf(Integer.MAX_VALUE) * (Long.valueOf(Integer.MAX_VALUE / 10)));
check("mtimesl", getVariable("ltimesm"));
check("mtimesi", Long.valueOf(Integer.MAX_VALUE) * 10);
check("itimesm", getVariable("mtimesi"));
check("ntimesm1", Double.valueOf(0.1D * 0.001D));
check("ntimesj", Double.valueOf(0.1) * 100);
check("jtimesn", getVariable("ntimesj"));
check("m1timesm", Double.valueOf(0.001d * Long.valueOf(Integer.MAX_VALUE)));
check("mtimesm1", getVariable("m1timesm"));
check("dtimesd1", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dtimesj", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(100, MAX_PRECISION)));
check("jtimesd", getVariable("dtimesj"));
check("dtimesm", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mtimesd", getVariable("dtimesm"));
check("dtimesn", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(0.1, MAX_PRECISION), MAX_PRECISION));
check("ntimesd", getVariable("dtimesn"));
}
public void test_operator_divide() {
doCompile("test_operator_divide");
check("idividej", 10 / 100);
check("ldividem", Long.valueOf(Integer.MAX_VALUE / 10) / Long.valueOf(Integer.MAX_VALUE));
check("mdividei", Long.valueOf(Integer.MAX_VALUE / 10));
check("idividem", 10 / Long.valueOf(Integer.MAX_VALUE));
check("ndividem1", Double.valueOf(0.1D / 0.001D));
check("ndividej", Double.valueOf(0.1D / 100));
check("jdividen", Double.valueOf(100 / 0.1D));
check("m1dividem", Double.valueOf(0.001D / Long.valueOf(Integer.MAX_VALUE)));
check("mdividem1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) / 0.001D));
check("ddivided1", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("ddividej", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jdivided", new BigDecimal(100, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("ddividem", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mdivided", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("ddividen", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("ndivided", new BigDecimal(0.1D, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operator_modulus() {
doCompile("test_operator_modulus");
check("imoduloj", 10 % 100);
check("lmodulom", Long.valueOf(Integer.MAX_VALUE / 10) % Long.valueOf(Integer.MAX_VALUE));
check("mmoduloi", Long.valueOf(Integer.MAX_VALUE % 10));
check("imodulom", 10 % Long.valueOf(Integer.MAX_VALUE));
check("nmodulom1", Double.valueOf(0.1D % 0.001D));
check("nmoduloj", Double.valueOf(0.1D % 100));
check("jmodulon", Double.valueOf(100 % 0.1D));
check("m1modulom", Double.valueOf(0.001D % Long.valueOf(Integer.MAX_VALUE)));
check("mmodulom1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) % 0.001D));
check("dmodulod1", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION));
check("dmoduloj", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION));
check("jmodulod", new BigDecimal(100, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dmodulom", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION));
check("mmodulod", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
check("dmodulon", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION));
check("nmodulod", new BigDecimal(0.1D, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION));
}
public void test_operators_unary() {
doCompile("test_operators_unary");
// postfix operators
// int
check("intPlusOrig", Integer.valueOf(10));
check("intPlusPlus", Integer.valueOf(10));
check("intPlus", Integer.valueOf(11));
check("intMinusOrig", Integer.valueOf(10));
check("intMinusMinus", Integer.valueOf(10));
check("intMinus", Integer.valueOf(9));
// long
check("longPlusOrig", Long.valueOf(10));
check("longPlusPlus", Long.valueOf(10));
check("longPlus", Long.valueOf(11));
check("longMinusOrig", Long.valueOf(10));
check("longMinusMinus", Long.valueOf(10));
check("longMinus", Long.valueOf(9));
// double
check("numberPlusOrig", Double.valueOf(10.1));
check("numberPlusPlus", Double.valueOf(10.1));
check("numberPlus", Double.valueOf(11.1));
check("numberMinusOrig", Double.valueOf(10.1));
check("numberMinusMinus", Double.valueOf(10.1));
check("numberMinus", Double.valueOf(9.1));
// decimal
check("decimalPlusOrig", new BigDecimal("10.1"));
check("decimalPlusPlus", new BigDecimal("10.1"));
check("decimalPlus", new BigDecimal("11.1"));
check("decimalMinusOrig", new BigDecimal("10.1"));
check("decimalMinusMinus", new BigDecimal("10.1"));
check("decimalMinus", new BigDecimal("9.1"));
// prefix operators
// integer
check("plusIntOrig", Integer.valueOf(10));
check("plusPlusInt", Integer.valueOf(11));
check("plusInt", Integer.valueOf(11));
check("minusIntOrig", Integer.valueOf(10));
check("minusMinusInt", Integer.valueOf(9));
check("minusInt", Integer.valueOf(9));
check("unaryInt", Integer.valueOf(-10));
// long
check("plusLongOrig", Long.valueOf(10));
check("plusPlusLong", Long.valueOf(11));
check("plusLong", Long.valueOf(11));
check("minusLongOrig", Long.valueOf(10));
check("minusMinusLong", Long.valueOf(9));
check("minusLong", Long.valueOf(9));
check("unaryLong", Long.valueOf(-10));
// double
check("plusNumberOrig", Double.valueOf(10.1));
check("plusPlusNumber", Double.valueOf(11.1));
check("plusNumber", Double.valueOf(11.1));
check("minusNumberOrig", Double.valueOf(10.1));
check("minusMinusNumber", Double.valueOf(9.1));
check("minusNumber", Double.valueOf(9.1));
check("unaryNumber", Double.valueOf(-10.1));
// decimal
check("plusDecimalOrig", new BigDecimal("10.1"));
check("plusPlusDecimal", new BigDecimal("11.1"));
check("plusDecimal", new BigDecimal("11.1"));
check("minusDecimalOrig", new BigDecimal("10.1"));
check("minusMinusDecimal", new BigDecimal("9.1"));
check("minusDecimal", new BigDecimal("9.1"));
check("unaryDecimal", new BigDecimal("-10.1"));
// record values
assertEquals(101, ((DataRecord) getVariable("plusPlusRecord")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("recordPlusPlus")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("modifiedPlusPlusRecord")).getField("Value").getValue());
assertEquals(101, ((DataRecord) getVariable("modifiedRecordPlusPlus")).getField("Value").getValue());
//record as parameter
assertEquals(99, ((DataRecord) getVariable("minusMinusRecord")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("recordMinusMinus")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("modifiedMinusMinusRecord")).getField("Value").getValue());
assertEquals(99, ((DataRecord) getVariable("modifiedRecordMinusMinus")).getField("Value").getValue());
// logical not
check("booleanValue", true);
check("negation", false);
check("doubleNegation", true);
}
public void test_operators_unary_record() {
doCompileExpectErrors("test_operators_unary_record", Arrays.asList(
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Illegal argument to ++/-- operator",
"Input record cannot be assigned to",
"Input record cannot be assigned to",
"Input record cannot be assigned to",
"Input record cannot be assigned to"
));
}
public void test_operator_equal() {
doCompile("test_operator_equal");
check("eq0", true);
check("eq1", true);
check("eq1a", true);
check("eq1b", true);
check("eq1c", false);
check("eq2", true);
check("eq3", true);
check("eq4", true);
check("eq5", true);
check("eq6", false);
check("eq7", true);
check("eq8", false);
check("eq9", true);
check("eq10", false);
check("eq11", true);
check("eq12", false);
check("eq13", true);
check("eq14", false);
check("eq15", false);
check("eq16", true);
check("eq17", false);
check("eq18", false);
check("eq19", false);
// byte
check("eq20", true);
check("eq21", true);
check("eq22", false);
check("eq23", false);
check("eq24", true);
check("eq25", false);
check("eq20c", true);
check("eq21c", true);
check("eq22c", false);
check("eq23c", false);
check("eq24c", true);
check("eq25c", false);
check("eq26", true);
check("eq27", true);
}
public void test_operator_non_equal(){
doCompile("test_operator_non_equal");
check("inei", false);
check("inej", true);
check("jnei", true);
check("jnej", false);
check("lnei", false);
check("inel", false);
check("lnej", true);
check("jnel", true);
check("lnel", false);
check("dnei", false);
check("ined", false);
check("dnej", true);
check("jned", true);
check("dnel", false);
check("lned", false);
check("dned", false);
check("dned_different_scale", false);
}
public void test_operator_in() {
doCompile("test_operator_in");
check("a", Integer.valueOf(1));
check("haystack", Collections.EMPTY_LIST);
check("needle", Integer.valueOf(2));
check("b1", true);
check("b2", false);
check("h2", Arrays.asList(2.1D, 2.0D, 2.2D));
check("b3", true);
check("h3", Arrays.asList("memento", "mori", "memento mori"));
check("n3", "memento mori");
check("b4", true);
}
public void test_operator_greater_less() {
doCompile("test_operator_greater_less");
check("eq1", true);
check("eq2", true);
check("eq3", true);
check("eq4", false);
check("eq5", true);
check("eq6", false);
check("eq7", true);
check("eq8", true);
check("eq9", true);
}
public void test_operator_ternary(){
doCompile("test_operator_ternary");
// simple use
check("trueValue", true);
check("falseValue", false);
check("res1", Integer.valueOf(1));
check("res2", Integer.valueOf(2));
// nesting in positive branch
check("res3", Integer.valueOf(1));
check("res4", Integer.valueOf(2));
check("res5", Integer.valueOf(3));
// nesting in negative branch
check("res6", Integer.valueOf(2));
check("res7", Integer.valueOf(3));
// nesting in both branches
check("res8", Integer.valueOf(1));
check("res9", Integer.valueOf(1));
check("res10", Integer.valueOf(2));
check("res11", Integer.valueOf(3));
check("res12", Integer.valueOf(2));
check("res13", Integer.valueOf(4));
check("res14", Integer.valueOf(3));
check("res15", Integer.valueOf(4));
}
public void test_operators_logical(){
doCompile("test_operators_logical");
//TODO: please double check this.
check("res1", false);
check("res2", false);
check("res3", true);
check("res4", true);
check("res5", false);
check("res6", false);
check("res7", true);
check("res8", false);
}
public void test_regex(){
doCompile("test_regex");
check("eq0", false);
check("eq1", true);
check("eq2", false);
check("eq3", true);
check("eq4", false);
check("eq5", true);
}
public void test_if() {
doCompile("test_if");
// if with single statement
check("cond1", true);
check("res1", true);
// if with mutliple statements (block)
check("cond2", true);
check("res21", true);
check("res22", true);
// else with single statement
check("cond3", false);
check("res31", false);
check("res32", true);
// else with multiple statements (block)
check("cond4", false);
check("res41", false);
check("res42", true);
check("res43", true);
// if with block, else with block
check("cond5", false);
check("res51", false);
check("res52", false);
check("res53", true);
check("res54", true);
// else-if with single statement
check("cond61", false);
check("cond62", true);
check("res61", false);
check("res62", true);
// else-if with multiple statements
check("cond71", false);
check("cond72", true);
check("res71", false);
check("res72", true);
check("res73", true);
// if-elseif-else test
check("cond81", false);
check("cond82", false);
check("res81", false);
check("res82", false);
check("res83", true);
// if with single statement + inactive else
check("cond9", true);
check("res91", true);
check("res92", false);
// if with multiple statements + inactive else with block
check("cond10", true);
check("res101", true);
check("res102", true);
check("res103", false);
check("res104", false);
// if with condition
check("i", 0);
check("j", 1);
check("res11", true);
}
public void test_switch() {
doCompile("test_switch");
// simple switch
check("cond1", 1);
check("res11", false);
check("res12", true);
check("res13", false);
// switch, no break
check("cond2", 1);
check("res21", false);
check("res22", true);
check("res23", true);
// default branch
check("cond3", 3);
check("res31", false);
check("res32", false);
check("res33", true);
// no default branch => no match
check("cond4", 3);
check("res41", false);
check("res42", false);
check("res43", false);
// multiple statements in a single case-branch
check("cond5", 1);
check("res51", false);
check("res52", true);
check("res53", true);
check("res54", false);
// single statement shared by several case labels
check("cond6", 1);
check("res61", false);
check("res62", true);
check("res63", true);
check("res64", false);
}
public void test_int_switch(){
doCompile("test_int_switch");
// simple switch
check("cond1", 1);
check("res11", true);
check("res12", false);
check("res13", false);
// first case is not followed by a break
check("cond2", 1);
check("res21", true);
check("res22", true);
check("res23", false);
// first and second case have multiple labels
check("cond3", 12);
check("res31", false);
check("res32", true);
check("res33", false);
// first and second case have multiple labels and no break after first group
check("cond4", 11);
check("res41", true);
check("res42", true);
check("res43", false);
// default case intermixed with other case labels in the second group
check("cond5", 11);
check("res51", true);
check("res52", true);
check("res53", true);
// default case intermixed, with break
check("cond6", 16);
check("res61", false);
check("res62", true);
check("res63", false);
// continue test
check("res7", Arrays.asList(
false, false, false,
true, true, false,
true, true, false,
false, true, false,
false, true, false,
false, false, true));
// return test
check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3"));
}
public void test_non_int_switch(){
doCompile("test_non_int_switch");
// simple switch
check("cond1", "1");
check("res11", true);
check("res12", false);
check("res13", false);
// first case is not followed by a break
check("cond2", "1");
check("res21", true);
check("res22", true);
check("res23", false);
// first and second case have multiple labels
check("cond3", "12");
check("res31", false);
check("res32", true);
check("res33", false);
// first and second case have multiple labels and no break after first group
check("cond4", "11");
check("res41", true);
check("res42", true);
check("res43", false);
// default case intermixed with other case labels in the second group
check("cond5", "11");
check("res51", true);
check("res52", true);
check("res53", true);
// default case intermixed, with break
check("cond6", "16");
check("res61", false);
check("res62", true);
check("res63", false);
// continue test
check("res7", Arrays.asList(
false, false, false,
true, true, false,
true, true, false,
false, true, false,
false, true, false,
false, false, true));
// return test
check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3"));
}
public void test_while() {
doCompile("test_while");
// simple while
check("res1", Arrays.asList(0, 1, 2));
// continue
check("res2", Arrays.asList(0, 2));
// break
check("res3", Arrays.asList(0));
}
public void test_do_while() {
doCompile("test_do_while");
// simple while
check("res1", Arrays.asList(0, 1, 2));
// continue
check("res2", Arrays.asList(0, null, 2));
// break
check("res3", Arrays.asList(0));
}
public void test_for() {
doCompile("test_for");
// simple loop
check("res1", Arrays.asList(0,1,2));
// continue
check("res2", Arrays.asList(0,null,2));
// break
check("res3", Arrays.asList(0));
// empty init
check("res4", Arrays.asList(0,1,2));
// empty update
check("res5", Arrays.asList(0,1,2));
// empty final condition
check("res6", Arrays.asList(0,1,2));
// all conditions empty
check("res7", Arrays.asList(0,1,2));
}
public void test_for1() {
//5125: CTL2: "for" cycle is EXTREMELY memory consuming
doCompile("test_for1");
checkEquals("counter", "COUNT");
}
@SuppressWarnings("unchecked")
public void test_foreach() {
doCompile("test_foreach");
check("intRes", Arrays.asList(VALUE_VALUE));
check("longRes", Arrays.asList(BORN_MILLISEC_VALUE));
check("doubleRes", Arrays.asList(AGE_VALUE));
check("decimalRes", Arrays.asList(CURRENCY_VALUE));
check("booleanRes", Arrays.asList(FLAG_VALUE));
check("stringRes", Arrays.asList(NAME_VALUE, CITY_VALUE));
check("dateRes", Arrays.asList(BORN_VALUE));
List<?> integerStringMapResTmp = (List<?>) getVariable("integerStringMapRes");
List<String> integerStringMapRes = new ArrayList<String>(integerStringMapResTmp.size());
for (Object o: integerStringMapResTmp) {
integerStringMapRes.add(String.valueOf(o));
}
List<Integer> stringIntegerMapRes = (List<Integer>) getVariable("stringIntegerMapRes");
List<DataRecord> stringRecordMapRes = (List<DataRecord>) getVariable("stringRecordMapRes");
Collections.sort(integerStringMapRes);
Collections.sort(stringIntegerMapRes);
assertEquals(Arrays.asList("0", "1", "2", "3", "4"), integerStringMapRes);
assertEquals(Arrays.asList(0, 1, 2, 3, 4), stringIntegerMapRes);
final int N = 5;
assertEquals(N, stringRecordMapRes.size());
int equalRecords = 0;
for (int i = 0; i < N; i++) {
for (DataRecord r: stringRecordMapRes) {
if (Integer.valueOf(i).equals(r.getField("Value").getValue())
&& "A string".equals(String.valueOf(r.getField("Name").getValue()))) {
equalRecords++;
break;
}
}
}
assertEquals(N, equalRecords);
}
public void test_return(){
doCompile("test_return");
check("lhs", Integer.valueOf(1));
check("rhs", Integer.valueOf(2));
check("res", Integer.valueOf(3));
}
public void test_return_incorrect() {
doCompileExpectError("test_return_incorrect", "Can't convert from 'string' to 'integer'");
}
public void test_return_void() {
doCompile("test_return_void");
}
public void test_overloading() {
doCompile("test_overloading");
check("res1", Integer.valueOf(3));
check("res2", "Memento mori");
}
public void test_overloading_incorrect() {
doCompileExpectErrors("test_overloading_incorrect", Arrays.asList(
"Duplicate function 'integer sum(integer, integer)'",
"Duplicate function 'integer sum(integer, integer)'"));
}
//Test case for 4038
public void test_function_parameter_without_type() {
doCompileExpectError("test_function_parameter_without_type", "Syntax error on token ')'");
}
public void test_duplicate_import() {
URL importLoc = getClass().getSuperclass().getResource("test_duplicate_import.ctl");
String expStr = "import '" + importLoc + "';\n";
expStr += "import '" + importLoc + "';\n";
doCompile(expStr, "test_duplicate_import");
}
/*TODO:
* public void test_invalid_import() {
URL importLoc = getClass().getResource("test_duplicate_import.ctl");
String expStr = "import '/a/b/c/d/e/f/g/h/i/j/k/l/m';\n";
expStr += expStr;
doCompileExpectError(expStr, "test_invalid_import", Arrays.asList("TODO: Unknown error"));
//doCompileExpectError(expStr, "test_duplicate_import", Arrays.asList("TODO: Unknown error"));
} */
public void test_built_in_functions(){
doCompile("test_built_in_functions");
check("notNullValue", Integer.valueOf(1));
checkNull("nullValue");
check("isNullRes1", false);
check("isNullRes2", true);
assertEquals("nvlRes1", getVariable("notNullValue"), getVariable("nvlRes1"));
check("nvlRes2", Integer.valueOf(2));
assertEquals("nvl2Res1", getVariable("notNullValue"), getVariable("nvl2Res1"));
check("nvl2Res2", Integer.valueOf(2));
check("iifRes1", Integer.valueOf(2));
check("iifRes2", Integer.valueOf(1));
}
public void test_mapping(){
doCompile("test_mapping");
// simple mappings
assertEquals("Name", NAME_VALUE, outputRecords[0].getField("Name").getValue().toString());
assertEquals("Age", AGE_VALUE, outputRecords[0].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[0].getField("City").getValue().toString());
assertEquals("Born", BORN_VALUE, outputRecords[0].getField("Born").getValue());
// * mapping
assertTrue(recordEquals(inputRecords[1], outputRecords[1]));
check("len", 2);
}
public void test_mapping_null_values() {
doCompile("test_mapping_null_values");
assertTrue(recordEquals(inputRecords[2], outputRecords[0]));
}
public void test_copyByName() {
doCompile("test_copyByName");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString());
}
public void test_copyByName_assignment() {
doCompile("test_copyByName_assignment");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue());
assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString());
}
public void test_copyByName_assignment1() {
doCompile("test_copyByName_assignment1");
assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue());
assertEquals("Age", null, outputRecords[3].getField("Age").getValue());
assertEquals("City", null, outputRecords[3].getField("City").getValue());
}
public void test_sequence(){
doCompile("test_sequence");
check("intRes", Arrays.asList(0,1,2));
check("longRes", Arrays.asList(Long.valueOf(0),Long.valueOf(1),Long.valueOf(2)));
check("stringRes", Arrays.asList("0","1","2"));
check("intCurrent", Integer.valueOf(2));
check("longCurrent", Long.valueOf(2));
check("stringCurrent", "2");
}
//TODO: If this test fails please double check whether the test is correct?
public void test_lookup(){
doCompile("test_lookup");
check("alphaResult", Arrays.asList("Andorra la Vella","Andorra la Vella"));
check("bravoResult", Arrays.asList("Bruxelles","Bruxelles"));
check("charlieResult", Arrays.asList("Chamonix","Chodov","Chomutov","Chamonix","Chodov","Chomutov"));
check("countResult", Arrays.asList(3,3));
check("charlieUpdatedCount", 5);
check("charlieUpdatedResult", Arrays.asList("Chamonix", "Cheb", "Chodov", "Chomutov", "Chrudim"));
check("putResult", true);
}
public void test_containerlib_append() {
doCompile("test_containerlib_append");
check("appendElem", Integer.valueOf(10));
check("appendList", Arrays.asList(1, 2, 3, 4, 5, 10));
check("stringList", Arrays.asList("horse","is","pretty","scary"));
check("stringList2", Arrays.asList("horse", null));
check("stringList3", Arrays.asList("horse", ""));
check("integerList1", Arrays.asList(1,2,3,4));
check("integerList2", Arrays.asList(1,2,null));
check("numberList1", Arrays.asList(0.21,1.1,2.2));
check("numberList2", Arrays.asList(1.1,null));
check("longList1", Arrays.asList(1l,2l,3L));
check("longList2", Arrays.asList(9L,null));
check("decList1", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("4.5"),new BigDecimal("6.7")));
check("decList2",Arrays.asList(new BigDecimal("1.1"), null));
}
public void test_containerlib_append_expect_error(){
try {
doCompile("function integer transform(){string[] listInput = null; append(listInput,'aa'); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte[] listInput = null; append(listInput,str2byte('third', 'utf-8')); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long[] listInput = null; append(listInput,15L); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] listInput = null; append(listInput,12); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal[] listInput = null; append(listInput,12.5d); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number[] listInput = null; append(listInput,12.36); return 0;}","test_containerlib_append_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
@SuppressWarnings("unchecked")
public void test_containerlib_clear() {
doCompile("test_containerlib_clear");
assertTrue(((List<Integer>) getVariable("integerList")).isEmpty());
assertTrue(((List<Integer>) getVariable("strList")).isEmpty());
assertTrue(((List<Integer>) getVariable("longList")).isEmpty());
assertTrue(((List<Integer>) getVariable("decList")).isEmpty());
assertTrue(((List<Integer>) getVariable("numList")).isEmpty());
assertTrue(((List<Integer>) getVariable("byteList")).isEmpty());
assertTrue(((List<Integer>) getVariable("dateList")).isEmpty());
assertTrue(((List<Integer>) getVariable("boolList")).isEmpty());
assertTrue(((List<Integer>) getVariable("emptyList")).isEmpty());
assertTrue(((Map<String,Integer>) getVariable("myMap")).isEmpty());
}
public void test_container_clear_expect_error(){
try {
doCompile("function integer transform(){boolean[] nullList = null; clear(nullList); return 0;}","test_container_clear_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[integer,string] myMap = null; clear(myMap); return 0;}","test_container_clear_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_copy() {
doCompile("test_containerlib_copy");
check("copyIntList", Arrays.asList(1, 2, 3, 4, 5));
check("returnedIntList", Arrays.asList(1, 2, 3, 4, 5));
check("copyLongList", Arrays.asList(21L,15L, null, 10L));
check("returnedLongList", Arrays.asList(21l, 15l, null, 10L));
check("copyBoolList", Arrays.asList(false,false,null,true));
check("returnedBoolList", Arrays.asList(false,false,null,true));
Calendar cal = Calendar.getInstance();
cal.set(2006, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2002, 03, 12, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
check("copyDateList",Arrays.asList(cal2.getTime(), null, cal.getTime()));
check("returnedDateList",Arrays.asList(cal2.getTime(), null, cal.getTime()));
check("copyStrList", Arrays.asList("Ashe", "Jax", null, "Rengar"));
check("returnedStrList", Arrays.asList("Ashe", "Jax", null, "Rengar"));
check("copyNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d));
check("returnedNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d));
check("copyDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3")));
check("returnedDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3")));
Map<String, String> expectedMap = new HashMap<String, String>();
expectedMap.put("a", "a");
expectedMap.put("b", "b");
expectedMap.put("c", "c");
expectedMap.put("d", "d");
check("copyStrMap", expectedMap);
check("returnedStrMap", expectedMap);
Map<Integer, Integer> intMap = new HashMap<Integer, Integer>();
intMap.put(1,12);
intMap.put(2,null);
intMap.put(3,15);
check("copyIntMap", intMap);
check("returnedIntMap", intMap);
Map<Long, Long> longMap = new HashMap<Long, Long>();
longMap.put(10L, 453L);
longMap.put(11L, null);
longMap.put(12L, 54755L);
check("copyLongMap", longMap);
check("returnedLongMap", longMap);
Map<BigDecimal, BigDecimal> decMap = new HashMap<BigDecimal, BigDecimal>();
decMap.put(new BigDecimal("2.2"), new BigDecimal("12.3"));
decMap.put(new BigDecimal("2.3"), new BigDecimal("45.6"));
check("copyDecMap", decMap);
check("returnedDecMap", decMap);
Map<Double, Double> doubleMap = new HashMap<Double, Double>();
doubleMap.put(new Double(12.3d), new Double(11.2d));
doubleMap.put(new Double(13.4d), new Double(78.9d));
check("copyNumMap",doubleMap);
check("returnedNumMap", doubleMap);
List<String> myList = new ArrayList<String>();
check("copyEmptyList", myList);
check("returnedEmptyList", myList);
assertTrue(((List<String>)(getVariable("copyEmptyList"))).isEmpty());
assertTrue(((List<String>)(getVariable("returnedEmptyList"))).isEmpty());
Map<String, String> emptyMap = new HashMap<String, String>();
check("copyEmptyMap", emptyMap);
check("returnedEmptyMap", emptyMap);
assertTrue(((HashMap<String,String>)(getVariable("copyEmptyMap"))).isEmpty());
assertTrue(((HashMap<String,String>)(getVariable("returnedEmptyMap"))).isEmpty());
}
public void test_containerlib_copy_expect_error(){
try {
doCompile("function integer transform(){string[] origList = null; string[] copyList; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] origList; string[] copyList = null; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string, string] orig = null; map[string, string] copy; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string, string] orig; map[string, string] copy = null; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_insert() {
doCompile("test_containerlib_insert");
check("copyStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV"));
check("retStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV"));
check("copyStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe"));
check("retStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe"));
Calendar cal = Calendar.getInstance();
cal.set(2009, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal1 = Calendar.getInstance();
cal1.set(2008, 2, 7, 0, 0, 0);
cal1.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2003, 01, 1, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
check("copyDateList", Arrays.asList(cal1.getTime(),cal.getTime()));
check("retDateList", Arrays.asList(cal1.getTime(),cal.getTime()));
check("copyDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime()));
check("retDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime()));
check("copyIntList", Arrays.asList(1,2,3,12,4,5,6,7));
check("retIntList", Arrays.asList(1,2,3,12,4,5,6,7));
check("copyLongList", Arrays.asList(14L,15l,16l,17l));
check("retLongList", Arrays.asList(14L,15l,16l,17l));
check("copyLongList2", Arrays.asList(20L,21L,22L,23l));
check("retLongList2", Arrays.asList(20L,21L,22L,23l));
check("copyNumList", Arrays.asList(12.3d,11.1d,15.4d));
check("retNumList", Arrays.asList(12.3d,11.1d,15.4d));
check("copyNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d));
check("retNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d));
check("copyDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3")));
check("retDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3")));
check("copyDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2")));
check("retDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2")));
check("copyEmpty", Arrays.asList(11));
check("retEmpty", Arrays.asList(11));
check("copyEmpty2", Arrays.asList(12,13));
check("retEmpty2", Arrays.asList(12,13));
check("copyEmpty3", Arrays.asList());
check("retEmpty3", Arrays.asList());
}
public void test_containerlib_insert_expect_error(){
try {
doCompile("function integer transform(){integer[] tmp = null; integer[] ret = insert(tmp,0,12); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] tmp; integer[] toAdd = null; integer[] ret = insert(tmp,0,toAdd); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,-1,12); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,10,12); return 0;}","test_containerlib_insert_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_isEmpty() {
doCompile("test_containerlib_isEmpty");
check("emptyMap", true);
check("emptyMap1", true);
check("fullMap", false);
check("fullMap1", false);
check("emptyList", true);
check("emptyList1", true);
check("fullList", false);
check("fullList1", false);
}
public void test_containerlib_isEmpty_expect_error(){
try {
doCompile("function integer transform(){integer[] i = null; boolean boo = i.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string, string] m = null; boolean boo = m.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_length(){
doCompile("test_containerlib_length");
check("lengthByte", 18);
check("lengthByte2", 18);
check("recordLength", 9);
check("recordLength2", 9);
check("listLength", 3);
check("listLength2", 3);
check("emptyListLength", 0);
check("emptyListLength2", 0);
check("emptyMapLength", 0);
check("emptyMapLength2", 0);
check("nullLength1", 0);
check("nullLength2", 0);
check("nullLength3", 0);
check("nullLength4", 0);
check("nullLength5", 0);
check("nullLength6", 0);
}
public void test_containerlib_poll() throws UnsupportedEncodingException {
doCompile("test_containerlib_poll");
check("intElem", Integer.valueOf(1));
check("intElem1", 2);
check("intList", Arrays.asList(3, 4, 5));
check("strElem", "Zyra");
check("strElem2", "Tresh");
check("strList", Arrays.asList("Janna", "Wu Kong"));
Calendar cal = Calendar.getInstance();
cal.set(2002, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem", cal.getTime());
cal.clear();
cal.set(2003,5,12,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem2", cal.getTime());
cal.clear();
cal.set(2006,9,15,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime()));
checkArray("byteElem", "Maoki".getBytes("UTF-8"));
checkArray("byteElem2", "Nasus".getBytes("UTF-8"));
check("longElem", 12L);
check("longElem2", 15L);
check("longList", Arrays.asList(16L,23L));
check("numElem", 23.6d);
check("numElem2", 15.9d);
check("numList", Arrays.asList(78.8d, 57.2d));
check("decElem", new BigDecimal("12.3"));
check("decElem2", new BigDecimal("23.4"));
check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6")));
check("emptyElem", null);
check("emptyElem2", null);
check("emptyList", Arrays.asList());
}
public void test_containerlib_poll_expect_error(){
try {
doCompile("function integer transform(){integer[] arr = null; integer i = poll(arr); return 0;}","test_containerlib_poll_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer[] arr = null; integer i = arr.poll(); return 0;}","test_containerlib_poll_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_pop() {
doCompile("test_containerlib_pop");
check("intElem", 5);
check("intElem2", 4);
check("intList", Arrays.asList(1, 2, 3));
check("longElem", 14L);
check("longElem2", 13L);
check("longList", Arrays.asList(11L,12L));
check("numElem", 11.5d);
check("numElem2", 11.4d);
check("numList", Arrays.asList(11.2d,11.3d));
check("decElem", new BigDecimal("22.5"));
check("decElem2", new BigDecimal("22.4"));
check("decList", Arrays.asList(new BigDecimal("22.2"), new BigDecimal("22.3")));
Calendar cal = Calendar.getInstance();
cal.set(2005, 8, 24, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem",cal.getTime());
cal.clear();
cal.set(2001, 6, 13, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem2", cal.getTime());
cal.clear();
cal.set(2010, 5, 11, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2011,3,3,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime(),cal2.getTime()));
check("strElem", "Ezrael");
check("strElem2", null);
check("strList", Arrays.asList("Kha-Zix", "Xerath"));
check("emptyElem", null);
check("emptyElem2", null);
}
public void test_containerlib_pop_expect_error(){
try {
doCompile("function integer transform(){string[] arr = null; string str = pop(arr); return 0;}","test_containerlib_pop_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] arr = null; string str = arr.pop(); return 0;}","test_containerlib_pop_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
@SuppressWarnings("unchecked")
public void test_containerlib_push() {
doCompile("test_containerlib_push");
check("intCopy", Arrays.asList(1, 2, 3));
check("intRet", Arrays.asList(1, 2, 3));
check("longCopy", Arrays.asList(12l,13l,14l));
check("longRet", Arrays.asList(12l,13l,14l));
check("numCopy", Arrays.asList(11.1d,11.2d,11.3d));
check("numRet", Arrays.asList(11.1d,11.2d,11.3d));
check("decCopy", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4")));
check("decRet", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4")));
check("strCopy", Arrays.asList("Fiora", "Nunu", "Amumu"));
check("strRet", Arrays.asList("Fiora", "Nunu", "Amumu"));
Calendar cal = Calendar.getInstance();
cal.set(2001, 5, 9, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal1 = Calendar.getInstance();
cal1.set(2005, 5, 9, 0, 0, 0);
cal1.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2011, 5, 9, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateCopy", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime()));
check("dateRet", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime()));
String str = null;
check("emptyCopy", Arrays.asList(str));
check("emptyRet", Arrays.asList(str));
// there is hardly any way to get an instance of DataRecord
// hence we just check if the list has correct size
// and if its elements have correct metadata
List<DataRecord> recordList = (List<DataRecord>) getVariable("recordList");
List<DataRecordMetadata> mdList = Arrays.asList(
graph.getDataRecordMetadata(OUTPUT_1),
graph.getDataRecordMetadata(INPUT_2),
graph.getDataRecordMetadata(INPUT_1)
);
assertEquals(mdList.size(), recordList.size());
for (int i = 0; i < mdList.size(); i++) {
assertEquals(mdList.get(i), recordList.get(i).getMetadata());
}
}
public void test_containerlib_push_expect_error(){
try {
doCompile("function integer transform(){string[] str = null; str.push('a'); return 0;}","test_containerlib_push_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] str = null; push(str, 'a'); return 0;}","test_containerlib_push_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_remove() {
doCompile("test_containerlib_remove");
check("intElem", 2);
check("intList", Arrays.asList(1, 3, 4, 5));
check("longElem", 13L);
check("longList", Arrays.asList(11l,12l,14l));
check("numElem", 11.3d);
check("numList", Arrays.asList(11.1d,11.2d,11.4d));
check("decElem", new BigDecimal("11.3"));
check("decList", Arrays.asList(new BigDecimal("11.1"),new BigDecimal("11.2"),new BigDecimal("11.4")));
Calendar cal = Calendar.getInstance();
cal.set(2002,10,13,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
check("dateElem", cal.getTime());
cal.clear();
cal.set(2001,10,13,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2003,10,13,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime(), cal2.getTime()));
check("strElem", "Shivana");
check("strList", Arrays.asList("Annie","Lux"));
}
public void test_containerlib_remove_expect_error(){
try {
doCompile("function integer transform(){string[] strList; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList; string str = strList.remove(0); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,5); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,-1); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = null; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_reverse_expect_error(){
try {
doCompile("function integer transform(){long[] longList = null; reverse(longList); return 0;}","test_containerlib_reverse_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long[] longList = null; long[] reversed = longList.reverse(); return 0;}","test_containerlib_reverse_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_reverse() {
doCompile("test_containerlib_reverse");
check("intList", Arrays.asList(5, 4, 3, 2, 1));
check("intList2", Arrays.asList(5, 4, 3, 2, 1));
check("longList", Arrays.asList(14l,13l,12l,11l));
check("longList2", Arrays.asList(14l,13l,12l,11l));
check("numList", Arrays.asList(1.3d,1.2d,1.1d));
check("numList2", Arrays.asList(1.3d,1.2d,1.1d));
check("decList", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1")));
check("decList2", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1")));
check("strList", Arrays.asList(null,"Lulu","Kog Maw"));
check("strList2", Arrays.asList(null,"Lulu","Kog Maw"));
Calendar cal = Calendar.getInstance();
cal.set(2001,2,1,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2002,2,1,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal2.getTime(),cal.getTime()));
check("dateList2", Arrays.asList(cal2.getTime(),cal.getTime()));
}
public void test_containerlib_sort() {
doCompile("test_containerlib_sort");
check("intList", Arrays.asList(1, 1, 2, 3, 5));
check("intList2", Arrays.asList(1, 1, 2, 3, 5));
check("longList", Arrays.asList(21l,22l,23l,24l));
check("longList2", Arrays.asList(21l,22l,23l,24l));
check("decList", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4")));
check("decList2", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4")));
check("numList", Arrays.asList(1.1d,1.2d,1.3d,1.4d));
check("numList2", Arrays.asList(1.1d,1.2d,1.3d,1.4d));
Calendar cal = Calendar.getInstance();
cal.set(2002,5,12,0,0,0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2003,5,12,0,0,0);
cal2.set(Calendar.MILLISECOND, 0);
Calendar cal3 = Calendar.getInstance();
cal3.set(2004,5,12,0,0,0);
cal3.set(Calendar.MILLISECOND, 0);
check("dateList", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime()));
check("dateList2", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime()));
check("strList", Arrays.asList("","Alistar", "Nocturne", "Soraka"));
check("strList2", Arrays.asList("","Alistar", "Nocturne", "Soraka"));
check("emptyList", Arrays.asList());
check("emptyList2", Arrays.asList());
}
public void test_containerlib_sort_expect_error(){
try {
doCompile("function integer transform(){string[] strList = ['Renektor', null, 'Jayce']; sort(strList); return 0;}","test_containerlib_sort_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] strList = null; sort(strList); return 0;}","test_containerlib_sort_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_containsAll() {
doCompile("test_containerlib_containsAll");
check("results", Arrays.asList(true, false, true, false, true, true, true, false, true, true, false));
check("test1", true);
check("test2", true);
check("test3", true);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", true);
check("test8", false);
check("test9", true);
check("test10", false);
check("test11", true);
check("test12", false);
check("test13", false);
check("test14", true);
check("test15", false);
check("test16", false);
}
public void test_containerlib_containsAll_expect_error(){
try {
doCompile("function integer transform(){integer[] intList = null; boolean b =intList.containsAll([1]); return 0;}","test_containerlib_containsAll_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_containsKey() {
doCompile("test_containerlib_containsKey");
check("results", Arrays.asList(false, true, false, true, false, true));
check("test1", true);
check("test2", false);
check("test3", true);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", true);
check("test8", true);
check("test9", true);
check("test10", false);
check("test11", true);
check("test12", true);
check("test13", false);
check("test14", true);
check("test15", true);
check("test16", false);
check("test17", true);
check("test18", true);
check("test19", false);
check("test20", false);
}
public void test_containerlib_containsKey_expect_error(){
try {
doCompile("function integer transform(){map[string, integer] emptyMap = null; boolean b = emptyMap.containsKey('a'); return 0;}","test_containerlib_containsKey_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_containsValue() {
doCompile("test_containerlib_containsValue");
check("results", Arrays.asList(true, false, false, true, false, false, true, false));
check("test1", true);
check("test2", true);
check("test3", false);
check("test4", true);
check("test5", true);
check("test6", false);
check("test7", false);
check("test8", true);
check("test9", true);
check("test10", false);
check("test11", true);
check("test12", true);
check("test13", false);
check("test14", true);
check("test15", true);
check("test16", false);
check("test17", true);
check("test18", true);
check("test19", false);
check("test20", true);
check("test21", true);
check("test22", false);
check("test23", true);
check("test24", true);
check("test25", false);
check("test26", false);
}
public void test_convertlib_containsValue_expect_error(){
try {
doCompile("function integer transform(){map[integer, long] nullMap = null; boolean b = nullMap.containsValue(18L); return 0;}","test_convertlib_containsValue_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_containerlib_getKeys() {
doCompile("test_containerlib_getKeys");
check("stringList", Arrays.asList("a","b"));
check("stringList2", Arrays.asList("a","b"));
check("integerList", Arrays.asList(5,7,2));
check("integerList2", Arrays.asList(5,7,2));
List<Date> list = new ArrayList<Date>();
Calendar cal = Calendar.getInstance();
cal.set(2008, 10, 12, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar cal2 = Calendar.getInstance();
cal2.set(2001, 5, 28, 0, 0, 0);
cal2.set(Calendar.MILLISECOND, 0);
list.add(cal.getTime());
list.add(cal2.getTime());
check("dateList", list);
check("dateList2", list);
check("longList", Arrays.asList(14L, 45L));
check("longList2", Arrays.asList(14L, 45L));
check("numList", Arrays.asList(12.3d, 13.4d));
check("numList2", Arrays.asList(12.3d, 13.4d));
check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6")));
check("decList2", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6")));
check("emptyList", Arrays.asList());
check("emptyList2", Arrays.asList());
}
public void test_containerlib_getKeys_expect_error(){
try {
doCompile("function integer transform(){map[string,string] strMap = null; string[] str = strMap.getKeys(); return 0;}","test_containerlib_getKeys_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string,string] strMap = null; string[] str = getKeys(strMap); return 0;}","test_containerlib_getKeys_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_cache() {
doCompile("test_stringlib_cache");
check("rep1", "The cat says meow. All cats say meow.");
check("rep2", "The cat says meow. All cats say meow.");
check("rep3", "The cat says meow. All cats say meow.");
check("find1", Arrays.asList("to", "to", "to", "tro", "to"));
check("find2", Arrays.asList("to", "to", "to", "tro", "to"));
check("find3", Arrays.asList("to", "to", "to", "tro", "to"));
check("split1", Arrays.asList("one", "two", "three", "four", "five"));
check("split2", Arrays.asList("one", "two", "three", "four", "five"));
check("split3", Arrays.asList("one", "two", "three", "four", "five"));
check("chop01", "ting soming choping function");
check("chop02", "ting soming choping function");
check("chop03", "ting soming choping function");
check("chop11", "testing end of lines cutting");
check("chop12", "testing end of lines cutting");
}
public void test_stringlib_charAt() {
doCompile("test_stringlib_charAt");
String input = "The QUICk !!$ broWn fox juMPS over the lazy DOG ";
String[] expected = new String[input.length()];
for (int i = 0; i < expected.length; i++) {
expected[i] = String.valueOf(input.charAt(i));
}
check("chars", Arrays.asList(expected));
}
public void test_stringlib_charAt_error(){
//test: attempt to access char at position, which is out of bounds -> upper bound
try {
doCompile("string test;function integer transform(){test = charAt('milk', 7);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: attempt to access char at position, which is out of bounds -> lower bound
try {
doCompile("string test;function integer transform(){test = charAt('milk', -1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: argument for position is null
try {
doCompile("string test; integer i = null; function integer transform(){test = charAt('milk', i);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is null
try {
doCompile("string test;function integer transform(){test = charAt(null, 1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is empty string
try {
doCompile("string test;function integer transform(){test = charAt('', 1);return 0;}", "test_stringlib_charAt_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_concat() {
doCompile("test_stringlib_concat");
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("concat", "");
check("concat1", "ello hi ELLO 2,today is " + format.format(new Date()));
check("concat2", "");
check("concat3", "clover");
check("test_null1", "null");
check("test_null2", "null");
check("test_null3","skynullisnullblue");
}
public void test_stringlib_countChar() {
doCompile("test_stringlib_countChar");
check("charCount", 3);
check("count2", 0);
}
public void test_stringlib_countChar_emptychar() {
// test: attempt to count empty chars in string.
try {
doCompile("integer charCount;function integer transform() {charCount = countChar('aaa','');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
// test: attempt to count empty chars in empty string.
try {
doCompile("integer charCount;function integer transform() {charCount = countChar('','');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 1
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null,'a');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 2
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null,'');return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
//test: null input - test 3
try {
doCompile("integer charCount;function integer transform() {charCount = countChar(null, null);return 0;}", "test_stringlib_countChar_emptychar");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_cut() {
doCompile("test_stringlib_cut");
check("cutInput", Arrays.asList("a", "1edf", "h3ijk"));
}
public void test_string_cut_expect_error() {
// test: Attempt to cut substring from position after the end of original string. E.g. string is 6 char long and
// user attempt to cut out after position 8.
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[28,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut substring longer then possible. E.g. string is 6 characters long and user cuts from
// position
// 4 substring 4 characters long
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,8]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut a substring with negative length
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,-3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// test: Attempt to cut substring from negative position. E.g cut([-3,3]).
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[-3,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is empty string
try {
doCompile("string input;string[] cutInput;function integer transform() {input = '';cutInput = cut(input,[0,3]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: second arg is null
try {
doCompile("string input;string[] cutInput;function integer transform() {input = 'aaaa';cutInput = cut(input,null);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: input is null
try {
doCompile("string input;string[] cutInput;function integer transform() {input = null;cutInput = cut(input,[5,11]);return 0;}", "test_stringlib_cut_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_editDistance() {
doCompile("test_stringlib_editDistance");
check("dist", 1);
check("dist1", 1);
check("dist2", 0);
check("dist5", 1);
check("dist3", 1);
check("dist4", 0);
check("dist6", 4);
check("dist7", 5);
check("dist8", 0);
check("dist9", 0);
}
public void test_stringlib_editDistance_expect_error(){
//test: input - empty string - first arg
try {
doCompile("integer test;function integer transform() {test = editDistance('','mark');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - null - first arg
try {
doCompile("integer test;function integer transform() {test = editDistance(null,'mark');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input- empty string - second arg
try {
doCompile("integer test;function integer transform() {test = editDistance('mark','');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - null - second argument
try {
doCompile("integer test;function integer transform() {test = editDistance('mark',null);return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - both empty
try {
doCompile("integer test;function integer transform() {test = editDistance('','');return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
//test: input - both null
try {
doCompile("integer test;function integer transform() {test = editDistance(null,null);return 0;}","test_stringlib_editDistance_expect_error");
} catch ( Exception e) {
// do nothing
}
}
public void test_stringlib_find() {
doCompile("test_stringlib_find");
check("findList", Arrays.asList("The quick br", "wn f", "x jumps ", "ver the lazy d", "g"));
check("findList2", Arrays.asList("mark.twain"));
check("findList3", Arrays.asList());
check("findList4", Arrays.asList("", "", "", "", ""));
check("findList5", Arrays.asList("twain"));
check("findList6", Arrays.asList(""));
}
public void test_stringlib_find_expect_error() {
//test: regexp group number higher then count of regexp groups
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu','(^[a-z]*).([a-z]*)',5); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: negative regexp group number
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu','(^[a-z]*).([a-z]*)',-1); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg1 null input
try {
doCompile("string[] findList;function integer transform() {findList = find(null,'(^[a-z]*).([a-z]*)'); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg2 null input - test1
try {
doCompile("string[] findList;function integer transform() {findList = find('mark.twain@javlin.eu',null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg2 null input - test2
try {
doCompile("string[] findList;function integer transform() {findList = find('',null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
//test: arg1 and arg2 null input
try {
doCompile("string[] findList;function integer transform() {findList = find(null,null); return 0;}", "test_stringlib_find_expect_error");
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_join() {
doCompile("test_stringlib_join");
//check("joinedString", "Bagr,3,3.5641,-87L,CTL2");
check("joinedString1", "80=5455.987\"-5=5455.987\"3=0.1");
check("joinedString2", "5.054.6567.0231.0");
//check("joinedString3", "554656723180=5455.987-5=5455.9873=0.1CTL242");
check("test_empty1", "abc");
check("test_empty2", "");
check("test_empty3"," ");
check("test_empty4","anullb");
check("test_empty5","80=5455.987-5=5455.9873=0.1");
check("test_empty6","80=5455.987 -5=5455.987 3=0.1");
check("test_null1","abc");
check("test_null2","");
check("test_null3","anullb");
check("test_null4","80=5455.987-5=5455.9873=0.1");
//CLO-1210
// check("test_empty7","a=xb=nullc=z");
// check("test_empty8","a=x b=null c=z");
// check("test_empty9","null=xeco=storm");
// check("test_empty10","null=x eco=storm");
// check("test_null5","a=xb=nullc=z");
// check("test_null6","null=xeco=storm");
}
public void test_stringlib_join_expect_error(){
try {
doCompile("function integer transform(){string s = join(';',null);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string[] tmp = null; string s = join(';',tmp);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){map[string,string] a = null; string s = join(';',a);return 0;}","test_stringlib_join_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_left() {
//CLO - 1193
// doCompile("test_stringlib_left");
// check("test1", "aa");
// check("test2", "aaa");
// check("test3", "");
// check("test4", null);
// check("test5", "abc");
// check("test6", "ab ");
// check("test7", " ");
// check("test8", " ");
// check("test9", "abc");
// check("test10", "abc");
// check("test11", "");
// check("test12", null);
}
public void test_stringlib_length() {
doCompile("test_stringlib_length");
check("lenght1", new BigDecimal(50));
check("stringLength", 8);
check("length_empty", 0);
check("length_null1", 0);
}
public void test_stringlib_lowerCase() {
doCompile("test_stringlib_lowerCase");
check("lower", "the quick !!$ brown fox jumps over the lazy dog bagr ");
check("lower_empty", "");
check("lower_null", null);
}
public void test_stringlib_matches() {
doCompile("test_stringlib_matches");
check("matches1", true);
check("matches2", true);
check("matches3", false);
check("matches4", true);
check("matches5", false);
check("matches6", false);
check("matches7", false);
check("matches8", false);
check("matches9", true);
check("matches10", true);
}
public void test_stringlib_matches_expect_error(){
//test: regexp param null - test 1
try {
doCompile("boolean test; function integer transform(){test = matches('aaa', null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp param null - test 2
try {
doCompile("boolean test; function integer transform(){test = matches('', null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp param null - test 3
try {
doCompile("boolean test; function integer transform(){test = matches(null, null); return 0;}","test_stringlib_matches_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_matchGroups() {
doCompile("test_stringlib_matchGroups");
check("result1", null);
check("result2", Arrays.asList(
//"(([^:]*)([:])([\\(]))(.*)(\\))(((
"zip:(zip:(/path/name?.zip)#innerfolder/file.zip)#innermostfolder?/filename*.txt",
"zip:(",
"zip",
":",
"(",
"zip:(/path/name?.zip)#innerfolder/file.zip",
")",
"#innermostfolder?/filename*.txt",
"#innermostfolder?/filename*.txt",
"
"innermostfolder?/filename*.txt",
null
)
);
check("result3", null);
check("test_empty1", null);
check("test_empty2", Arrays.asList(""));
check("test_null1", null);
check("test_null2", null);
}
public void test_stringlib_matchGroups_expect_error(){
//test: regexp is null - test 1
try {
doCompile("string[] test; function integer transform(){test = matchGroups('eat all the cookies',null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
//test: regexp is null - test 2
try {
doCompile("string[] test; function integer transform(){test = matchGroups('',null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
//test: regexp is null - test 3
try {
doCompile("string[] test; function integer transform(){test = matchGroups(null,null); return 0;}","test_stringlib_matchGroups_expect_error");
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_matchGroups_unmodifiable() {
try {
doCompile("test_stringlib_matchGroups_unmodifiable");
fail();
} catch (RuntimeException re) {
};
}
public void test_stringlib_metaphone() {
doCompile("test_stringlib_metaphone");
check("metaphone1", "XRS");
check("metaphone2", "KWNTLN");
check("metaphone3", "KWNT");
check("metaphone4", "");
check("metaphone5", "");
check("test_empty1", "");
check("test_empty2", "");
check("test_null1", null);
check("test_null2", null);
}
public void test_stringlib_nysiis() {
doCompile("test_stringlib_nysiis");
check("nysiis1", "CAP");
check("nysiis2", "CAP");
check("nysiis3", "1234");
check("nysiis4", "C2 PRADACTAN");
check("nysiis_empty", "");
check("nysiis_null", null);
}
public void test_stringlib_replace() {
doCompile("test_stringlib_replace");
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("rep", format.format(new Date()).replaceAll("[lL]", "t"));
check("rep1", "The cat says meow. All cats say meow.");
check("rep2", "intruders must die");
check("test_empty1", "a");
check("test_empty2", "");
check("test_null", null);
check("test_null2","");
check("test_null3","bbb");
check("test_null4",null);
}
public void test_stringlib_replace_expect_error(){
//test: regexp null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b',null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test2
try {
doCompile("string test; function integer transform(){test = replace('',null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test3
try {
doCompile("string test; function integer transform(){test = replace(null,null,'b'); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b','a+',null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// //test: arg3 null - test2
// try {
// doCompile("string test; function integer transform(){test = replace('','a+',null); return 0;}","test_stringlib_replace_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
// //test: arg3 null - test3
// try {
// doCompile("string test; function integer transform(){test = replace(null,'a+',null); return 0;}","test_stringlib_replace_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
//test: regexp and arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace('a b',null,null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp and arg3 null - test1
try {
doCompile("string test; function integer transform(){test = replace(null,null,null); return 0;}","test_stringlib_replace_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_right() {
doCompile("test_stringlib_right");
check("righ", "y dog");
check("rightNotPadded", "y dog");
check("rightPadded", "y dog");
check("padded", " y dog");
check("notPadded", "y dog");
check("short", "Dog");
check("shortNotPadded", "Dog");
check("shortPadded", " Dog");
check("simple", "milk");
check("test_null1", null);
check("test_null2", null);
check("test_null3", " ");
check("test_empty1", "");
check("test_empty2", "");
check("test_empty3"," ");
}
public void test_stringlib_soundex() {
doCompile("test_stringlib_soundex");
check("soundex1", "W630");
check("soundex2", "W643");
check("test_null", null);
check("test_empty", "");
}
public void test_stringlib_split() {
doCompile("test_stringlib_split");
check("split1", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g"));
check("test_empty", Arrays.asList(""));
check("test_empty2", Arrays.asList("","a","a"));
List<String> tmp = new ArrayList<String>();
tmp.add(null);
check("test_null", tmp);
}
public void test_stringlib_split_expect_error(){
//test: regexp null - test1
try {
doCompile("function integer transform(){string[] s = split('aaa',null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test2
try {
doCompile("function integer transform(){string[] s = split('',null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp null - test3
try {
doCompile("function integer transform(){string[] s = split(null,null); return 0;}","test_stringlib_split_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_substring() {
doCompile("test_stringlib_substring");
check("subs", "UICk ");
check("test1", "");
check("test_empty", "");
}
public void test_stringlib_substring_expect_error(){
try {
doCompile("function integer transform(){string test = substring('arabela',4,19);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',15,3);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',2,-3);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('arabela',-5,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('',0,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring('',7,7);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,0,0);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,0,4);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = substring(null,1,4);return 0;}","test_stringlib_substring_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_trim() {
doCompile("test_stringlib_trim");
check("trim1", "im The QUICk !!$ broWn fox juMPS over the lazy DOG");
check("trim_empty", "");
check("trim_null", null);
}
public void test_stringlib_upperCase() {
doCompile("test_stringlib_upperCase");
check("upper", "THE QUICK !!$ BROWN FOX JUMPS OVER THE LAZY DOG BAGR ");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_isFormat() {
doCompile("test_stringlib_isFormat");
check("test", "test");
check("isBlank", Boolean.FALSE);
check("blank", "");
checkNull("nullValue");
check("isBlank1", true);
check("isBlank2", true);
check("isAscii1", true);
check("isAscii2", false);
check("isAscii3", true);
check("isAscii4", true);
check("isNumber", false);
check("isNumber1", false);
check("isNumber2", true);
check("isNumber3", true);
check("isNumber4", false);
check("isNumber5", true);
check("isNumber6", true);
check("isNumber7", false);
check("isNumber8", false);
check("isInteger", false);
check("isInteger1", false);
check("isInteger2", false);
check("isInteger3", true);
check("isInteger4", false);
check("isInteger5", false);
check("isLong", true);
check("isLong1", false);
check("isLong2", false);
check("isLong3", false);
check("isLong4", false);
check("isDate", true);
check("isDate1", false);
// "kk" allows hour to be 1-24 (as opposed to HH allowing hour to be 0-23)
check("isDate2", true);
check("isDate3", true);
check("isDate4", false);
check("isDate5", true);
check("isDate6", true);
check("isDate7", false);
check("isDate9", false);
check("isDate10", false);
check("isDate11", false);
check("isDate12", true);
check("isDate13", false);
check("isDate14", false);
// empty string: invalid
check("isDate15", false);
check("isDate16", false);
check("isDate17", true);
check("isDate18", true);
check("isDate19", false);
check("isDate20", false);
check("isDate21", false);
/* CLO-1190
check("isDate22", false);
check("isDate23", false);
check("isDate24", true);
check("isDate25", false);
*/
}
public void test_stringlib_empty_strings() {
String[] expressions = new String[] {
"isInteger(?)",
"isNumber(?)",
"isLong(?)",
"isAscii(?)",
"isBlank(?)",
"isDate(?, \"yyyy\")",
"isUrl(?)",
"string x = ?; length(x)",
"lowerCase(?)",
"matches(?, \"\")",
"NYSIIS(?)",
"removeBlankSpace(?)",
"removeDiacritic(?)",
"removeNonAscii(?)",
"removeNonPrintable(?)",
"replace(?, \"a\", \"a\")",
"translate(?, \"ab\", \"cd\")",
"trim(?)",
"upperCase(?)",
"chop(?)",
"concat(?)",
"getAlphanumericChars(?)",
};
StringBuilder sb = new StringBuilder();
for (String expr : expressions) {
String emptyString = expr.replace("?", "\"\"");
boolean crashesEmpty = test_expression_crashes(emptyString);
assertFalse("Function " + emptyString + " crashed", crashesEmpty);
String nullString = expr.replace("?", "null");
boolean crashesNull = test_expression_crashes(nullString);
sb.append(String.format("|%20s|%5s|%5s|%n", expr, crashesEmpty ? "CRASH" : "ok", crashesNull ? "CRASH" : "ok"));
}
System.out.println(sb.toString());
}
private boolean test_expression_crashes(String expr) {
String expStr = "function integer transform() { " + expr + "; return 0; }";
try {
doCompile(expStr, "test_stringlib_empty_null_strings");
return false;
} catch (RuntimeException e) {
return true;
}
}
public void test_stringlib_removeBlankSpace() {
String expStr =
"string r1;\n" +
"string str_empty;\n" +
"string str_null;\n" +
"function integer transform() {\n" +
"r1=removeBlankSpace(\"" + StringUtils.specCharToString(" a b\nc\rd e \u000Cf\r\n") + "\");\n" +
"printErr(r1);\n" +
"str_empty = removeBlankSpace('');\n" +
"str_null = removeBlankSpace(null);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr, "test_removeBlankSpace");
check("r1", "abcdef");
check("str_empty", "");
check("str_null", null);
}
public void test_stringlib_removeNonPrintable() {
doCompile("test_stringlib_removeNonPrintable");
check("nonPrintableRemoved", "AHOJ");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_getAlphanumericChars() {
String expStr =
"string an1;\n" +
"string an2;\n" +
"string an3;\n" +
"string an4;\n" +
"string an5;\n" +
"string an6;\n" +
"string an7;\n" +
"string an8;\n" +
"string an9;\n" +
"string an10;\n" +
"string an11;\n" +
"string an12;\n" +
"string an13;\n" +
"string an14;\n" +
"string an15;\n" +
"function integer transform() {\n" +
"an1=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\");\n" +
"an2=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,true);\n" +
"an3=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,false);\n" +
"an4=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,true);\n" +
"an5=getAlphanumericChars(\"\");\n" +
"an6=getAlphanumericChars(\"\",true,true);\n"+
"an7=getAlphanumericChars(\"\",true,false);\n"+
"an8=getAlphanumericChars(\"\",false,true);\n"+
"an9=getAlphanumericChars(null);\n" +
"an10=getAlphanumericChars(null,false,false);\n" +
"an11=getAlphanumericChars(null,true,false);\n" +
"an12=getAlphanumericChars(null,false,true);\n" +
"an13=getAlphanumericChars(' 0 ľeškó11');\n" +
"an14=getAlphanumericChars(' 0 ľeškó11', false, false);\n" +
//CLO-1174
"string tmp = \""+StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\";\n"+
"printErr('BEFORE DO COMPILE: '+tmp); \n"+
"an15=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,false);\n" +
"printErr('AFTER GET_ALPHA_NUMERIC_CHARS: '+ an15);\n" +
"return 0;\n" +
"}\n";
doCompile(expStr, "test_getAlphanumericChars");
check("an1", "a1bcde2f");
check("an2", "a1bcde2f");
check("an3", "abcdef");
check("an4", "12");
check("an5", "");
check("an6", "");
check("an7", "");
check("an8", "");
check("an9", null);
check("an10", null);
check("an11", null);
check("an12", null);
check("an13", "0ľeškó11");
check("an14"," 0 ľeškó11");
//CLO-1174
String tmp = StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n");
System.out.println("FROM JAVA - AFTER DO COMPILE: "+ tmp);
//check("an15", tmp);
}
public void test_stringlib_indexOf(){
doCompile("test_stringlib_indexOf");
check("index",2);
check("index1",9);
check("index2",0);
check("index3",-1);
check("index4",6);
check("index5",-1);
check("index6",0);
check("index7",4);
check("index8",4);
check("index9", -1);
check("index10", 2);
check("index_empty1", -1);
check("index_empty2", 0);
check("index_empty3", 0);
check("index_empty4", -1);
}
public void test_stringlib_indexOf_expect_error(){
//test: second arg is null - test1
try {
doCompile("integer index;function integer transform() {index = indexOf('hello world',null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: second arg is null - test2
try {
doCompile("integer index;function integer transform() {index = indexOf('',null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: first arg is null - test1
try {
doCompile("integer index;function integer transform() {index = indexOf(null,'a'); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: first arg is null - test2
try {
doCompile("integer index;function integer transform() {index = indexOf(null,''); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: both args are null
try {
doCompile("integer index;function integer transform() {index = indexOf(null,null); return 0;}","test_stringlib_indexOf_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_removeDiacritic(){
doCompile("test_stringlib_removeDiacritic");
check("test","tescik");
check("test1","zabicka");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_translate(){
doCompile("test_stringlib_translate");
check("trans","hippi");
check("trans1","hipp");
check("trans2","hippi");
check("trans3","");
check("trans4","y lanuaX nXXd thX lXttXr X");
check("trans5", "hello");
check("test_empty1", "");
check("test_empty2", "");
check("test_null", null);
}
public void test_stringlib_translate_expect_error(){
try {
doCompile("function integer transform(){string test = translate('bla bla',null,'o');return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate('bla bla','a',null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate('bla bla',null,null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,'a',null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,null,'a');return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string test = translate(null,null,null);return 0;}","test_stringlib_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_removeNonAscii(){
doCompile("test_stringlib_removeNonAscii");
check("test1", "Sun is shining");
check("test2", "");
check("test_empty", "");
check("test_null", null);
}
public void test_stringlib_chop() {
doCompile("test_stringlib_chop");
check("s1", "hello");
check("s6", "hello");
check("s5", "hello");
check("s2", "hello");
check("s7", "helloworld");
check("s3", "hello ");
check("s4", "hello");
check("s8", "hello");
check("s9", "world");
check("s10", "hello");
check("s11", "world");
check("s12", "mark.twain");
check("s13", "two words");
check("s14", "");
check("s15", "");
check("s16", "");
check("s17", "");
check("s18", "");
check("s19", "word");
check("s20", "");
check("s21", "");
check("s22", "mark.twain");
}
public void test_stringlib_chop_expect_error() {
//test: arg is null
try {
doCompile("string test;function integer transform() {test = chop(null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp pattern is null
try {
doCompile("string test;function integer transform() {test = chop('aaa', null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: regexp pattern is null - test 2
try {
doCompile("string test;function integer transform() {test = chop('', null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null
try {
doCompile("string test;function integer transform() {test = chop(null, 'aaa');return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null - test2
try {
doCompile("string test;function integer transform() {test = chop(null, '');return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: arg is null - test3
try {
doCompile("string test;function integer transform() {test = chop(null, null);return 0;}","test_strlib_chop_erxpect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_bitSet(){
doCompile("test_bitwise_bitSet");
check("test1", 3);
check("test2", 15);
check("test3", 34);
check("test4", 3l);
check("test5", 15l);
check("test6", 34l);
}
public void test_bitwise_bitSet_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer var1 = null;"
+ "integer var2 = 3;"
+ "boolean var3 = false;"
+ "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer var1 = 512;"
+ "integer var2 = null;"
+ "boolean var3 = false;"
+ "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer var1 = 512;"
+ "integer var2 = 3;"
+ "boolean var3 = null;"
+ "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = 512l;"
+ "integer var2 = 3;"
+ "boolean var3 = null;"
+ "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = 512l;"
+ "integer var2 = null;"
+ "boolean var3 = true;"
+ "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = null;"
+ "integer var2 = 3;"
+ "boolean var3 = true;"
+ "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_bitIsSet(){
doCompile("test_bitwise_bitIsSet");
check("test1", true);
check("test2", false);
check("test3", false);
check("test4", false);
check("test5", true);
check("test6", false);
check("test7", false);
check("test8", false);
}
public void test_bitwise_bitIsSet_expect_error(){
try {
doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(11,i); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = 12l; boolean b = bitIsSet(i,null); return 0;}","test_bitwise_bitIsSet_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_or() {
doCompile("test_bitwise_or");
check("resultInt1", 1);
check("resultInt2", 1);
check("resultInt3", 3);
check("resultInt4", 3);
check("resultLong1", 1l);
check("resultLong2", 1l);
check("resultLong3", 3l);
check("resultLong4", 3l);
}
public void test_bitwise_or_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer input1 = 12; "
+ "integer input2 = null; "
+ "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer input1 = null; "
+ "integer input2 = 13; "
+ "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long input1 = null; "
+ "long input2 = 13l; "
+ "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long input1 = 23l; "
+ "long input2 = null; "
+ "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_and() {
doCompile("test_bitwise_and");
check("resultInt1", 0);
check("resultInt2", 1);
check("resultInt3", 0);
check("resultInt4", 1);
check("resultLong1", 0l);
check("resultLong2", 1l);
check("resultLong3", 0l);
check("resultLong4", 1l);
//CLO-1385
// check("test_mixed1", 12l);
// check("test_mixed2", 12l);
}
public void test_bitwise_and_expect_error(){
try {
doCompile("function integer transform(){\n"
+ "integer a = null; integer b = 16;\n"
+ "integer i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "integer a = 16; integer b = null;\n"
+ "integer i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "long a = 16l; long b = null;\n"
+ "long i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){\n"
+ "long a = null; long b = 10l;\n"
+ "long i = bitAnd(a,b);\n"
+ "return 0;}",
"test_bitwise_end_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_xor() {
doCompile("test_bitwise_xor");
check("resultInt1", 1);
check("resultInt2", 0);
check("resultInt3", 3);
check("resultInt4", 2);
check("resultLong1", 1l);
check("resultLong2", 0l);
check("resultLong3", 3l);
check("resultLong4", 2l);
}
public void test_bitwise_xor_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer var1 = null;"
+ "integer var2 = 123;"
+ "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "integer var1 = 23;"
+ "integer var2 = null;"
+ "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = null;"
+ "long var2 = 123l;"
+ "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "long var1 = 2135l;"
+ "long var2 = null;"
+ "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_lshift() {
doCompile("test_bitwise_lshift");
check("resultInt1", 2);
check("resultInt2", 4);
check("resultInt3", 10);
check("resultInt4", 20);
check("resultInt5", -2147483648);
check("resultLong1", 2l);
check("resultLong2", 4l);
check("resultLong3", 10l);
check("resultLong4", 20l);
check("resultLong5",-9223372036854775808l);
}
public void test_bitwise_lshift_expect_error(){
try {
doCompile("function integer transform(){integer input = null; integer i = bitLShift(input,2); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer input = null; integer i = bitLShift(44,input); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitLShift(input,4l); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitLShift(444l,input); return 0;}","test_bitwise_lshift_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_bitwise_rshift() {
doCompile("test_bitwise_rshift");
check("resultInt1", 2);
check("resultInt2", 0);
check("resultInt3", 4);
check("resultInt4", 2);
check("resultLong1", 2l);
check("resultLong2", 0l);
check("resultLong3", 4l);
check("resultLong4", 2l);
check("test_neg1", 0);
check("test_neg2", 0);
check("test_neg3", 0l);
check("test_neg4", 0l);
// CLO-1399
// check("test_mix1", 2);
// check("test_mix2", 2);
}
public void test_bitwise_rshift_expect_error(){
try {
doCompile("function integer transform(){"
+ "integer var1 = 23;"
+ "integer var2 = null;"
+ "integer i = bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){"
+ "integer var1 = null;"
+ "integer var2 = 78;"
+ "integer u = bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){"
+ "long var1 = 23l;"
+ "long var2 = null;"
+ "long l =bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){"
+ "long var1 = null;"
+ "long var2 = 84l;"
+ "long l = bitRShift(var1,var2);"
+ "return 0;}","test_bitwise_rshift_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_bitwise_negate() {
doCompile("test_bitwise_negate");
check("resultInt", -59081717);
check("resultLong", -3321654987654105969L);
check("test_zero_int", -1);
check("test_zero_long", -1l);
}
public void test_bitwise_negate_expect_error(){
try {
doCompile("function integer transform(){integer input = null; integer i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; long i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_set_bit() {
doCompile("test_set_bit");
check("resultInt1", 0x2FF);
check("resultInt2", 0xFB);
check("resultLong1", 0x4000000000000l);
check("resultLong2", 0xFFDFFFFFFFFFFFFl);
check("resultBool1", true);
check("resultBool2", false);
check("resultBool3", true);
check("resultBool4", false);
}
public void test_mathlib_abs() {
doCompile("test_mathlib_abs");
check("absIntegerPlus", new Integer(10));
check("absIntegerMinus", new Integer(1));
check("absLongPlus", new Long(10));
check("absLongMinus", new Long(1));
check("absDoublePlus", new Double(10.0));
check("absDoubleMinus", new Double(1.0));
check("absDecimalPlus", new BigDecimal(5.0));
check("absDecimalMinus", new BigDecimal(5.0));
}
public void test_mathlib_abs_expect_error(){
try {
doCompile("function integer transform(){ \n "
+ "integer tmp;\n "
+ "tmp = null; \n"
+ " integer i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "long tmp;\n "
+ "tmp = null; \n"
+ "long i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "double tmp;\n "
+ "tmp = null; \n"
+ "double i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){ \n "
+ "decimal tmp;\n "
+ "tmp = null; \n"
+ "decimal i = abs(tmp); \n "
+ "return 0;}",
"test_mathlib_abs_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_ceil() {
doCompile("test_mathlib_ceil");
check("ceil1", -3.0);
check("intResult", Arrays.asList(2.0, 3.0));
check("longResult", Arrays.asList(2.0, 3.0));
check("doubleResult", Arrays.asList(3.0, -3.0));
check("decimalResult", Arrays.asList(3.0, -3.0));
}
public void test_mathlib_ceil_expect_error(){
try {
doCompile("function integer transform(){integer var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_e() {
doCompile("test_mathlib_e");
check("varE", Math.E);
}
public void test_mathlib_exp() {
doCompile("test_mathlib_exp");
check("ex", Math.exp(1.123));
check("test1", Math.exp(2));
check("test2", Math.exp(22));
check("test3", Math.exp(23));
check("test4", Math.exp(94));
}
public void test_mathlib_exp_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_floor() {
doCompile("test_mathlib_floor");
check("floor1", -4.0);
check("intResult", Arrays.asList(2.0, 3.0));
check("longResult", Arrays.asList(2.0, 3.0));
check("doubleResult", Arrays.asList(2.0, -4.0));
check("decimalResult", Arrays.asList(2.0, -4.0));
}
public void test_math_lib_floor_expect_error(){
try {
doCompile("function integer transform(){integer input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input= null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_log() {
doCompile("test_mathlib_log");
check("ln", Math.log(3));
check("test_int", Math.log(32));
check("test_long", Math.log(14l));
check("test_double", Math.log(12.9));
check("test_decimal", Math.log(23.7));
}
public void test_math_log_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){long input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){decimal input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){double input = null; number n = log(input); return 0;}","test_math_log_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_mathlib_log10() {
doCompile("test_mathlib_log10");
check("varLog10", Math.log10(3));
check("test_int", Math.log10(5));
check("test_long", Math.log10(90L));
check("test_decimal", Math.log10(32.1));
check("test_number", Math.log10(84.12));
}
public void test_mathlib_log10_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_pi() {
doCompile("test_mathlib_pi");
check("varPi", Math.PI);
}
public void test_mathlib_pow() {
doCompile("test_mathlib_pow");
check("power1", Math.pow(3,1.2));
check("power2", Double.NaN);
check("intResult", Arrays.asList(8d, 8d, 8d, 8d));
check("longResult", Arrays.asList(8d, 8d, 8d, 8d));
check("doubleResult", Arrays.asList(8d, 8d, 8d, 8d));
check("decimalResult", Arrays.asList(8d, 8d, 8d, 8d));
}
public void test_mathlib_pow_expect_error(){
try {
doCompile("function integer transform(){integer var1 = 12; integer var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer var1 = null; integer var2 = 2; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long var1 = 12l; long var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long var1 = null; long var2 = 12L; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number var1 = 12.2; number var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number var1 = null; number var2 = 2.1; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal var1 = 12.2d; decimal var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal var1 = null; decimal var2 = 45.3d; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_round() {
doCompile("test_mathlib_round");
check("round1", -4l);
check("intResult", Arrays.asList(2l, 3l));
check("longResult", Arrays.asList(2l, 3l));
check("doubleResult", Arrays.asList(2l, 4l));
check("decimalResult", Arrays.asList(2l, 4l));
}
public void test_mathlib_round_expect_error(){
try {
doCompile("function integer transform(){number input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_sqrt() {
doCompile("test_mathlib_sqrt");
check("sqrtPi", Math.sqrt(Math.PI));
check("sqrt9", Math.sqrt(9));
check("test_int", 2.0);
check("test_long", Math.sqrt(64L));
check("test_num", Math.sqrt(86.9));
check("test_dec", Math.sqrt(34.5));
}
public void test_mathlib_sqrt_expect_error(){
try {
doCompile("function integer transform(){integer input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){number input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_randomInteger(){
doCompile("test_mathlib_randomInteger");
assertNotNull(getVariable("test1"));
check("test2", 2);
}
public void test_mathlib_randomInteger_expect_error(){
try {
doCompile("function integer transform(){integer i = randomInteger(1,null); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = randomInteger(null,null); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = randomInteger(null, -3); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = randomInteger(1,-7); return 0;}","test_mathlib_randomInteger_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_mathlib_randomLong(){
doCompile("test_mathlib_randomLong");
assertNotNull(getVariable("test1"));
check("test2", 15L);
}
public void test_mathlib_randomLong_expect_error(){
try {
doCompile("function integer transform(){long lo = randomLong(15L, null); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long lo = randomLong(null, null); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long lo = randomLong(null, 15L); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long lo = randomLong(15L, 10L); return 0;}","test_mathlib_randomLong_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_cache() {
doCompile("test_datelib_cache");
check("b11", true);
check("b12", true);
check("b21", true);
check("b22", true);
check("b31", true);
check("b32", true);
check("b41", true);
check("b42", true);
checkEquals("date3", "date3d");
checkEquals("date4", "date4d");
checkEquals("date7", "date7d");
checkEquals("date8", "date8d");
}
public void test_datelib_trunc() {
doCompile("test_datelib_trunc");
check("truncDate", new GregorianCalendar(2004, 00, 02).getTime());
}
public void test_datelib_truncDate() {
doCompile("test_datelib_truncDate");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)};
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, portion[0]);
cal.set(Calendar.MINUTE, portion[1]);
cal.set(Calendar.SECOND, portion[2]);
cal.set(Calendar.MILLISECOND, portion[3]);
check("truncBornDate", cal.getTime());
}
public void test_datelib_today() {
doCompile("test_datelib_today");
Date expectedDate = new Date();
//the returned date does not need to be exactly the same date which is in expectedData variable
//let say 1000ms is tolerance for equality
assertTrue("todayDate", Math.abs(expectedDate.getTime() - ((Date) getVariable("todayDate")).getTime()) < 1000);
}
public void test_datelib_zeroDate() {
doCompile("test_datelib_zeroDate");
check("zeroDate", new Date(0));
}
public void test_datelib_dateDiff() {
doCompile("test_datelib_dateDiff");
long diffYears = Years.yearsBetween(new DateTime(), new DateTime(BORN_VALUE)).getYears();
check("ddiff", diffYears);
long[] results = {1, 12, 52, 365, 8760, 525600, 31536000, 31536000000L};
String[] vars = {"ddiffYears", "ddiffMonths", "ddiffWeeks", "ddiffDays", "ddiffHours", "ddiffMinutes", "ddiffSeconds", "ddiffMilliseconds"};
for (int i = 0; i < results.length; i++) {
check(vars[i], results[i]);
}
}
public void test_datelib_dateDiff_epect_error(){
try {
doCompile("function integer transform(){long i = dateDiff(null,today(),millisec);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = dateDiff(today(),null,millisec);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = dateDiff(today(),today(),null);return 0;}","test_datelib_dateDiff_epect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_dateAdd() {
doCompile("test_datelib_dateAdd");
check("datum", new Date(BORN_MILLISEC_VALUE + 100));
}
public void test_datelib_dateAdd_expect_error(){
try {
doCompile("function integer transform(){date d = dateAdd(null,120,second); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = dateAdd(today(),null,second); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = dateAdd(today(),120,null); return 0;}","test_datelib_dateAdd_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_extractTime() {
doCompile("test_datelib_extractTime");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)};
cal.clear();
cal.set(Calendar.HOUR_OF_DAY, portion[0]);
cal.set(Calendar.MINUTE, portion[1]);
cal.set(Calendar.SECOND, portion[2]);
cal.set(Calendar.MILLISECOND, portion[3]);
check("bornExtractTime", cal.getTime());
check("originalDate", BORN_VALUE);
}
public void test_datelib_extractTime_expect_error(){
try {
doCompile("function integer transform(){date d = extractTime(null); return 0;}","test_datelib_extractTime_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_extractDate() {
doCompile("test_datelib_extractDate");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
int[] portion = new int[]{cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)};
cal.clear();
cal.set(Calendar.DAY_OF_MONTH, portion[0]);
cal.set(Calendar.MONTH, portion[1]);
cal.set(Calendar.YEAR, portion[2]);
check("bornExtractDate", cal.getTime());
check("originalDate", BORN_VALUE);
}
public void test_datelib_extractDate_expect_error(){
try {
doCompile("function integer transform(){date d = extractDate(null); return 0;}","test_datelib_extractDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_createDate() {
doCompile("test_datelib_createDate");
Calendar cal = Calendar.getInstance();
// no time zone
cal.clear();
cal.set(2013, 5, 11);
check("date1", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime1", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis1", cal.getTime());
// literal
cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
cal.clear();
cal.set(2013, 5, 11);
check("date2", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime2", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis2", cal.getTime());
// variable
cal.clear();
cal.set(2013, 5, 11);
check("date3", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
check("dateTime3", cal.getTime());
cal.clear();
cal.set(2013, 5, 11, 14, 27, 53);
cal.set(Calendar.MILLISECOND, 123);
check("dateTimeMillis3", cal.getTime());
}
public void test_datelib_getPart() {
doCompile("test_datelib_getPart");
Calendar cal = Calendar.getInstance();
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT+1"));
cal.set(2013, 5, 11, 14, 46, 34);
cal.set(Calendar.MILLISECOND, 123);
Date date = cal.getTime();
cal = Calendar.getInstance();
cal.setTime(date);
// no time zone
check("year1", cal.get(Calendar.YEAR));
check("month1", cal.get(Calendar.MONTH) + 1);
check("day1", cal.get(Calendar.DAY_OF_MONTH));
check("hour1", cal.get(Calendar.HOUR_OF_DAY));
check("minute1", cal.get(Calendar.MINUTE));
check("second1", cal.get(Calendar.SECOND));
check("millisecond1", cal.get(Calendar.MILLISECOND));
cal.setTimeZone(TimeZone.getTimeZone("GMT+5"));
// literal
check("year2", cal.get(Calendar.YEAR));
check("month2", cal.get(Calendar.MONTH) + 1);
check("day2", cal.get(Calendar.DAY_OF_MONTH));
check("hour2", cal.get(Calendar.HOUR_OF_DAY));
check("minute2", cal.get(Calendar.MINUTE));
check("second2", cal.get(Calendar.SECOND));
check("millisecond2", cal.get(Calendar.MILLISECOND));
// variable
check("year3", cal.get(Calendar.YEAR));
check("month3", cal.get(Calendar.MONTH) + 1);
check("day3", cal.get(Calendar.DAY_OF_MONTH));
check("hour3", cal.get(Calendar.HOUR_OF_DAY));
check("minute3", cal.get(Calendar.MINUTE));
check("second3", cal.get(Calendar.SECOND));
check("millisecond3", cal.get(Calendar.MILLISECOND));
check("year_null", 2013);
check("month_null", 6);
check("day_null", 11);
check("hour_null", 15);
check("minute_null", cal.get(Calendar.MINUTE));
check("second_null", cal.get(Calendar.SECOND));
check("milli_null", cal.get(Calendar.MILLISECOND));
}
public void test_datelib_getPart_expect_error(){
try {
doCompile("function integer transform(){integer i = getYear(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getMonth(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getDay(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getHour(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getMinute(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getSecond(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = getMillisecond(null); return 0;}","test_datelib_getPart_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_datelib_randomDate() {
doCompile("test_datelib_randomDate");
final long HOUR = 60L * 60L * 1000L;
Date BORN_VALUE_NO_MILLIS = new Date(BORN_VALUE.getTime() / 1000L * 1000L);
check("noTimeZone1", BORN_VALUE);
check("noTimeZone2", BORN_VALUE_NO_MILLIS);
check("withTimeZone1", new Date(BORN_VALUE_NO_MILLIS.getTime() + 2*HOUR)); // timezone changes from GMT+5 to GMT+3
check("withTimeZone2", new Date(BORN_VALUE_NO_MILLIS.getTime() - 2*HOUR)); // timezone changes from GMT+3 to GMT+5
assertNotNull(getVariable("patt_null"));
}
public void test_datelib_randomDate_expect_error(){
try {
doCompile("function integer transform(){date a = null; date b = today(); "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date a = today(); date b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date a = null; date b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = 843484317231l; long b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = null; long b = 12115641158l; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long a = null; long b = null; "
+ "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "string a = null; string b = '2006-11-12'; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){"
+ "string a = '2006-11-12'; string b = null; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//wrong format
try {
doCompile("function integer transform(){"
+ "string a = '2006-10-12'; string b = '2006-11-12'; string pattern='yyyy:MM:dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//start date bigger then end date
try {
doCompile("function integer transform(){"
+ "string a = '2008-10-12'; string b = '2006-11-12'; string pattern='yyyy-MM-dd';"
+ "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_cache() {
// set default locale to en.US so the date is formatted uniformly on all systems
Locale.setDefault(Locale.US);
doCompile("test_convertlib_cache");
Calendar cal = Calendar.getInstance();
cal.set(2000, 6, 20, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date checkDate = cal.getTime();
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy MMM dd");
check("sdate1", format.format(new Date()));
check("sdate2", format.format(new Date()));
check("date01", checkDate);
check("date02", checkDate);
check("date03", checkDate);
check("date04", checkDate);
check("date11", checkDate);
check("date12", checkDate);
check("date13", checkDate);
}
public void test_convertlib_base64byte() {
doCompile("test_convertlib_base64byte");
assertTrue(Arrays.equals((byte[])getVariable("base64input"), Base64.decode("The quick brown fox jumps over the lazy dog")));
}
public void test_convertlib_base64byte_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){byte b = base64byte(null); return 0;}","test_convertlib_base64byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_bits2str() {
doCompile("test_convertlib_bits2str");
check("bitsAsString1", "00000000");
check("bitsAsString2", "11111111");
check("bitsAsString3", "010100000100110110100000");
}
public void test_convertlib_bits2str_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = bits2str(null); return 0;}","test_convertlib_bits2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_bool2num() {
doCompile("test_convertlib_bool2num");
check("resultTrue", 1);
check("resultFalse", 0);
}
public void test_convertlib_bool2num_expect_error(){
// CLO-1255
// //this test should be expected to success in future
// try {
// doCompile("function integer transform(){integer s = bool2num(null);return 0;}","test_convertlib_bool2num_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_byte2base64() {
doCompile("test_convertlib_byte2base64");
check("inputBase64", Base64.encodeBytes("Abeceda zedla deda".getBytes()));
}
public void test_convertlib_byte2base64_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = byte2base64(null);return 0;}","test_convertlib_byte2base64_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_byte2hex() {
doCompile("test_convertlib_byte2hex");
check("hexResult", "41626563656461207a65646c612064656461");
check("test_null", null);
}
public void test_convertlib_date2long() {
doCompile("test_convertlib_date2long");
check("bornDate", BORN_MILLISEC_VALUE);
check("zeroDate", 0l);
}
public void test_convertlib_date2long_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){long l = date2long(null);return 0;}","test_convertlib_date2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_date2num() {
doCompile("test_convertlib_date2num");
Calendar cal = Calendar.getInstance();
cal.setTime(BORN_VALUE);
check("yearDate", 1987);
check("monthDate", 5);
check("secondDate", 0);
check("yearBorn", cal.get(Calendar.YEAR));
check("monthBorn", cal.get(Calendar.MONTH) + 1); //Calendar enumerates months from 0, not 1;
check("secondBorn", cal.get(Calendar.SECOND));
check("yearMin", 1970);
check("monthMin", 1);
check("weekMin", 1);
check("weekMinCs", 1);
check("dayMin", 1);
check("hourMin", 1); //TODO: check!
check("minuteMin", 0);
check("secondMin", 0);
check("millisecMin", 0);
}
public void test_convertlib_date2num_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){number num = date2num(null,null); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
//this test should be expected to success in future
try {
doCompile("function integer transform(){number num = date2num(1982-09-02,null); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
//this test should be expected to success in future
try {
doCompile("function integer transform(){number num = date2num(null,year); return 0;}","test_convertlib_date2num_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_date2str() {
doCompile("test_convertlib_date2str");
check("inputDate", "1987:05:12");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd");
check("bornDate", sdf.format(BORN_VALUE));
SimpleDateFormat sdfCZ = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("cs.CZ"));
check("czechBornDate", sdfCZ.format(BORN_VALUE));
SimpleDateFormat sdfEN = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("en"));
check("englishBornDate", sdfEN.format(BORN_VALUE));
{
String[] locales = {"en", "pl", null, "cs.CZ", null};
List<String> expectedDates = new ArrayList<String>();
for (String locale: locales) {
expectedDates.add(new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale(locale)).format(BORN_VALUE));
}
check("loopTest", expectedDates);
}
SimpleDateFormat sdfGMT8 = new SimpleDateFormat("yyyy:MMMM:dd z", MiscUtils.createLocale("en"));
sdfGMT8.setTimeZone(TimeZone.getTimeZone("GMT+8"));
check("timeZone", sdfGMT8.format(BORN_VALUE));
}
public void test_convertlib_date2str_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){string s = date2str(null,'yyyy:MMMM:dd', 'cs.CZ', 'GMT+8');return 0;}","test_convertlib_date2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = date2str(1985-11-12,null, 'cs.CZ', 'GMT+8');return 0;}","test_convertlib_date2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_decimal2double() {
doCompile("test_convertlib_decimal2double");
check("toDouble", 0.007d);
}
public void test_convertlib_decimal2double_except_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){double d = decimal2double(null); return 0;}","test_convertlib_decimal2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_decimal2integer() {
doCompile("test_convertlib_decimal2integer");
check("toInteger", 0);
check("toInteger2", -500);
check("toInteger3", 1000000);
}
public void test_convertlib_decimal2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = decimal2integer(null); return 0;}","test_convertlib_decimal2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_decimal2long() {
doCompile("test_convertlib_decimal2long");
check("toLong", 0l);
check("toLong2", -500l);
check("toLong3", 10000000000l);
}
public void test_convertlib_decimal2long_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){long i = decimal2long(null); return 0;}","test_convertlib_decimal2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_double2integer() {
doCompile("test_convertlib_double2integer");
check("toInteger", 0);
check("toInteger2", -500);
check("toInteger3", 1000000);
}
public void test_convertlib_double2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = double2integer(null); return 0;}","test_convertlib_doublel2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_double2long() {
doCompile("test_convertlib_double2long");
check("toLong", 0l);
check("toLong2", -500l);
check("toLong3", 10000000000l);
}
public void test_convertlib_double2long_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){long l = double2long(null); return 0;}","test_convertlib_doublel2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_getFieldName() {
doCompile("test_convertlib_getFieldName");
check("fieldNames",Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency"));
}
public void test_convertlib_getFieldType() {
doCompile("test_convertlib_getFieldType");
check("fieldTypes",Arrays.asList(DataFieldType.STRING.getName(), DataFieldType.NUMBER.getName(), DataFieldType.STRING.getName(),
DataFieldType.DATE.getName(), DataFieldType.LONG.getName(), DataFieldType.INTEGER.getName(), DataFieldType.BOOLEAN.getName(),
DataFieldType.BYTE.getName(), DataFieldType.DECIMAL.getName()));
}
public void test_convertlib_hex2byte() {
doCompile("test_convertlib_hex2byte");
assertTrue(Arrays.equals((byte[])getVariable("fromHex"), BYTEARRAY_VALUE));
check("test_null", null);
}
public void test_convertlib_long2date() {
doCompile("test_convertlib_long2date");
check("fromLong1", new Date(0));
check("fromLong2", new Date(50000000000L));
check("fromLong3", new Date(-5000L));
}
public void test_convertlib_long2date_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){date d = long2date(null); return 0;}","test_convertlib_long2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_long2integer() {
doCompile("test_convertlib_long2integer");
check("fromLong1", 10);
check("fromLong2", -10);
}
public void test_convertlib_long2integer_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){integer i = long2integer(null); return 0;}","test_convertlib_long2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_long2packDecimal() {
doCompile("test_convertlib_long2packDecimal");
assertTrue(Arrays.equals((byte[])getVariable("packedLong"), new byte[] {5, 0, 12}));
}
public void test_convertlib_long2packDecimal_expect_error(){
//this test should be expected to success in future
try {
doCompile("function integer transform(){byte b = long2packDecimal(null); return 0;}","test_convertlib_long2packDecimal_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_md5() {
doCompile("test_convertlib_md5");
assertTrue(Arrays.equals((byte[])getVariable("md5Hash1"), Digest.digest(DigestType.MD5, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("md5Hash2"), Digest.digest(DigestType.MD5, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.MD5, "")));
}
public void test_convertlib_md5_expect_error(){
//CLO-1254
// //this test should be expected to success in future
// try {
// doCompile("function integer transform(){byte b = md5(null); return 0;}","test_convertlib_md5_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_num2bool() {
doCompile("test_convertlib_num2bool");
check("integerTrue", true);
check("integerFalse", false);
check("longTrue", true);
check("longFalse", false);
check("doubleTrue", true);
check("doubleFalse", false);
check("decimalTrue", true);
check("decimalFalse", false);
}
public void test_convertlib_num2bool_expect_error(){
//this test should be expected to success in future
//test: integer
try {
doCompile("integer input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: long
try {
doCompile("long input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: double
try {
doCompile("double input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: decimal
try {
doCompile("decimal input; function integer transform(){input=null; boolean b = num2bool(input); return 0;}","test_convertlib_num2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_num2str() {
System.out.println("num2str() test:");
doCompile("test_convertlib_num2str");
check("intOutput", Arrays.asList("16", "10000", "20", "10", "1.235E3", "12 350 001 Kcs"));
check("longOutput", Arrays.asList("16", "10000", "20", "10", "1.235E13", "12 350 001 Kcs"));
check("doubleOutput", Arrays.asList("16.16", "0x1.028f5c28f5c29p4", "1.23548E3", "12 350 001,1 Kcs"));
check("decimalOutput", Arrays.asList("16.16", "1235.44", "12 350 001,1 Kcs"));
check("test_null_dec", "NaN");
}
public void test_converlib_num2str_expect_error(){
//this test should be expected to success in future
//test: integer
try {
doCompile("integer input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: long
try {
doCompile("long input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//this test should be expected to success in future
//test: double
try {
doCompile("double input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
// //this test should be expected to success in future
// //test: decimal
// try {
// doCompile("decimal input; function integer transform(){input=null; string str = num2str(input); return 0;}","test_converlib_num2str_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_packdecimal2long() {
doCompile("test_convertlib_packDecimal2long");
check("unpackedLong", PackedDecimal.parse(BYTEARRAY_VALUE));
}
public void test_convertlib_packdecimal2long_expect_error(){
try {
doCompile("function integer transform(){long l =packDecimal2long(null); return 0;}","test_convertlib_packdecimal2long_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_sha() {
doCompile("test_convertlib_sha");
assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA, "")));
}
public void test_convertlib_sha_expect_error(){
// CLO-1258
// try {
// doCompile("function integer transform(){byte b = sha(null); return 0;}","test_convertlib_sha_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_sha256() {
doCompile("test_convertlib_sha256");
assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA256, "The quick brown fox jumps over the lazy dog")));
assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA256, BYTEARRAY_VALUE)));
assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA256, "")));
}
public void test_convertlib_sha256_expect_error(){
// CLO-1258
// try {
// doCompile("function integer transform(){byte b = sha256(null); return 0;}","test_convertlib_sha256_expect_error");
// fail();
// } catch (Exception e) {
// // do nothing
}
public void test_convertlib_str2bits() {
doCompile("test_convertlib_str2bits");
//TODO: uncomment -> test will pass, but is that correct?
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits1"), new byte[] {0/*, 0, 0, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits2"), new byte[] {-1/*, 0, 0, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("textAsBits3"), new byte[] {10, -78, 5/*, 0, 0, 0, 0, 0*/}));
assertTrue(Arrays.equals((byte[]) getVariable("test_empty"), new byte[] {}));
}
public void test_convertlib_str2bits_expect_error(){
try {
doCompile("function integer transform(){byte b = str2bits(null); return 0;}","test_convertlib_str2bits_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2bool() {
doCompile("test_convertlib_str2bool");
check("fromTrueString", true);
check("fromFalseString", false);
}
public void test_convertlib_str2bool_expect_error(){
try {
doCompile("function integer transform(){boolean b = str2bool('asd'); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){boolean b = str2bool(''); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
try {
doCompile("function integer transform(){boolean b = str2bool(null); return 0;}","test_convertlib_str2bool_expect_error");
fail();
} catch (Exception e) {
// do nothing;
}
}
public void test_convertlib_str2date() {
doCompile("test_convertlib_str2date");
Calendar cal = Calendar.getInstance();
cal.set(2050, 4, 19, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date checkDate = cal.getTime();
check("date1", checkDate);
check("date2", checkDate);
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
cal.set(2013, 04, 30, 17, 15, 12);
check("withTimeZone1", cal.getTime());
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("GMT-8"));
cal.set(2013, 04, 30, 17, 15, 12);
check("withTimeZone2", cal.getTime());
assertFalse(getVariable("withTimeZone1").equals(getVariable("withTimeZone2")));
}
public void test_convertlib_str2date_expect_error(){
try {
doCompile("function integer transform(){date d = str2date('1987-11-17', null); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date(null, 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date(null, null); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('1987-11-17', 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('1987-33-17', 'yyyy-MM-dd'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){date d = str2date('17.11.1987', null, 'cs.CZ'); return 0;}","test_convertlib_str2date_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2decimal() {
doCompile("test_convertlib_str2decimal");
check("parsedDecimal1", new BigDecimal("100.13"));
check("parsedDecimal2", new BigDecimal("123123123.123"));
check("parsedDecimal3", new BigDecimal("-350000.01"));
check("parsedDecimal4", new BigDecimal("1000000"));
check("parsedDecimal5", new BigDecimal("1000000.99"));
check("parsedDecimal6", new BigDecimal("123123123.123"));
check("parsedDecimal7", new BigDecimal("5.01"));
}
public void test_convertlib_str2decimal_expect_result(){
try {
doCompile("function integer transform(){decimal d = str2decimal(''); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal(null); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK','#.#CZ'); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){decimal d = str2decimal(null,'#.# US'); return 0;}","test_convertlib_str2decimal_expect_result");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2double() {
doCompile("test_convertlib_str2double");
check("parsedDouble1", 100.13);
check("parsedDouble2", 123123123.123);
check("parsedDouble3", -350000.01);
}
public void test_convertlib_str2double_expect_error(){
try {
doCompile("function integer transform(){double d = str2double(''); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double(null); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('text'); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('0.90c',null); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){double d = str2double('0.90c','#.# c'); return 0;}","test_convertlib_str2double_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2integer() {
doCompile("test_convertlib_str2integer");
check("parsedInteger1", 123456789);
check("parsedInteger2", 123123);
check("parsedInteger3", -350000);
check("parsedInteger4", 419);
}
public void test_convertlib_str2integer_expect_error(){
try {
doCompile("function integer transform(){integer i = str2integer('abc'); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = str2integer(''); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){integer i = str2integer(null); return 0;}","test_convertlib_str2integer_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_str2long() {
doCompile("test_convertlib_str2long");
check("parsedLong1", 1234567890123L);
check("parsedLong2", 123123123456789L);
check("parsedLong3", -350000L);
check("parsedLong4", 133L);
}
public void test_convertlib_str2long_expect_error(){
try {
doCompile("function integer transform(){long i = str2long('abc'); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long(''); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){long i = str2long(null); return 0;}","test_convertlib_str2long_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_toString() {
doCompile("test_convertlib_toString");
check("integerString", "10");
check("longString", "110654321874");
check("doubleString", "1.547874E-14");
check("decimalString", "-6847521431.1545874");
check("listString", "[not ALI A, not ALI B, not ALI D..., but, ALI H!]");
check("mapString", "{1=Testing, 2=makes, 3=me, 4=crazy :-)}");
String byteMapString = getVariable("byteMapString").toString();
assertTrue(byteMapString.contains("1=value1"));
assertTrue(byteMapString.contains("2=value2"));
String fieldByteMapString = getVariable("fieldByteMapString").toString();
assertTrue(fieldByteMapString.contains("key1=value1"));
assertTrue(fieldByteMapString.contains("key2=value2"));
check("byteListString", "[firstElement, secondElement]");
check("fieldByteListString", "[firstElement, secondElement]");
// CLO-1262
// check("test_null_l", "null");
// check("test_null_dec", "null");
// check("test_null_d", "null");
// check("test_null_i", "null");
}
public void test_convertlib_str2byte() {
doCompile("test_convertlib_str2byte");
checkArray("utf8Hello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("utf8Horse", new byte[] { 80, -59, -103, -61, -83, 108, 105, -59, -95, 32, -59, -66, 108, 117, -59, -91, 111, 117, -60, -115, 107, -61, -67, 32, 107, -59, -81, -59, -120, 32, 112, -60, -101, 108, 32, -60, -113, -61, -95, 98, 108, 115, 107, -61, -87, 32, -61, -77, 100, 121 });
checkArray("utf8Math", new byte[] { -62, -67, 32, -30, -123, -109, 32, -62, -68, 32, -30, -123, -107, 32, -30, -123, -103, 32, -30, -123, -101, 32, -30, -123, -108, 32, -30, -123, -106, 32, -62, -66, 32, -30, -123, -105, 32, -30, -123, -100, 32, -30, -123, -104, 32, -30, -126, -84, 32, -62, -78, 32, -62, -77, 32, -30, -128, -96, 32, -61, -105, 32, -30, -122, -112, 32, -30, -122, -110, 32, -30, -122, -108, 32, -30, -121, -110, 32, -30, -128, -90, 32, -30, -128, -80, 32, -50, -111, 32, -50, -110, 32, -30, -128, -109, 32, -50, -109, 32, -50, -108, 32, -30, -126, -84, 32, -50, -107, 32, -50, -106, 32, -49, -128, 32, -49, -127, 32, -49, -126, 32, -49, -125, 32, -49, -124, 32, -49, -123, 32, -49, -122, 32, -49, -121, 32, -49, -120, 32, -49, -119 });
checkArray("utf16Hello", new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 });
checkArray("utf16Horse", new byte[] { -2, -1, 0, 80, 1, 89, 0, -19, 0, 108, 0, 105, 1, 97, 0, 32, 1, 126, 0, 108, 0, 117, 1, 101, 0, 111, 0, 117, 1, 13, 0, 107, 0, -3, 0, 32, 0, 107, 1, 111, 1, 72, 0, 32, 0, 112, 1, 27, 0, 108, 0, 32, 1, 15, 0, -31, 0, 98, 0, 108, 0, 115, 0, 107, 0, -23, 0, 32, 0, -13, 0, 100, 0, 121 });
checkArray("utf16Math", new byte[] { -2, -1, 0, -67, 0, 32, 33, 83, 0, 32, 0, -68, 0, 32, 33, 85, 0, 32, 33, 89, 0, 32, 33, 91, 0, 32, 33, 84, 0, 32, 33, 86, 0, 32, 0, -66, 0, 32, 33, 87, 0, 32, 33, 92, 0, 32, 33, 88, 0, 32, 32, -84, 0, 32, 0, -78, 0, 32, 0, -77, 0, 32, 32, 32, 0, 32, 0, -41, 0, 32, 33, -112, 0, 32, 33, -110, 0, 32, 33, -108, 0, 32, 33, -46, 0, 32, 32, 38, 0, 32, 32, 48, 0, 32, 3, -111, 0, 32, 3, -110, 0, 32, 32, 19, 0, 32, 3, -109, 0, 32, 3, -108, 0, 32, 32, -84, 0, 32, 3, -107, 0, 32, 3, -106, 0, 32, 3, -64, 0, 32, 3, -63, 0, 32, 3, -62, 0, 32, 3, -61, 0, 32, 3, -60, 0, 32, 3, -59, 0, 32, 3, -58, 0, 32, 3, -57, 0, 32, 3, -56, 0, 32, 3, -55 });
checkArray("macHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("macHorse", new byte[] { 80, -34, -110, 108, 105, -28, 32, -20, 108, 117, -23, 111, 117, -117, 107, -7, 32, 107, -13, -53, 32, 112, -98, 108, 32, -109, -121, 98, 108, 115, 107, -114, 32, -105, 100, 121 });
checkArray("asciiHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("isoHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("isoHorse", new byte[] { 80, -8, -19, 108, 105, -71, 32, -66, 108, 117, -69, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 });
checkArray("cpHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 });
checkArray("cpHorse", new byte[] { 80, -8, -19, 108, 105, -102, 32, -98, 108, 117, -99, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 });
}
public void test_convertlib_str2byte_expect_error(){
try {
doCompile("function integer transform(){byte b = str2byte(null,'utf-8'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'utf-16'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'MacCentralEurope'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'ascii'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'iso-8859-2'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte(null,'windows-1250'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace','knock'); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_convertlib_byte2str() {
doCompile("test_convertlib_byte2str");
String hello = "Hello World!";
String horse = "Příliš žluťoučký kůň pěl ďáblské ódy";
String math = "½ ⅓ ¼ ⅕ ⅙ ⅛ ⅔ ⅖ ¾ ⅗ ⅜ ⅘ € ² ³ † × ← → ↔ ⇒ … ‰ Α Β – Γ Δ € Ε Ζ π ρ ς σ τ υ φ χ ψ ω";
check("utf8Hello", hello);
check("utf8Horse", horse);
check("utf8Math", math);
check("utf16Hello", hello);
check("utf16Horse", horse);
check("utf16Math", math);
check("macHello", hello);
check("macHorse", horse);
check("asciiHello", hello);
check("isoHello", hello);
check("isoHorse", horse);
check("cpHello", hello);
check("cpHorse", horse);
}
public void test_convertlib_byte2str_expect_error(){
try {
doCompile("function integer transform(){string s = byte2str(null,'utf-8'); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = byte2str(null,null); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
try {
doCompile("function integer transform(){string s = byte2str(str2byte('hello', 'utf-8'),null); return 0;}","test_convertlib_byte2str_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_conditional_fail() {
doCompile("test_conditional_fail");
check("result", 3);
}
public void test_expression_statement(){
// test case for issue 4174
doCompileExpectErrors("test_expression_statement", Arrays.asList("Syntax error, statement expected","Syntax error, statement expected"));
}
public void test_dictionary_read() {
doCompile("test_dictionary_read");
check("s", "Verdon");
check("i", Integer.valueOf(211));
check("l", Long.valueOf(226));
check("d", BigDecimal.valueOf(239483061));
check("n", Double.valueOf(934.2));
check("a", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime());
check("b", true);
byte[] y = (byte[]) getVariable("y");
assertEquals(10, y.length);
assertEquals(89, y[9]);
check("sNull", null);
check("iNull", null);
check("lNull", null);
check("dNull", null);
check("nNull", null);
check("aNull", null);
check("bNull", null);
check("yNull", null);
check("stringList", Arrays.asList("aa", "bb", null, "cc"));
check("dateList", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000)));
@SuppressWarnings("unchecked")
List<byte[]> byteList = (List<byte[]>) getVariable("byteList");
assertDeepEquals(byteList, Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78}));
}
public void test_dictionary_write() {
doCompile("test_dictionary_write");
assertEquals(832, graph.getDictionary().getValue("i") );
assertEquals("Guil", graph.getDictionary().getValue("s"));
assertEquals(Long.valueOf(540), graph.getDictionary().getValue("l"));
assertEquals(BigDecimal.valueOf(621), graph.getDictionary().getValue("d"));
assertEquals(934.2, graph.getDictionary().getValue("n"));
assertEquals(new GregorianCalendar(1992, GregorianCalendar.DECEMBER, 2).getTime(), graph.getDictionary().getValue("a"));
assertEquals(true, graph.getDictionary().getValue("b"));
byte[] y = (byte[]) graph.getDictionary().getValue("y");
assertEquals(2, y.length);
assertEquals(18, y[0]);
assertEquals(-94, y[1]);
assertEquals(Arrays.asList("xx", null), graph.getDictionary().getValue("stringList"));
assertEquals(Arrays.asList(new Date(98000), null, new Date(76000)), graph.getDictionary().getValue("dateList"));
@SuppressWarnings("unchecked")
List<byte[]> byteList = (List<byte[]>) graph.getDictionary().getValue("byteList");
assertDeepEquals(byteList, Arrays.asList(null, new byte[] {(byte) 0xAB, (byte) 0xCD}, new byte[] {(byte) 0xEF}));
check("assignmentReturnValue", "Guil");
}
public void test_dictionary_write_null() {
doCompile("test_dictionary_write_null");
assertEquals(null, graph.getDictionary().getValue("s"));
assertEquals(null, graph.getDictionary().getValue("sVerdon"));
assertEquals(null, graph.getDictionary().getValue("i") );
assertEquals(null, graph.getDictionary().getValue("i211") );
assertEquals(null, graph.getDictionary().getValue("l"));
assertEquals(null, graph.getDictionary().getValue("l452"));
assertEquals(null, graph.getDictionary().getValue("d"));
assertEquals(null, graph.getDictionary().getValue("d621"));
assertEquals(null, graph.getDictionary().getValue("n"));
assertEquals(null, graph.getDictionary().getValue("n9342"));
assertEquals(null, graph.getDictionary().getValue("a"));
assertEquals(null, graph.getDictionary().getValue("a1992"));
assertEquals(null, graph.getDictionary().getValue("b"));
assertEquals(null, graph.getDictionary().getValue("bTrue"));
assertEquals(null, graph.getDictionary().getValue("y"));
assertEquals(null, graph.getDictionary().getValue("yFib"));
}
public void test_dictionary_invalid_key(){
doCompileExpectErrors("test_dictionary_invalid_key", Arrays.asList("Dictionary entry 'invalid' does not exist"));
}
public void test_dictionary_string_to_int(){
doCompileExpectErrors("test_dictionary_string_to_int", Arrays.asList("Type mismatch: cannot convert from 'string' to 'integer'","Type mismatch: cannot convert from 'string' to 'integer'"));
}
public void test_utillib_sleep() {
long time = System.currentTimeMillis();
doCompile("test_utillib_sleep");
long tmp = System.currentTimeMillis() - time;
assertTrue("sleep() function didn't pause execution "+ tmp, tmp >= 1000);
}
public void test_utillib_random_uuid() {
doCompile("test_utillib_random_uuid");
assertNotNull(getVariable("uuid"));
}
public void test_stringlib_randomString(){
doCompile("string test; function integer transform(){test = randomString(1,3); return 0;}","test_stringlib_randomString");
assertNotNull(getVariable("test"));
}
public void test_stringlib_validUrl() {
doCompile("test_stringlib_url");
check("urlValid", Arrays.asList(true, true, false, true, false, true));
check("protocol", Arrays.asList("http", "https", null, "sandbox", null, "zip"));
check("userInfo", Arrays.asList("", "chuck:norris", null, "", null, ""));
check("host", Arrays.asList("example.com", "server.javlin.eu", null, "cloveretl.test.scenarios", null, ""));
check("port", Arrays.asList(-1, 12345, -2, -1, -2, -1));
check("path", Arrays.asList("", "/backdoor/trojan.cgi", null, "/graph/UDR_FileURL_SFTP_OneGzipFileSpecified.grf", null, "(sftp://test:test@koule/home/test/data-in/file2.zip)"));
check("query", Arrays.asList("", "hash=SHA560;god=yes", null, "", null, ""));
check("ref", Arrays.asList("", "autodestruct", null, "", null, "innerfolder2/URLIn21.txt"));
}
public void test_stringlib_escapeUrl() {
doCompile("test_stringlib_escapeUrl");
check("escaped", "http://example.com/foo%20bar%5E");
check("unescaped", "http://example.com/foo bar^");
}
public void test_stringlib_escapeUrl_unescapeUrl_expect_error(){
//test: escape - empty string
try {
doCompile("string test; function integer transform() {test = escapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: escape - null string
try {
doCompile("string test; function integer transform() {test = escapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescape - empty string
try {
doCompile("string test; function integer transform() {test = unescapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescape - null
try {
doCompile("string test; function integer transform() {test = unescapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: escape - invalid URL
try {
doCompile("string test; function integer transform() {test = escapeUrl('somewhere over the rainbow'); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
//test: unescpae - invalid URL
try {
doCompile("string test; function integer transform() {test = unescapeUrl('mister%20postman'); return 0;}","test_stringlib_escapeUrl_expect_error");
fail();
} catch (Exception e) {
// do nothing
}
}
public void test_stringlib_resolveParams() {
doCompile("test_stringlib_resolveParams");
check("resultNoParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
check("resultFalseFalseParams", "Special character representing new line is: \\n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in");
check("resultTrueFalseParams", "Special character representing new line is: \n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in");
check("resultFalseTrueParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
check("resultTrueTrueParams", "Special character representing new line is: \n calling CTL function MESSAGE; $DATAIN_DIR=./data-in");
}
public void test_utillib_getEnvironmentVariables() {
doCompile("test_utillib_getEnvironmentVariables");
check("empty", false);
}
public void test_utillib_getJavaProperties() {
String key1 = "my.testing.property";
String key2 = "my.testing.property2";
String value = "my value";
String value2;
assertNull(System.getProperty(key1));
assertNull(System.getProperty(key2));
System.setProperty(key1, value);
try {
doCompile("test_utillib_getJavaProperties");
value2 = System.getProperty(key2);
} finally {
System.clearProperty(key1);
assertNull(System.getProperty(key1));
System.clearProperty(key2);
assertNull(System.getProperty(key2));
}
check("java_specification_name", "Java Platform API Specification");
check("my_testing_property", value);
assertEquals("my value 2", value2);
}
public void test_utillib_getParamValues() {
doCompile("test_utillib_getParamValues");
Map<String, String> params = new HashMap<String, String>();
params.put("PROJECT", ".");
params.put("DATAIN_DIR", "./data-in");
params.put("COUNT", "3");
params.put("NEWLINE", "\\n"); // special characters should NOT be resolved
check("params", params);
}
public void test_utillib_getParamValue() {
doCompile("test_utillib_getParamValue");
Map<String, String> params = new HashMap<String, String>();
params.put("PROJECT", ".");
params.put("DATAIN_DIR", "./data-in");
params.put("COUNT", "3");
params.put("NEWLINE", "\\n"); // special characters should NOT be resolved
params.put("NONEXISTING", null);
check("params", params);
}
public void test_stringlib_getUrlParts() {
doCompile("test_stringlib_getUrlParts");
List<Boolean> isUrl = Arrays.asList(true, true, true, true, false);
List<String> path = Arrays.asList(
"/users/a6/15e83578ad5cba95c442273ea20bfa/msf-183/out5.txt",
"/data-in/fileOperation/input.txt",
"/data/file.txt",
"/data/file.txt",
null);
List<String> protocol = Arrays.asList("sftp", "sandbox", "ftp", "https", null);
List<String> host = Arrays.asList(
"ava-fileManipulator1-devel.getgooddata.com",
"cloveretl.test.scenarios",
"ftp.test.com",
"www.test.com",
null);
List<Integer> port = Arrays.asList(-1, -1, 21, 80, -2);
List<String> userInfo = Arrays.asList(
"user%40gooddata.com:password",
"",
"test:test",
"test:test",
null);
List<String> ref = Arrays.asList("", "", "", "", null);
List<String> query = Arrays.asList("", "", "", "", null);
check("isUrl", isUrl);
check("path", path);
check("protocol", protocol);
check("host", host);
check("port", port);
check("userInfo", userInfo);
check("ref", ref);
check("query", query);
check("isURL_empty", false);
check("path_empty", null);
check("protocol_empty", null);
check("host_empty", null);
check("port_empty", -2);
check("userInfo_empty", null);
check("ref_empty", null);
check("query_empty", null);
check("isURL_null", false);
check("path_null", null);
check("protocol_null", null);
check("host_null", null);
check("port_null", -2);
check("userInfo_null", null);
check("ref_null", null);
check("query_empty", null);
}
}
|
package org.voovan.network;
import org.voovan.network.exception.ReadMessageException;
import org.voovan.network.exception.SendMessageException;
import org.voovan.network.handler.SynchronousHandler;
import org.voovan.tools.buffer.ByteBufferChannel;
import org.voovan.tools.TEnv;
import org.voovan.tools.collection.Attributes;
import org.voovan.tools.event.EventRunner;
import org.voovan.tools.hashwheeltimer.HashWheelTask;
import org.voovan.tools.hashwheeltimer.HashWheelTimer;
import org.voovan.tools.log.Logger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.util.concurrent.TimeoutException;
public abstract class IoSession<T extends SocketContext> extends Attributes {
public static HashWheelTimer SOCKET_IDLE_WHEEL_TIME = null;
public static HashWheelTimer getIdleWheelTimer() {
if(SOCKET_IDLE_WHEEL_TIME == null) {
synchronized (IoSession.class) {
if(SOCKET_IDLE_WHEEL_TIME == null) {
SOCKET_IDLE_WHEEL_TIME = new HashWheelTimer("SocketIdle", 60, 1000);
SOCKET_IDLE_WHEEL_TIME.rotate();
}
}
}
return SOCKET_IDLE_WHEEL_TIME;
}
private boolean sslMode = false;
private SSLParser sslParser;
private MessageLoader messageLoader;
protected ByteBufferChannel readByteBufferChannel;
protected ByteBufferChannel sendByteBufferChannel;
private T socketContext;
private long lastIdleTime = -1;
private HashWheelTask checkIdleTask;
private HeartBeat heartBeat;
private State state;
private SelectionKey selectionKey;
private SocketSelector socketSelector;
public class State {
private volatile boolean init = true;
private volatile boolean connect = false;
private volatile boolean receive = false;
private volatile boolean send = false;
private volatile boolean flush = false;
private volatile boolean close = false;
public boolean isInit() {
return init;
}
public void setInit(boolean init) {
this.init = init;
}
public boolean isConnect() {
return connect;
}
public void setConnect(boolean connect) {
this.connect = connect;
}
public boolean isReceive() {
return receive;
}
public void setReceive(boolean receive) {
this.receive = receive;
}
public boolean isSend() {
return send;
}
public void setSend(boolean send) {
this.send = send;
}
public boolean isFlush() {
return flush;
}
public void setFlush(boolean flush) {
this.flush = flush;
}
public boolean isClose() {
return close;
}
public void setClose(boolean close) {
this.close = close;
}
}
/**
*
* @param socketContext socketContext
*/
public IoSession(T socketContext){
this.socketContext = socketContext;
this.state = new State();
readByteBufferChannel = new ByteBufferChannel(socketContext.getReadBufferSize());
sendByteBufferChannel = new ByteBufferChannel(socketContext.getSendBufferSize());
sendByteBufferChannel.setThreadSafe(true);
messageLoader = new MessageLoader(this);
checkIdle();
}
/**
* Socket
* @return Socket
*/
public SocketSelector getSocketSelector() {
return socketSelector;
}
/**
* Socket
* @param socketSelector Socket
*/
protected void setSocketSelector(SocketSelector socketSelector) {
this.socketSelector = socketSelector;
}
/**
* Event
* @return Event
*/
protected EventRunner getEventRunner() {
return socketSelector.getEventRunner();
}
/**
* SelectionKey
* @return SelectionKey
*/
protected SelectionKey getSelectionKey() {
return selectionKey;
}
/**
* SelectionKey
* @param selectionKey SelectionKey
*/
void setSelectionKey(SelectionKey selectionKey) {
this.selectionKey = selectionKey;
}
/**
*
* @return
*/
public HeartBeat getHeartBeat() {
return heartBeat;
}
/**
*
* @return
*/
void setHeartBeat(HeartBeat heartBeat) {
this.heartBeat = heartBeat;
}
/**
*
* @return
*/
public State getState() {
return state;
}
public void checkIdle(){
if(socketContext.getIdleInterval() > 0) {
if(checkIdleTask == null){
final IoSession session = this;
checkIdleTask = new HashWheelTask() {
public void run() {
long timeDiff = System.currentTimeMillis() - lastIdleTime;
if (timeDiff >= socketContext.getIdleInterval() * 1000) {
boolean isConnect = false;
if(session.state.isInit() ||
session.state.isConnect()) {
return;
}
if(session.state.isClose()){
session.cancelIdle();
return;
}
isConnect = session.isConnected();
if(!isConnect){
session.cancelIdle();
session.close();
this.cancel();
return;
}
if(socketContext.getIdleInterval() < 1){
return;
}
EventTrigger.fireIdle(session);
lastIdleTime = System.currentTimeMillis();
}
}
};
checkIdleTask.run();
getIdleWheelTimer().addTask(checkIdleTask, 1, true);
}
}
}
public void cancelIdle(){
if(checkIdleTask!=null) {
checkIdleTask.cancel();
checkIdleTask = null;
if(heartBeat!=null){
heartBeat = null;
}
}
}
/**
*
* @return
*/
public int getIdleInterval() {
return socketContext.getIdleInterval();
}
/**
*
* @param idleInterval
*/
public void setIdleInterval(int idleInterval) {
socketContext.setIdleInterval(idleInterval);
}
/**
*
*
* @return
*/
public ByteBufferChannel getReadByteBufferChannel() {
return readByteBufferChannel;
}
/**
*
*
* @return
*/
public ByteBufferChannel getSendByteBufferChannel() {
return sendByteBufferChannel;
}
/**
* SSLParser
* @return SSLParser
*/
public SSLParser getSSLParser() {
return sslParser;
}
/**
* SSLParser
* @param sslParser SSL
*/
protected void setSSLParser(SSLParser sslParser) {
if(this.sslParser == null && sslParser!=null){
this.sslParser = sslParser;
sslMode = true;
}
}
public boolean isSSLMode() {
return sslMode;
}
/**
* IP
* @return IP
*/
public abstract String localAddress();
/**
*
* @return -1
*/
public abstract int loaclPort();
/**
* IP
* @return ip
*/
public abstract String remoteAddress();
/**
*
* @return -1
*/
public abstract int remotePort();
/**
* socket
* @return socket , null
*/
public T socketContext() {
return socketContext;
};
/**
*
* @return
* @throws IOException IO
*/
protected int read0() throws IOException {
return socketSelector.readFromChannel(socketContext, socketContext.socketChannel());
}
/**
*
* @param byteBuffer ByteBuffer, enabledMessageSpliter(false) ,.
* @return
* @throws IOException IO
* */
public int read(ByteBuffer byteBuffer) throws IOException {
int readSize = -1;
if (byteBuffer != null && !this.getReadByteBufferChannel().isReleased()) {
readSize = this.getReadByteBufferChannel().readHead(byteBuffer);
}
if(!this.isConnected() && readSize <= 0){
readSize = -1;
close();
}
return readSize;
}
/**
*
* filter decoder
* @return
* @throws ReadMessageException
*/
public Object syncRead() throws ReadMessageException {
Object readObject = null;
SynchronousHandler synchronousHandler = null;
if(socketContext.handler() instanceof SynchronousHandler) {
synchronousHandler = (SynchronousHandler) socketContext.handler();
}else{
throw new ReadMessageException("Use the syncRead method must set an object of SynchronousHandler into the socket handler ");
}
try {
if(isConnected()) {
readObject = synchronousHandler.getResponse(socketContext.getReadTimeout());
} else {
close();
}
if(readObject == null && !isConnected()) {
throw new ReadMessageException("Method syncRead error! Socket is disconnected");
}
if(readObject instanceof Throwable){
Exception exception = (Exception) readObject;
if (exception != null) {
throw new ReadMessageException("Method syncRead error! Error by " +
exception.getClass().getSimpleName() + ". " + exception.getMessage(), exception);
}
} else {
return readObject;
}
} catch (TimeoutException e) {
throw new ReadMessageException("syncRead readFromChannel timeout or socket is disconnect");
}
return readObject;
}
/**
* JVM SocketChannel
* onSent
* @param buffer
* @return
*/
protected int send0(ByteBuffer buffer) {
if(socketSelector != null) {
return socketSelector.writeToChannel(socketContext, buffer);
} else {
return -1;
}
}
/**
*
* @param buffer ByteBuffer
* @return
*/
protected int sendToBuffer(ByteBuffer buffer) {
try {
return sendByteBufferChannel.writeEnd(buffer);
} catch (Exception e) {
if (socketContext.isConnected()) {
Logger.error("IoSession.sendByBuffer buffer failed", e);
} else {
close();
}
}
return -1;
}
/**
*
* filter encoder
* @param obj
* @throws SendMessageException
*/
public void syncSend(Object obj) throws SendMessageException{
// ssl
try {
state.setFlush(true);
if(sslParser!=null) {
TEnv.waitThrow(socketContext.getReadTimeout(), ()->!sslParser.handShakeDone);
}
if (obj != null) {
try {
EventProcess.sendMessage(this, obj);
flush();
}catch (Exception e){
throw new SendMessageException("Method syncSend error! Error by "+
e.getClass().getSimpleName() + ".",e);
}
}
} catch (TimeoutException e) {
throw new SendMessageException("Method syncSend error! Error by "+
e.getClass().getSimpleName() + ".",e);
} finally {
state.setFlush(false);
}
}
/**
*
* onSent ,
* @param buffer byte
* @return
*/
public int send(ByteBuffer buffer){
try {
if(buffer.limit() + sendByteBufferChannel.size() > sendByteBufferChannel.getMaxSize()){
flush();
}
if(sslParser!=null && sslParser.isHandShakeDone()) {
//warpData session.sendByBuffer
sslParser.warpData(buffer);
return buffer.limit();
} else {
return sendToBuffer(buffer);
}
} catch (IOException e) {
Logger.error("IoSession.writeToChannel data failed" ,e);
}
return -1;
}
/**
* socketChannel
*/
public void flush() {
if(sendByteBufferChannel.size()>0) {
ByteBuffer byteBuffer = sendByteBufferChannel.getByteBuffer();
try {
int size = send0(byteBuffer);
if(size >= 0) {
EventTrigger.fireFlush(this);
} else {
this.close();
}
} finally {
sendByteBufferChannel.compact();
}
}
}
/**
*
* @return
*/
public MessageLoader getMessageLoader() {
return messageLoader;
}
/**
*
* @return
*/
protected abstract MessageSplitter getMessagePartition();
/**
*
* @param useSpliter true ,false , onRecive
*/
public void enabledMessageSpliter(boolean useSpliter) {
messageLoader.enable(useSpliter);
}
/**
*
* @return true: ,false:
*/
public abstract boolean isConnected();
/**
*
* @return true: ,false:
*/
public abstract boolean isOpen();
/**
*
* @return
*/
public abstract boolean close();
public void release() {
if(socketContext.isRegister() && socketSelector!=null) {
socketSelector.unRegister(selectionKey);
} else {
readByteBufferChannel.release();
sendByteBufferChannel.release();
}
}
@Override
public abstract String toString();
}
|
package edu.cuny.citytech.defaultrefactoring.core.utils;
import static org.eclipse.jdt.internal.corext.refactoring.structure.TypeVariableUtil.composeMappings;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeParameter;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.internal.corext.refactoring.structure.TypeVariableMaplet;
/**
* TypeVariableUtils customized for use with default method refactoring.
* @see {@link org.eclipse.jdt.internal.corext.refactoring.structure.TypeVariableUtil}
* @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi Khatchadourian</a>
*
*/
@SuppressWarnings("restriction")
public final class TypeVariableUtil {
private TypeVariableUtil() {
}
/**
* Returns a type variable mapping from a subclass to a superclass.
*
* @param subtype
* the type representing the subclass
* @param supertype
* the type representing the superclass
* @return a type variable mapping. The mapping entries consist of simple
* type variable names.
* @throws JavaModelException
* if the signature of one of the types involved could not be
* retrieved
*/
public static TypeVariableMaplet[] subTypeToSuperType(final IType subtype, IType implementedInterface,
final IType supertype) throws JavaModelException {
Assert.isNotNull(subtype);
Assert.isNotNull(supertype);
final TypeVariableMaplet[] mapping = subTypeToInheritedType(subtype, implementedInterface);
if (mapping.length > 0) {
final ITypeParameter[] range = supertype.getTypeParameters();
if (range.length > 0) {
final String signature = subtype.getSuperclassTypeSignature();
if (signature != null) {
final String[] domain = getVariableSignatures(signature);
if (domain.length > 0)
return composeMappings(mapping, signaturesToParameters(domain, range));
}
}
}
return mapping;
}
/**
* Creates a type variable mapping from a domain to a range.
*
* @param domain
* the domain of the mapping
* @param range
* the range of the mapping
* @return a possibly empty type variable mapping
*/
private static TypeVariableMaplet[] signaturesToParameters(final String[] domain, final ITypeParameter[] range) {
Assert.isNotNull(domain);
Assert.isNotNull(range);
Assert.isTrue(domain.length == 0 || domain.length == range.length);
final List<TypeVariableMaplet> list = new ArrayList<TypeVariableMaplet>();
String source = null;
String target = null;
for (int index = 0; index < domain.length; index++) {
source = Signature.toString(domain[index]);
target = range[index].getElementName();
list.add(new TypeVariableMaplet(source, index, target, index));
}
final TypeVariableMaplet[] result = new TypeVariableMaplet[list.size()];
list.toArray(result);
return result;
}
/**
* Returns a type variable mapping from a subclass to a superclass.
*
* @param type
* the type representing the subclass class
* @return a type variable mapping. The mapping entries consist of simple
* type variable names.
* @throws JavaModelException
* if the signature of one of the types involved could not be
* retrieved
*/
public static TypeVariableMaplet[] subTypeToInheritedType(final IType type, IType implementedInterface)
throws JavaModelException {
Assert.isNotNull(type);
final ITypeParameter[] domain = type.getTypeParameters();
if (domain.length > 0) {
String fullyQualifiedParameterizedName = implementedInterface.getFullyQualifiedParameterizedName();
// RK: strip off bounds if present. Otherwise, createTypeSignature() won't work.
fullyQualifiedParameterizedName = fullyQualifiedParameterizedName.replaceAll(" extends [^>]*", "");
fullyQualifiedParameterizedName = fullyQualifiedParameterizedName.replaceAll(" super [^>]*", "");
final String signature = Signature.createTypeSignature(
fullyQualifiedParameterizedName, implementedInterface.isResolved());
if (signature != null) {
final String[] range = getVariableSignatures(signature);
if (range.length > 0)
return parametersToSignatures(domain, range, true);
}
}
return new TypeVariableMaplet[0];
}
/**
* Returns the type variable signatures of the specified parameterized type
* signature, or an empty array if none.
*
* @param signature
* the signature to get its type variable signatures from. The
* signature must be a parameterized type signature.
* @return a possibly empty array of type variable signatures
* @see Signature#getTypeArguments(String)
*/
private static String[] getVariableSignatures(final String signature) {
Assert.isNotNull(signature);
String[] result = null;
try {
result = Signature.getTypeArguments(signature);
} catch (IllegalArgumentException exception) {
result = new String[0];
}
return result;
}
/**
* Creates a type variable mapping from a domain to a range.
*
* @param domain
* the domain of the mapping
* @param range
* the range of the mapping
* @param indexes
* <code>true</code> if the indexes should be compared,
* <code>false</code> if the names should be compared
* @return a possibly empty type variable mapping
*/
private static TypeVariableMaplet[] parametersToSignatures(final ITypeParameter[] domain, final String[] range,
final boolean indexes) {
Assert.isNotNull(domain);
Assert.isNotNull(range);
final Set<TypeVariableMaplet> set = new HashSet<TypeVariableMaplet>();
ITypeParameter source = null;
String target = null;
String element = null;
String signature = null;
for (int index = 0; index < domain.length; index++) {
source = domain[index];
for (int offset = 0; offset < range.length; offset++) {
target = range[offset];
element = source.getElementName();
signature = Signature.toString(target);
if (indexes) {
if (offset == index)
set.add(new TypeVariableMaplet(element, index, signature, offset));
} else {
if (element.equals(signature))
set.add(new TypeVariableMaplet(element, index, signature, offset));
}
}
}
final TypeVariableMaplet[] result = new TypeVariableMaplet[set.size()];
set.toArray(result);
return result;
}
/**
* Returns all type variable names of the indicated member not mapped by the
* specified type variable mapping.
*
* @param mapping
* the type variable mapping. The entries of this mapping must be
* simple type variable names.
* @param declaring
* the declaring type of the indicated member
* @param member
* the member to determine its unmapped type variable names
* @return a possibly empty array of unmapped type variable names
* @throws JavaModelException
* if the type parameters of the member could not be determined
*/
public static String[] getUnmappedVariables(final TypeVariableMaplet[] mapping, final IType declaring,
final IMember member) throws JavaModelException {
return org.eclipse.jdt.internal.corext.refactoring.structure.TypeVariableUtil.getUnmappedVariables(mapping,
declaring, member);
}
}
|
package com.bignerdranch.expandablerecyclerview.Adapter;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.ClickListeners.ExpandCollapseListener;
import com.bignerdranch.expandablerecyclerview.ClickListeners.ParentItemClickListener;
import com.bignerdranch.expandablerecyclerview.Model.ParentObject;
import com.bignerdranch.expandablerecyclerview.Model.ParentWrapper;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ChildViewHolder;
import com.bignerdranch.expandablerecyclerview.ViewHolder.ParentViewHolder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* The Base class for an Expandable RecyclerView Adapter
* <p/>
* Provides the base for a user to implement binding custom views to a Parent ViewHolder and a
* Child ViewHolder
*
* @author Ryan Brooks
* @version 1.0
* @since 5/27/2015
*/
public abstract class ExpandableRecyclerAdapter<PVH extends ParentViewHolder, CVH extends ChildViewHolder> extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ParentItemClickListener {
private static final String TAG = ExpandableRecyclerAdapter.class.getClass().getSimpleName();
private static final String STABLE_ID_MAP = "ExpandableRecyclerAdapter.StableIdMap";
private static final String STABLE_ID_LIST = "ExpandableRecyclerAdapter.StableIdList";
private static final int TYPE_PARENT = 0;
private static final int TYPE_CHILD = 1;
public static final int CUSTOM_ANIMATION_VIEW_NOT_SET = -1;
public static final long DEFAULT_ROTATE_DURATION_MS = 200l;
public static final long CUSTOM_ANIMATION_DURATION_NOT_SET = -1l;
protected Context mContext;
protected List<Object> mItemList;
protected List<ParentObject> mParentItemList;
private HashMap<Long, Boolean> mStableIdMap;
private ExpandableRecyclerAdapterHelper mExpandableRecyclerAdapterHelper;
private ExpandCollapseListener mExpandCollapseListener;
private boolean mParentAndIconClickable = false;
private int mCustomParentAnimationViewId = CUSTOM_ANIMATION_VIEW_NOT_SET;
private long mAnimationDuration = CUSTOM_ANIMATION_DURATION_NOT_SET;
/**
* Public constructor for the base ExpandableRecyclerView. This constructor takes in no
* extra parameters for custom clickable views and animation durations. This means a click of
* the parent item will trigger the expansion.
*
* @param context
* @param parentItemList
*/
public ExpandableRecyclerAdapter(Context context, List<ParentObject> parentItemList) {
mContext = context;
mParentItemList = parentItemList;
mItemList = generateObjectList(parentItemList);
mExpandableRecyclerAdapterHelper = new ExpandableRecyclerAdapterHelper(mItemList);
mStableIdMap = generateStableIdMapFromList(mExpandableRecyclerAdapterHelper.getHelperItemList());
}
/**
* Public constructor for a more robust ExpandableRecyclerView. This constructor takes in an
* id for a custom clickable view that will trigger the expansion or collapsing of the child.
* By default, a parent item click is the trigger for the expanding/collapsing.
*
* @param context
* @param parentItemList
* @param customParentAnimationViewId
*/
public ExpandableRecyclerAdapter(Context context, List<ParentObject> parentItemList,
int customParentAnimationViewId) {
mContext = context;
mParentItemList = parentItemList;
mItemList = generateObjectList(parentItemList);
mExpandableRecyclerAdapterHelper = new ExpandableRecyclerAdapterHelper(mItemList);
mStableIdMap = generateStableIdMapFromList(mExpandableRecyclerAdapterHelper.getHelperItemList());
mCustomParentAnimationViewId = customParentAnimationViewId;
}
/**
* Public constructor for even more robust ExpandableRecyclerView. This constructor takes in
* both an id for a custom clickable view that will trigger the expansion or collapsing of the
* child along with a long for a custom duration in MS for the rotation animation.
*
* @param context
* @param parentItemList
* @param customParentAnimationViewId
* @param animationDuration
*/
public ExpandableRecyclerAdapter(Context context, List<ParentObject> parentItemList,
int customParentAnimationViewId, long animationDuration) {
mContext = context;
mParentItemList = parentItemList;
mItemList = generateObjectList(parentItemList);
mExpandableRecyclerAdapterHelper = new ExpandableRecyclerAdapterHelper(mItemList);
mStableIdMap = generateStableIdMapFromList(mExpandableRecyclerAdapterHelper.getHelperItemList());
mCustomParentAnimationViewId = customParentAnimationViewId;
mAnimationDuration = animationDuration;
}
/**
* Override of RecyclerView's default onCreateViewHolder.
* <p/>
* This implementation determines if the item is a child or a parent view and will then call
* the respective onCreateViewHolder method that the user must implement in their custom
* implementation.
*
* @param viewGroup
* @param viewType
* @return the ViewHolder that cooresponds to the item at the position.
*/
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewType == TYPE_PARENT) {
PVH pvh = onCreateParentViewHolder(viewGroup);
pvh.setParentItemClickListener(this);
return pvh;
} else if (viewType == TYPE_CHILD) {
return onCreateChildViewHolder(viewGroup);
} else {
throw new IllegalStateException("Incorrect ViewType found");
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (mExpandableRecyclerAdapterHelper.getHelperItemAtPosition(position) instanceof ParentWrapper) {
PVH parentViewHolder = (PVH) holder;
if (mParentAndIconClickable) {
if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET
&& mAnimationDuration != CUSTOM_ANIMATION_DURATION_NOT_SET) {
parentViewHolder.setCustomClickableViewAndItem(mCustomParentAnimationViewId);
parentViewHolder.setAnimationDuration(mAnimationDuration);
} else if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET) {
parentViewHolder.setCustomClickableViewAndItem(mCustomParentAnimationViewId);
parentViewHolder.cancelAnimation();
} else {
parentViewHolder.setMainItemClickToExpand();
}
} else {
if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET
&& mAnimationDuration != CUSTOM_ANIMATION_DURATION_NOT_SET) {
parentViewHolder.setCustomClickableViewOnly(mCustomParentAnimationViewId);
parentViewHolder.setAnimationDuration(mAnimationDuration);
} else if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET) {
parentViewHolder.setCustomClickableViewOnly(mCustomParentAnimationViewId);
parentViewHolder.cancelAnimation();
} else {
parentViewHolder.setMainItemClickToExpand();
}
}
parentViewHolder.setExpanded(((ParentWrapper) mExpandableRecyclerAdapterHelper.getHelperItemAtPosition(position)).isExpanded());
onBindParentViewHolder(parentViewHolder, position, mItemList.get(position));
} else if (mItemList.get(position) == null) {
throw new IllegalStateException("Incorrect ViewHolder found");
} else {
onBindChildViewHolder((CVH) holder, position, mItemList.get(position));
}
}
/**
* Creates the Parent ViewHolder. Called from onCreateViewHolder when the item is a ParenObject.
*
* @param parentViewGroup
* @return ParentViewHolder that the user must create and inflate.
*/
public abstract PVH onCreateParentViewHolder(ViewGroup parentViewGroup);
/**
* Creates the Child ViewHolder. Called from onCreateViewHolder when the item is a ChildObject.
*
* @param childViewGroup
* @return ChildViewHolder that the user must create and inflate.
*/
public abstract CVH onCreateChildViewHolder(ViewGroup childViewGroup);
/**
* Binds the data to the ParentViewHolder. Called from onBindViewHolder when the item is a
* ParentObject
*
* @param parentViewHolder
* @param position
*/
public abstract void onBindParentViewHolder(PVH parentViewHolder, int position, Object parentObject);
/**
* Binds the data to the ChildViewHolder. Called from onBindViewHolder when the item is a
* ChildObject
*
* @param childViewHolder
* @param position
*/
public abstract void onBindChildViewHolder(CVH childViewHolder, int position, Object childObject);
/**
* Returns the size of the list that contains Parent and Child objects
*
* @return integer value of the size of the Parent/Child list
*/
@Override
public int getItemCount() {
return mItemList.size();
}
@Override
public int getItemViewType(int position) {
if (mItemList.get(position) instanceof ParentObject) {
return TYPE_PARENT;
} else if (mItemList.get(position) == null) {
throw new IllegalStateException("Null object added");
} else {
return TYPE_CHILD;
}
}
/**
* On click listener implementation for the ParentObject. This is called from ParentViewHolder.
* See OnClick in ParentViewHolder
*
* @param position
*/
@Override
public void onParentItemClickListener(int position) {
if (mItemList.get(position) instanceof ParentObject) {
ParentObject parentObject = (ParentObject) mItemList.get(position);
expandParent(parentObject, position);
}
}
/**
* Setter for the Default rotation duration (200 MS)
*/
public void setParentClickableViewAnimationDefaultDuration() {
mAnimationDuration = DEFAULT_ROTATE_DURATION_MS;
}
/**
* Setter for a custom rotation animation duration in MS
*
* @param animationDuration in MS
*/
public void setParentClickableViewAnimationDuration(long animationDuration) {
mAnimationDuration = animationDuration;
}
/**
* Setter for a custom clickable view to expand or collapse the item. This should be passed
* as a reference to the View's R.id
*
* @param customParentAnimationViewId
*/
public void setCustomParentAnimationViewId(int customParentAnimationViewId) {
mCustomParentAnimationViewId = customParentAnimationViewId;
}
/**
* Set the ability to be able to click both the whole parent view and the custom button to trigger
* expanding and collapsing
*
* @param parentAndIconClickable
*/
public void setParentAndIconExpandOnClick(boolean parentAndIconClickable) {
mParentAndIconClickable = parentAndIconClickable;
}
/**
* Call this when removing the animtion. This will set the parent item to be the expand/collapse
* trigger. It will also disable the rotation animation.
*/
public void removeAnimation() {
mCustomParentAnimationViewId = CUSTOM_ANIMATION_VIEW_NOT_SET;
mAnimationDuration = CUSTOM_ANIMATION_DURATION_NOT_SET;
}
public void addExpandCollapseListener(ExpandCollapseListener expandCollapseListener) {
mExpandCollapseListener = expandCollapseListener;
}
/**
* Method called to expand a ParentObject when clicked. This handles saving state, adding the
* corresponding child objects to the list (the recyclerview list) and updating that list.
* It also calls the appropriate ExpandCollapseListener methods, if it exists
*
* @param parentObject
* @param position
*/
private void expandParent(ParentObject parentObject, int position) {
ParentWrapper parentWrapper = (ParentWrapper) mExpandableRecyclerAdapterHelper.getHelperItemAtPosition(position);
if (parentWrapper == null) {
return;
}
if (parentWrapper.isExpanded()) {
parentWrapper.setExpanded(false);
if (mExpandCollapseListener != null) {
int expandedCountBeforePosition = getExpandedItemCount(position);
mExpandCollapseListener.onRecyclerViewItemCollapsed(position - expandedCountBeforePosition);
}
mStableIdMap.put(parentWrapper.getStableId(), false);
List<Object> childObjectList = ((ParentObject) parentWrapper.getParentObject()).getChildObjectList();
if (childObjectList != null) {
for (int i = childObjectList.size() - 1; i >= 0; i
mItemList.remove(position + i + 1);
mExpandableRecyclerAdapterHelper.getHelperItemList().remove(position + i + 1);
notifyItemRemoved(position + i + 1);
}
}
} else {
parentWrapper.setExpanded(true);
if (mExpandCollapseListener != null) {
int expandedCountBeforePosition = getExpandedItemCount(position);
mExpandCollapseListener.onRecyclerViewItemExpanded(position - expandedCountBeforePosition);
}
mStableIdMap.put(parentWrapper.getStableId(), true);
List<Object> childObjectList = ((ParentObject) parentWrapper.getParentObject()).getChildObjectList();
if (childObjectList != null) {
for (int i = 0; i < childObjectList.size(); i++) {
mItemList.add(position + i + 1, childObjectList.get(i));
mExpandableRecyclerAdapterHelper.getHelperItemList().add(position + i + 1, childObjectList.get(i));
notifyItemInserted(position + i + 1);
}
}
}
}
/**
* Method to get the number of expanded children before the specified position.
*
* @param position
* @return number of expanded children before the specified position
*/
private int getExpandedItemCount(int position) {
if (position == 0) {
return 0;
}
int expandedCount = 0;
for (int i = 0; i < position; i++) {
Object object = mItemList.get(i);
if (!(object instanceof ParentObject)) {
expandedCount++;
}
}
return expandedCount;
}
/**
* Generates a HashMap for storing expanded state when activity is rotated or onResume() is called.
*
* @param itemList
* @return HashMap containing the Object's stable id along with a boolean indicating its expanded
* state
*/
private HashMap<Long, Boolean> generateStableIdMapFromList(List<Object> itemList) {
HashMap<Long, Boolean> parentObjectHashMap = new HashMap<>();
for (int i = 0; i < itemList.size(); i++) {
if (itemList.get(i) != null) {
ParentWrapper parentWrapper = (ParentWrapper) mExpandableRecyclerAdapterHelper.getHelperItemAtPosition(i);
parentObjectHashMap.put(parentWrapper.getStableId(), parentWrapper.isExpanded());
}
}
return parentObjectHashMap;
}
/**
* Generates an ArrayList of type Object for keeping track of all objects including children
* that are added to the RV. Takes in a list of parents so the user doesn't have to pass in
* a list of objects.
*
* @param parentObjectList the list of all parent objects provided by the user
* @return ArrayList of type Object that handles the items in the RV
*/
private ArrayList<Object> generateObjectList(List<ParentObject> parentObjectList) {
ArrayList<Object> objectList = new ArrayList<>();
for (ParentObject parentObject : parentObjectList) {
objectList.add(parentObject);
}
return objectList;
}
/**
* Should be called from onSaveInstanceState of Activity that holds the RecyclerView. This will
* make sure to add the generated HashMap as an extra to the bundle to be used in
* OnRestoreInstanceState().
*
* @param savedInstanceStateBundle
* @return the Bundle passed in with the Id HashMap added if applicable
*/
public Bundle onSaveInstanceState(Bundle savedInstanceStateBundle) {
savedInstanceStateBundle.putSerializable(STABLE_ID_MAP, mStableIdMap);
return savedInstanceStateBundle;
}
/**
* Should be called from onRestoreInstanceState of Activity that contains the ExpandingRecyclerView.
* This will fetch the HashMap that was saved in onSaveInstanceState() and use it to restore
* the expanded states before the rotation or onSaveInstanceState was called.
*
* @param savedInstanceStateBundle
*/
public void onRestoreInstanceState(Bundle savedInstanceStateBundle) {
if (savedInstanceStateBundle == null) {
return;
}
if (!savedInstanceStateBundle.containsKey(STABLE_ID_MAP)) {
return;
}
mStableIdMap = (HashMap<Long, Boolean>) savedInstanceStateBundle.getSerializable(STABLE_ID_MAP);
int i = 0;
while (i < mExpandableRecyclerAdapterHelper.getHelperItemList().size()) {
if (mExpandableRecyclerAdapterHelper.getHelperItemAtPosition(i) instanceof ParentWrapper) {
ParentWrapper parentWrapper = (ParentWrapper) mExpandableRecyclerAdapterHelper.getHelperItemAtPosition(i);
if (mStableIdMap.containsKey(parentWrapper.getStableId())) {
parentWrapper.setExpanded(mStableIdMap.get(parentWrapper.getStableId()));
if (parentWrapper.isExpanded()) {
List<Object> childObjectList = ((ParentObject) parentWrapper.getParentObject()).getChildObjectList();
if (childObjectList != null) {
for (int j = 0; j < childObjectList.size(); j++) {
i++;
mItemList.add(i, childObjectList.get(j));
mExpandableRecyclerAdapterHelper.getHelperItemList().add(i, childObjectList.get(j));
}
}
}
} else {
parentWrapper.setExpanded(false);
}
}
i++;
}
notifyDataSetChanged();
}
}
|
package org.deuce.transaction.tl2;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.deuce.transaction.TransactionException;
import org.deuce.transaction.tl2.field.BooleanWriteFieldAccess;
import org.deuce.transaction.tl2.field.ByteWriteFieldAccess;
import org.deuce.transaction.tl2.field.CharWriteFieldAccess;
import org.deuce.transaction.tl2.field.DoubleWriteFieldAccess;
import org.deuce.transaction.tl2.field.FloatWriteFieldAccess;
import org.deuce.transaction.tl2.field.IntWriteFieldAccess;
import org.deuce.transaction.tl2.field.LongWriteFieldAccess;
import org.deuce.transaction.tl2.field.ObjectWriteFieldAccess;
import org.deuce.transaction.tl2.field.ReadFieldAccess;
import org.deuce.transaction.tl2.field.ShortWriteFieldAccess;
import org.deuce.transaction.tl2.field.WriteFieldAccess;
import org.deuce.transaction.tl2.pool.Pool;
import org.deuce.transaction.tl2.pool.ResourceFactory;
import org.deuce.transform.Exclude;
import org.deuce.trove.TObjectProcedure;
/**
* TL2 implementation
*
* @author Guy Korland
* @since 1.0
*/
@Exclude
final public class Context implements org.deuce.transaction.Context{
final static AtomicInteger clock = new AtomicInteger( 0);
final private ReadSet readSet = new ReadSet();
final private WriteSet writeSet = new WriteSet();
private ReadFieldAccess currentReadFieldAccess = null;
//Used by the thread to mark locks it holds.
final private byte[] locksMarker = new byte[LockTable.LOCKS_SIZE /8 + 1];
final private LockProcedure lockProcedure = new LockProcedure(locksMarker);
//Marked on beforeRead, used for the double lock check
private int localClock;
private int lastReadLock;
//Global lock used to allow only one irrevocable transaction solely.
final private static ReentrantReadWriteLock irrevocableAccessLock = new ReentrantReadWriteLock();
private boolean irrevocableState = false;
final private TObjectProcedure<WriteFieldAccess> putProcedure = new TObjectProcedure<WriteFieldAccess>(){
@Override
public boolean execute(WriteFieldAccess writeField) {
writeField.put();
return true;
}
};
public Context(){
this.localClock = clock.get();
}
@Override
public void init(int atomicBlockId, String metainf){
this.currentReadFieldAccess = null;
this.readSet.clear();
this.writeSet.clear();
this.localClock = clock.get();
this.objectPool.clear();
this.booleanPool.clear();
this.bytePool.clear();
this.charPool.clear();
this.shortPool.clear();
this.intPool.clear();
this.longPool.clear();
this.floatPool.clear();
this.doublePool.clear();
//Lock according to the transaction irrevocable state
if(irrevocableState)
irrevocableAccessLock.writeLock().lock();
else
irrevocableAccessLock.readLock().lock();
}
@Override
public boolean commit(){
try
{
if (writeSet.isEmpty()) // if the writeSet is empty no need to lock a thing.
return true;
try
{
// pre commit validation phase
writeSet.forEach(lockProcedure);
readSet.checkClock(localClock);
}
catch( TransactionException exception){
lockProcedure.unlockAll();
return false;
}
// commit new values and release locks
writeSet.forEach(putProcedure);
lockProcedure.setAndUnlockAll();
return true;
}
finally{
if(irrevocableState){
irrevocableState = false;
irrevocableAccessLock.writeLock().unlock();
}
else{
irrevocableAccessLock.readLock().unlock();
}
}
}
@Override
public void rollback(){
irrevocableAccessLock.readLock().unlock();
}
private WriteFieldAccess onReadAccess0( Object obj, long field){
ReadFieldAccess current = currentReadFieldAccess;
int hash = current.hashCode();
// Check the read is still valid
LockTable.checkLock(hash, localClock, lastReadLock);
// Check if it is already included in the write set
return writeSet.contains( current);
}
private void addWriteAccess0( WriteFieldAccess write){
// Add to write set
writeSet.put( write);
}
@Override
public void beforeReadAccess(Object obj, long field) {
ReadFieldAccess next = readSet.getNext();
currentReadFieldAccess = next;
next.init(obj, field);
// Check the read is still valid
lastReadLock = LockTable.checkLock(next.hashCode(), localClock);
}
@Override
public Object onReadAccess( Object obj, Object value, long field){
WriteFieldAccess writeAccess = onReadAccess0(obj, field);
if( writeAccess == null)
return value;
return ((ObjectWriteFieldAccess)writeAccess).getValue();
}
@Override
public boolean onReadAccess(Object obj, boolean value, long field) {
WriteFieldAccess writeAccess = onReadAccess0(obj, field);
if( writeAccess == null)
return value;
return ((BooleanWriteFieldAccess)writeAccess).getValue();
}
@Override
public byte onReadAccess(Object obj, byte value, long field) {
WriteFieldAccess writeAccess = onReadAccess0(obj, field);
if( writeAccess == null)
return value;
return ((ByteWriteFieldAccess)writeAccess).getValue();
}
@Override
public char onReadAccess(Object obj, char value, long field) {
WriteFieldAccess writeAccess = onReadAccess0(obj, field);
if( writeAccess == null)
return value;
return ((CharWriteFieldAccess)writeAccess).getValue();
}
@Override
public short onReadAccess(Object obj, short value, long field) {
WriteFieldAccess writeAccess = onReadAccess0(obj, field);
if( writeAccess == null)
return value;
return ((ShortWriteFieldAccess)writeAccess).getValue();
}
@Override
public int onReadAccess(Object obj, int value, long field) {
WriteFieldAccess writeAccess = onReadAccess0(obj, field);
if( writeAccess == null)
return value;
return ((IntWriteFieldAccess)writeAccess).getValue();
}
@Override
public long onReadAccess(Object obj, long value, long field) {
WriteFieldAccess writeAccess = onReadAccess0(obj, field);
if( writeAccess == null)
return value;
return ((LongWriteFieldAccess)writeAccess).getValue();
}
@Override
public float onReadAccess(Object obj, float value, long field) {
WriteFieldAccess writeAccess = onReadAccess0(obj, field);
if( writeAccess == null)
return value;
return ((FloatWriteFieldAccess)writeAccess).getValue();
}
@Override
public double onReadAccess(Object obj, double value, long field) {
WriteFieldAccess writeAccess = onReadAccess0(obj, field);
if( writeAccess == null)
return value;
return ((DoubleWriteFieldAccess)writeAccess).getValue();
}
@Override
public void onWriteAccess( Object obj, Object value, long field){
ObjectWriteFieldAccess next = objectPool.getNext();
next.set(value, obj, field);
addWriteAccess0(next);
}
@Override
public void onWriteAccess(Object obj, boolean value, long field) {
BooleanWriteFieldAccess next = booleanPool.getNext();
next.set(value, obj, field);
addWriteAccess0(next);
}
@Override
public void onWriteAccess(Object obj, byte value, long field) {
ByteWriteFieldAccess next = bytePool.getNext();
next.set(value, obj, field);
addWriteAccess0(next);
}
@Override
public void onWriteAccess(Object obj, char value, long field) {
CharWriteFieldAccess next = charPool.getNext();
next.set(value, obj, field);
addWriteAccess0(next);
}
@Override
public void onWriteAccess(Object obj, short value, long field) {
ShortWriteFieldAccess next = shortPool.getNext();
next.set(value, obj, field);
addWriteAccess0(next);
}
@Override
public void onWriteAccess(Object obj, int value, long field) {
IntWriteFieldAccess next = intPool.getNext();
next.set(value, obj, field);
addWriteAccess0(next);
}
@Override
public void onWriteAccess(Object obj, long value, long field) {
LongWriteFieldAccess next = longPool.getNext();
next.set(value, obj, field);
addWriteAccess0(next);
}
@Override
public void onWriteAccess(Object obj, float value, long field) {
FloatWriteFieldAccess next = floatPool.getNext();
next.set(value, obj, field);
addWriteAccess0(next);
}
@Override
public void onWriteAccess(Object obj, double value, long field) {
DoubleWriteFieldAccess next = doublePool.getNext();
next.set(value, obj, field);
addWriteAccess0(next);
}
private static class ObjectResourceFactory implements ResourceFactory<ObjectWriteFieldAccess>{
@Override
public ObjectWriteFieldAccess newInstance() {
return new ObjectWriteFieldAccess();
}
}
final private Pool<ObjectWriteFieldAccess> objectPool = new Pool<ObjectWriteFieldAccess>(new ObjectResourceFactory());
private static class BooleanResourceFactory implements ResourceFactory<BooleanWriteFieldAccess>{
@Override
public BooleanWriteFieldAccess newInstance() {
return new BooleanWriteFieldAccess();
}
}
final private Pool<BooleanWriteFieldAccess> booleanPool = new Pool<BooleanWriteFieldAccess>(new BooleanResourceFactory());
private static class ByteResourceFactory implements ResourceFactory<ByteWriteFieldAccess>{
@Override
public ByteWriteFieldAccess newInstance() {
return new ByteWriteFieldAccess();
}
}
final private Pool<ByteWriteFieldAccess> bytePool = new Pool<ByteWriteFieldAccess>( new ByteResourceFactory());
private static class CharResourceFactory implements ResourceFactory<CharWriteFieldAccess>{
@Override
public CharWriteFieldAccess newInstance() {
return new CharWriteFieldAccess();
}
}
final private Pool<CharWriteFieldAccess> charPool = new Pool<CharWriteFieldAccess>(new CharResourceFactory());
private static class ShortResourceFactory implements ResourceFactory<ShortWriteFieldAccess>{
@Override
public ShortWriteFieldAccess newInstance() {
return new ShortWriteFieldAccess();
}
}
final private Pool<ShortWriteFieldAccess> shortPool = new Pool<ShortWriteFieldAccess>( new ShortResourceFactory());
private static class IntResourceFactory implements ResourceFactory<IntWriteFieldAccess>{
@Override
public IntWriteFieldAccess newInstance() {
return new IntWriteFieldAccess();
}
}
final private Pool<IntWriteFieldAccess> intPool = new Pool<IntWriteFieldAccess>( new IntResourceFactory());
private static class LongResourceFactory implements ResourceFactory<LongWriteFieldAccess>{
@Override
public LongWriteFieldAccess newInstance() {
return new LongWriteFieldAccess();
}
}
final private Pool<LongWriteFieldAccess> longPool = new Pool<LongWriteFieldAccess>( new LongResourceFactory());
private static class FloatResourceFactory implements ResourceFactory<FloatWriteFieldAccess>{
@Override
public FloatWriteFieldAccess newInstance() {
return new FloatWriteFieldAccess();
}
}
final private Pool<FloatWriteFieldAccess> floatPool = new Pool<FloatWriteFieldAccess>( new FloatResourceFactory());
private static class DoubleResourceFactory implements ResourceFactory<DoubleWriteFieldAccess>{
@Override
public DoubleWriteFieldAccess newInstance() {
return new DoubleWriteFieldAccess();
}
}
final private Pool<DoubleWriteFieldAccess> doublePool = new Pool<DoubleWriteFieldAccess>( new DoubleResourceFactory());
@Override
public void onIrrevocableAccess() {
if(irrevocableState) // already in irrevocable state so no need to restart transaction.
return;
irrevocableState = true;
throw TransactionException.STATIC_TRANSACTION;
}
}
|
package io.quarkus.rest.deployment.framework;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.BiFunction;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.Type.Kind;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import io.quarkus.deployment.util.AsmUtil;
import io.quarkus.rest.deployment.framework.EndpointIndexer.ParameterExtractor;
import io.quarkus.rest.runtime.core.parameters.converters.DelegatingParameterConverterSupplier;
import io.quarkus.rest.runtime.core.parameters.converters.ParameterConverter;
import io.quarkus.rest.runtime.core.parameters.converters.ParameterConverterSupplier;
import io.quarkus.rest.runtime.injection.QuarkusRestInjectionContext;
import io.quarkus.rest.runtime.injection.QuarkusRestInjectionTarget;
public class ClassInjectorTransformer implements BiFunction<String, ClassVisitor, ClassVisitor> {
private static final String WEB_APPLICATION_EXCEPTION_BINARY_NAME = WebApplicationException.class.getName().replace('.',
'/');
private static final String NOT_FOUND_EXCEPTION_BINARY_NAME = NotFoundException.class.getName().replace('.', '/');
private static final String BAD_REQUEST_EXCEPTION_BINARY_NAME = BadRequestException.class.getName().replace('.', '/');
private static final String PARAMETER_CONVERTER_BINARY_NAME = ParameterConverter.class.getName()
.replace('.', '/');
private static final String PARAMETER_CONVERTER_DESCRIPTOR = "L" + PARAMETER_CONVERTER_BINARY_NAME + ";";
private static final String QUARKUS_REST_INJECTION_TARGET_BINARY_NAME = QuarkusRestInjectionTarget.class.getName()
.replace('.', '/');
private static final String QUARKUS_REST_INJECTION_CONTEXT_BINARY_NAME = QuarkusRestInjectionContext.class.getName()
.replace('.', '/');
private static final String QUARKUS_REST_INJECTION_CONTEXT_DESCRIPTOR = "L" + QUARKUS_REST_INJECTION_CONTEXT_BINARY_NAME
+ ";";
private static final String INJECT_METHOD_NAME = "__quarkus_rest_inject";
private static final String INJECT_METHOD_DESCRIPTOR = "(" + QUARKUS_REST_INJECTION_CONTEXT_DESCRIPTOR + ")V";
private final Map<FieldInfo, ParameterExtractor> fieldExtractors;
public ClassInjectorTransformer(Map<FieldInfo, ParameterExtractor> fieldExtractors) {
this.fieldExtractors = fieldExtractors;
}
@Override
public ClassVisitor apply(String classname, ClassVisitor visitor) {
return new ClassInjectorVisitor(Opcodes.ASM8, visitor, fieldExtractors);
}
static class ClassInjectorVisitor extends ClassVisitor {
private Map<FieldInfo, ParameterExtractor> fieldExtractors;
private String thisName;
private boolean implementInterface = true;
public ClassInjectorVisitor(int api, ClassVisitor classVisitor, Map<FieldInfo, ParameterExtractor> fieldExtractors) {
super(api, classVisitor);
this.fieldExtractors = fieldExtractors;
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
for (String iface : interfaces) {
if (QUARKUS_REST_INJECTION_TARGET_BINARY_NAME.equals(iface)) {
implementInterface = false;
break;
}
}
if (implementInterface) {
String[] newInterfaces = new String[interfaces.length + 1];
newInterfaces[0] = QUARKUS_REST_INJECTION_TARGET_BINARY_NAME;
System.arraycopy(interfaces, 0, newInterfaces, 1, interfaces.length);
super.visit(version, access, name, signature, superName, newInterfaces);
} else {
super.visit(version, access, name, signature, superName, interfaces);
}
thisName = name;
}
@Override
public void visitEnd() {
// FIXME: handle setters
// FIXME: handle multi fields
// FIXME: handle converters
if (implementInterface) {
MethodVisitor injectMethod = visitMethod(Opcodes.ACC_PUBLIC, INJECT_METHOD_NAME, INJECT_METHOD_DESCRIPTOR, null,
null);
injectMethod.visitParameter("ctx", 0 /* modifiers */);
injectMethod.visitCode();
for (Entry<FieldInfo, ParameterExtractor> entry : fieldExtractors.entrySet()) {
FieldInfo fieldInfo = entry.getKey();
ParameterExtractor extractor = entry.getValue();
switch (extractor.getType()) {
case BEAN:
// this
injectMethod.visitIntInsn(Opcodes.ALOAD, 0);
// our bean param field
injectMethod.visitFieldInsn(Opcodes.GETFIELD, thisName, fieldInfo.name(),
AsmUtil.getDescriptor(fieldInfo.type(), name -> null));
// ctx param
injectMethod.visitIntInsn(Opcodes.ALOAD, 1);
// call inject on our bean param field
injectMethod.visitMethodInsn(Opcodes.INVOKEINTERFACE, QUARKUS_REST_INJECTION_TARGET_BINARY_NAME,
INJECT_METHOD_NAME,
INJECT_METHOD_DESCRIPTOR, true);
break;
case ASYNC_RESPONSE:
case BODY:
// spec says not supported
break;
case CONTEXT:
// already set by CDI
break;
case FORM:
injectParameterWithConverter(injectMethod, "getFormParameter", fieldInfo, extractor, true);
break;
case HEADER:
injectParameterWithConverter(injectMethod, "getHeader", fieldInfo, extractor, true);
break;
case MATRIX:
injectParameterWithConverter(injectMethod, "getMatrixParameter", fieldInfo, extractor, true);
break;
case COOKIE:
injectParameterWithConverter(injectMethod, "getCookieParameter", fieldInfo, extractor, false);
break;
case PATH:
injectParameterWithConverter(injectMethod, "getPathParameter", fieldInfo, extractor, false);
break;
case QUERY:
injectParameterWithConverter(injectMethod, "getQueryParameter", fieldInfo, extractor, true);
break;
default:
break;
}
}
injectMethod.visitInsn(Opcodes.RETURN);
injectMethod.visitEnd();
injectMethod.visitMaxs(0, 0);
}
super.visitEnd();
}
private void injectParameterWithConverter(MethodVisitor injectMethod, String methodName, FieldInfo fieldInfo,
ParameterExtractor extractor, boolean extraSingleParameter) {
// spec says:
/*
* 3.2 Fields and Bean Properties
* if the field or property is annotated with @MatrixParam, @QueryParam or @PathParam then an implementation
* MUST generate an instance of NotFoundException (404 status) that wraps the thrown exception and no
* entity; if the field or property is annotated with @HeaderParam or @CookieParam then an implementation
* MUST generate an instance of BadRequestException (400 status) that wraps the thrown exception and
* no entity.
* 3.3.2 Parameters
* Exceptions thrown during construction of @FormParam annotated parameter values are treated the same as if
* the parameter were annotated with @HeaderParam.
*/
Label tryStart, tryEnd = null, tryWebAppHandler = null, tryHandler = null;
switch (extractor.getType()) {
case MATRIX:
case QUERY:
case PATH:
case HEADER:
case COOKIE:
case FORM:
tryStart = new Label();
tryEnd = new Label();
tryWebAppHandler = new Label();
tryHandler = new Label();
injectMethod.visitTryCatchBlock(tryStart, tryEnd, tryWebAppHandler, WEB_APPLICATION_EXCEPTION_BINARY_NAME);
injectMethod.visitTryCatchBlock(tryStart, tryEnd, tryHandler, "java/lang/Throwable");
injectMethod.visitLabel(tryStart);
break;
}
// push the parameter value
loadParameter(injectMethod, methodName, extractor, extraSingleParameter);
Label valueWasNull = new Label();
// dup to test it
injectMethod.visitInsn(Opcodes.DUP);
injectMethod.visitJumpInsn(Opcodes.IFNULL, valueWasNull);
convertParameter(injectMethod, extractor);
// inject this (for the put field) before the injected value
injectMethod.visitIntInsn(Opcodes.ALOAD, 0);
injectMethod.visitInsn(Opcodes.SWAP);
if (fieldInfo.type().kind() == Kind.PRIMITIVE) {
// this already does the right checkcast
AsmUtil.unboxIfRequired(injectMethod, fieldInfo.type());
} else {
// FIXME: this is totally wrong wrt. generics
injectMethod.visitTypeInsn(Opcodes.CHECKCAST, fieldInfo.type().name().toString('/'));
}
// store our param field
injectMethod.visitFieldInsn(Opcodes.PUTFIELD, thisName, fieldInfo.name(),
AsmUtil.getDescriptor(fieldInfo.type(), name -> null));
Label endLabel = new Label();
injectMethod.visitJumpInsn(Opcodes.GOTO, endLabel);
// if the value was null, we don't set it
injectMethod.visitLabel(valueWasNull);
// we have a null value for the object we wanted to inject on the stack
injectMethod.visitInsn(Opcodes.POP);
if (tryEnd != null) {
// skip the catch block
injectMethod.visitJumpInsn(Opcodes.GOTO, endLabel);
injectMethod.visitLabel(tryEnd);
// start the web app catch block
injectMethod.visitLabel(tryWebAppHandler);
// exception is on the stack, just throw it
injectMethod.visitInsn(Opcodes.ATHROW);
// start the catch block
injectMethod.visitLabel(tryHandler);
String exceptionBinaryName;
switch (extractor.getType()) {
case MATRIX:
case QUERY:
case PATH:
exceptionBinaryName = NOT_FOUND_EXCEPTION_BINARY_NAME;
break;
case HEADER:
case COOKIE:
case FORM:
exceptionBinaryName = BAD_REQUEST_EXCEPTION_BINARY_NAME;
break;
default:
throw new IllegalStateException(
"Should not have been trying to catch exceptions for parameter of type " + extractor.getType());
}
injectMethod.visitTypeInsn(Opcodes.NEW, exceptionBinaryName);
// [x, instance]
injectMethod.visitInsn(Opcodes.DUP_X1);
// [instance, x, instance]
injectMethod.visitInsn(Opcodes.SWAP);
// [instance, instance, x]
injectMethod.visitMethodInsn(Opcodes.INVOKESPECIAL, exceptionBinaryName, "<init>", "(Ljava/lang/Throwable;)V",
false);
injectMethod.visitInsn(Opcodes.ATHROW);
}
// really done
injectMethod.visitLabel(endLabel);
}
private void convertParameter(MethodVisitor injectMethod, ParameterExtractor extractor) {
ParameterConverterSupplier converter = extractor.getConverter();
// do we need converters?
if (converter instanceof DelegatingParameterConverterSupplier) {
// must first instantiate the delegate if there is one
ParameterConverterSupplier delegate = ((DelegatingParameterConverterSupplier) converter).getDelegate();
if (delegate != null) {
String delegateBinaryName = delegate.getClassName().replace('.', '/');
injectMethod.visitTypeInsn(Opcodes.NEW, delegateBinaryName);
injectMethod.visitInsn(Opcodes.DUP);
injectMethod.visitMethodInsn(Opcodes.INVOKESPECIAL, delegateBinaryName, "<init>",
"()V", false);
} else {
// no delegate
injectMethod.visitInsn(Opcodes.ACONST_NULL);
}
// now call the static method on the delegator
String delegatorBinaryName = converter.getClassName().replace('.', '/');
injectMethod.visitMethodInsn(Opcodes.INVOKESTATIC, delegatorBinaryName, "convert",
"(Ljava/lang/Object;" + PARAMETER_CONVERTER_DESCRIPTOR + ")Ljava/lang/Object;", false);
// now we got ourselves a converted value
} else if (converter != null) {
// instantiate our converter
String converterBinaryName = converter.getClassName().replace('.', '/');
injectMethod.visitTypeInsn(Opcodes.NEW, converterBinaryName);
injectMethod.visitInsn(Opcodes.DUP);
injectMethod.visitMethodInsn(Opcodes.INVOKESPECIAL, converterBinaryName, "<init>",
"()V", false);
// at this point we have [val, converter] and we need to reverse that order
injectMethod.visitInsn(Opcodes.SWAP);
// now call the convert method on the converter
injectMethod.visitMethodInsn(Opcodes.INVOKEINTERFACE, PARAMETER_CONVERTER_BINARY_NAME, "convert",
"(Ljava/lang/Object;)Ljava/lang/Object;", true);
// now we got ourselves a converted value
}
}
private void loadParameter(MethodVisitor injectMethod, String methodName, ParameterExtractor extractor,
boolean extraSingleParameter) {
// ctx param
injectMethod.visitIntInsn(Opcodes.ALOAD, 1);
// name param
injectMethod.visitLdcInsn(extractor.getName());
String methodSignature;
if (extraSingleParameter) {
// single param
injectMethod.visitLdcInsn(extractor.isSingle());
methodSignature = "(Ljava/lang/String;Z)Ljava/lang/Object;";
} else {
methodSignature = "(Ljava/lang/String;)Ljava/lang/String;";
}
// call methodName on the ctx
injectMethod.visitMethodInsn(Opcodes.INVOKEINTERFACE, QUARKUS_REST_INJECTION_CONTEXT_BINARY_NAME, methodName,
methodSignature, true);
// deal with default value
if (extractor.getDefaultValue() != null) {
// dup to test it
injectMethod.visitInsn(Opcodes.DUP);
Label wasNonNullTarget = new Label();
injectMethod.visitJumpInsn(Opcodes.IFNONNULL, wasNonNullTarget);
// it was null, so let's eat the null value on the stack
injectMethod.visitInsn(Opcodes.POP);
// replace it with the default value
injectMethod.visitLdcInsn(extractor.getDefaultValue());
injectMethod.visitLabel(wasNonNullTarget);
}
}
}
}
|
package org.jcoderz.commons;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
/**
* This is the Base class for all checked exceptions.
*
* <p>In the {@link org.jcoderz.commons package overview} you can find a
* general statement when to use checked exceptions.</p>
*
* <p>This class can never be directly used. Services must implement a
* general service specific Exception (generated initially by the service
* framework code generator) from which they can derive more concrete
* service specific exceptions. There are some common used exceptions
* available as direct subclasses of this class. If appropriate this
* classes must be used prior generating own classes.</p>
*
* <p>Most functionality is implemented and documented by the
* {@link org.jcoderz.commons.LoggableImpl} which is used a member of
* objects of this class. Other stuff is handled by the base class
* {@link java.lang.Exception}.</p>
*
*
* @see org.jcoderz.commons
* @author Andreas Mandel
*/
public class BaseException
extends Exception
implements Loggable
{
static final long serialVersionUID = 2L;
/** The loggable implementation. */
private final LoggableImpl mLoggable;
/**
* Constructor getting an log message info.
*
* @param messageInfo the log message info for this exception
*/
protected BaseException (LogMessageInfo messageInfo)
{
super(messageInfo.getSymbol());
mLoggable = new LoggableImpl(this, messageInfo);
}
/**
* Constructor getting an log message info and a root exception.
*
* @param messageInfo the log message info for this exception
* @param cause the problem that caused this exception to be thrown
*/
protected BaseException (LogMessageInfo messageInfo, Throwable cause)
{
super(messageInfo.getSymbol(), cause);
mLoggable = new LoggableImpl(this, messageInfo, cause);
}
/** {@inheritDoc} */
public Throwable initCause (Throwable cause)
{
super.initCause(cause);
mLoggable.initCause(cause);
return this;
}
/** {@inheritDoc} */
public final void addParameter (String name, Serializable value)
{
mLoggable.addParameter(name, value);
}
/** {@inheritDoc} */
public String getInstanceId ()
{
return mLoggable.getInstanceId();
}
/** {@inheritDoc} */
public final String getMessage ()
{
return mLoggable.getMessage();
}
/** {@inheritDoc} */
public final void log ()
{
mLoggable.log();
}
/** {@inheritDoc} */
public Throwable getCause ()
{
return mLoggable.getCause();
}
/** {@inheritDoc} */
public long getEventTime ()
{
return mLoggable.getEventTime();
}
/** {@inheritDoc} */
public LogMessageInfo getLogMessageInfo ()
{
return mLoggable.getLogMessageInfo();
}
/** {@inheritDoc} */
public String getNodeId ()
{
return mLoggable.getNodeId();
}
/** {@inheritDoc} */
public List getParameter (String name)
{
return mLoggable.getParameter(name);
}
/** {@inheritDoc} */
public Set getParameterNames ()
{
return mLoggable.getParameterNames();
}
/** {@inheritDoc} */
public long getThreadId ()
{
return mLoggable.getThreadId();
}
/** {@inheritDoc} */
public String getTrackingNumber ()
{
return mLoggable.getTrackingNumber();
}
/** {@inheritDoc} */
public String getSourceClass ()
{
return mLoggable.getSourceClass();
}
/** {@inheritDoc} */
public String getSourceMethod ()
{
return mLoggable.getSourceMethod();
}
/** {@inheritDoc} */
public String toString ()
{
return mLoggable.toString();
}
LoggableImpl getExceptionImpl ()
{
return mLoggable;
}
}
|
package org.hibernate.ogm.datastore.infinispan.impl;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.hibernate.ogm.datastore.spi.DatastoreProvider;
import org.hibernate.ogm.datastore.spi.DefaultDatastoreNames;
import org.hibernate.ogm.dialect.GridDialect;
import org.hibernate.ogm.dialect.infinispan.InfinispanDialect;
import org.hibernate.service.jndi.spi.JndiService;
import org.hibernate.service.spi.*;
import org.infinispan.Cache;
import org.infinispan.config.Configuration;
import org.infinispan.config.ConfigurationValidatingVisitor;
import org.infinispan.config.GlobalConfiguration;
import org.infinispan.config.InfinispanConfiguration;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.hibernate.HibernateException;
import org.hibernate.ogm.util.impl.Log;
import org.hibernate.ogm.util.impl.LoggerFactory;
import org.hibernate.ogm.util.impl.StringHelper;
import org.hibernate.service.jta.platform.spi.JtaPlatform;
/**
* Provides access to Infinispan's CacheManager; one CacheManager is needed for all caches,
* it can be taken via JNDI or started by this ServiceProvider; in this case it will also
* be stopped when no longer needed.
*
* @author Sanne Grinovero
* @author Emmanuel Bernard <emmanuel@hibernate.org>
*/
public class InfinispanDatastoreProvider implements DatastoreProvider, Startable, Stoppable,
ServiceRegistryAwareService, Configurable {
private JtaPlatform jtaPlatform;
private JndiService jndiService;
private Map cfg;
private Map<String,Cache> caches;
private boolean isCacheProvided;
private boolean started = false;
@Override
public Class<? extends GridDialect> getDefaultDialect() {
return InfinispanDialect.class;
}
/**
* The configuration property to use as key to define a custom configuration for Infinispan.
*/
public static final String INFINISPAN_CONFIGURATION_RESOURCENAME = "hibernate.ogm.infinispan.configuration_resourcename";
/**
* The key for the configuration property to define the jndi name of the cachemanager.
* If this property is defined, the cachemanager will be looked up via JNDI.
* JNDI properties passed in the form <tt>hibernate.jndi.*</tt> are used to define the context properties.
*/
public static final String CACHE_MANAGER_RESOURCE_PROP = "hibernate.ogm.infinispan.cachemanager_jndiname";
public static final String INFINISPAN_DEFAULT_CONFIG = "org/hibernate/ogm/datastore/infinispan/default-config.xml";
private static final Log log = LoggerFactory.make();
private EmbeddedCacheManager cacheManager;
public void start() {
if ( started ) {
// ServiceRegistry might invoke start multiple times, but always from the same initialization thread.
//TODO remove the start flag: no longer needed after HHH-7147
return;
}
try {
String jndiProperty = (String) cfg.get( CACHE_MANAGER_RESOURCE_PROP );
if ( jndiProperty == null ) {
String cfgName = (String) cfg.get( INFINISPAN_CONFIGURATION_RESOURCENAME );
if ( StringHelper.isEmpty( cfgName ) ) {
cfgName = INFINISPAN_DEFAULT_CONFIG;
}
log.tracef("Initializing Infinispan from configuration file at %1$s", cfgName);
cacheManager = createCustomCacheManager( cfgName, jtaPlatform );
isCacheProvided = false;
}
else {
log.tracef("Retrieving Infinispan from JNDI at %1$s", jndiProperty);
cacheManager = (EmbeddedCacheManager) jndiService.locate(jndiProperty);
isCacheProvided = true;
}
}
catch (RuntimeException e) {
throw log.unableToInitializeInfinispan( e );
}
eagerlyInitializeCaches(cacheManager);
//clear resources
this.jtaPlatform = null;
this.jndiService = null;
this.cfg = null;
this.started = true;
}
/**
* Need to make sure all needed caches are started before state transfer happens.
* This prevents this node to return undefined cache errors during replication
* when other nodes join this one.
* @param cacheManager
*/
private void eagerlyInitializeCaches(EmbeddedCacheManager cacheManager) {
caches = new ConcurrentHashMap<String, Cache> (3);
putInLocalCache(cacheManager, DefaultDatastoreNames.ASSOCIATION_STORE);
putInLocalCache(cacheManager, DefaultDatastoreNames.ENTITY_STORE);
putInLocalCache(cacheManager, DefaultDatastoreNames.IDENTIFIER_STORE);
}
private void putInLocalCache(EmbeddedCacheManager cacheManager, String cacheName) {
caches.put(
cacheName,
cacheManager.getCache(cacheName)
);
}
private EmbeddedCacheManager createCustomCacheManager(String cfgName, JtaPlatform platform) {
try {
InfinispanConfiguration configuration = InfinispanConfiguration.newInfinispanConfiguration(
cfgName, InfinispanConfiguration.resolveSchemaPath(),
new ConfigurationValidatingVisitor(),
Thread.currentThread().getContextClassLoader() );
GlobalConfiguration globalConfiguration = configuration.parseGlobalConfiguration();
Configuration defaultConfiguration = configuration.parseDefaultConfiguration();
TransactionManagerLookupDelegator transactionManagerLookupDelegator = new TransactionManagerLookupDelegator( platform );
final DefaultCacheManager cacheManager = new DefaultCacheManager( globalConfiguration, defaultConfiguration, true );
for (Map.Entry<String, Configuration> entry : configuration.parseNamedConfigurations().entrySet()) {
Configuration cfg = entry.getValue();
if ( transactionManagerLookupDelegator.isValid() ) {
cfg.fluent().transactionManagerLookup(transactionManagerLookupDelegator);
}
cacheManager.defineConfiguration( entry.getKey(), cfg );
}
cacheManager.start();
return cacheManager;
} catch (RuntimeException re) {
throw raiseConfigurationError( re, cfgName );
}
catch (IOException e) {
throw raiseConfigurationError( e, cfgName );
}
}
public EmbeddedCacheManager getEmbeddedCacheManager() {
return cacheManager;
}
//prefer generic form over specific ones to prepare for flexible cache setting
public Cache getCache(String name) {
return caches.get(name);
}
public void stop() {
if ( !isCacheProvided && cacheManager != null ) {
cacheManager.stop();
}
}
private HibernateException raiseConfigurationError(Exception e, String cfgName) {
return new HibernateException(
"Could not start Infinispan CacheManager using as configuration file: " + cfgName, e
);
}
@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
jtaPlatform = serviceRegistry.getService( JtaPlatform.class );
jndiService = serviceRegistry.getService( JndiService.class );
}
@Override
public void configure(Map configurationValues) {
cfg = configurationValues;
}
}
|
// This file is part of the OpenNMS(R) Application.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// and included code are below.
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
// Modifications:
// 2007 May 06: Eliminate a warning. - dj@opennms.org
// 2006 Apr 27: Added support for pathOutageEnabled
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// For more information contact:
package org.opennms.netmgt.config;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Category;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.opennms.core.utils.IPSorter;
import org.opennms.core.utils.IpListFromUrl;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.config.map.adapter.Celement;
import org.opennms.netmgt.config.map.adapter.Cmap;
import org.opennms.netmgt.config.map.adapter.Csubmap;
import org.opennms.netmgt.config.map.adapter.Package;
import org.opennms.netmgt.config.map.adapter.MapsAdapterConfiguration;
import org.opennms.netmgt.config.map.adapter.ExcludeRange;
import org.opennms.netmgt.config.map.adapter.IncludeRange;
import org.opennms.netmgt.filter.FilterDaoFactory;
/**
*
* @author <a href="mailto:antonio@openms.it">Antonio Russo</a>
* @author <a href="mailto:brozow@openms.org">Mathew Brozowski</a>
* @author <a href="mailto:david@opennms.org">David Hustace</a>
*/
abstract public class MapsAdapterConfigManager implements MapsAdapterConfig {
/**
* @author <a href="mailto:antonio@opennms.org">Antonio Russo</a>
* @param reader
* @param localServer
* @param verifyServer
* @throws MarshalException
* @throws ValidationException
* @throws IOException
*/
public MapsAdapterConfigManager(Reader reader,String serverName, boolean verifyServer) throws MarshalException, ValidationException, IOException {
m_localServer = serverName;
m_verifyServer = verifyServer;
reloadXML(reader);
}
/**
* The config class loaded from the config file
*/
private MapsAdapterConfiguration m_config;
/**
* A boolean flag to indicate If a filter rule against the local OpenNMS
* server has to be used.
*/
private static boolean m_verifyServer;
/**
* The name of the local OpenNMS server
*/
private static String m_localServer;
/**
* A mapping of the configured URLs to a list of the specific IPs configured
* in each - so as to avoid file reads
*/
private Map<String, List<String>> m_urlIPMap;
/**
* A mapping of the configured package to a list of IPs selected via filter
* rules, so as to avoid database access.
*/
private Map<Package, List<String>> m_pkgIpMap;
/**
* A mapping of the configured submaps to a list of maps
*/
private Map<String,List<String>> m_submapNameMapNameMap;
/**
* A mapping of the configured mapName to cmaps
*/
private Map<String,Cmap> m_mapNameCmapMap;
public MapsAdapterConfigManager() {
}
protected synchronized void reloadXML(Reader reader) throws MarshalException, ValidationException, IOException {
m_config = (MapsAdapterConfiguration) Unmarshaller.unmarshal(MapsAdapterConfiguration.class, reader);
createUrlIpMap();
createPackageIpListMap();
createSubMapMapMap();
createmapNameCmapMap();
verifyMapConsistency();
verifyMapHasLoop();
}
private boolean hasCmaps() {
return (m_config.getCmaps() != null);
}
/**
* Go through the maps adapter configuration and build a mapping of each
* configured mapname to container cmap.
*
*/
private void createmapNameCmapMap() {
m_mapNameCmapMap = new HashMap<String, Cmap>();
if (hasCmaps()) {
Iterator<Cmap> ite = m_config.getCmaps().iterateCmap();
while (ite.hasNext()) {
Cmap cmap = ite.next();
m_mapNameCmapMap.put(cmap.getMapName(), cmap);
log().debug("createmapNameCmapMap: Added map: " +cmap.getMapName());
}
}
}
/**
* Go through the maps adapter configuration and build a mapping of each
* configured submap to container map.
*
*/
private void createSubMapMapMap() {
m_submapNameMapNameMap = new HashMap<String, List<String>>();
if (hasCmaps()) {
Iterator<Cmap> ite = m_config.getCmaps().iterateCmap();
while (ite.hasNext()) {
Cmap cmap = ite.next();
Iterator<Csubmap> sub_ite = cmap.iterateCsubmap();
while (sub_ite.hasNext()) {
Csubmap csubmap = sub_ite.next();
String subMapName = csubmap.getName();
List<String> containermaps = new ArrayList<String>();
if (m_submapNameMapNameMap.containsKey(subMapName)) {
containermaps = m_submapNameMapNameMap.get(subMapName);
}
containermaps.add(cmap.getMapName());
m_submapNameMapNameMap.put(subMapName, containermaps);
log().debug("createSubMapMapMap: added container map: " + cmap.getMapName() + " to submap: " + subMapName);
}
}
}
}
/**
* Verify that no loop are in maps definition
*/
private void verifyMapConsistency() throws ValidationException {
Iterator<String> ite = m_submapNameMapNameMap.keySet().iterator();
while (ite.hasNext()) {
// verify cmap exists!
String mapName = ite.next();
if (!cmapExist(mapName))
throw new ValidationException("Defined a submap without defining the map: mapName " + mapName);
}
}
/**
* Verify that all maps are well defined
*/
private void verifyMapHasLoop() throws ValidationException {
// TODO use the Floyd's Cycle-Finding Algorithm
/*
* String startnode;
* String slownode = startnode;
* String fastnode1 = startnode;
* String fastnode2 = startnode;
* while (slownode && fastnode1 = fastnode2.next && fastnode2 = fastnode1.next) {
* if (slownode == fastnode1 || slownode == fastnode2) return true;
* slownode.next;
* }
* return false;
*/
/* Iterator<String> ite = m_submapNameMapNameMap.keySet().iterator();
while (ite.hasNext()) {
// verify cmap exists!
String mapName = ite.next();
Iterator<String> sub_ite = m_submapNameMapNameMap.get(mapName).iterator();
while (sub_ite.hasNext()) {
String nextElementMap = sub_ite.next();
}
}
*/
}
private boolean cmapExist(String mapName) {
if (hasCmaps()) {
Iterator<Cmap> ite = m_config.getCmaps().iterateCmap();
while (ite.hasNext()) {
if (ite.next().getMapName().equals(mapName)) return true;
}
}
return false;
}
/**
* Go through the maps adapter configuration and build a mapping of each
* configured URL to a list of IPs configured in that URL - done at init()
* time so that repeated file reads can be avoided
*/
private void createUrlIpMap() {
m_urlIPMap = new HashMap<String, List<String>>();
for(Package pkg : packages()) {
for(String url : includeURLs(pkg)) {
List<String> iplist = IpListFromUrl.parse(url);
if (iplist.size() > 0) {
m_urlIPMap.put(url, iplist);
}
}
}
}
/**
* This method is used to establish package against iplist mapping, with
* which, the iplist is selected per package via the configured filter rules
* from the database.
*/
private void createPackageIpListMap() {
m_pkgIpMap = new HashMap<Package, List<String>>();
for(Package pkg : packages()) {
// Get a list of ipaddress per package agaist the filter rules from
// database and populate the package, IP list map.
try {
List<String> ipList = getIpList(pkg);
log().debug("createPackageIpMap: package " + pkg.getName() + ": ipList size = " + ipList.size());
if (ipList.size() > 0) {
m_pkgIpMap.put(pkg, ipList);
}
} catch (Throwable t) {
log().error("createPackageIpMap: failed to map package: " + pkg.getName() + " to an IP List: " + t, t);
}
}
}
private List<String> getIpList(Package pkg) {
StringBuffer filterRules = new StringBuffer(pkg.getFilter().getContent());
if (m_verifyServer) {
filterRules.append(" & (serverName == ");
filterRules.append('\"');
filterRules.append(m_localServer);
filterRules.append('\"');
filterRules.append(")");
}
log().debug("createPackageIpMap: package is " + pkg.getName() + ". filer rules are " + filterRules.toString());
List<String> ipList = FilterDaoFactory.getInstance().getIPList(filterRules.toString());
return ipList;
}
/**
* This method is used to determine if the named interface is included in
* the passed package definition. If the interface belongs to the package
* then a value of true is returned. If the interface does not belong to the
* package a false value is returned.
*
* <strong>Note: </strong>Evaluation of the interface against a package
* filter will only work if the IP is already in the database.
*
* @param iface
* The interface to test against the package.
* @param pkg
* The package to check for the inclusion of the interface.
*
* @return True if the interface is included in the package, false
* otherwise.
*/
private synchronized boolean interfaceInPackage(String iface, Package pkg) {
Category log = log();
boolean filterPassed = false;
// get list of IPs in this package
List<String> ipList = m_pkgIpMap.get(pkg);
if (ipList != null && ipList.size() > 0) {
filterPassed = ipList.contains(iface);
}
if (log.isDebugEnabled())
log.debug("interfaceInPackage: Interface " + iface + " passed filter for package " + pkg.getName() + "?: " + filterPassed);
if (!filterPassed)
return false;
// Ensure that the interface is in the specific list or
// that it is in the include range and is not excluded
boolean has_specific = false;
boolean has_range_include = false;
boolean has_range_exclude = false;
// if there are NO include ranges then treat act as if the user include
// the range 0.0.0.0 - 255.255.255.255
has_range_include = pkg.getIncludeRangeCount() == 0 && pkg.getSpecificCount() == 0;
long addr = IPSorter.convertToLong(iface);
Enumeration<IncludeRange> eincs = pkg.enumerateIncludeRange();
while (!has_range_include && eincs.hasMoreElements()) {
IncludeRange rng = eincs.nextElement();
long start = IPSorter.convertToLong(rng.getBegin());
if (addr > start) {
long end = IPSorter.convertToLong(rng.getEnd());
if (addr <= end) {
has_range_include = true;
}
} else if (addr == start) {
has_range_include = true;
}
}
Enumeration<String> espec = pkg.enumerateSpecific();
while (!has_specific && espec.hasMoreElements()) {
long speca = IPSorter.convertToLong(espec.nextElement());
if (speca == addr)
has_specific = true;
}
Enumeration<String> eurl = pkg.enumerateIncludeUrl();
while (!has_specific && eurl.hasMoreElements()) {
has_specific = interfaceInUrl(iface, eurl.nextElement());
}
Enumeration<ExcludeRange> eex = pkg.enumerateExcludeRange();
while (!has_range_exclude && !has_specific && eex.hasMoreElements()) {
ExcludeRange rng = eex.nextElement();
long start = IPSorter.convertToLong(rng.getBegin());
if (addr > start) {
long end = IPSorter.convertToLong(rng.getEnd());
if (addr <= end) {
has_range_exclude = true;
}
} else if (addr == start) {
has_range_exclude = true;
}
}
return has_specific || (has_range_include && !has_range_exclude);
}
/**
* This method is used to determine if the named interface is included in
* the passed package's url includes. If the interface is found in any of
* the URL files, then a value of true is returned, else a false value is
* returned.
*
* <pre>
*
* The file URL is read and each entry in this file checked. Each line
* in the URL file can be one of -
* <IP><space>#<comments>
* or
* <IP>
* or
* #<comments>
*
* Lines starting with a '#' are ignored and so are characters after
* a '<space>#' in a line.
*
* </pre>
*
* @param addr
* The interface to test against the package's URL
* @param url
* The url file to read
*
* @return True if the interface is included in the url, false otherwise.
*/
private boolean interfaceInUrl(String addr, String url) {
boolean bRet = false;
// get list of IPs in this URL
List<String> iplist = m_urlIPMap.get(url);
if (iplist != null && iplist.size() > 0) {
bRet = iplist.contains(addr);
}
return bRet;
}
/**
* Returns a list of package names that the ip belongs to, null if none.
*
* <strong>Note: </strong>Evaluation of the interface against a package
* filter will only work if the IP is alrady in the database.
*
* @param ipaddr
* the interface to check
*
* @return a list of package names that the ip belongs to, null if none
*/
public synchronized List<String> getAllPackageMatches(String ipaddr) {
List<String> matchingPkgs = new ArrayList<String>();
for(Package pkg : packages()) {
boolean inPkg = interfaceInPackage(ipaddr, pkg);
if (inPkg) {
matchingPkgs.add(pkg.getName());
}
}
return matchingPkgs;
}
public Iterable<Package> packages() {
return getConfiguration().getPackageCollection();
}
public Iterable<String> includeURLs(Package pkg) {
return pkg.getIncludeUrlCollection();
}
/**
* Return the poller configuration object.
*/
public synchronized MapsAdapterConfiguration getConfiguration() {
return m_config;
}
private Category log() {
return ThreadCategory.getInstance(this.getClass());
}
// methods from interface
public List<Cmap> getAllMaps() {
if (hasCmaps()) {
return getConfiguration().getCmaps().getCmapCollection();
}
return new ArrayList<Cmap>();
}
public Map<String, Celement> getElementByAddress(String ipaddr) {
Map<String,Celement> mapAndElements = new HashMap<String, Celement>();
if (hasCmaps()) {
List<String> pkgs = getAllPackageMatches(ipaddr);
Iterator<Cmap> ite = getConfiguration().getCmaps().getCmapCollection().iterator();
while (ite.hasNext()) {
Cmap cmap = ite.next();
Iterator<Celement> cels = cmap.getCelementCollection().iterator();
boolean found = false;
while (cels.hasNext()) {
Celement celement = cels.next();
Iterator<String> pkgname = pkgs.iterator();
while (pkgname.hasNext()) {
if (pkgname.next().equals(celement.getPackage())) {
mapAndElements.put(cmap.getMapName(), celement);
found = true;
break;
}
}
if (found) break;
}
}
}
return mapAndElements;
}
public List<Csubmap> getSubMaps(String mapName) {
if (hasCmaps()) {
Iterator<Cmap> ite = getConfiguration().getCmaps().getCmapCollection().iterator();
while (ite.hasNext()) {
Cmap cmap = ite.next();
if (cmap.getMapName().equals(mapName))
return cmap.getCsubmapCollection();
}
}
return new ArrayList<Csubmap>();
}
public int getMapElementDimension() {
return getConfiguration().getElementDimension();
}
public Map<String,Csubmap> getContainerMaps(String submapName) {
Map<String,Csubmap> cmaps = new HashMap<String, Csubmap>();
if (m_submapNameMapNameMap.containsKey(submapName)) {
Iterator<String> ite = m_submapNameMapNameMap.get(submapName).iterator();
while (ite.hasNext()) {
String mapName = ite.next();
Cmap cmap = m_mapNameCmapMap.get(mapName);
Iterator<Csubmap> sub_ite = cmap.iterateCsubmap();
while (sub_ite.hasNext()) {
Csubmap csubmap = sub_ite.next();
if (csubmap.getName().equals(submapName)) {
cmaps.put(mapName,csubmap);
break;
}
}
}
}
return cmaps;
}
public Map<String, List<Csubmap>> getsubMaps() {
Map<String,List<Csubmap>> csubmaps = new HashMap<String, List<Csubmap>>();
if (hasCmaps()) {
Iterator<Cmap> ite = getConfiguration().getCmaps().getCmapCollection().iterator();
while (ite.hasNext()) {
Cmap cmap = ite.next();
if (cmap.getCsubmapCount() > 0) {
csubmaps.put(cmap.getMapName(), cmap.getCsubmapCollection());
}
}
}
return csubmaps;
}
/**
* This method is used to rebuild the package agaist iplist mapping when
* needed. When a node gained service event occurs, poller has to determine
* which package the ip/service combination is in, but if the interface is a
* newly added one, the package iplist should be rebuilt so that poller
* could know which package this ip/service pair is in.
*/
public synchronized void rebuildPackageIpListMap() {
createPackageIpListMap();
}
}
|
package org.eclipse.persistence.testing.tests.jpa.criteria;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.Parameter;
import javax.persistence.Query;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Fetch;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.metamodel.EmbeddableType;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.persistence.config.CacheUsage;
import org.eclipse.persistence.config.QueryHints;
import org.eclipse.persistence.config.QueryType;
import org.eclipse.persistence.config.ResultSetConcurrency;
import org.eclipse.persistence.config.ResultSetType;
import org.eclipse.persistence.config.ResultType;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.jpa.JpaQuery;
import org.eclipse.persistence.queries.Cursor;
import org.eclipse.persistence.queries.ScrollableCursor;
import org.eclipse.persistence.sessions.DatabaseSession;
import org.eclipse.persistence.testing.framework.QuerySQLTracker;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import org.eclipse.persistence.testing.models.jpa.advanced.Address;
import org.eclipse.persistence.testing.models.jpa.advanced.AdvancedTableCreator;
import org.eclipse.persistence.testing.models.jpa.advanced.Dealer;
import org.eclipse.persistence.testing.models.jpa.advanced.Employee;
import org.eclipse.persistence.testing.models.jpa.advanced.EmployeePopulator;
import org.eclipse.persistence.testing.models.jpa.advanced.EmploymentPeriod;
import org.eclipse.persistence.testing.models.jpa.advanced.PhoneNumber;
import org.eclipse.persistence.testing.models.jpa.advanced.Project;
import org.eclipse.persistence.testing.tests.jpa.jpql.JUnitDomainObjectComparer;
/**
* <p>
* <b>Purpose</b>: Test advanced JPA Query functionality.
* <p>
* <b>Description</b>: This tests query hints, caching and query optimization.
* <p>
*/
public class AdvancedCriteriaQueryTestSuite extends JUnitTestCase {
static JUnitDomainObjectComparer comparer; //the global comparer object used in all tests
public AdvancedCriteriaQueryTestSuite() {
super();
}
public AdvancedCriteriaQueryTestSuite(String name) {
super(name);
}
// This method is run at the start of EVERY test case method.
public void setUp() {
}
// This method is run at the end of EVERY test case method.
public void tearDown() {
clearCache();
}
//This suite contains all tests contained in this class
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("AdvancedQueryTestSuite");
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSetup"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testInCollectionEntity"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testInCollectionPrimitives"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testProd"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSize"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testJoinDistinct"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSome"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testWhereConjunction"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testWhereDisjunction"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testWhereConjunctionAndDisjunction"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testVerySimpleJoin"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testGroupByHaving"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testAlternateSelection"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSubqueryExists"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSubQuery"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testInSubQuery"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testInLiteral"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testInlineInParameter"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSimpleJoin"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSimpleFetch"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testObjectResultType"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSimple"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSimpleWhere"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSimpleWhereObject"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testSharedWhere"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testTupleQuery"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testQueryCacheFirstCacheHits"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testQueryCacheOnlyCacheHits"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testQueryCacheOnlyCacheHitsOnSession"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testQueryExactPrimaryKeyCacheHits"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testQueryHintFetch"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testCursors"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testIsEmpty"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testNeg"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testIsMember"));
suite.addTest(new AdvancedCriteriaQueryTestSuite("testIsMemberEntity"));
return suite;
}
/**
* The setup is done as a test, both to record its failure, and to allow execution in the server.
*/
public void testSetup() {
clearCache();
DatabaseSession session = JUnitTestCase.getServerSession();
//create a new EmployeePopulator
EmployeePopulator employeePopulator = new EmployeePopulator();
new AdvancedTableCreator().replaceTables(session);
//initialize the global comparer object
comparer = new JUnitDomainObjectComparer();
//set the session for the comparer to use
comparer.setSession((AbstractSession)session.getActiveSession());
//Populate the tables
employeePopulator.buildExamples();
//Persist the examples in the database
employeePopulator.persistExample(session);
}
public void testAlternateSelection() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("select p.teamLeader from Project p where p.name = 'Sales Reporting'").getResultList();
Metamodel mm = em.getMetamodel();
CriteriaBuilder qbuilder = em.getCriteriaBuilder();
CriteriaQuery<Employee> cquery = qbuilder.createQuery(Employee.class);
Root<Project> spouse = cquery.from(Project.class);
cquery.where(qbuilder.equal(spouse.get("name"), "Sales Reporting")).select(spouse.<Employee> get("teamLeader"));
TypedQuery<Employee> tquery = em.createQuery(cquery);
assertTrue("Did not find the correct leaders of Project Swirly Dirly.", tquery.getResultList().size() > 1);
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
/**
* Test that a cache hit will occur on a primary key query.
*/
public void testTupleQuery() {
EntityManager em = createEntityManager();
QuerySQLTracker counter = null;
beginTransaction(em);
try {
// Load an employee into the cache.
CriteriaBuilder qb = em.getCriteriaBuilder();
Query query = em.createQuery(em.getCriteriaBuilder().createQuery(Employee.class));
List result = query.getResultList();
Employee employee = (Employee)result.get(0);
// Count SQL.
counter = new QuerySQLTracker(getServerSession());
// Query by primary key.
CriteriaQuery<Tuple> cq = qb.createQuery(Tuple.class);
Root from = cq.from(Employee.class);
cq.multiselect(from.get("id"), from.get("firstName"));
cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")), qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName"))));
TypedQuery<Tuple> typedQuery = em.createQuery(cq);
typedQuery.setParameter("id", employee.getId());
typedQuery.setParameter("firstName", employee.getFirstName());
Tuple queryResult = typedQuery.getSingleResult();
assertTrue("Query Results do not match selection", queryResult.get(0).equals(employee.getId()) && queryResult.get(1).equals(employee.getFirstName()));
} finally {
rollbackTransaction(em);
if (counter != null) {
counter.remove();
}
}
}
public void testSharedWhere() {
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
CriteriaBuilder qb = em.getCriteriaBuilder();
Root<Employee> root = cq.from(em.getMetamodel().entity(Employee.class));
cq.where(qb.equal(root.get("firstName"), qb.literal("Bob")));
TypedQuery<Employee> tq = em.createQuery(cq);
List<Employee> result = tq.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
assertTrue("Did not return Employee", result.get(0).getClass().equals(Employee.class));
assertTrue("Employee had wrong firstname", ((Employee) result.get(0)).getFirstName().equalsIgnoreCase("bob"));
CriteriaQuery<Employee> cq2 = em.getCriteriaBuilder().createQuery(Employee.class);
cq2.where(cq.getRestriction());
TypedQuery<Employee> tq2 = em.createQuery(cq);
List<Employee> result2 = tq.getResultList();
assertTrue("Employee's did not match with query with same where clause", comparer.compareObjects(result.get(0), result2.get(0)));
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testSimple(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
List<Employee> result = em.createQuery(cq).getResultList();
assertFalse("No Employees were returned", result.isEmpty());
assertTrue("Did not return Employee", result.get(0).getClass().equals(Employee.class));
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testGroupByHaving(){
EntityManager em = createEntityManager();
em.createQuery("Select e.address, count(e) from Employee e group by e.address having count(e.address) < 3").getResultList();
beginTransaction(em);
try {
Metamodel mm = em.getMetamodel();
CriteriaBuilder qbuilder = em.getCriteriaBuilder();
CriteriaQuery<Object> cquery = qbuilder.createQuery();
Root<Employee> customer = cquery.from(Employee.class);
EntityType<Employee> Customer_ = customer.getModel();
EmbeddableType<EmploymentPeriod> Country_ = mm.embeddable(EmploymentPeriod.class);
cquery.multiselect(customer.get(Customer_.getSingularAttribute("period", EmploymentPeriod.class)), qbuilder.count(customer)).groupBy(customer.get(Customer_.getSingularAttribute("period", EmploymentPeriod.class))).having(qbuilder.gt(qbuilder.count(customer.get(Customer_.getSingularAttribute("period", EmploymentPeriod.class))), 3));
List<Object> result = em.createQuery(cquery).getResultList();
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testInLiteral(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
In<String> in = qb.in(emp.get("address").<String>get("city"));
in.value("Ottawa").value("Halifax").value("Toronto");
cq.where(in);
List<Employee> result = em.createQuery(cq).getResultList();
assertFalse("No Employees were returned", result.isEmpty());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testInSubQuery(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
Subquery<String> sq = cq.subquery(String.class);
Root<Address> sqEmp = sq.from(Address.class);
sq.select(sqEmp.<String>get("city"));
sq.where(qb.notLike(sqEmp.<String>get("city"), "5"));
In<String> in = qb.in(emp.get("address").<String>get("city"));
in.value(sq);
cq.where(in);
List<Employee> result = em.createQuery(cq).getResultList();
assertFalse("No Employees were returned", result.isEmpty());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testInCollectionEntity(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
Root<PhoneNumber> phone = cq.from(PhoneNumber.class);
cq.where(qb.and(qb.equal(phone.get("areaCode"), "613"), phone.in(emp.<Collection<?>>get("phoneNumbers"))));
Query query = em.createQuery(cq);
List<Employee> result = query.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testInCollectionPrimitives(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
Root<PhoneNumber> phone = cq.from(PhoneNumber.class);
cq.where(qb.literal("Bug fixes").in(emp.<Collection<?>>get("responsibilities")));
Query query = em.createQuery(cq);
List<Employee> result = query.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testInlineInParameter(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
cq.where(emp.get("address").<String>get("city").in(qb.parameter(String.class, "city")));
Query query = em.createQuery(cq);
query.setParameter("city", "Ottawa");
List<Employee> result = query.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testIsEmpty(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
cq.where(qb.isEmpty(emp.<Collection<PhoneNumber>>get("phoneNumbers")));
List<Employee> result = em.createQuery(cq).getResultList();
assertFalse("No Employees were returned", result.isEmpty());
for (Employee e : result){
assertTrue("PhoneNumbers Found", e.getPhoneNumbers().isEmpty());
}
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testNeg(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
cq.where(qb.lessThan(qb.neg(qb.size(emp.<Collection<PhoneNumber>>get("phoneNumbers"))), 0));
List<Employee> result = em.createQuery(cq).getResultList();
assertFalse("No Employees were returned", result.isEmpty());
for (Employee e : result){
assertTrue("PhoneNumbers Found", ! e.getPhoneNumbers().isEmpty());
}
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testNullIf(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
cq.where(qb.isNull(qb.nullif(qb.size(emp.<Collection<PhoneNumber>>get("phoneNumbers")), qb.parameter(Integer.class))));
List<Employee> result = em.createQuery(cq).getResultList();
assertFalse("No Employees were returned", result.isEmpty());
for (Employee e : result){
assertTrue("PhoneNumbers Found", ! e.getPhoneNumbers().isEmpty());
}
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testIsMember(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
cq.where(qb.isMember(qb.parameter(String.class,"1"), emp.<Collection<String>>get("responsibilities")));
Query query = em.createQuery(cq);
query.setParameter("1", "Sort files");
List<Employee> result = query.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
for (Employee e : result){
assertTrue("Employee Found without Responcibilities", e.getResponsibilities().contains("Sort files"));
}
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testIsMemberEntity(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
Root<Employee> emp = cq.from(Employee.class);
Root<PhoneNumber> phone = cq.from(PhoneNumber.class);
cq.where(qb.and(qb.equal(phone.get("areaCode"), "416"), qb.isMember(phone, emp.<Collection<PhoneNumber>>get("phoneNumbers"))));
Query query = em.createQuery(cq);
List<Employee> result = query.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
for (Employee e : result){
boolean areacode = false;
for (PhoneNumber p : e.getPhoneNumbers()){
areacode = areacode || p.getAreaCode().equals("416");
}
assertTrue("No PhoneNumbers with '416'area code", areacode);
}
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testVerySimpleJoin(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
CriteriaBuilder qb = em.getCriteriaBuilder();
Root<Employee> root = cq.from(em.getMetamodel().entity(Employee.class));
root.join("phoneNumbers");
cq.distinct(true);
TypedQuery<Employee> tq = em.createQuery(cq);
List<Employee> result = tq.getResultList();
for (Employee emp : result){
assertFalse("Found someone without a phone", emp.getPhoneNumbers().isEmpty());
}
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testSimpleJoin(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
CriteriaBuilder qb = em.getCriteriaBuilder();
Root<Employee> root = cq.from(em.getMetamodel().entity(Employee.class));
root.join("phoneNumbers");
cq.where(qb.isEmpty(root.<Collection<PhoneNumber>>get("phoneNumbers")));
TypedQuery<Employee> tq = em.createQuery(cq);
List<Employee> result = tq.getResultList();
assertTrue("Found employee but joins should have canceled isEmpty", result.isEmpty());
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testSimpleWhere(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
CriteriaBuilder qb = em.getCriteriaBuilder();
Root<Employee> root = cq.from(em.getMetamodel().entity(Employee.class));
cq.where(qb.equal(root.get("firstName"), qb.literal("Bob")));
TypedQuery<Employee> tq = em.createQuery(cq);
List<Employee> result = tq.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
assertTrue("Did not return Employee", result.get(0).getClass().equals(Employee.class));
assertTrue("Employee had wrong firstname", ((Employee)result.get(0)).getFirstName().equalsIgnoreCase("bob"));
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testWhereDisjunction(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
CriteriaBuilder qb = em.getCriteriaBuilder();
cq.where(qb.disjunction());
TypedQuery<Employee> tq = em.createQuery(cq);
List<Employee> result = tq.getResultList();
assertTrue("Employees were returned", result.isEmpty());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testWhereConjunction(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
CriteriaBuilder qb = em.getCriteriaBuilder();
cq.where(qb.conjunction());
TypedQuery<Employee> tq = em.createQuery(cq);
List<Employee> result = tq.getResultList();
assertFalse("Employees were returned", result.isEmpty());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testJoinDistinct(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaBuilder qbuilder = em.getCriteriaBuilder();
CriteriaQuery<Employee> cquery = qbuilder.createQuery(Employee.class);
Root<Employee> customer = cquery.from(Employee.class);
Fetch<Employee, Project> o = customer.fetch("phoneNumbers", JoinType.LEFT);
cquery.where(customer.get("address").get("city").in("Ottawa", "Halifax"));
cquery.select(customer).distinct(true);
TypedQuery<Employee> tquery = em.createQuery(cquery);
List<Employee> result = tquery.getResultList();
assertFalse ("No results found", result.isEmpty());
Long count = (Long)em.createQuery("Select count(e) from Employee e where e.address.city in ('Ottawa', 'Halifax')").getSingleResult();
assertTrue("Incorrect number of results returned", result.size() == count);
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testWhereConjunctionAndDisjunction(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
CriteriaBuilder qb = em.getCriteriaBuilder();
cq.where(qb.and(qb.disjunction(), qb.conjunction()));
TypedQuery<Employee> tq = em.createQuery(cq);
List<Employee> result = tq.getResultList();
assertTrue("Employees were returned", result.isEmpty());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testSimpleWhereObject(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
CriteriaBuilder qb = em.getCriteriaBuilder();
Root<Employee> root = cq.from(em.getMetamodel().entity(Employee.class));
cq.where(qb.equal(root.get("firstName"), qb.literal("Bob")));
TypedQuery<Employee> tq = em.createQuery(cq);
List<Employee> result = tq.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
assertTrue("Did not return Employee", result.get(0).getClass().equals(Employee.class));
assertTrue("Employee had wrong firstname", ((Employee)result.get(0)).getFirstName().equalsIgnoreCase("bob"));
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testSimpleFetch(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
CriteriaBuilder qb = em.getCriteriaBuilder();
Root<Employee> root = cq.from(em.getMetamodel().entity(Employee.class));
root.fetch("projects");
cq.where(qb.equal(root.get("firstName"), qb.literal("Bob")));
TypedQuery<Employee> tq = em.createQuery(cq);
List<Employee> result = tq.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
ObjectOutputStream stream = new ObjectOutputStream(byteStream);
stream.writeObject(result.get(0));
stream.flush();
byte arr[] = byteStream.toByteArray();
ByteArrayInputStream inByteStream = new ByteArrayInputStream(arr);
ObjectInputStream inObjStream = new ObjectInputStream(inByteStream);
Employee emp = (Employee) inObjStream.readObject();
assertTrue("Did not return Employee", emp.getClass().equals(Employee.class));
assertTrue("Employee had wrong firstname", emp.getFirstName().equalsIgnoreCase("bob"));
emp.getProjects().size(); //may cause exception
} catch (IOException e) {
fail("Failed during serialization");
} catch (ClassNotFoundException e) {
fail("Failed during serialization");
}
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testSize(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
// em.createQuery("Select size(e.responsibilities) from Employee e").getResultList();
CriteriaBuilder qbuilder = em.getCriteriaBuilder();
CriteriaQuery<Object[]> cquery = qbuilder.createQuery(Object[].class);
Root<Employee> customer = cquery.from(Employee.class);
cquery.select(qbuilder.array(customer.get("id"), qbuilder.size(customer.<Collection<String>>get("responsibilities"))));
TypedQuery<Object[]> tquery = em.createQuery(cquery);
List<Object[]> result = tquery.getResultList();
for(Object[] value : result){
assertTrue("Incorrect responsibilities count", em.find(Employee.class, value[0]).getResponsibilities().size() == ((Integer)value[1]).intValue());
}
// No assert as version is not actually a mapped field in dealer.
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testSome(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("SELECT e from Employee e, IN(e.phoneNumbers) p where p.type = some(select p2.type from PhoneNumber p2 where p2.areaCode = '613')").getResultList();
CriteriaBuilder qbuilder = em.getCriteriaBuilder();
CriteriaQuery<Employee> cquery = qbuilder.createQuery(Employee.class);
// Get Root Customer
Root<Employee> customer = cquery.from(Employee.class);
// Join Customer-Order
Join<Employee, PhoneNumber> orders= customer.join("phoneNumbers");
// create Subquery instance
Subquery<String> sq = cquery.subquery(String.class);
// Create Roots
Root<PhoneNumber> order = sq.from(PhoneNumber.class);
// Create SubQuery
sq.select(order.<String>get("type")).
where(qbuilder.equal(order.get("areaCode"), "613"));
// Create Main Query with SubQuery
cquery.where(qbuilder.equal(orders.<String>get("type"), qbuilder.some(sq)));
cquery.distinct(true);
em.createQuery(cquery).getResultList();
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testSubQuery(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaBuilder qbuilder = em.getCriteriaBuilder();
CriteriaQuery<Employee> cquery = qbuilder.createQuery(Employee.class);
Root<Employee> customer = cquery.from(Employee.class);
Join<Employee, Dealer> o = customer.join("dealers");
cquery.select(customer).distinct(true);
Subquery<Integer> sq = cquery.subquery(Integer.class);
Root<Dealer> sqo = sq.from(Dealer.class);
sq.select(qbuilder.min(sqo.<Integer>get("version")));
cquery.where(qbuilder.equal(o.get("version"), sq));
TypedQuery<Employee> tquery = em.createQuery(cquery);
List<Employee> result = tquery.getResultList();
// No assert as version is not actually a mapped field in dealer.
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testSubqueryExists(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("SELECT e FROM Employee e WHERE EXISTS (SELECT p FROM e.projects p)").getResultList();
CriteriaBuilder qbuilder = em.getCriteriaBuilder();
CriteriaQuery<Employee> cquery = qbuilder.createQuery(Employee.class);
Root<Employee> customer = cquery.from(Employee.class);
cquery.select(customer).distinct(true);
// create correlated subquery
Subquery<Project> sq = cquery.subquery(Project.class);
Root<Employee> sqc = sq.correlate(customer);
Path<Project> sqo = sqc.join("projects");
sq.select(sqo);
cquery.where(qbuilder.not(qbuilder.exists(sq)));
TypedQuery<Employee> tquery = em.createQuery(cquery);
List<Employee> result = tquery.getResultList();
for (Employee emp : result){
assertTrue("Found someone not from Ottawa", emp.getProjects().isEmpty());
}
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
/**
* Test cursored queries.
*/
public void testCursors() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
// Test cusored stream.
Query query = em.createQuery(em.getCriteriaBuilder().createQuery(Employee.class));
query.setHint(QueryHints.CURSOR, true);
query.setHint(QueryHints.CURSOR_INITIAL_SIZE, 2);
query.setHint(QueryHints.CURSOR_PAGE_SIZE, 5);
query.setHint(QueryHints.CURSOR_SIZE, "Select count(*) from CMP3_EMPLOYEE");
Cursor cursor = (Cursor)query.getSingleResult();
cursor.nextElement();
cursor.size();
cursor.close();
// Test cursor result API.
JpaQuery jpaQuery = (JpaQuery)((EntityManager)em.getDelegate()).createQuery(em.getCriteriaBuilder().createQuery(Employee.class));
jpaQuery.setHint(QueryHints.CURSOR, true);
cursor = jpaQuery.getResultCursor();
cursor.nextElement();
cursor.size();
cursor.close();
// Test scrollable cursor.
jpaQuery = (JpaQuery)((EntityManager)em.getDelegate()).createQuery(em.getCriteriaBuilder().createQuery(Employee.class));
jpaQuery.setHint(QueryHints.SCROLLABLE_CURSOR, true);
jpaQuery.setHint(QueryHints.RESULT_SET_CONCURRENCY, ResultSetConcurrency.ReadOnly);
jpaQuery.setHint(QueryHints.RESULT_SET_TYPE, ResultSetType.DEFAULT);
ScrollableCursor scrollableCursor = (ScrollableCursor)jpaQuery.getResultCursor();
scrollableCursor.next();
scrollableCursor.close();
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
/**
* Test the result type of various queries.
*/
public void testObjectResultType() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
// Load an employee into the cache.
Query query = em.createQuery(em.getCriteriaBuilder().createQuery(Employee.class));
List result = query.getResultList();
Employee employee = (Employee)result.get(0);
CriteriaBuilder qb = em.getCriteriaBuilder();
// Test multi object, as an array.
CriteriaQuery<?> cq = qb.createQuery(Object[].class);
Root<Employee> from = cq.from(Employee.class);
cq.multiselect(from, from.get("address"), from.get("id"));
Parameter<String> firstNameParam = qb.parameter(from.<String>get("firstName").getModel().getBindableJavaType(), "firstName");
cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")),qb.equal(from.get("firstName"), firstNameParam)));
query = em.createQuery(cq);
query.setParameter("id", employee.getId());
query.setParameter(firstNameParam, employee.getFirstName());
Object[] arrayResult = (Object[])query.getSingleResult();
if ((arrayResult.length != 3) && (arrayResult[0] != employee) || (arrayResult[1] != employee.getAddress()) || (!arrayResult[2].equals(employee.getId()))) {
fail("Array result not correct: " + arrayResult);
}
List listResult = query.getResultList();
arrayResult = (Object[])listResult.get(0);
if ((arrayResult.length != 3) || (arrayResult[0] != employee) || (arrayResult[1] != employee.getAddress()) || (!arrayResult[2].equals(employee.getId()))) {
fail("Array result not correct: " + arrayResult);
}
// Test single object, as an array.
cq = qb.createQuery(Object[].class);
from = cq.from(Employee.class);
cq.multiselect(from.get("id"));
cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")), (qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName")))));
query = em.createQuery(cq);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Array);
query.setParameter("id", employee.getId());
query.setParameter("firstName", employee.getFirstName());
arrayResult = (Object[])query.getSingleResult();
if ((arrayResult.length != 1) || (!arrayResult[0].equals(employee.getId()))) {
fail("Array result not correct: " + arrayResult);
}
listResult = query.getResultList();
arrayResult = (Object[])listResult.get(0);
if ((arrayResult.length != 1) || (!arrayResult[0].equals(employee.getId()))) {
fail("Array result not correct: " + arrayResult);
}
// Test multi object, as a Map.
cq = qb.createQuery(Object[].class);
from = cq.from(Employee.class);
cq.multiselect(from.alias("employee"), from.get("address").alias("address"), from.get("id").alias("id"));
cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")), qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName"))));
query = em.createQuery(cq);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Map);
query.setParameter("id", employee.getId());
query.setParameter("firstName", employee.getFirstName());
Map mapResult = (Map)query.getSingleResult();
if ((mapResult.size() != 3) ||(mapResult.get("employee") != employee) || (mapResult.get("address") != employee.getAddress()) || (!mapResult.get("id").equals(employee.getId()))) {
fail("Map result not correct: " + mapResult);
}
listResult = query.getResultList();
mapResult = (Map)listResult.get(0);
if ((mapResult.size() != 3) ||(mapResult.get("employee") != employee) || (mapResult.get("address") != employee.getAddress()) || (!mapResult.get("id").equals(employee.getId()))) {
fail("Map result not correct: " + mapResult);
}
// Test single object, as a Map.
cq = qb.createQuery(Object[].class);
from = cq.from(Employee.class);
cq.multiselect(from.get("id").alias("id"));
cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")), qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName"))));
query = em.createQuery(cq);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Map);
query.setParameter("id", employee.getId());
query.setParameter("firstName", employee.getFirstName());
mapResult = (Map)query.getSingleResult();
if ((mapResult.size() != 1) || (!mapResult.get("id").equals(employee.getId()))) {
fail("Map result not correct: " + mapResult);
}
listResult = query.getResultList();
mapResult = (Map)listResult.get(0);
if ((mapResult.size() != 1) || (!mapResult.get("id").equals(employee.getId()))) {
fail("Map result not correct: " + mapResult);
}
// Test single object, as an array.
cq = qb.createQuery(Employee.class);
from = cq.from(Employee.class);
cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")), qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName"))));
query = em.createQuery(cq);
query.setHint(QueryHints.QUERY_TYPE, QueryType.Report);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Array);
query.setParameter("id", employee.getId());
query.setParameter("firstName", employee.getFirstName());
arrayResult = (Object[])query.getSingleResult();
if (arrayResult[0] != employee) {
fail("Array result not correct: " + arrayResult);
}
// Test single object, as value.
cq = qb.createQuery(Object[].class);
from = cq.from(Employee.class);
cq.multiselect(from.get("id"));
cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")), qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName"))));
query = em.createQuery(cq);
query.setParameter("id", employee.getId());
query.setParameter("firstName", employee.getFirstName());
Object valueResult = query.getSingleResult();
if (! valueResult.equals(employee.getId())) {
fail("Value result not correct: " + valueResult);
}
listResult = query.getResultList();
valueResult = listResult.get(0);
if (! valueResult.equals(employee.getId())) {
fail("Value result not correct: " + valueResult);
}
// Test multi object, as value.
cq = qb.createQuery(Object[].class);
from = cq.from(Employee.class);
cq.multiselect(from.get("id"), from.get("firstName"));
cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")), qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName"))));
query = em.createQuery(cq);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Value);
query.setParameter("id", employee.getId());
query.setParameter("firstName", employee.getFirstName());
valueResult = query.getSingleResult();
if (! valueResult.equals(employee.getId())) {
fail("Value result not correct: " + valueResult);
}
// Test single object, as attribute.
cq = qb.createQuery(Object[].class);
from = cq.from(Employee.class);
cq.multiselect(from.get("id"));
cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")), qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName"))));
query = em.createQuery(cq);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Attribute);
query.setParameter("id", employee.getId());
query.setParameter("firstName", employee.getFirstName());
valueResult = query.getSingleResult();
if (! valueResult.equals(employee.getId())) {
fail("Value result not correct: " + valueResult);
}
listResult = query.getResultList();
valueResult = listResult.get(0);
if (! valueResult.equals(employee.getId())) {
fail("Value result not correct: " + valueResult);
}
} finally {
rollbackTransaction(em);
}
}
/**
* Test that a cache hit will occur on a primary key query.
*/
public void testQueryExactPrimaryKeyCacheHits() {
EntityManager em = createEntityManager();
beginTransaction(em);
QuerySQLTracker counter = null;
try {
// Load an employee into the cache.
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery cq = qb.createQuery(Employee.class);
Query query = em.createQuery(cq);
List result = query.getResultList();
Employee employee = (Employee)result.get(0);
// Count SQL.
counter = new QuerySQLTracker(getServerSession());
// Query by primary key.
cq = qb.createQuery(Employee.class);
Root from = cq.from(Employee.class);
cq.where(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")));
query = em.createQuery(cq);
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.CheckCacheByExactPrimaryKey);
query.setParameter("id", employee.getId());
Employee queryResult = (Employee)query.getSingleResult();
if (queryResult != employee) {
fail("Employees are not equal: " + employee + ", " + queryResult);
}
if (counter.getSqlStatements().size() > 0) {
fail("Cache hit do not occur: " + counter.getSqlStatements());
}
} finally {
rollbackTransaction(em);
if (counter != null) {
counter.remove();
}
}
}
public void testQueryHintFetch(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
CriteriaQuery<Employee> cq = em.getCriteriaBuilder().createQuery(Employee.class);
CriteriaBuilder qb = em.getCriteriaBuilder();
Root<Employee> root = cq.from(em.getMetamodel().entity(Employee.class));
cq.where(qb.equal(root.get("firstName"), qb.literal("Bob")));
TypedQuery<Employee> tq = em.createQuery(cq);
tq.setHint(QueryHints.FETCH, "e.projects");
List<Employee> result = tq.getResultList();
assertFalse("No Employees were returned", result.isEmpty());
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
ObjectOutputStream stream = new ObjectOutputStream(byteStream);
stream.writeObject(result.get(0));
stream.flush();
byte arr[] = byteStream.toByteArray();
ByteArrayInputStream inByteStream = new ByteArrayInputStream(arr);
ObjectInputStream inObjStream = new ObjectInputStream(inByteStream);
Employee emp = (Employee) inObjStream.readObject();
assertTrue("Did not return Employee", emp.getClass().equals(Employee.class));
assertTrue("Employee had wrong firstname", emp.getFirstName().equalsIgnoreCase("bob"));
emp.getProjects().size(); //may cause exception
} catch (IOException e) {
fail("Failed during serialization");
} catch (ClassNotFoundException e) {
fail("Failed during serialization");
}
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testProd(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
// em.createQuery("Select size(e.responsibilities) from Employee e").getResultList();
CriteriaBuilder qbuilder = em.getCriteriaBuilder();
CriteriaQuery<BigInteger> cquery = qbuilder.createQuery(BigInteger.class);
Root<Employee> customer = cquery.from(Employee.class);
cquery.select(qbuilder.toBigInteger(qbuilder.prod(qbuilder.literal(BigInteger.valueOf(5)),customer.<Integer>get("salary"))));
TypedQuery<BigInteger> tquery = em.createQuery(cquery);
List<BigInteger> result = tquery.getResultList();
for(BigInteger value : result){
assertTrue("Incorrect arithmatic returned ", value.mod(BigInteger.valueOf(5)).equals(BigInteger.valueOf(0)));
}
// No assert as version is not actually a mapped field in dealer.
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
/**
* Test that a cache hit will occur on a query.
*/
public void testQueryCacheFirstCacheHits() {
EntityManager em = createEntityManager();
beginTransaction(em);
QuerySQLTracker counter = null;
try {
// Load an employee into the cache.
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery cq = qb.createQuery(Employee.class);
Query query = em.createQuery(cq);
List result = query.getResultList();
Employee employee = (Employee)result.get(result.size() - 1);
// Count SQL.
counter = new QuerySQLTracker(getServerSession());
// Query by primary key.
cq = qb.createQuery(Employee.class);
Root from = cq.from(Employee.class);
cq.where(qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName")));
query = em.createQuery(cq);
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.CheckCacheThenDatabase);
query.setParameter("firstName", employee.getFirstName());
Employee queryResult = (Employee)query.getSingleResult();
if (!queryResult.getFirstName().equals(employee.getFirstName())) {
fail("Employees are not equal: " + employee + ", " + queryResult);
}
if (counter.getSqlStatements().size() > 0) {
fail("Cache hit do not occur: " + counter.getSqlStatements());
}
} finally {
rollbackTransaction(em);
if (counter != null) {
counter.remove();
}
}
}
/**
* Test that a cache hit will occur on a query.
*/
public void testQueryCacheOnlyCacheHits() {
EntityManager em = createEntityManager();
beginTransaction(em);
QuerySQLTracker counter = null;
try {
// Load an employee into the cache.
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery cq = qb.createQuery(Employee.class);
Query query = em.createQuery(cq);
List result = query.getResultList();
Employee employee = (Employee)result.get(result.size() - 1);
// Count SQL.
counter = new QuerySQLTracker(getServerSession());
// Query by primary key.
cq = qb.createQuery(Employee.class);
Root from = cq.from(Employee.class);
cq.where(qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName")));
query = em.createQuery(cq);
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.CheckCacheOnly);
query.setParameter("firstName", employee.getFirstName());
// Test that list works as well.
query.getResultList();
if (counter.getSqlStatements().size() > 0) {
fail("Cache hit do not occur: " + counter.getSqlStatements());
}
} finally {
rollbackTransaction(em);
if (counter != null) {
counter.remove();
}
}
}
/**
* Test that a cache hit will occur on a query when the object is not in the unit of work/em.
*/
public void testQueryCacheOnlyCacheHitsOnSession() {
EntityManager em = createEntityManager();
beginTransaction(em);
QuerySQLTracker counter = null;
try {
// Load an employee into the cache.
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery cq = qb.createQuery(Employee.class);
Query query = em.createQuery(cq);
List result = query.getResultList();
Employee employee = (Employee)result.get(result.size() - 1);
// Count SQL.
counter = new QuerySQLTracker(getServerSession());
// Query by primary key.
rollbackTransaction(em);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
cq = qb.createQuery(Employee.class);
Root from = cq.from(Employee.class);
cq.where(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")));
query = em.createQuery(cq);
query.setHint(QueryHints.QUERY_TYPE, QueryType.ReadObject);
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.CheckCacheOnly);
query.setParameter("id", employee.getId());
if (query.getSingleResult() == null) {
fail("Query did not check session cache.");
}
if (counter.getSqlStatements().size() > 0) {
fail("Cache hit do not occur: " + counter.getSqlStatements());
}
rollbackTransaction(em);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
cq = qb.createQuery(Employee.class);
from = cq.from(Employee.class);
cq.where(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")));
query = em.createQuery(cq);
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.CheckCacheOnly);
query.setParameter("id", employee.getId());
if (query.getResultList().size() != 1) {
fail("Query did not check session cache.");
}
if (counter.getSqlStatements().size() > 0) {
fail("Cache hit do not occur: " + counter.getSqlStatements());
}
} finally {
if (counter != null) {
counter.remove();
}
rollbackTransaction(em);
closeEntityManager(em);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.