diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/component/application-registry/src/main/java/org/exoplatform/application/registry/impl/ApplicationRegistryServiceImpl.java b/component/application-registry/src/main/java/org/exoplatform/application/registry/impl/ApplicationRegistryServiceImpl.java index e6731e02a..f0d09836d 100644 --- a/component/application-registry/src/main/java/org/exoplatform/application/registry/impl/ApplicationRegistryServiceImpl.java +++ b/component/application-registry/src/main/java/org/exoplatform/application/registry/impl/ApplicationRegistryServiceImpl.java @@ -1,665 +1,665 @@ /** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.application.registry.impl; import org.chromattic.api.ChromatticSession; import org.exoplatform.application.gadget.Gadget; import org.exoplatform.application.gadget.GadgetRegistryService; import org.exoplatform.application.registry.Application; import org.exoplatform.application.registry.ApplicationCategoriesPlugins; import org.exoplatform.application.registry.ApplicationCategory; import org.exoplatform.application.registry.ApplicationRegistryService; import org.exoplatform.commons.chromattic.ChromatticLifeCycle; import org.exoplatform.commons.chromattic.ChromatticManager; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.component.ComponentPlugin; import org.exoplatform.container.component.RequestLifeCycle; import org.exoplatform.portal.config.UserACL; import org.exoplatform.portal.config.model.ApplicationType; import org.exoplatform.portal.pom.config.POMSessionManager; import org.exoplatform.portal.pom.spi.portlet.Portlet; import org.exoplatform.portal.pom.spi.wsrp.WSRP; import org.gatein.common.i18n.LocalizedString; import org.gatein.common.logging.Logger; import org.gatein.common.logging.LoggerFactory; import org.gatein.mop.api.content.ContentType; import org.gatein.mop.api.content.Customization; import org.gatein.pc.api.PortletInvoker; import org.gatein.pc.api.info.MetaInfo; import org.gatein.pc.api.info.PortletInfo; import org.picocontainer.Startable; import java.util.*; /** * The fundamental reason that motives to use tasks is because of the JMX access that does not * setup a context and therefore the task either reuse the existing context setup by the portal * or create a temporary context when accessed by JMX. * * @author <a href="mailto:[email protected]">Julien Viet</a> * @version $Revision$ */ public class ApplicationRegistryServiceImpl implements ApplicationRegistryService, Startable { /** . */ private static final String INTERNAL_PORTLET_TAG = "gatein_internal"; /** . */ private static final String REMOTE_CATEGORY_NAME = "remote"; /** . */ private List<ApplicationCategoriesPlugins> plugins; /** . */ private final ChromatticManager manager; /** . */ private final ChromatticLifeCycle lifeCycle; /** . */ private final Logger log = LoggerFactory.getLogger(ApplicationRegistryServiceImpl.class); /** . */ final POMSessionManager mopManager; private static final String REMOTE_DISPLAY_NAME_SUFFIX = " (remote)"; public ApplicationRegistryServiceImpl(ChromatticManager manager, POMSessionManager mopManager) { ApplicationRegistryChromatticLifeCycle lifeCycle = (ApplicationRegistryChromatticLifeCycle)manager.getLifeCycle("app"); lifeCycle.registry = this; // this.manager = manager; this.lifeCycle = lifeCycle; this.mopManager = mopManager; } public ContentRegistry getContentRegistry() { ChromatticSession session = lifeCycle.getChromattic().openSession(); ContentRegistry registry = session.findByPath(ContentRegistry.class, "app:applications"); if (registry == null) { registry = session.insert(ContentRegistry.class, "app:applications"); } return registry; } public void initListener(ComponentPlugin com) throws Exception { if (com instanceof ApplicationCategoriesPlugins) { if (plugins == null) { plugins = new ArrayList<ApplicationCategoriesPlugins>(); } plugins.add((ApplicationCategoriesPlugins)com); } } public List<ApplicationCategory> getApplicationCategories( final Comparator<ApplicationCategory> sortComparator, String accessUser, final ApplicationType<?>... appTypes) throws Exception { final List<ApplicationCategory> categories = new ArrayList<ApplicationCategory>(); // ContentRegistry registry = getContentRegistry(); // for (CategoryDefinition categoryDef : registry.getCategoryList()) { ApplicationCategory category = load(categoryDef, appTypes); categories.add(category); } // if (sortComparator != null) { Collections.sort(categories, sortComparator); } // return categories; } public List<ApplicationCategory> getApplicationCategories(String accessUser, ApplicationType<?>... appTypes) throws Exception { return getApplicationCategories(null, accessUser, appTypes); } public List<ApplicationCategory> getApplicationCategories() throws Exception { return getApplicationCategories(null); } public List<ApplicationCategory> getApplicationCategories(Comparator<ApplicationCategory> sortComparator) throws Exception { return getApplicationCategories(sortComparator, null); } public ApplicationCategory getApplicationCategory(final String name) throws Exception { ContentRegistry registry = getContentRegistry(); // CategoryDefinition categoryDef = registry.getCategory(name); if (categoryDef != null) { ApplicationCategory applicationCategory = load(categoryDef); return applicationCategory; } // return null; } public void save(final ApplicationCategory category) throws Exception { ContentRegistry registry = getContentRegistry(); // String categoryName = category.getName(); // CategoryDefinition categoryDef = registry.getCategory(categoryName); if (categoryDef == null) { categoryDef = registry.createCategory(categoryName); } // categoryDef.setDisplayName(category.getDisplayName()); categoryDef.setCreationDate(category.getCreatedDate()); categoryDef.setLastModificationDate(category.getModifiedDate()); categoryDef.setDescription(category.getDescription()); categoryDef.setAccessPermissions(category.getAccessPermissions()); } public void remove(final ApplicationCategory category) throws Exception { ContentRegistry registry = getContentRegistry(); registry.getCategoryMap().remove(category.getName()); } public List<Application> getApplications(ApplicationCategory category, ApplicationType<?>... appTypes) throws Exception { return getApplications(category, null, appTypes); } public List<Application> getApplications( final ApplicationCategory category, final Comparator<Application> sortComparator, final ApplicationType<?>... appTypes) throws Exception { ContentRegistry registry = getContentRegistry(); // CategoryDefinition categoryDef = registry.getCategory(category.getName()); List<Application> applications = load(categoryDef, appTypes).getApplications(); // if (sortComparator != null) { Collections.sort(applications, sortComparator); } // return applications; } public List<Application> getAllApplications() throws Exception { List<Application> applications = new ArrayList<Application>(); List<ApplicationCategory> categories = getApplicationCategories(); for (ApplicationCategory category : categories) { applications.addAll(getApplications(category)); } return applications; } public Application getApplication(String id) throws Exception { String[] fragments = id.split("/"); if (fragments.length < 2) { throw new Exception("Invalid Application Id: [" + id + "]"); } return getApplication(fragments[0], fragments[1]); } public Application getApplication(final String category, final String name) throws Exception { ContentRegistry registry = getContentRegistry(); // CategoryDefinition categoryDef = registry.getCategory(category); if (categoryDef != null) { ContentDefinition contentDef = categoryDef.getContentMap().get(name); if (contentDef != null) { return load(contentDef); } } // return null; } public void save(final ApplicationCategory category, final Application application) throws Exception { ContentRegistry registry = getContentRegistry(); // String categoryName = category.getName(); CategoryDefinition categoryDef = registry.getCategory(categoryName); if (categoryDef == null) { categoryDef = registry.createCategory(categoryName); save(category, categoryDef); } // ContentDefinition contentDef = null; CategoryDefinition applicationCategoryDef = registry.getCategory(application.getCategoryName()); String applicationName = application.getApplicationName(); if (applicationCategoryDef != null) { contentDef = applicationCategoryDef.getContentMap().get(applicationName); } if (contentDef == null) { String contentId = application.getContentId(); ContentType<?> contentType = application.getType().getContentType(); String definitionName = application.getApplicationName(); contentDef = categoryDef.createContent(definitionName, contentType, contentId); } else { // A JCR move actually categoryDef.getContentList().add(contentDef); } // Update state save(application, contentDef); } public void update(final Application application) throws Exception { ContentRegistry registry = getContentRegistry(); // String categoryName = application.getCategoryName(); CategoryDefinition categoryDef = registry.getCategory(categoryName); if (categoryDef == null) { throw new IllegalStateException(); } // ContentDefinition contentDef = categoryDef.getContentMap().get(application.getApplicationName()); if (contentDef == null) { throw new IllegalStateException(); } // Update state save(application, contentDef); } public void remove(final Application app) throws Exception { if (app == null) { throw new NullPointerException(); } // ContentRegistry registry = getContentRegistry(); // String categoryName = app.getCategoryName(); CategoryDefinition categoryDef = registry.getCategory(categoryName); // if (categoryDef != null) { String contentName = app.getApplicationName(); categoryDef.getContentMap().remove(contentName); } } public void importExoGadgets() throws Exception { ContentRegistry registry = getContentRegistry(); // ExoContainer container = ExoContainerContext.getCurrentContainer(); GadgetRegistryService gadgetService = (GadgetRegistryService)container.getComponentInstanceOfType(GadgetRegistryService.class); List<Gadget> eXoGadgets = gadgetService.getAllGadgets(); // if (eXoGadgets != null) { ArrayList<String> permissions = new ArrayList<String>(); permissions.add(UserACL.EVERYONE); String categoryName = "Gadgets"; // CategoryDefinition category = registry.getCategory(categoryName); if (category == null) { category = registry.createCategory(categoryName); category.setDisplayName(categoryName); category.setDescription(categoryName); category.setAccessPermissions(permissions); } // for (Gadget ele : eXoGadgets) { ContentDefinition app = category.getContentMap().get(ele.getName()); if (app == null) { app = category.createContent(ele.getName(), org.exoplatform.portal.pom.spi.gadget.Gadget.CONTENT_TYPE, ele.getName()); app.setDisplayName(ele.getTitle()); app.setDescription(ele.getDescription()); app.setAccessPermissions(permissions); } } } } public void importAllPortlets() throws Exception { ContentRegistry registry = getContentRegistry(); // log.info("About to import portlets in application registry"); // ExoContainer manager = ExoContainerContext.getCurrentContainer(); PortletInvoker portletInvoker = (PortletInvoker)manager.getComponentInstance(PortletInvoker.class); Set<org.gatein.pc.api.Portlet> portlets = portletInvoker.getPortlets(); // portlet: for (org.gatein.pc.api.Portlet portlet : portlets) { PortletInfo info = portlet.getInfo(); String portletApplicationName = info.getApplicationName(); String portletName = info.getName(); // Need to sanitize portlet and application names in case they contain characters that would // cause an improper Application name portletApplicationName = portletApplicationName.replace('/', '_'); portletName = portletName.replace('/', '_'); LocalizedString keywordsLS = info.getMeta().getMetaValue(MetaInfo.KEYWORDS); // Set<String> categoryNames = new HashSet<String>(); // Process keywords if (keywordsLS != null) { String keywords = keywordsLS.getDefaultString(); if (keywords != null && keywords.length() != 0) { for (String categoryName : keywords.split(",")) { // Trim name categoryName = categoryName.trim(); if (INTERNAL_PORTLET_TAG.equalsIgnoreCase(categoryName)) { log.debug("Skipping portlet (" + portletApplicationName + "," + portletName + ") + tagged as internal"); continue portlet; } else { categoryNames.add(categoryName); } } } } // If no keywords, use the portlet application name if (categoryNames.isEmpty()) { categoryNames.add(portletApplicationName.trim()); } // Additionally categorise the portlet as remote boolean remote = portlet.isRemote(); if (remote) { categoryNames.add(REMOTE_CATEGORY_NAME); } // log.info("Importing portlet (" + portletApplicationName + "," + portletName + ") in categories " + categoryNames); - // Process categoriy names + // Process category names for (String categoryName : categoryNames) { CategoryDefinition category = registry.getCategory(categoryName); // if (category == null) { category = registry.createCategory(categoryName); category.setDisplayName(categoryName); } // ContentDefinition app = category.getContentMap().get(portletName); if (app == null) { MetaInfo metaInfo = portlet.getInfo().getMeta(); LocalizedString descriptionLS = metaInfo.getMetaValue(MetaInfo.DESCRIPTION); LocalizedString displayNameLS = metaInfo.getMetaValue(MetaInfo.DISPLAY_NAME); String displayName = getLocalizedStringValue(displayNameLS, portletName); ContentType<?> contentType; String contentId; if (remote) { contentType = WSRP.CONTENT_TYPE; contentId = portlet.getContext().getId(); displayName += REMOTE_DISPLAY_NAME_SUFFIX; // add remote to display name to make it more obvious that the portlet is remote } else { contentType = Portlet.CONTENT_TYPE; contentId = info.getApplicationName() + "/" + info.getName(); } // app = category.createContent(portletName, contentType, contentId); app.setDisplayName(displayName); app.setDescription(getLocalizedStringValue(descriptionLS, portletName)); } } } } private boolean isApplicationType(Application app, ApplicationType<?>... appTypes) { if (appTypes == null || appTypes.length == 0) { return true; } for (ApplicationType<?> appType : appTypes) { if (appType.equals(app.getType())) { return true; } } return false; } private void save(ApplicationCategory category, CategoryDefinition categoryDef) { categoryDef.setDisplayName(category.getDisplayName()); categoryDef.setDescription(category.getDescription()); categoryDef.setAccessPermissions(category.getAccessPermissions()); categoryDef.setCreationDate(category.getCreatedDate()); categoryDef.setLastModificationDate(category.getModifiedDate()); } private ApplicationCategory load(CategoryDefinition categoryDef, ApplicationType<?>... appTypes) { ApplicationCategory category = new ApplicationCategory(); // category.setName(categoryDef.getName()); category.setDisplayName(categoryDef.getDisplayName()); category.setDescription(categoryDef.getDescription()); category.setAccessPermissions(new ArrayList<String>(categoryDef.getAccessPermissions())); category.setCreatedDate(categoryDef.getCreationDate()); category.setModifiedDate(categoryDef.getLastModificationDate()); // for (ContentDefinition contentDef : categoryDef.getContentList()) { Application application = load(contentDef); if (isApplicationType(application, appTypes)) { category.getApplications().add(application); } } // return category; } private void save(Application application, ContentDefinition contentDef) { contentDef.setDisplayName(application.getDisplayName()); contentDef.setDescription(application.getDescription()); contentDef.setAccessPermissions(application.getAccessPermissions()); contentDef.setCreationDate(application.getCreatedDate()); contentDef.setLastModificationDate(application.getModifiedDate()); } private Application load(ContentDefinition contentDef) { Customization customization = contentDef.getCustomization(); // ContentType<?> contentType = customization.getType(); ApplicationType<?> applicationType = ApplicationType.getType(contentType); // Application application = new Application(); application.setId(contentDef.getCategory().getName() + "/" + contentDef.getName()); application.setCategoryName(contentDef.getCategory().getName()); application.setType(applicationType); application.setApplicationName(contentDef.getName()); application.setIconURL(getApplicationIconURL(contentDef)); application.setDisplayName(contentDef.getDisplayName()); application.setDescription(contentDef.getDescription()); application.setAccessPermissions(new ArrayList<String>(contentDef.getAccessPermissions())); application.setCreatedDate(contentDef.getCreationDate()); application.setModifiedDate(contentDef.getLastModificationDate()); application.setStorageId(customization.getId()); application.setContentId(customization.getContentId()); return application; } private String getLocalizedStringValue(LocalizedString localizedString, String portletName) { if (localizedString == null || localizedString.getDefaultString() == null) { return portletName; } else { return localizedString.getDefaultString(); } } private static String getApplicationIconURL(ContentDefinition contentDef) { Customization customization = contentDef.getCustomization(); if (customization != null) { ContentType type = customization.getType(); String contentId = customization.getContentId(); if (type == Portlet.CONTENT_TYPE) { String[] chunks = contentId.split("/"); if (chunks.length == 2) { return "/" + chunks[0] + "/skin/DefaultSkin/portletIcons/" + chunks[1] + ".png"; } } else if (type == WSRP.CONTENT_TYPE) { return "/eXoResources/skin/sharedImages/Icon80x80/DefaultPortlet.png"; } else if (type == org.exoplatform.portal.pom.spi.gadget.Gadget.CONTENT_TYPE) { return "/" + "eXoGadgets" + "/skin/DefaultSkin/portletIcons/" + contentId + ".png"; } } // return null; } public void start() { if (plugins != null) { RequestLifeCycle.begin(manager); boolean save = false; try { if (this.getApplicationCategories().size() < 1) { for (ApplicationCategoriesPlugins plugin : plugins) { plugin.run(); } } save = true; } catch (Exception e) { // log.error(e); e.printStackTrace(); } finally { // lifeCycle.closeContext(context, true); manager.getSynchronization().setSaveOnClose(save); RequestLifeCycle.end(); } } } public void stop() { } }
true
true
public void importAllPortlets() throws Exception { ContentRegistry registry = getContentRegistry(); // log.info("About to import portlets in application registry"); // ExoContainer manager = ExoContainerContext.getCurrentContainer(); PortletInvoker portletInvoker = (PortletInvoker)manager.getComponentInstance(PortletInvoker.class); Set<org.gatein.pc.api.Portlet> portlets = portletInvoker.getPortlets(); // portlet: for (org.gatein.pc.api.Portlet portlet : portlets) { PortletInfo info = portlet.getInfo(); String portletApplicationName = info.getApplicationName(); String portletName = info.getName(); // Need to sanitize portlet and application names in case they contain characters that would // cause an improper Application name portletApplicationName = portletApplicationName.replace('/', '_'); portletName = portletName.replace('/', '_'); LocalizedString keywordsLS = info.getMeta().getMetaValue(MetaInfo.KEYWORDS); // Set<String> categoryNames = new HashSet<String>(); // Process keywords if (keywordsLS != null) { String keywords = keywordsLS.getDefaultString(); if (keywords != null && keywords.length() != 0) { for (String categoryName : keywords.split(",")) { // Trim name categoryName = categoryName.trim(); if (INTERNAL_PORTLET_TAG.equalsIgnoreCase(categoryName)) { log.debug("Skipping portlet (" + portletApplicationName + "," + portletName + ") + tagged as internal"); continue portlet; } else { categoryNames.add(categoryName); } } } } // If no keywords, use the portlet application name if (categoryNames.isEmpty()) { categoryNames.add(portletApplicationName.trim()); } // Additionally categorise the portlet as remote boolean remote = portlet.isRemote(); if (remote) { categoryNames.add(REMOTE_CATEGORY_NAME); } // log.info("Importing portlet (" + portletApplicationName + "," + portletName + ") in categories " + categoryNames); // Process categoriy names for (String categoryName : categoryNames) { CategoryDefinition category = registry.getCategory(categoryName); // if (category == null) { category = registry.createCategory(categoryName); category.setDisplayName(categoryName); } // ContentDefinition app = category.getContentMap().get(portletName); if (app == null) { MetaInfo metaInfo = portlet.getInfo().getMeta(); LocalizedString descriptionLS = metaInfo.getMetaValue(MetaInfo.DESCRIPTION); LocalizedString displayNameLS = metaInfo.getMetaValue(MetaInfo.DISPLAY_NAME); String displayName = getLocalizedStringValue(displayNameLS, portletName); ContentType<?> contentType; String contentId; if (remote) { contentType = WSRP.CONTENT_TYPE; contentId = portlet.getContext().getId(); displayName += REMOTE_DISPLAY_NAME_SUFFIX; // add remote to display name to make it more obvious that the portlet is remote } else { contentType = Portlet.CONTENT_TYPE; contentId = info.getApplicationName() + "/" + info.getName(); } // app = category.createContent(portletName, contentType, contentId); app.setDisplayName(displayName); app.setDescription(getLocalizedStringValue(descriptionLS, portletName)); } } } }
public void importAllPortlets() throws Exception { ContentRegistry registry = getContentRegistry(); // log.info("About to import portlets in application registry"); // ExoContainer manager = ExoContainerContext.getCurrentContainer(); PortletInvoker portletInvoker = (PortletInvoker)manager.getComponentInstance(PortletInvoker.class); Set<org.gatein.pc.api.Portlet> portlets = portletInvoker.getPortlets(); // portlet: for (org.gatein.pc.api.Portlet portlet : portlets) { PortletInfo info = portlet.getInfo(); String portletApplicationName = info.getApplicationName(); String portletName = info.getName(); // Need to sanitize portlet and application names in case they contain characters that would // cause an improper Application name portletApplicationName = portletApplicationName.replace('/', '_'); portletName = portletName.replace('/', '_'); LocalizedString keywordsLS = info.getMeta().getMetaValue(MetaInfo.KEYWORDS); // Set<String> categoryNames = new HashSet<String>(); // Process keywords if (keywordsLS != null) { String keywords = keywordsLS.getDefaultString(); if (keywords != null && keywords.length() != 0) { for (String categoryName : keywords.split(",")) { // Trim name categoryName = categoryName.trim(); if (INTERNAL_PORTLET_TAG.equalsIgnoreCase(categoryName)) { log.debug("Skipping portlet (" + portletApplicationName + "," + portletName + ") + tagged as internal"); continue portlet; } else { categoryNames.add(categoryName); } } } } // If no keywords, use the portlet application name if (categoryNames.isEmpty()) { categoryNames.add(portletApplicationName.trim()); } // Additionally categorise the portlet as remote boolean remote = portlet.isRemote(); if (remote) { categoryNames.add(REMOTE_CATEGORY_NAME); } // log.info("Importing portlet (" + portletApplicationName + "," + portletName + ") in categories " + categoryNames); // Process category names for (String categoryName : categoryNames) { CategoryDefinition category = registry.getCategory(categoryName); // if (category == null) { category = registry.createCategory(categoryName); category.setDisplayName(categoryName); } // ContentDefinition app = category.getContentMap().get(portletName); if (app == null) { MetaInfo metaInfo = portlet.getInfo().getMeta(); LocalizedString descriptionLS = metaInfo.getMetaValue(MetaInfo.DESCRIPTION); LocalizedString displayNameLS = metaInfo.getMetaValue(MetaInfo.DISPLAY_NAME); String displayName = getLocalizedStringValue(displayNameLS, portletName); ContentType<?> contentType; String contentId; if (remote) { contentType = WSRP.CONTENT_TYPE; contentId = portlet.getContext().getId(); displayName += REMOTE_DISPLAY_NAME_SUFFIX; // add remote to display name to make it more obvious that the portlet is remote } else { contentType = Portlet.CONTENT_TYPE; contentId = info.getApplicationName() + "/" + info.getName(); } // app = category.createContent(portletName, contentType, contentId); app.setDisplayName(displayName); app.setDescription(getLocalizedStringValue(descriptionLS, portletName)); } } } }
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/InvocationGenerator.java b/src/main/java/com/redhat/ceylon/compiler/js/InvocationGenerator.java index a704a897..5a18ca24 100644 --- a/src/main/java/com/redhat/ceylon/compiler/js/InvocationGenerator.java +++ b/src/main/java/com/redhat/ceylon/compiler/js/InvocationGenerator.java @@ -1,506 +1,509 @@ package com.redhat.ceylon.compiler.js; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Functional; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ParameterList; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.UnionType; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Tree; /** Generates js code for invocation expression (named and positional). */ public class InvocationGenerator { private final GenerateJsVisitor gen; private final JsIdentifierNames names; private final RetainedVars retainedVars; InvocationGenerator(GenerateJsVisitor owner, JsIdentifierNames names, RetainedVars rv) { gen = owner; this.names = names; retainedVars = rv; } void generateInvocation(Tree.InvocationExpression that) { if (that.getNamedArgumentList()!=null) { Tree.NamedArgumentList argList = that.getNamedArgumentList(); if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.MemberOrTypeExpression && ((Tree.MemberOrTypeExpression)that.getPrimary()).getDeclaration() == null) { final String fname = names.createTempVariable(); gen.out("(", fname, "="); //Call a native js constructor passing a native js object as parameter that.getPrimary().visit(gen); gen.out(",", fname, ".$$===undefined?new ", fname, "("); nativeObject(argList); gen.out("):", fname, "("); nativeObject(argList); gen.out("))"); } else { gen.out("("); Map<String, String> argVarNames = defineNamedArguments(that.getPrimary(), argList); that.getPrimary().visit(gen); Tree.TypeArguments targs = that.getPrimary() instanceof Tree.BaseMemberOrTypeExpression ? ((Tree.BaseMemberOrTypeExpression)that.getPrimary()).getTypeArguments() : null; if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) { Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary(); if (mte.getDeclaration() instanceof Functional) { Functional f = (Functional) mte.getDeclaration(); applyNamedArguments(argList, f, argVarNames, gen.getSuperMemberScope(mte)!=null, targs); } } gen.out(")"); } } else { Tree.PositionalArgumentList argList = that.getPositionalArgumentList(); Tree.Primary typeArgSource = that.getPrimary(); //In nested invocation expressions, use the first invocation as source for type arguments while (typeArgSource instanceof Tree.InvocationExpression) { typeArgSource = ((Tree.InvocationExpression)typeArgSource).getPrimary(); } Tree.TypeArguments targs = typeArgSource instanceof Tree.StaticMemberOrTypeExpression ? ((Tree.StaticMemberOrTypeExpression)typeArgSource).getTypeArguments() : null; if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.BaseTypeExpression && ((Tree.BaseTypeExpression)that.getPrimary()).getDeclaration() == null) { gen.out("("); //Could be a dynamic object, or a Ceylon one //We might need to call "new" so we need to get all the args to pass directly later final List<String> argnames = generatePositionalArguments(that.getPrimary(), argList, argList.getPositionalArguments(), false, true); if (!argnames.isEmpty()) { gen.out(","); } final String fname = names.createTempVariable(); gen.out(fname,"="); that.getPrimary().visit(gen); String fuckingargs = ""; if (!argnames.isEmpty()) { fuckingargs = argnames.toString().substring(1); fuckingargs = fuckingargs.substring(0, fuckingargs.length()-1); } gen.out(",", fname, ".$$===undefined?new ", fname, "(", fuckingargs, "):", fname, "(", fuckingargs, "))"); //TODO we lose type args for now return; } else { that.getPrimary().visit(gen); if (gen.opts.isOptimize() && (gen.getSuperMemberScope(that.getPrimary()) != null)) { gen.out(".call(this"); if (!argList.getPositionalArguments().isEmpty()) { gen.out(","); } } else if (that.getPrimary().getTypeModel().getDeclaration().inherits(gen.getTypeUtils().metaClass)) { //metamodel Classes are AppliedClass$metamodel which contains "tipo", a ref to the actual class gen.out(".tipo("); } else { gen.out("("); } //Check if args have params boolean fillInParams = !argList.getPositionalArguments().isEmpty(); for (Tree.PositionalArgument arg : argList.getPositionalArguments()) { fillInParams &= arg.getParameter() == null; } if (fillInParams) { //Get the callable and try to assign params from there ProducedType callable = that.getPrimary().getTypeModel().getSupertype( gen.getTypeUtils().callable); if (callable != null) { //This is a tuple with the arguments to the callable //(can be union with empty if first param is defaulted) ProducedType callableArgs = callable.getTypeArgumentList().get(1).minus( gen.getTypeUtils().empty.getType()); //This is the type of the first argument - ProducedType argtype = callableArgs.getTypeArgumentList().get(1); + boolean isSequenced = !gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration()); + ProducedType argtype = callableArgs.getTypeArgumentList().get( + isSequenced ? 0 : 1); Parameter p = null; int c = 0; for (Tree.PositionalArgument arg : argList.getPositionalArguments()) { if (p == null) { p = new Parameter(); p.setName("arg"+c); p.setDeclaration(that.getPrimary().getTypeModel().getDeclaration()); Value v = new Value(); v.setContainer(that.getPositionalArgumentList().getScope()); v.setType(argtype); p.setModel(v); - if (callableArgs == null) { + if (callableArgs == null || isSequenced) { p.setSequenced(true); - } else { + } else if (!isSequenced) { ProducedType next = callableArgs.getTypeArgumentList().get(2); if (next.getSupertype(gen.getTypeUtils().tuple) == null) { //It's not a tuple, so no more regular parms. It can be: //empty|tuple if defaulted params //empty if no more params //sequential if sequenced param if (next.getDeclaration() instanceof UnionType) { //empty|tuple callableArgs = next.minus(gen.getTypeUtils().empty.getType()); - argtype = callableArgs.getTypeArgumentList().get(1); + isSequenced = !gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration()); + argtype = callableArgs.getTypeArgumentList().get(isSequenced ? 0 : 1); } else { //we'll bet on sequential (if it's empty we don't care anyway) argtype = next; callableArgs = null; } } else { //If it's a tuple then there are more params callableArgs = next; argtype = callableArgs.getTypeArgumentList().get(1); } } } arg.setParameter(p); c++; if (!p.isSequenced()) { p = null; } } } } generatePositionalArguments(that.getPrimary(), argList, argList.getPositionalArguments(), false, false); } if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) { if (argList.getPositionalArguments().size() > 0) { gen.out(","); } Declaration bmed = ((Tree.StaticMemberOrTypeExpression)typeArgSource).getDeclaration(); if (bmed instanceof Functional) { //If there are fewer arguments than there are parameters... if (((Functional) bmed).getParameterLists().get(0).getParameters().size() > argList.getPositionalArguments().size()) { //It could be because all args will be sequenced/defaulted... if (argList.getPositionalArguments().isEmpty()) { gen.out("undefined,"); } else { //Or because the last argument is a comprehension or a spread Tree.PositionalArgument parg = argList.getPositionalArguments().get( argList.getPositionalArguments().size()-1); if (!(parg instanceof Tree.Comprehension || parg instanceof Tree.SpreadArgument)) { gen.out("undefined,"); } } } if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) { Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments( ((Functional) bmed).getTypeParameters(), targs.getTypeModels()); if (invargs != null) { TypeUtils.printTypeArguments(typeArgSource, invargs, gen); } else { gen.out("/*TARGS != TPARAMS!!!! WTF?????*/"); } } } } gen.out(")"); } } /** Generates the code to evaluate the expressions in the named argument list and assign them * to variables, then returns a map with the parameter names and the corresponding variable names. */ Map<String, String> defineNamedArguments(Tree.Primary primary, Tree.NamedArgumentList argList) { Map<String, String> argVarNames = new HashMap<String, String>(); for (Tree.NamedArgument arg: argList.getNamedArguments()) { Parameter p = arg.getParameter(); final String paramName; if (p == null && gen.isInDynamicBlock()) { paramName = arg.getIdentifier().getText(); } else { paramName = arg.getParameter().getName(); } String varName = names.createTempVariable(paramName); argVarNames.put(paramName, varName); retainedVars.add(varName); gen.out(varName, "="); arg.visit(gen); gen.out(","); } Tree.SequencedArgument sarg = argList.getSequencedArgument(); if (sarg!=null) { String paramName = sarg.getParameter().getName(); String varName = names.createTempVariable(paramName); argVarNames.put(paramName, varName); retainedVars.add(varName); gen.out(varName, "="); generatePositionalArguments(primary, argList, sarg.getPositionalArguments(), true, false); gen.out(","); } return argVarNames; } void applyNamedArguments(Tree.NamedArgumentList argList, Functional func, Map<String, String> argVarNames, boolean superAccess, Tree.TypeArguments targs) { boolean firstList = true; for (com.redhat.ceylon.compiler.typechecker.model.ParameterList plist : func.getParameterLists()) { List<String> argNames = argList.getNamedArgumentList().getArgumentNames(); boolean first=true; if (firstList && superAccess) { gen.out(".call(this"); if (!plist.getParameters().isEmpty()) { gen.out(","); } } else { gen.out("("); } for (Parameter p : plist.getParameters()) { if (!first) gen.out(","); boolean namedArgumentGiven = argNames.contains(p.getName()); if (namedArgumentGiven) { gen.out(argVarNames.get(p.getName())); } else if (p.isSequenced()) { gen.out(GenerateJsVisitor.getClAlias(), "getEmpty()"); } else if (argList.getSequencedArgument()!=null) { String pname = argVarNames.get(p.getName()); gen.out(pname==null ? "undefined" : pname); } else if (p.isDefaulted()) { gen.out("undefined"); } else { //It's an empty Iterable gen.out(GenerateJsVisitor.getClAlias(), "getEmpty()"); } first = false; } if (targs != null && !targs.getTypeModels().isEmpty()) { Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments( func.getTypeParameters(), targs.getTypeModels()); if (!first) gen.out(","); TypeUtils.printTypeArguments(argList, invargs, gen); } gen.out(")"); firstList = false; } } /** Generate a list of PositionalArguments, optionally assigning a variable name to each one * and returning the variable names. */ List<String> generatePositionalArguments(Tree.Primary primary, Tree.ArgumentList that, List<Tree.PositionalArgument> args, final boolean forceSequenced, final boolean generateVars) { if (!args.isEmpty()) { final List<String> argvars = new ArrayList<String>(args.size()); boolean first=true; boolean opened=false; ProducedType sequencedType=null; for (Tree.PositionalArgument arg : args) { Tree.Expression expr; Parameter pd = arg.getParameter(); if (arg instanceof Tree.ListedArgument) { if (!first) gen.out(","); expr = ((Tree.ListedArgument) arg).getExpression(); ProducedType exprType = expr.getTypeModel(); boolean dyncheck = gen.isInDynamicBlock() && !TypeUtils.isUnknown(pd) && exprType.containsUnknowns(); if (forceSequenced || (pd != null && pd.isSequenced())) { if (dyncheck) { //We don't have a real type so get the one declared in the parameter exprType = pd.getType(); } if (sequencedType == null) { sequencedType=exprType; } else { ArrayList<ProducedType> cases = new ArrayList<ProducedType>(2); Util.addToUnion(cases, sequencedType); Util.addToUnion(cases, exprType); if (cases.size() > 1) { UnionType ut = new UnionType(that.getUnit()); ut.setCaseTypes(cases); sequencedType = ut.getType(); } else { sequencedType = cases.get(0); } } if (!opened) { if (generateVars) { final String argvar = names.createTempVariable(); argvars.add(argvar); gen.out(argvar, "="); } gen.out("["); } opened=true; } else if (generateVars) { final String argvar = names.createTempVariable(); argvars.add(argvar); gen.out(argvar, "="); } TypedDeclaration decl = pd == null ? null : pd.getModel(); int boxType = gen.boxUnboxStart(expr.getTerm(), decl); if (dyncheck) { TypeUtils.generateDynamicCheck(((Tree.ListedArgument) arg).getExpression(), pd.getType(), gen); } else { arg.visit(gen); } if (boxType == 4) { gen.out(","); //Add parameters describeMethodParameters(expr.getTerm()); gen.out(","); TypeUtils.printTypeArguments(arg, arg.getTypeModel().getTypeArguments(), gen); } gen.boxUnboxEnd(boxType); } else if (arg instanceof Tree.SpreadArgument || arg instanceof Tree.Comprehension) { if (arg instanceof Tree.SpreadArgument) { expr = ((Tree.SpreadArgument) arg).getExpression(); } else { expr = null; } if (opened) { gen.closeSequenceWithReifiedType(that, gen.getTypeUtils().wrapAsIterableArguments(sequencedType)); gen.out(".chain("); sequencedType=null; } else if (!first) { gen.out(","); } if (arg instanceof Tree.SpreadArgument) { TypedDeclaration td = pd == null ? null : pd.getModel(); int boxType = gen.boxUnboxStart(expr.getTerm(), td); if (boxType == 4) { arg.visit(gen); gen.out(","); describeMethodParameters(expr.getTerm()); gen.out(","); TypeUtils.printTypeArguments(arg, arg.getTypeModel().getTypeArguments(), gen); } else if (pd == null) { if (gen.isInDynamicBlock() && primary instanceof Tree.MemberOrTypeExpression && ((Tree.MemberOrTypeExpression)primary).getDeclaration() == null && arg.getTypeModel() != null && arg.getTypeModel().getDeclaration().inherits((gen.getTypeUtils().tuple))) { //Spread dynamic parameter ProducedType tupleType = arg.getTypeModel(); ProducedType targ = tupleType.getTypeArgumentList().get(2); arg.visit(gen); gen.out(".get(0)"); int i = 1; while (!targ.getDeclaration().inherits(gen.getTypeUtils().empty)) { gen.out(","); arg.visit(gen); gen.out(".get("+(i++)+")"); targ = targ.getTypeArgumentList().get(2); } } else { arg.visit(gen); } } else if (pd.isSequenced()) { arg.visit(gen); } else { arg.visit(gen); gen.out(".get(0)"); //Find out if there are more params final ParameterList moreParams; if (pd.getDeclaration() instanceof Method) { moreParams = ((Method)pd.getDeclaration()).getParameterLists().get(0); } else { moreParams = ((com.redhat.ceylon.compiler.typechecker.model.Class)pd.getDeclaration()).getParameterList(); } boolean found = false; int c = 1; for (Parameter restp : moreParams.getParameters()) { if (found) { gen.out(","); arg.visit(gen); gen.out(".get(", Integer.toString(c++), ")||undefined"); } else { found = restp.equals(pd); } } } gen.boxUnboxEnd(boxType); } else { ((Tree.Comprehension)arg).visit(gen); } if (opened) { gen.out(","); if (expr == null) { //it's a comprehension TypeUtils.printTypeArguments(that, gen.getTypeUtils().wrapAsIterableArguments(arg.getTypeModel()), gen); } else { ProducedType spreadType = TypeUtils.findSupertype(gen.getTypeUtils().sequential, expr.getTypeModel()); TypeUtils.printTypeArguments(that, spreadType.getTypeArguments(), gen); } gen.out(")"); } if (arg instanceof Tree.Comprehension) { break; } } first = false; } if (sequencedType != null) { gen.closeSequenceWithReifiedType(that, gen.getTypeUtils().wrapAsIterableArguments(sequencedType)); } return argvars; } return Collections.emptyList(); } /** Generate the code to create a native js object. */ void nativeObject(Tree.NamedArgumentList argList) { if (argList.getSequencedArgument() == null) { gen.out("{"); boolean first = true; for (Tree.NamedArgument arg : argList.getNamedArguments()) { if (first) { first = false; } else { gen.out(","); } gen.out(arg.getIdentifier().getText(), ":"); arg.visit(gen); } gen.out("}"); } else { String arr = null; if (argList.getNamedArguments().size() > 0) { gen.out("function()"); gen.beginBlock(); arr = names.createTempVariable(); gen.out("var ", arr, "="); } gen.out("["); boolean first = true; for (Tree.PositionalArgument arg : argList.getSequencedArgument().getPositionalArguments()) { if (first) { first = false; } else { gen.out(","); } arg.visit(gen); } gen.out("]"); if (argList.getNamedArguments().size() > 0) { gen.endLine(true); for (Tree.NamedArgument arg : argList.getNamedArguments()) { gen.out(arr, ".", arg.getIdentifier().getText(), "="); arg.visit(gen); gen.endLine(true); } gen.out("return ", arr, ";"); gen.endBlock(); gen.out("()"); } } } private void describeMethodParameters(Tree.Term term) { Method _m = null; if (term instanceof Tree.FunctionArgument) { _m = (((Tree.FunctionArgument)term).getDeclarationModel()); } else if (term instanceof Tree.MemberOrTypeExpression) { if (((Tree.MemberOrTypeExpression)term).getDeclaration() instanceof Method) { _m = (Method)((Tree.MemberOrTypeExpression)term).getDeclaration(); } } else if (term instanceof Tree.InvocationExpression) { gen.getTypeUtils().encodeTupleAsParameterListForRuntime(term.getTypeModel(), gen); return; } else { gen.out("/*WARNING Callable EXPR of type ", term.getClass().getName(), "*/"); } if (_m == null) { gen.out("[]"); } else { TypeUtils.encodeParameterListForRuntime(term, _m.getParameterLists().get(0), gen); } } }
false
true
void generateInvocation(Tree.InvocationExpression that) { if (that.getNamedArgumentList()!=null) { Tree.NamedArgumentList argList = that.getNamedArgumentList(); if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.MemberOrTypeExpression && ((Tree.MemberOrTypeExpression)that.getPrimary()).getDeclaration() == null) { final String fname = names.createTempVariable(); gen.out("(", fname, "="); //Call a native js constructor passing a native js object as parameter that.getPrimary().visit(gen); gen.out(",", fname, ".$$===undefined?new ", fname, "("); nativeObject(argList); gen.out("):", fname, "("); nativeObject(argList); gen.out("))"); } else { gen.out("("); Map<String, String> argVarNames = defineNamedArguments(that.getPrimary(), argList); that.getPrimary().visit(gen); Tree.TypeArguments targs = that.getPrimary() instanceof Tree.BaseMemberOrTypeExpression ? ((Tree.BaseMemberOrTypeExpression)that.getPrimary()).getTypeArguments() : null; if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) { Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary(); if (mte.getDeclaration() instanceof Functional) { Functional f = (Functional) mte.getDeclaration(); applyNamedArguments(argList, f, argVarNames, gen.getSuperMemberScope(mte)!=null, targs); } } gen.out(")"); } } else { Tree.PositionalArgumentList argList = that.getPositionalArgumentList(); Tree.Primary typeArgSource = that.getPrimary(); //In nested invocation expressions, use the first invocation as source for type arguments while (typeArgSource instanceof Tree.InvocationExpression) { typeArgSource = ((Tree.InvocationExpression)typeArgSource).getPrimary(); } Tree.TypeArguments targs = typeArgSource instanceof Tree.StaticMemberOrTypeExpression ? ((Tree.StaticMemberOrTypeExpression)typeArgSource).getTypeArguments() : null; if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.BaseTypeExpression && ((Tree.BaseTypeExpression)that.getPrimary()).getDeclaration() == null) { gen.out("("); //Could be a dynamic object, or a Ceylon one //We might need to call "new" so we need to get all the args to pass directly later final List<String> argnames = generatePositionalArguments(that.getPrimary(), argList, argList.getPositionalArguments(), false, true); if (!argnames.isEmpty()) { gen.out(","); } final String fname = names.createTempVariable(); gen.out(fname,"="); that.getPrimary().visit(gen); String fuckingargs = ""; if (!argnames.isEmpty()) { fuckingargs = argnames.toString().substring(1); fuckingargs = fuckingargs.substring(0, fuckingargs.length()-1); } gen.out(",", fname, ".$$===undefined?new ", fname, "(", fuckingargs, "):", fname, "(", fuckingargs, "))"); //TODO we lose type args for now return; } else { that.getPrimary().visit(gen); if (gen.opts.isOptimize() && (gen.getSuperMemberScope(that.getPrimary()) != null)) { gen.out(".call(this"); if (!argList.getPositionalArguments().isEmpty()) { gen.out(","); } } else if (that.getPrimary().getTypeModel().getDeclaration().inherits(gen.getTypeUtils().metaClass)) { //metamodel Classes are AppliedClass$metamodel which contains "tipo", a ref to the actual class gen.out(".tipo("); } else { gen.out("("); } //Check if args have params boolean fillInParams = !argList.getPositionalArguments().isEmpty(); for (Tree.PositionalArgument arg : argList.getPositionalArguments()) { fillInParams &= arg.getParameter() == null; } if (fillInParams) { //Get the callable and try to assign params from there ProducedType callable = that.getPrimary().getTypeModel().getSupertype( gen.getTypeUtils().callable); if (callable != null) { //This is a tuple with the arguments to the callable //(can be union with empty if first param is defaulted) ProducedType callableArgs = callable.getTypeArgumentList().get(1).minus( gen.getTypeUtils().empty.getType()); //This is the type of the first argument ProducedType argtype = callableArgs.getTypeArgumentList().get(1); Parameter p = null; int c = 0; for (Tree.PositionalArgument arg : argList.getPositionalArguments()) { if (p == null) { p = new Parameter(); p.setName("arg"+c); p.setDeclaration(that.getPrimary().getTypeModel().getDeclaration()); Value v = new Value(); v.setContainer(that.getPositionalArgumentList().getScope()); v.setType(argtype); p.setModel(v); if (callableArgs == null) { p.setSequenced(true); } else { ProducedType next = callableArgs.getTypeArgumentList().get(2); if (next.getSupertype(gen.getTypeUtils().tuple) == null) { //It's not a tuple, so no more regular parms. It can be: //empty|tuple if defaulted params //empty if no more params //sequential if sequenced param if (next.getDeclaration() instanceof UnionType) { //empty|tuple callableArgs = next.minus(gen.getTypeUtils().empty.getType()); argtype = callableArgs.getTypeArgumentList().get(1); } else { //we'll bet on sequential (if it's empty we don't care anyway) argtype = next; callableArgs = null; } } else { //If it's a tuple then there are more params callableArgs = next; argtype = callableArgs.getTypeArgumentList().get(1); } } } arg.setParameter(p); c++; if (!p.isSequenced()) { p = null; } } } } generatePositionalArguments(that.getPrimary(), argList, argList.getPositionalArguments(), false, false); } if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) { if (argList.getPositionalArguments().size() > 0) { gen.out(","); } Declaration bmed = ((Tree.StaticMemberOrTypeExpression)typeArgSource).getDeclaration(); if (bmed instanceof Functional) { //If there are fewer arguments than there are parameters... if (((Functional) bmed).getParameterLists().get(0).getParameters().size() > argList.getPositionalArguments().size()) { //It could be because all args will be sequenced/defaulted... if (argList.getPositionalArguments().isEmpty()) { gen.out("undefined,"); } else { //Or because the last argument is a comprehension or a spread Tree.PositionalArgument parg = argList.getPositionalArguments().get( argList.getPositionalArguments().size()-1); if (!(parg instanceof Tree.Comprehension || parg instanceof Tree.SpreadArgument)) { gen.out("undefined,"); } } } if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) { Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments( ((Functional) bmed).getTypeParameters(), targs.getTypeModels()); if (invargs != null) { TypeUtils.printTypeArguments(typeArgSource, invargs, gen); } else { gen.out("/*TARGS != TPARAMS!!!! WTF?????*/"); } } } } gen.out(")"); } }
void generateInvocation(Tree.InvocationExpression that) { if (that.getNamedArgumentList()!=null) { Tree.NamedArgumentList argList = that.getNamedArgumentList(); if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.MemberOrTypeExpression && ((Tree.MemberOrTypeExpression)that.getPrimary()).getDeclaration() == null) { final String fname = names.createTempVariable(); gen.out("(", fname, "="); //Call a native js constructor passing a native js object as parameter that.getPrimary().visit(gen); gen.out(",", fname, ".$$===undefined?new ", fname, "("); nativeObject(argList); gen.out("):", fname, "("); nativeObject(argList); gen.out("))"); } else { gen.out("("); Map<String, String> argVarNames = defineNamedArguments(that.getPrimary(), argList); that.getPrimary().visit(gen); Tree.TypeArguments targs = that.getPrimary() instanceof Tree.BaseMemberOrTypeExpression ? ((Tree.BaseMemberOrTypeExpression)that.getPrimary()).getTypeArguments() : null; if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) { Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary(); if (mte.getDeclaration() instanceof Functional) { Functional f = (Functional) mte.getDeclaration(); applyNamedArguments(argList, f, argVarNames, gen.getSuperMemberScope(mte)!=null, targs); } } gen.out(")"); } } else { Tree.PositionalArgumentList argList = that.getPositionalArgumentList(); Tree.Primary typeArgSource = that.getPrimary(); //In nested invocation expressions, use the first invocation as source for type arguments while (typeArgSource instanceof Tree.InvocationExpression) { typeArgSource = ((Tree.InvocationExpression)typeArgSource).getPrimary(); } Tree.TypeArguments targs = typeArgSource instanceof Tree.StaticMemberOrTypeExpression ? ((Tree.StaticMemberOrTypeExpression)typeArgSource).getTypeArguments() : null; if (gen.isInDynamicBlock() && that.getPrimary() instanceof Tree.BaseTypeExpression && ((Tree.BaseTypeExpression)that.getPrimary()).getDeclaration() == null) { gen.out("("); //Could be a dynamic object, or a Ceylon one //We might need to call "new" so we need to get all the args to pass directly later final List<String> argnames = generatePositionalArguments(that.getPrimary(), argList, argList.getPositionalArguments(), false, true); if (!argnames.isEmpty()) { gen.out(","); } final String fname = names.createTempVariable(); gen.out(fname,"="); that.getPrimary().visit(gen); String fuckingargs = ""; if (!argnames.isEmpty()) { fuckingargs = argnames.toString().substring(1); fuckingargs = fuckingargs.substring(0, fuckingargs.length()-1); } gen.out(",", fname, ".$$===undefined?new ", fname, "(", fuckingargs, "):", fname, "(", fuckingargs, "))"); //TODO we lose type args for now return; } else { that.getPrimary().visit(gen); if (gen.opts.isOptimize() && (gen.getSuperMemberScope(that.getPrimary()) != null)) { gen.out(".call(this"); if (!argList.getPositionalArguments().isEmpty()) { gen.out(","); } } else if (that.getPrimary().getTypeModel().getDeclaration().inherits(gen.getTypeUtils().metaClass)) { //metamodel Classes are AppliedClass$metamodel which contains "tipo", a ref to the actual class gen.out(".tipo("); } else { gen.out("("); } //Check if args have params boolean fillInParams = !argList.getPositionalArguments().isEmpty(); for (Tree.PositionalArgument arg : argList.getPositionalArguments()) { fillInParams &= arg.getParameter() == null; } if (fillInParams) { //Get the callable and try to assign params from there ProducedType callable = that.getPrimary().getTypeModel().getSupertype( gen.getTypeUtils().callable); if (callable != null) { //This is a tuple with the arguments to the callable //(can be union with empty if first param is defaulted) ProducedType callableArgs = callable.getTypeArgumentList().get(1).minus( gen.getTypeUtils().empty.getType()); //This is the type of the first argument boolean isSequenced = !gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration()); ProducedType argtype = callableArgs.getTypeArgumentList().get( isSequenced ? 0 : 1); Parameter p = null; int c = 0; for (Tree.PositionalArgument arg : argList.getPositionalArguments()) { if (p == null) { p = new Parameter(); p.setName("arg"+c); p.setDeclaration(that.getPrimary().getTypeModel().getDeclaration()); Value v = new Value(); v.setContainer(that.getPositionalArgumentList().getScope()); v.setType(argtype); p.setModel(v); if (callableArgs == null || isSequenced) { p.setSequenced(true); } else if (!isSequenced) { ProducedType next = callableArgs.getTypeArgumentList().get(2); if (next.getSupertype(gen.getTypeUtils().tuple) == null) { //It's not a tuple, so no more regular parms. It can be: //empty|tuple if defaulted params //empty if no more params //sequential if sequenced param if (next.getDeclaration() instanceof UnionType) { //empty|tuple callableArgs = next.minus(gen.getTypeUtils().empty.getType()); isSequenced = !gen.getTypeUtils().tuple.equals(callableArgs.getDeclaration()); argtype = callableArgs.getTypeArgumentList().get(isSequenced ? 0 : 1); } else { //we'll bet on sequential (if it's empty we don't care anyway) argtype = next; callableArgs = null; } } else { //If it's a tuple then there are more params callableArgs = next; argtype = callableArgs.getTypeArgumentList().get(1); } } } arg.setParameter(p); c++; if (!p.isSequenced()) { p = null; } } } } generatePositionalArguments(that.getPrimary(), argList, argList.getPositionalArguments(), false, false); } if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) { if (argList.getPositionalArguments().size() > 0) { gen.out(","); } Declaration bmed = ((Tree.StaticMemberOrTypeExpression)typeArgSource).getDeclaration(); if (bmed instanceof Functional) { //If there are fewer arguments than there are parameters... if (((Functional) bmed).getParameterLists().get(0).getParameters().size() > argList.getPositionalArguments().size()) { //It could be because all args will be sequenced/defaulted... if (argList.getPositionalArguments().isEmpty()) { gen.out("undefined,"); } else { //Or because the last argument is a comprehension or a spread Tree.PositionalArgument parg = argList.getPositionalArguments().get( argList.getPositionalArguments().size()-1); if (!(parg instanceof Tree.Comprehension || parg instanceof Tree.SpreadArgument)) { gen.out("undefined,"); } } } if (targs != null && targs.getTypeModels() != null && !targs.getTypeModels().isEmpty()) { Map<TypeParameter, ProducedType> invargs = TypeUtils.matchTypeParametersWithArguments( ((Functional) bmed).getTypeParameters(), targs.getTypeModels()); if (invargs != null) { TypeUtils.printTypeArguments(typeArgSource, invargs, gen); } else { gen.out("/*TARGS != TPARAMS!!!! WTF?????*/"); } } } } gen.out(")"); } }
diff --git a/src/org/clapper/curn/output/html/HTMLOutputHandler.java b/src/org/clapper/curn/output/html/HTMLOutputHandler.java index 28da724..6012d7e 100644 --- a/src/org/clapper/curn/output/html/HTMLOutputHandler.java +++ b/src/org/clapper/curn/output/html/HTMLOutputHandler.java @@ -1,312 +1,315 @@ /*---------------------------------------------------------------------------*\ $Id$ \*---------------------------------------------------------------------------*/ package org.clapper.curn.htmloutput; import org.clapper.curn.OutputHandler; import org.clapper.curn.FeedException; import org.clapper.curn.Util; import org.clapper.curn.Version; import org.clapper.curn.FeedInfo; import org.clapper.curn.ConfigFile; import org.clapper.curn.parser.RSSChannel; import org.clapper.curn.parser.RSSItem; import org.clapper.util.text.Unicode; import org.clapper.util.text.TextUtils; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.Collection; import java.util.Iterator; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.net.URL; import org.w3c.dom.Node; import org.w3c.dom.html.HTMLTableRowElement; import org.w3c.dom.html.HTMLTableCellElement; import org.w3c.dom.html.HTMLAnchorElement; /** * Provides an output handler that produces HTML output. * * @see OutputHandler * @see org.clapper.curn.curn * @see org.clapper.curn.parser.RSSChannel * * @version <tt>$Revision$</tt> */ public class HTMLOutputHandler implements OutputHandler { /*----------------------------------------------------------------------*\ Private Constants \*----------------------------------------------------------------------*/ private static final DateFormat OUTPUT_DATE_FORMAT = new SimpleDateFormat ("dd MMM, yyyy, HH:mm:ss"); /*----------------------------------------------------------------------*\ Private Instance Data \*----------------------------------------------------------------------*/ private PrintWriter out = null; private RSSOutputHTML doc = null; private String oddItemRowClass = null; private String oddChannelClass = null; private int rowCount = 0; private int channelCount = 0; private ConfigFile config = null; private HTMLTableRowElement channelRow = null; private HTMLTableRowElement channelSeparatorRow = null; private Node channelRowParent = null; private HTMLAnchorElement itemAnchor = null; private HTMLTableCellElement itemTitleTD = null; private HTMLTableCellElement itemDescTD = null; private HTMLTableCellElement channelTD = null; /*----------------------------------------------------------------------*\ Constructor \*----------------------------------------------------------------------*/ /** * Construct a new <tt>HTMLOutputHandler</tt>. */ public HTMLOutputHandler() { } /*----------------------------------------------------------------------*\ Public Methods \*----------------------------------------------------------------------*/ /** * Initializes the output handler for another set of RSS channels. * * @param writer the <tt>PrintWriter</tt> where the handler should send * output * @param config the parsed <i>curn</i> configuration data * * @throws FeedException initialization error */ public void init (PrintWriter writer, ConfigFile config) throws FeedException { this.doc = new RSSOutputHTML(); this.config = config; this.out = writer; this.oddChannelClass = doc.getElementChannelTD().getClassName(); this.oddItemRowClass = doc.getElementItemTitleTD().getClassName(); this.channelRow = doc.getElementChannelRow(); this.channelSeparatorRow = doc.getElementChannelSeparatorRow(); this.channelRowParent = channelRow.getParentNode(); this.itemAnchor = doc.getElementItemAnchor(); this.itemTitleTD = doc.getElementItemTitleTD(); this.itemDescTD = doc.getElementItemDescTD(); this.channelTD = doc.getElementChannelTD(); } /** * Display the list of <tt>RSSItem</tt> news items to whatever output * is defined for the underlying class. * * @param channel The channel containing the items to emit. The method * should emit all the items in the channel; the caller * is responsible for clearing out any items that should * not be seen. * @param feedInfo Information about the feed, from the configuration * * @throws FeedException unable to write output */ public void displayChannel (RSSChannel channel, FeedInfo feedInfo) throws FeedException { Collection items = channel.getItems(); if (items.size() == 0) return; int i = 0; Iterator it; Date date; channelCount++; // Insert separator row first. channelRowParent.insertBefore (channelSeparatorRow.cloneNode (true), channelSeparatorRow); // Do the rows of output. doc.getElementChannelDate().removeAttribute ("id"); doc.getElementItemDate().removeAttribute ("id"); for (i = 0, it = items.iterator(); it.hasNext(); i++, rowCount++) { RSSItem item = (RSSItem) it.next(); if (i == 0) { // First row in channel has channel title and link. doc.setTextChannelTitle (channel.getTitle()); date = null; if (config.showDates()) date = channel.getPublicationDate(); if (date != null) doc.setTextChannelDate (OUTPUT_DATE_FORMAT.format (date)); else doc.setTextChannelDate (""); itemAnchor.setHref (item.getLink().toExternalForm()); } else { doc.setTextChannelTitle (""); doc.setTextChannelDate (""); itemAnchor.setHref (""); } String title = item.getTitle(); doc.setTextItemTitle ((title == null) ? "(No Title)" : title); String desc = null; if (! feedInfo.summarizeOnly()) { desc = item.getSummary(); if (TextUtils.stringIsEmpty (desc)) { // Hack for feeds that have no summary but have // content. If the content is small enough, use it as // the summary. desc = item.getFirstContentOfType (new String[] { "text/plain", "text/html" }); if (! TextUtils.stringIsEmpty (desc)) { desc = desc.trim(); if (desc.length() > CONTENT_AS_SUMMARY_MAXSIZE) desc = null; } } } else { - desc = desc.trim(); + if (TextUtils.stringIsEmpty (desc)) + desc = null; + else + desc = desc.trim(); } if (desc == null) desc = String.valueOf (Unicode.NBSP); doc.setTextItemDescription (desc); itemAnchor.setHref (item.getLink().toExternalForm()); date = null; if (config.showDates()) date = item.getPublicationDate(); if (date != null) doc.setTextItemDate (OUTPUT_DATE_FORMAT.format (date)); else doc.setTextItemDate (""); itemTitleTD.removeAttribute ("class"); itemDescTD.removeAttribute ("class"); if ((rowCount % 2) == 1) { // Want to use the "odd row" class to distinguish the // rows. For the description, though, only do that if // if's not empty. itemTitleTD.setAttribute ("class", oddItemRowClass); if (desc != null) itemDescTD.setAttribute ("class", oddItemRowClass); } if ((channelCount % 2) == 1) channelTD.setClassName (oddChannelClass); else channelTD.setClassName (""); channelRowParent.insertBefore (channelRow.cloneNode (true), channelSeparatorRow); } } /** * Flush any buffered-up output. <i>curn</i> calls this method * once, after calling <tt>displayChannelItems()</tt> for all channels. * * @throws FeedException unable to write output */ public void flush() throws FeedException { // Remove the cloneable row. removeElement (doc.getElementChannelRow()); // Add configuration info, if available. doc.setTextVersion (Version.VERSION); URL configFileURL = config.getConfigurationFileURL(); if (configFileURL == null) removeElement (doc.getElementConfigFileRow()); else doc.setTextConfigURL (configFileURL.toString()); // Write the document. out.print (doc.toDocument()); out.flush(); // Kill the document. doc = null; } /** * Get the content (i.e., MIME) type for output produced by this output * handler. * * @return the content type */ public String getContentType() { return "text/html"; } /*----------------------------------------------------------------------*\ Private Methods \*----------------------------------------------------------------------*/ /** * Remove an element from the document. * * @param element the <tt>Node</tt> representing the element in the DOM */ private void removeElement (Node element) { Node parentNode = element.getParentNode(); if (parentNode != null) parentNode.removeChild (element); } }
true
true
public void displayChannel (RSSChannel channel, FeedInfo feedInfo) throws FeedException { Collection items = channel.getItems(); if (items.size() == 0) return; int i = 0; Iterator it; Date date; channelCount++; // Insert separator row first. channelRowParent.insertBefore (channelSeparatorRow.cloneNode (true), channelSeparatorRow); // Do the rows of output. doc.getElementChannelDate().removeAttribute ("id"); doc.getElementItemDate().removeAttribute ("id"); for (i = 0, it = items.iterator(); it.hasNext(); i++, rowCount++) { RSSItem item = (RSSItem) it.next(); if (i == 0) { // First row in channel has channel title and link. doc.setTextChannelTitle (channel.getTitle()); date = null; if (config.showDates()) date = channel.getPublicationDate(); if (date != null) doc.setTextChannelDate (OUTPUT_DATE_FORMAT.format (date)); else doc.setTextChannelDate (""); itemAnchor.setHref (item.getLink().toExternalForm()); } else { doc.setTextChannelTitle (""); doc.setTextChannelDate (""); itemAnchor.setHref (""); } String title = item.getTitle(); doc.setTextItemTitle ((title == null) ? "(No Title)" : title); String desc = null; if (! feedInfo.summarizeOnly()) { desc = item.getSummary(); if (TextUtils.stringIsEmpty (desc)) { // Hack for feeds that have no summary but have // content. If the content is small enough, use it as // the summary. desc = item.getFirstContentOfType (new String[] { "text/plain", "text/html" }); if (! TextUtils.stringIsEmpty (desc)) { desc = desc.trim(); if (desc.length() > CONTENT_AS_SUMMARY_MAXSIZE) desc = null; } } } else { desc = desc.trim(); } if (desc == null) desc = String.valueOf (Unicode.NBSP); doc.setTextItemDescription (desc); itemAnchor.setHref (item.getLink().toExternalForm()); date = null; if (config.showDates()) date = item.getPublicationDate(); if (date != null) doc.setTextItemDate (OUTPUT_DATE_FORMAT.format (date)); else doc.setTextItemDate (""); itemTitleTD.removeAttribute ("class"); itemDescTD.removeAttribute ("class"); if ((rowCount % 2) == 1) { // Want to use the "odd row" class to distinguish the // rows. For the description, though, only do that if // if's not empty. itemTitleTD.setAttribute ("class", oddItemRowClass); if (desc != null) itemDescTD.setAttribute ("class", oddItemRowClass); } if ((channelCount % 2) == 1) channelTD.setClassName (oddChannelClass); else channelTD.setClassName (""); channelRowParent.insertBefore (channelRow.cloneNode (true), channelSeparatorRow); } }
public void displayChannel (RSSChannel channel, FeedInfo feedInfo) throws FeedException { Collection items = channel.getItems(); if (items.size() == 0) return; int i = 0; Iterator it; Date date; channelCount++; // Insert separator row first. channelRowParent.insertBefore (channelSeparatorRow.cloneNode (true), channelSeparatorRow); // Do the rows of output. doc.getElementChannelDate().removeAttribute ("id"); doc.getElementItemDate().removeAttribute ("id"); for (i = 0, it = items.iterator(); it.hasNext(); i++, rowCount++) { RSSItem item = (RSSItem) it.next(); if (i == 0) { // First row in channel has channel title and link. doc.setTextChannelTitle (channel.getTitle()); date = null; if (config.showDates()) date = channel.getPublicationDate(); if (date != null) doc.setTextChannelDate (OUTPUT_DATE_FORMAT.format (date)); else doc.setTextChannelDate (""); itemAnchor.setHref (item.getLink().toExternalForm()); } else { doc.setTextChannelTitle (""); doc.setTextChannelDate (""); itemAnchor.setHref (""); } String title = item.getTitle(); doc.setTextItemTitle ((title == null) ? "(No Title)" : title); String desc = null; if (! feedInfo.summarizeOnly()) { desc = item.getSummary(); if (TextUtils.stringIsEmpty (desc)) { // Hack for feeds that have no summary but have // content. If the content is small enough, use it as // the summary. desc = item.getFirstContentOfType (new String[] { "text/plain", "text/html" }); if (! TextUtils.stringIsEmpty (desc)) { desc = desc.trim(); if (desc.length() > CONTENT_AS_SUMMARY_MAXSIZE) desc = null; } } } else { if (TextUtils.stringIsEmpty (desc)) desc = null; else desc = desc.trim(); } if (desc == null) desc = String.valueOf (Unicode.NBSP); doc.setTextItemDescription (desc); itemAnchor.setHref (item.getLink().toExternalForm()); date = null; if (config.showDates()) date = item.getPublicationDate(); if (date != null) doc.setTextItemDate (OUTPUT_DATE_FORMAT.format (date)); else doc.setTextItemDate (""); itemTitleTD.removeAttribute ("class"); itemDescTD.removeAttribute ("class"); if ((rowCount % 2) == 1) { // Want to use the "odd row" class to distinguish the // rows. For the description, though, only do that if // if's not empty. itemTitleTD.setAttribute ("class", oddItemRowClass); if (desc != null) itemDescTD.setAttribute ("class", oddItemRowClass); } if ((channelCount % 2) == 1) channelTD.setClassName (oddChannelClass); else channelTD.setClassName (""); channelRowParent.insertBefore (channelRow.cloneNode (true), channelSeparatorRow); } }
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dEntity.java b/src/main/java/net/aufdemrand/denizen/objects/dEntity.java index 07e6161d5..0cd22d693 100644 --- a/src/main/java/net/aufdemrand/denizen/objects/dEntity.java +++ b/src/main/java/net/aufdemrand/denizen/objects/dEntity.java @@ -1,1993 +1,1994 @@ package net.aufdemrand.denizen.objects; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.aufdemrand.denizen.objects.properties.*; import net.aufdemrand.denizen.objects.properties.entity.*; import net.aufdemrand.denizen.scripts.ScriptRegistry; import net.aufdemrand.denizen.scripts.containers.core.EntityScriptContainer; import net.aufdemrand.denizen.tags.Attribute; import net.aufdemrand.denizen.utilities.Utilities; import net.aufdemrand.denizen.utilities.debugging.dB; import net.aufdemrand.denizen.utilities.nbt.CustomNBT; import net.citizensnpcs.api.CitizensAPI; import net.citizensnpcs.api.npc.NPC; import net.minecraft.server.v1_7_R1.EntityLiving; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.craftbukkit.v1_7_R1.CraftWorld; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftCreature; import org.bukkit.craftbukkit.v1_7_R1.entity.CraftLivingEntity; import org.bukkit.entity.*; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; public class dEntity implements dObject, Adjustable { ////////////////// // OBJECT FETCHER //////////////// /** * Gets a dEntity Object from a string form. </br> * </br> * Unique dEntities: </br> * n@13 will return the entity object of NPC 13 </br> * e@5884 will return the entity object for the entity with the entityid of 5884 </br> * e@jimmys_pet will return the saved entity object for the id 'jimmys pet' </br> * p@aufdemrand will return the entity object for aufdemrand </br> * </br> * New dEntities: </br> * zombie will return an unspawned Zombie dEntity </br> * super_creeper will return an unspawned custom 'Super_Creeper' dEntity </br> * * @param string the string or dScript argument String * @return a dEntity, or null */ @Fetchable("e") public static dEntity valueOf(String string) { if (string == null) return null; Matcher m; /////// // Handle objects with properties through the object fetcher m = ObjectFetcher.DESCRIBED_PATTERN.matcher(string); if (m.matches()) { return ObjectFetcher.getObjectFrom(dEntity.class, string); } // Choose a random entity type if "RANDOM" is used if (string.equalsIgnoreCase("RANDOM")) { EntityType randomType = null; // When selecting a random entity type, ignore invalid or inappropriate ones while (randomType == null || randomType.name().matches("^(COMPLEX_PART|DROPPED_ITEM|ENDER_CRYSTAL" + "|ENDER_DRAGON|FISHING_HOOK|ITEM_FRAME|LEASH_HITCH|LIGHTNING" + "|PAINTING|PLAYER|UNKNOWN|WEATHER|WITHER|WITHER_SKULL)$")) { randomType = EntityType.values()[Utilities.getRandom().nextInt(EntityType.values().length)]; } return new dEntity(randomType, "RANDOM"); } /////// // Match @object format // Make sure string matches what this interpreter can accept. m = entity_by_id.matcher(string); if (m.matches()) { String entityGroup = m.group(1).toUpperCase(); // NPC entity if (entityGroup.matches("N@")) { dNPC npc = dNPC.valueOf(string); if (npc != null) return new dEntity(npc.getCitizen()); else dB.echoError("NPC '" + string + "' does not exist!"); } // Player entity else if (entityGroup.matches("P@")) { LivingEntity returnable = aH.getPlayerFrom(m.group(2)).getPlayerEntity(); if (returnable != null) return new dEntity(returnable); else dB.echoError("Invalid Player! '" + entityGroup + "' could not be found. Has the player logged off?"); } // Assume entity else { if (aH.matchesInteger(m.group(2))) { int entityID = Integer.valueOf(m.group(2)); Entity entity = null; for (World world : Bukkit.getWorlds()) { net.minecraft.server.v1_7_R1.Entity nmsEntity = ((CraftWorld) world).getHandle().getEntity(entityID); // Make sure the nmsEntity is valid, to prevent // unpleasant errors if (nmsEntity != null) { entity = nmsEntity.getBukkitEntity(); break; } } if (entity != null) return new dEntity(entity); return null; } // else if (isSaved(m.group(2))) // return getSaved(m.group(2)); } } string = string.replace("e@", ""); //////// // Match Custom Entity if (ScriptRegistry.containsScript(string, EntityScriptContainer.class)) { // Construct a new custom unspawned entity from script return ScriptRegistry.getScriptContainerAs(m.group(0), EntityScriptContainer.class).getEntityFrom(); } //////// // Match Entity_Type m = entity_with_data.matcher(string); if (m.matches()) { String data1 = null; String data2 = null; if (m.group(2) != null) { data1 = m.group(2); } if (m.group(3) != null) { data2 = m.group(3); } for (EntityType type : EntityType.values()) { if (type.name().equalsIgnoreCase(m.group(1))) // Construct a new 'vanilla' unspawned dEntity return new dEntity(type, data1, data2); } } dB.log("valueOf dEntity returning null: " + string); return null; } final static Pattern entity_by_id = Pattern.compile("(n@|e@|p@)(.+)", Pattern.CASE_INSENSITIVE); final static Pattern entity_with_data = Pattern.compile("(\\w+),?(\\w+)?,?(\\w+)?", Pattern.CASE_INSENSITIVE); public static boolean matches(String arg) { // Accept anything that starts with a valid entity object identifier. Matcher m; m = entity_by_id.matcher(arg); if (m.matches()) return true; // No longer picky about e@.. let's remove it from the arg arg = arg.replace("e@", "").toUpperCase(); // Allow 'random' if (arg.equals("RANDOM")) return true; // Allow any entity script if (ScriptRegistry.containsScript(arg, EntityScriptContainer.class)) return true; // Use regex to make some matcher groups m = entity_with_data.matcher(arg); if (m.matches()) { // Check first word with a valid entity_type (other groups are datas used in constructors) for (EntityType type : EntityType.values()) if (type.name().equals(m.group(1))) return true; } // No luck otherwise! return false; } ///////////////////// // CONSTRUCTORS ////////////////// public dEntity(Entity entity) { if (entity != null) { this.entity = entity; this.uuid = entity.getUniqueId(); this.entity_type = entity.getType(); if (CitizensAPI.getNPCRegistry().isNPC(entity)) { this.npc = CitizensAPI.getNPCRegistry().getNPC(entity); } } else dB.echoError("Entity referenced is null!"); } public dEntity(EntityType entityType) { if (entityType != null) { this.entity = null; this.entity_type = entityType; } else dB.echoError("Entity_type referenced is null!"); } public dEntity(EntityType entityType, String data1) { if (entityType != null) { this.entity = null; this.entity_type = entityType; this.data1 = data1; } else dB.echoError("Entity_type referenced is null!"); } public dEntity(EntityType entityType, String data1, String data2) { if (entityType != null) { this.entity = null; this.entity_type = entityType; this.data1 = data1; this.data2 = data2; } else dB.echoError("Entity_type referenced is null!"); } public dEntity(NPC npc) { if (npc != null) { this.npc = npc; if (npc.isSpawned()) { this.entity = npc.getEntity(); this.entity_type = npc.getEntity().getType(); this.uuid = entity.getUniqueId(); } } else dB.echoError("NPC referenced is null!"); } ///////////////////// // INSTANCE FIELDS/METHODS ///////////////// private Entity entity = null; private EntityType entity_type = null; private String data1 = null; private String data2 = null; private DespawnedEntity despawned_entity = null; private NPC npc = null; private UUID uuid = null; public EntityType getEntityType() { return entity_type; } /** * Returns the unique UUID of this entity * * @return The UUID */ public UUID getUUID() { return uuid; } /** * Get the dObject that most accurately describes this entity, * useful for automatically saving dEntities to contexts as * dNPCs and dPlayers * * @return The dObject */ public dObject getDenizenObject() { if (entity == null) return null; if (isNPC()) return new dNPC(getNPC()); else if (isPlayer()) return new dPlayer(getPlayer()); else return this; } /** * Get the Bukkit entity corresponding to this dEntity * * @return the underlying Bukkit entity */ public Entity getBukkitEntity() { return entity; } /** * Get the living entity corresponding to this dEntity * * @return The living entity */ public LivingEntity getLivingEntity() { if (entity instanceof LivingEntity) return (LivingEntity) entity; else return null; } /** * Check whether this dEntity is a living entity * * @return true or false */ public boolean isLivingEntity() { return (entity instanceof LivingEntity); } /** * Get the NPC corresponding to this dEntity * * @return The NPC */ public NPC getNPC() { if (npc != null) return npc; else if (entity != null && CitizensAPI.getNPCRegistry().isNPC(entity)) return CitizensAPI.getNPCRegistry().getNPC(entity); else return null; } /** * Get the dNPC corresponding to this dEntity * * @return The dNPC */ public dNPC getDenizenNPC() { if (npc != null) return new dNPC(npc); else if (entity != null && CitizensAPI.getNPCRegistry().isNPC(entity)) return new dNPC(CitizensAPI.getNPCRegistry().getNPC(entity)); else return null; } /** * Check whether this dEntity is an NPC * * @return true or false */ public boolean isNPC() { if (npc != null) return true; else if (entity != null && CitizensAPI.getNPCRegistry().isNPC(entity)) return true; else return false; } /** * Get the Player corresponding to this dEntity * * @return The Player */ public Player getPlayer() { return (Player) entity; } /** * Get the dPlayer corresponding to this dEntity * * @return The dPlayer */ public dPlayer getDenizenPlayer() { return new dPlayer(getPlayer()); } /** * Check whether this dEntity is a Player * * @return true or false */ public boolean isPlayer() { return !isNPC() && entity instanceof Player; } /** * Get this dEntity as a Projectile * * @return The Projectile */ public Projectile getProjectile() { return (Projectile) entity; } /** * Check whether this dEntity is a Projectile * * @return true or false */ public boolean isProjectile() { return entity instanceof Projectile; } /** * Get this Projectile entity's shooter * * @return A dEntity of the shooter */ public dEntity getShooter() { if (hasShooter()) return new dEntity((LivingEntity) getProjectile().getShooter()); else return null; } /** * Set this Projectile entity's shooter * */ public void setShooter(dEntity shooter) { if (isProjectile() && shooter.isLivingEntity()) getProjectile().setShooter(shooter.getLivingEntity()); } /** * Check whether this entity has a shooter. * * @return true or false */ public boolean hasShooter() { return isProjectile() && getProjectile().getShooter() != null && getProjectile().getShooter() instanceof LivingEntity; // TODO: Handle other shooter source thingy types } /** * Returns this entity's dInventory. * * @return the entity's dInventory */ public dInventory getInventory() { if (isLivingEntity() && getLivingEntity() instanceof InventoryHolder) return new dInventory((InventoryHolder) getLivingEntity()); else return null; } /** * Returns this entity's equipment (i.e. armor contents) * as a 4-slot dInventory * * @return the entity's dInventory */ public dInventory getEquipment() { if (isLivingEntity()) return new dInventory(InventoryType.CRAFTING) .add(getLivingEntity().getEquipment().getArmorContents()); else return null; } /** * Whether this entity identifies as a generic * entity type, for instance "e@cow", instead of * a spawned entity * * @return true or false */ public boolean isGeneric() { return !isUnique(); } /** * Get the location of this entity * * @return The Location */ public dLocation getLocation() { if (isUnique() && entity != null) { return new dLocation(entity.getLocation()); } return null; } /** * Get the eye location of this entity * * @return The location */ public dLocation getEyeLocation() { if (!isGeneric() && isLivingEntity()) { return new dLocation(getLivingEntity().getEyeLocation()); } return null; } /** * Gets the velocity of this entity * * @return The velocity's vector */ public Vector getVelocity() { if (!isGeneric()) { return entity.getVelocity(); } return null; } /** * Sets the velocity of this entity * */ public void setVelocity(Vector vector) { if (!isGeneric()) { entity.setVelocity(vector); } } /** * Gets the world of this entity * * @return The entity's world */ public World getWorld() { if (!isGeneric()) { return entity.getWorld(); } return null; } public void spawnAt(Location location) { // If the entity is already spawned, teleport it. if (isNPC()) { if (getNPC().isSpawned()) getNPC().teleport(location, TeleportCause.PLUGIN); else { getNPC().spawn(location); entity = getNPC().getEntity(); uuid = getNPC().getEntity().getUniqueId(); } } else if (entity != null && isUnique()) entity.teleport(location); else { if (entity_type != null) { if (despawned_entity != null) { // If entity had a custom_script, use the script to rebuild the base entity. if (despawned_entity.custom_script != null) { } // TODO: Build entity from custom script // Else, use the entity_type specified/remembered else entity = location.getWorld().spawnEntity(location, entity_type); getLivingEntity().teleport(location); getLivingEntity().getEquipment().setArmorContents(despawned_entity.equipment); getLivingEntity().setHealth(despawned_entity.health); despawned_entity = null; } else { org.bukkit.entity.Entity ent = null; if (entity_type.name().matches("PLAYER")) { NPC npc = CitizensAPI.getNPCRegistry().createNPC(EntityType.PLAYER, data1); npc.spawn(location); entity = npc.getEntity(); uuid = entity.getUniqueId(); } else if (entity_type.name().matches("FALLING_BLOCK")) { Material material = null; if (data1 != null && dMaterial.matches(data1)) { material = dMaterial.valueOf(data1).getMaterial(); // If we did not get a block with "RANDOM", or we got // air or portals, keep trying while (data1.equalsIgnoreCase("RANDOM") && ((!material.isBlock()) || material == Material.AIR || material == Material.PORTAL || material == Material.ENDER_PORTAL)) { material = dMaterial.valueOf(data1).getMaterial(); } } // If material is null or not a block, default to SAND if (material == null || (!material.isBlock())) { material = Material.SAND; } byte materialData = 0; // Get special data value from data2 if it is a valid integer if (data2 != null && aH.matchesInteger(data2)) { materialData = (byte) aH.getIntegerFrom(data2); } // This is currently the only way to spawn a falling block ent = location.getWorld().spawnFallingBlock(location, material, materialData); entity = ent; uuid = entity.getUniqueId(); } else { ent = location.getWorld().spawnEntity(location, entity_type); entity = ent; uuid = entity.getUniqueId(); if (entity_type.name().matches("PIG_ZOMBIE")) { // Give pig zombies golden swords by default, unless data2 specifies // a different weapon if (!dItem.matches(data1)) { data1 = "gold_sword"; } ((PigZombie) entity).getEquipment() .setItemInHand(dItem.valueOf(data1).getItemStack()); } else if (entity_type.name().matches("SKELETON")) { // Give skeletons bows by default, unless data2 specifies // a different weapon if (!dItem.matches(data2)) { data2 = "bow"; } ((Skeleton) entity).getEquipment() .setItemInHand(dItem.valueOf(data2).getItemStack()); } // If there is some special subtype data associated with this dEntity, // use the setSubtype method to set it in a clean, object-oriented // way that uses reflection // // Otherwise, just use entity-specific methods manually if (data1 != null) { try { // Allow creepers to be powered if (ent instanceof Creeper && data1.equalsIgnoreCase("POWERED")) { ((Creeper) entity).setPowered(true); } // Allow setting of blocks held by endermen else if (ent instanceof Enderman && dMaterial.matches(data1)) { ((Enderman) entity).setCarriedMaterial(dMaterial.valueOf(data1).getMaterialData()); } // Allow setting of horse variants and colors else if (ent instanceof Horse) { setSubtype("org.bukkit.entity.Horse", "org.bukkit.entity.Horse$Variant", "setVariant", data1); if (data2 != null) { setSubtype("org.bukkit.entity.Horse", "org.bukkit.entity.Horse$Color", "setColor", data2); } } // Allow setting of ocelot types else if (ent instanceof Ocelot) { setSubtype("org.bukkit.entity.Ocelot", "org.bukkit.entity.Ocelot$Type", "setCatType", data1); } // Allow setting of sheep colors else if (ent instanceof Sheep) { setSubtype("org.bukkit.entity.Sheep", "org.bukkit.DyeColor", "setColor", data1); } // Allow setting of skeleton types else if (ent instanceof Skeleton) { setSubtype("org.bukkit.entity.Skeleton", "org.bukkit.entity.Skeleton$SkeletonType", "setSkeletonType", data1); } // Allow setting of slime sizes else if (ent instanceof Slime && aH.matchesInteger(data1)) { ((Slime) entity).setSize(aH.getIntegerFrom(data1)); } // Allow setting of villager professions else if (ent instanceof Villager) { setSubtype("org.bukkit.entity.Villager", "org.bukkit.entity.Villager$Profession", "setProfession", data1); } } catch (Exception e) { dB.echoError(e); } } } } } else dB.echoError("Cannot spawn a null dEntity!"); for (Mechanism mechanism: mechanisms) { adjust(mechanism); } mechanisms.clear(); } } public void despawn() { despawned_entity = new DespawnedEntity(this); getLivingEntity().remove(); } public void respawn() { if (despawned_entity != null) spawnAt(despawned_entity.location); else if (entity == null) dB.echoError("Cannot respawn a null dEntity!"); } public boolean isSpawned() { return entity != null && isValid(); } public boolean isValid() { return entity.isValid(); } public void remove() { entity.remove(); } public void teleport(Location location) { if (isNPC()) getNPC().teleport(location, TeleportCause.PLUGIN); else entity.teleport(location); } /** * Make this entity target another living entity, attempting both * old entity AI and new entity AI targeting methods * * @param target The LivingEntity target */ public void target(LivingEntity target) { // If the target is not null, cast it to an NMS EntityLiving // as well for one of the two methods below EntityLiving nmsTarget = target != null ? ((CraftLivingEntity) target).getHandle() : null; ((CraftCreature) entity).getHandle(). setGoalTarget(nmsTarget); ((CraftCreature) entity).getHandle(). setGoalTarget(((CraftLivingEntity) target).getHandle()); ((CraftCreature) entity).setTarget(target); } /** * Set the subtype of this entity by using the chosen method and Enum from * this Bukkit entity's class and: * 1) using a random subtype if value is "RANDOM" * 2) looping through the entity's subtypes until one matches the value string * * Example: setSubtype("org.bukkit.entity.Ocelot", "org.bukkit.entity.Ocelot$Type", "setCatType", "SIAMESE_CAT"); * * @param entityName The name of the entity's class. * @param typeName The name of the entity class' Enum with subtypes. * @param method The name of the method used to set the subtype of this entity. * @param value The value of the subtype. */ public void setSubtype (String entityName, String typeName, String method, String value) throws Exception { Class<?> entityClass = Class.forName(entityName); Class<?> typeClass = Class.forName(typeName); Object[] types = typeClass.getEnumConstants(); if (value.equalsIgnoreCase("RANDOM")) { entityClass.getMethod(method, typeClass).invoke(entity, types[Utilities.getRandom().nextInt(types.length)]); } else { for (Object type : types) { if (type.toString().equalsIgnoreCase(value)) { entityClass.getMethod(method, typeClass).invoke(entity, type); break; } } } } public void setEntity(Entity entity) { this.entity = entity; } // Used to store some information about a livingEntity while it's despawned private class DespawnedEntity { Double health = null; Location location = null; ItemStack[] equipment = null; String custom_script = null; public DespawnedEntity(dEntity entity) { if (entity != null) { // Save some important info to rebuild the entity health = entity.getLivingEntity().getHealth(); location = entity.getLivingEntity().getLocation(); equipment = entity.getLivingEntity().getEquipment().getArmorContents(); if (CustomNBT.hasCustomNBT(entity.getLivingEntity(), "denizen-script-id")) custom_script = CustomNBT.getCustomNBT(entity.getLivingEntity(), "denizen-script-id"); } } } public int comparesTo(dEntity entity) { // If provided is unique, and both are the same unique entity, return 1. if (entity.isUnique() && entity.identify().equals(identify())) return 1; // If provided isn't unique... if (!entity.isUnique()) { // Return 1 if this object isn't unique either, but matches if (!isUnique() && entity.identify().equals(identify())) return 1; // Return 1 if the provided object isn't unique, but whose entity_type // matches this object, even if this object is unique. if (entity_type == entity.entity_type) return 1; } return 0; } ///////////////////// // dObject Methods /////////////////// private String prefix = "Entity"; @Override public String getObjectType() { return "Entity"; } @Override public String getPrefix() { return prefix; } @Override public dEntity setPrefix(String prefix) { this.prefix = prefix; return this; } @Override public String debug() { return "<G>" + prefix + "='<Y>" + identify() + "<G>' "; } @Override public String identify() { // Check if entity is a Player or NPC if (entity != null) { if (isNPC()) return "n@" + getNPC().getId(); else if (isPlayer()) return "p@" + getPlayer().getName(); // // Check if entity is a 'notable entity' // if (isSaved(this)) // return "e@" + getSaved(this); else if (isSpawned()) return "e@" + entity.getEntityId(); } // Check if an entity_type is available if (entity_type != null) return "e@" + entity_type.name(); return "null"; } @Override public String identifySimple() { // TODO: Change up when entities identify with properties return identify(); } public String identifyType() { if (isNPC()) return "npc"; else if (isPlayer()) return "player"; else return "e@" + entity_type.name(); } @Override public String toString() { return identify(); } @Override public boolean isUnique() { return (isPlayer() || isNPC() || isSpawned()); // || isSaved() } @Override public String getAttribute(Attribute attribute) { if (attribute == null) return null; if (entity == null) { dB.echoError("dEntity has returned null."); return Element.NULL.getAttribute(attribute); } ///////////////////// // DEBUG ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Boolean) // @description // Debugs the entity in the log and returns true. // --> if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the entity's debug with no color. // --> if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the entity's debug. // --> if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the prefix of the entity. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns 'Entity', the type of this dObject. // --> if (attribute.startsWith("type")) { return new Element(getObjectType()) .getAttribute(attribute.fulfill(1)); } ///////////////////// // IDENTIFICATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_id> // @returns dScript/Element // @description // If the entity has a script ID, returns the dScript of that ID. // Otherwise, returns the name of the entity type. // --> if (attribute.startsWith("custom_id")) { if (CustomNBT.hasCustomNBT(getLivingEntity(), "denizen-script-id")) return new dScript(CustomNBT.getCustomNBT(getLivingEntity(), "denizen-script-id")) .getAttribute(attribute.fulfill(1)); else return new Element(entity.getType().name()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_name> // @returns Element // @description // If the entity has a custom name, returns the name as an Element. // Otherwise, returns null. // --> if (attribute.startsWith("custom_name")) { if (getLivingEntity().getCustomName() == null) return "null"; return new Element(getLivingEntity().getCustomName()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_name.visible> // @returns Element(Boolean) // @description // Returns true if the entity's custom name is visible. // --> if (attribute.startsWith("custom_name.visible")) return new Element(getLivingEntity().isCustomNameVisible()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the entity's temporary server entity ID. // --> if (attribute.startsWith("eid")) return new Element(entity.getEntityId()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the name of the entity. // --> if (attribute.startsWith("name")) { if (isNPC()) return new Element(getNPC().getName()) .getAttribute(attribute.fulfill(1)); if (entity instanceof Player) return new Element(((Player) entity).getName()) .getAttribute(attribute.fulfill(1)); return new Element(entity.getType().getName()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_reason> // @returns String // @description // Returns the reason an entity was spawned. // --> if (attribute.startsWith("spawn_reason")) { if (entity.getMetadata("spawnreason").size() == 0) return "null"; return new Element(entity.getMetadata("spawnreason").get(0).asString()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the permanent unique ID of the entity. // --> if (attribute.startsWith("uuid")) return new Element(getUUID().toString()) .getAttribute(attribute.fulfill(1)); ///////////////////// // INVENTORY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as boots, or null // if none. // --> if (attribute.startsWith("equipment.boots")) { if (getLivingEntity().getEquipment().getBoots() != null) { return new dItem(getLivingEntity().getEquipment().getBoots()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as a chestplate, or null // if none. // --> else if (attribute.startsWith("equipment.chestplate") || attribute.startsWith("equipment.chest")) { if (getLivingEntity().getEquipment().getChestplate() != null) { return new dItem(getLivingEntity().getEquipment().getChestplate()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as a helmet, or null // if none. // --> else if (attribute.startsWith("equipment.helmet") || attribute.startsWith("equipment.head")) { if (getLivingEntity().getEquipment().getHelmet() != null) { return new dItem(getLivingEntity().getEquipment().getHelmet()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as leggings, or null // if none. // --> else if (attribute.startsWith("equipment.leggings") || attribute.startsWith("equipment.legs")) { if (getLivingEntity().getEquipment().getLeggings() != null) { return new dItem(getLivingEntity().getEquipment().getLeggings()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dInventory // @description // returns a dInventory containing the entity's equipment. // --> else if (attribute.startsWith("equipment")) { // The only way to return correct size for dInventory // created from equipment is to use a CRAFTING type // that has the expected 4 slots return getEquipment().getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_in_hand> // @returns dItem // @description // returns the item the entity is holding, or i@air // if none. // --> if (attribute.startsWith("item_in_hand") || attribute.startsWith("iteminhand")) return new dItem(getLivingEntity().getEquipment().getItemInHand()) .getAttribute(attribute.fulfill(1)); ///////////////////// // LOCATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_see[<entity>]> // @returns Element(Boolean) // @description // Returns whether the entity can see the specified other entity. // --> if (attribute.startsWith("can_see")) { if (attribute.hasContext(1) && dEntity.matches(attribute.getContext(1))) { dEntity toEntity = dEntity.valueOf(attribute.getContext(1)); return new Element(getLivingEntity().hasLineOfSight(toEntity.getBukkitEntity())).getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]_location> // @returns dLocation // @description // returns the location of the entity's eyes. // --> if (attribute.startsWith("eye_location")) return new dLocation(getEyeLocation()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_eye_height> // @returns Element(Boolean) // @description // Returns the height of the entity's eyes above its location. // --> if (attribute.startsWith("get_eye_height")) { if (isLivingEntity()) return new Element(getLivingEntity().getEyeHeight()) .getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_on[<range>]> // @returns dLocation // @description // Returns the location of the block the entity is looking at. // Optionally, specify a maximum range to find the location from. // --> if (attribute.startsWith("location.cursor_on")) { int range = attribute.getIntContext(2); if (range < 1) range = 50; return new dLocation(getLivingEntity().getTargetBlock(null, range).getLocation().clone()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_on> // @returns dLocation // @description // Returns the location of what the entity is standing on. // --> if (attribute.startsWith("location.standing_on")) return new dLocation(entity.getLocation().clone().add(0, -1, 0)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the entity. // --> if (attribute.startsWith("location")) { return new dLocation(entity.getLocation()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the movement velocity of the entity. // Note: Does not accurately calculate player clientside movement velocity. // --> if (attribute.startsWith("velocity")) { return new dLocation(entity.getVelocity().toLocation(entity.getWorld())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dWorld // @description // Returns the world the entity is in. // --> if (attribute.startsWith("world")) { return new dWorld(entity.getWorld()) .getAttribute(attribute.fulfill(1)); } ///////////////////// // STATE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_pickup_items> // @returns Element(Boolean) // @description // Returns whether the entity can pick up items. // --> if (attribute.startsWith("can_pickup_items")) return new Element(getLivingEntity().getCanPickupItems()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_distance> // @returns Element(Decimal) // @description // Returns how far the entity has fallen. // --> if (attribute.startsWith("fall_distance")) return new Element(entity.getFallDistance()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_time> // @returns Duration // @description // Returns the duration for which the entity will remain on fire // --> if (attribute.startsWith("fire_time")) return new Duration(entity.getFireTicks() / 20) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_leash_holder> // @returns dPlayer // @description // Returns the leash holder of entity. // --> if (attribute.startsWith("get_leash_holder")) { if (isLivingEntity() && getLivingEntity().isLeashed()) { return new dEntity(getLivingEntity().getLeashHolder()) .getAttribute(attribute.fulfill(1)); } else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_passenger> // @returns dEntity // @description // If the entity has a passenger, returns the passenger as a dEntity. // Otherwise, returns null. // --> if (attribute.startsWith("get_passenger")) { if (!entity.isEmpty()) return new dEntity(entity.getPassenger()) .getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_shooter> // @returns dEntity // @description // If the entity is a projectile with a shooter, gets its shooter // Otherwise, returns null. // --> if (attribute.startsWith("get_shooter") || attribute.startsWith("shooter")) { if (isProjectile() && hasShooter()) return getShooter().getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_vehicle> // @returns dEntity // @description // If the entity is in a vehicle, returns the vehicle as a dEntity. // Otherwise, returns null. // --> if (attribute.startsWith("get_vehicle")) { if (entity.isInsideVehicle()) return new dEntity(entity.getVehicle()) .getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_effect[<effect>]> // @returns Element(Boolean) // @description // Returns whether the entity has a specified effect. // If no effect is specified, returns whether the entity has any effect. // --> // TODO: add list_effects ? if (attribute.startsWith("has_effect")) { Boolean returnElement = false; - if (attribute.hasContext(1)) + if (attribute.hasContext(1)) { for (org.bukkit.potion.PotionEffect effect : getLivingEntity().getActivePotionEffects()) if (effect.getType().equals(PotionEffectType.getByName(attribute.getContext(1)))) returnElement = true; - else if (!getLivingEntity().getActivePotionEffects().isEmpty()) returnElement = true; + } + else if (!getLivingEntity().getActivePotionEffects().isEmpty()) returnElement = true; return new Element(returnElement).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns a formatted value of the player's current health level. // May be 'dying', 'seriously wounded', 'injured', 'scraped', or 'healthy'. // --> if (attribute.startsWith("health.formatted")) { double maxHealth = getLivingEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHealth = attribute.getIntContext(2); if ((float) getLivingEntity().getHealth() / maxHealth < .10) return new Element("dying").getAttribute(attribute.fulfill(2)); else if ((float) getLivingEntity().getHealth() / maxHealth < .40) return new Element("seriously wounded").getAttribute(attribute.fulfill(2)); else if ((float) getLivingEntity().getHealth() / maxHealth < .75) return new Element("injured").getAttribute(attribute.fulfill(2)); else if ((float) getLivingEntity().getHealth() / maxHealth < 1) return new Element("scraped").getAttribute(attribute.fulfill(2)); else return new Element("healthy").getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the maximum health of the entity. // --> if (attribute.startsWith("health.max")) return new Element(getLivingEntity().getMaxHealth()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the entity's current health as a percentage. // --> if (attribute.startsWith("health.percentage")) { double maxHealth = getLivingEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHealth = attribute.getIntContext(2); return new Element((getLivingEntity().getHealth() / maxHealth) * 100) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the current health of the entity. // --> if (attribute.startsWith("health")) return new Element(getLivingEntity().getHealth()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_empty> // @returns Element(Boolean) // @description // Returns whether the entity does not have a passenger. // --> if (attribute.startsWith("is_empty")) return new Element(entity.isEmpty()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_inside_vehicle> // @returns Element(Boolean) // @description // Returns whether the entity is inside a vehicle. // --> if (attribute.startsWith("is_inside_vehicle")) return new Element(entity.isInsideVehicle()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_leashed> // @returns Element(Boolean) // @description // Returns whether the entity is leashed. // --> if (attribute.startsWith("is_leashed")) { if (isLivingEntity()) return new Element(getLivingEntity().isLeashed()) .getAttribute(attribute.fulfill(1)); else return Element.FALSE .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_on_ground> // @returns Element(Boolean) // @description // Returns whether the entity is supported by a block. // --> if (attribute.startsWith("is_on_ground")) return new Element(entity.isOnGround()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_persistent> // @returns Element(Boolean) // @description // Returns whether the entity will not be removed completely when far away from players. // --> if (attribute.startsWith("is_persistent")) { if (isLivingEntity()) return new Element(!getLivingEntity().getRemoveWhenFarAway()) .getAttribute(attribute.fulfill(1)); else return Element.FALSE .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_spawned> // @returns Element(Boolean) // @description // Returns whether the entity is spawned. // --> if (attribute.startsWith("is_spawned")) { return new Element(isSpawned()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dPlayer // @description // Returns the player that last killed the entity. // --> if (attribute.startsWith("killer")) return new dPlayer(getLivingEntity().getKiller()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_damage.amount> // @returns Element(Decimal) // @description // Returns the amount of the last damage taken by the entity. // --> if (attribute.startsWith("last_damage.amount")) return new Element(getLivingEntity().getLastDamage()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_damage.cause> // @returns Element // @description // Returns the cause of the last damage taken by the entity. // --> if (attribute.startsWith("last_damage.cause")) return new Element(entity.getLastDamageCause().getCause().name()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_damage.duration> // @returns Duration // @description // Returns the duration of the last damage taken by the entity. // --> if (attribute.startsWith("last_damage.duration")) return new Duration((long) getLivingEntity().getNoDamageTicks()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Duration // @description // Returns the maximum duration of oxygen the entity can have. // --> if (attribute.startsWith("oxygen.max")) return new Duration((long) getLivingEntity().getMaximumAir()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Duration // @description // Returns the duration of oxygen the entity has left. // --> if (attribute.startsWith("oxygen")) return new Duration((long) getLivingEntity().getRemainingAir()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_when_far> // @returns Element(Boolean) // @description // Returns if the entity despawns when away from players. // --> if (attribute.startsWith("remove_when_far")) return new Element(getLivingEntity().getRemoveWhenFarAway()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_lived> // @returns Duration // @description // Returns how long the entity has lived. // --> if (attribute.startsWith("time_lived")) return new Duration(entity.getTicksLived() / 20) .getAttribute(attribute.fulfill(1)); ///////////////////// // TYPE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_type> // @returns Element // @description // Returns the type of the entity. // --> if (attribute.startsWith("entity_type")) { return new Element(entity_type.name()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_living> // @returns Element(Boolean) // @description // Returns whether the entity is a living entity. // --> if (attribute.startsWith("is_living")) { return new Element(isLivingEntity()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_mob> // @returns Element(Boolean) // @description // Returns whether the entity is a mob (Not a player or NPC). // --> if (attribute.startsWith("is_mob")) { if (!isPlayer() && !isNPC()) return Element.TRUE.getAttribute(attribute.fulfill(1)); else return Element.FALSE.getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_npc> // @returns Element(Boolean) // @description // Returns whether the entity is an NPC. // --> if (attribute.startsWith("is_npc")) { return new Element(isNPC()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_player> // @returns Element(Boolean) // @description // Returns whether the entity is a player. // --> if (attribute.startsWith("is_player")) { return new Element(isPlayer()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_projectile> // @returns Element(Boolean) // @description // Returns whether the entity is a projectile. // --> if (attribute.startsWith("is_projectile")) { return new Element(isProjectile()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_tameable> // @returns Element(Boolean) // @description // Returns whether the entity is tameable. // If this returns true, it will enable access to: // <@link mechanism dEntity.tame>, <@link mechanism dEntity.owner>, // <@link tag [email protected]_tamed>, and <@link tag [email protected]_owner> // --> if (attribute.startsWith("is_tameable")) return new Element(EntityTame.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_ageable> // @returns Element(Boolean) // @description // Returns whether the entity is ageable. // If this returns true, it will enable access to: // <@link mechanism dEntity.age>, <@link mechanism dEntity.age_lock>, // <@link tag [email protected]_baby>, <@link tag [email protected]>, // and <@link tag [email protected]_age_locked> // --> if (attribute.startsWith("is_ageable")) return new Element(EntityAge.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_frame> // @returns Element(Boolean) // @description // Returns whether the entity can hold a framed item. // If this returns true, it will enable access to: // <@link mechanism dEntity.framed>, <@link tag [email protected]_item>, // <@link tag [email protected]_framed_item>, and <@link tag [email protected]_item_rotation> // --> if (attribute.startsWith("is_frame")) return new Element(EntityFramed.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_colorable> // @returns Element(Boolean) // @description // Returns whether the entity can be colored. // If this returns true, it will enable access to: // <@link mechanism dEntity.color> and <@link tag [email protected]> // --> if (attribute.startsWith("is_colorable")) return new Element(EntityColor.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_powerable> // @returns Element(Boolean) // @description // Returns whether the entity can be powered. // If this returns true, it will enable access to: // <@link mechanism dEntity.powered> and <@link tag [email protected]> // --> if (attribute.startsWith("is_powerable")) return new Element(EntityPowered.describes(this)) .getAttribute(attribute.fulfill(1)); ///////////////////// // PROPERTY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Boolean) // @description // Returns the entity's full description, including all properties. // --> if (attribute.startsWith("describe")) return new Element("e@" + getEntityType().name().toLowerCase() + PropertyParser.getPropertiesString(this)) .getAttribute(attribute.fulfill(1)); // Iterate through this object's properties' attributes for (Property property : PropertyParser.getProperties(this)) { String returned = property.getAttribute(attribute); if (returned != null) return returned; } return new Element(identify()).getAttribute(attribute); } private ArrayList<Mechanism> mechanisms = new ArrayList<Mechanism>(); @Override public void adjust(Mechanism mechanism) { if (isGeneric()) { mechanisms.add(mechanism); return; } Element value = mechanism.getValue(); // <--[mechanism] // @object dEntity // @name can_pickup_items // @input Element(Boolean) // @description // Sets whether the entity can pick up items. // @tags // <[email protected]_pickup_items> // --> if (mechanism.matches("can_pickup_items") && mechanism.requireBoolean()) getLivingEntity().setCanPickupItems(value.asBoolean()); // <--[mechanism] // @object dEntity // @name custom_name // @input Element // @description // Sets the custom name of the entity. // @tags // <[email protected]_name> // --> if (mechanism.matches("custom_name")) getLivingEntity().setCustomName(value.asString()); // <--[mechanism] // @object dEntity // @name custom_name_visibility // @input Element(Boolean) // @description // Sets whether the custom name is visible. // @tags // <[email protected]_name.visible> // --> if (mechanism.matches("custom_name_visibility") && mechanism.requireBoolean()) getLivingEntity().setCustomNameVisible(value.asBoolean()); // <--[mechanism] // @object dEntity // @name fall_distance // @input Element(Float) // @description // Sets the fall distance. // @tags // <[email protected]_distance> // --> if (mechanism.matches("fall_distance") && mechanism.requireFloat()) entity.setFallDistance(value.asFloat()); // <--[mechanism] // @object dEntity // @name fire_time // @input Duration // @description // Sets the entity's current fire time (time before the entity stops being on fire). // @tags // <[email protected]_time> // --> if (mechanism.matches("fire_time") && mechanism.requireObject(Duration.class)) entity.setFireTicks(value.asType(Duration.class).getTicksAsInt()); // <--[mechanism] // @object dEntity // @name leash_holder // @input dEntity // @description // Sets the entity holding this entity by leash. // @tags // <[email protected]_leashed> // <[email protected]_leash_holder> // --> if (mechanism.matches("leash_holder") && mechanism.requireObject(dEntity.class)) getLivingEntity().setLeashHolder(value.asType(dEntity.class).getBukkitEntity()); // <--[mechanism] // @object dEntity // @name passenger // @input dEntity // @description // Sets the passenger of this entity. // @tags // <[email protected]_passenger> // <[email protected]_empty> // --> if (mechanism.matches("passenger") && mechanism.requireObject(dEntity.class)) entity.setPassenger(value.asType(dEntity.class).getBukkitEntity()); // <--[mechanism] // @object dEntity // @name time_lived // @input Duration // @description // Sets the amount of time this entity has lived for. // @tags // <[email protected]_lived> // --> if (mechanism.matches("time_lived") && mechanism.requireObject(Duration.class)) entity.setTicksLived(value.asType(Duration.class).getTicksAsInt()); // <--[mechanism] // @object dEntity // @name remaining_air // @input Element(Number) // @description // Sets how much air the entity has remaining before it drowns. // @tags // <[email protected]> // <[email protected]> // --> if (mechanism.matches("remaining_air") && mechanism.requireInteger()) getLivingEntity().setRemainingAir(value.asInt()); // <--[mechanism] // @object dEntity // @name remove_effects // @input None // @description // Removes all potion effects from the entity. // @tags // <[email protected]_effect[<effect>]> // --> if (mechanism.matches("remove_effects")) for (PotionEffect potionEffect : this.getLivingEntity().getActivePotionEffects()) getLivingEntity().removePotionEffect(potionEffect.getType()); // <--[mechanism] // @object dEntity // @name remove_when_far_away // @input Element(Boolean) // @description // Sets whether the entity should be removed entirely when despawned. // @tags // <[email protected]_when_far> // --> if (mechanism.matches("remove_when_far_away") && mechanism.requireBoolean()) getLivingEntity().setRemoveWhenFarAway(value.asBoolean()); // <--[mechanism] // @object dEntity // @name velocity // @input dLocation // @description // Sets the entity's movement velocity. // @tags // <[email protected]> // --> if (mechanism.matches("velocity") && mechanism.requireObject(dLocation.class)) { entity.setVelocity(value.asType(dLocation.class).toVector()); } // Iterate through this object's properties' mechanisms for (Property property : PropertyParser.getProperties(this)) { property.adjust(mechanism); if (mechanism.fulfilled()) break; } if (!mechanism.fulfilled()) mechanism.reportInvalid(); } }
false
true
public String getAttribute(Attribute attribute) { if (attribute == null) return null; if (entity == null) { dB.echoError("dEntity has returned null."); return Element.NULL.getAttribute(attribute); } ///////////////////// // DEBUG ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Boolean) // @description // Debugs the entity in the log and returns true. // --> if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the entity's debug with no color. // --> if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the entity's debug. // --> if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the prefix of the entity. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns 'Entity', the type of this dObject. // --> if (attribute.startsWith("type")) { return new Element(getObjectType()) .getAttribute(attribute.fulfill(1)); } ///////////////////// // IDENTIFICATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_id> // @returns dScript/Element // @description // If the entity has a script ID, returns the dScript of that ID. // Otherwise, returns the name of the entity type. // --> if (attribute.startsWith("custom_id")) { if (CustomNBT.hasCustomNBT(getLivingEntity(), "denizen-script-id")) return new dScript(CustomNBT.getCustomNBT(getLivingEntity(), "denizen-script-id")) .getAttribute(attribute.fulfill(1)); else return new Element(entity.getType().name()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_name> // @returns Element // @description // If the entity has a custom name, returns the name as an Element. // Otherwise, returns null. // --> if (attribute.startsWith("custom_name")) { if (getLivingEntity().getCustomName() == null) return "null"; return new Element(getLivingEntity().getCustomName()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_name.visible> // @returns Element(Boolean) // @description // Returns true if the entity's custom name is visible. // --> if (attribute.startsWith("custom_name.visible")) return new Element(getLivingEntity().isCustomNameVisible()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the entity's temporary server entity ID. // --> if (attribute.startsWith("eid")) return new Element(entity.getEntityId()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the name of the entity. // --> if (attribute.startsWith("name")) { if (isNPC()) return new Element(getNPC().getName()) .getAttribute(attribute.fulfill(1)); if (entity instanceof Player) return new Element(((Player) entity).getName()) .getAttribute(attribute.fulfill(1)); return new Element(entity.getType().getName()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_reason> // @returns String // @description // Returns the reason an entity was spawned. // --> if (attribute.startsWith("spawn_reason")) { if (entity.getMetadata("spawnreason").size() == 0) return "null"; return new Element(entity.getMetadata("spawnreason").get(0).asString()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the permanent unique ID of the entity. // --> if (attribute.startsWith("uuid")) return new Element(getUUID().toString()) .getAttribute(attribute.fulfill(1)); ///////////////////// // INVENTORY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as boots, or null // if none. // --> if (attribute.startsWith("equipment.boots")) { if (getLivingEntity().getEquipment().getBoots() != null) { return new dItem(getLivingEntity().getEquipment().getBoots()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as a chestplate, or null // if none. // --> else if (attribute.startsWith("equipment.chestplate") || attribute.startsWith("equipment.chest")) { if (getLivingEntity().getEquipment().getChestplate() != null) { return new dItem(getLivingEntity().getEquipment().getChestplate()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as a helmet, or null // if none. // --> else if (attribute.startsWith("equipment.helmet") || attribute.startsWith("equipment.head")) { if (getLivingEntity().getEquipment().getHelmet() != null) { return new dItem(getLivingEntity().getEquipment().getHelmet()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as leggings, or null // if none. // --> else if (attribute.startsWith("equipment.leggings") || attribute.startsWith("equipment.legs")) { if (getLivingEntity().getEquipment().getLeggings() != null) { return new dItem(getLivingEntity().getEquipment().getLeggings()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dInventory // @description // returns a dInventory containing the entity's equipment. // --> else if (attribute.startsWith("equipment")) { // The only way to return correct size for dInventory // created from equipment is to use a CRAFTING type // that has the expected 4 slots return getEquipment().getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_in_hand> // @returns dItem // @description // returns the item the entity is holding, or i@air // if none. // --> if (attribute.startsWith("item_in_hand") || attribute.startsWith("iteminhand")) return new dItem(getLivingEntity().getEquipment().getItemInHand()) .getAttribute(attribute.fulfill(1)); ///////////////////// // LOCATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_see[<entity>]> // @returns Element(Boolean) // @description // Returns whether the entity can see the specified other entity. // --> if (attribute.startsWith("can_see")) { if (attribute.hasContext(1) && dEntity.matches(attribute.getContext(1))) { dEntity toEntity = dEntity.valueOf(attribute.getContext(1)); return new Element(getLivingEntity().hasLineOfSight(toEntity.getBukkitEntity())).getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]_location> // @returns dLocation // @description // returns the location of the entity's eyes. // --> if (attribute.startsWith("eye_location")) return new dLocation(getEyeLocation()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_eye_height> // @returns Element(Boolean) // @description // Returns the height of the entity's eyes above its location. // --> if (attribute.startsWith("get_eye_height")) { if (isLivingEntity()) return new Element(getLivingEntity().getEyeHeight()) .getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_on[<range>]> // @returns dLocation // @description // Returns the location of the block the entity is looking at. // Optionally, specify a maximum range to find the location from. // --> if (attribute.startsWith("location.cursor_on")) { int range = attribute.getIntContext(2); if (range < 1) range = 50; return new dLocation(getLivingEntity().getTargetBlock(null, range).getLocation().clone()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_on> // @returns dLocation // @description // Returns the location of what the entity is standing on. // --> if (attribute.startsWith("location.standing_on")) return new dLocation(entity.getLocation().clone().add(0, -1, 0)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the entity. // --> if (attribute.startsWith("location")) { return new dLocation(entity.getLocation()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the movement velocity of the entity. // Note: Does not accurately calculate player clientside movement velocity. // --> if (attribute.startsWith("velocity")) { return new dLocation(entity.getVelocity().toLocation(entity.getWorld())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dWorld // @description // Returns the world the entity is in. // --> if (attribute.startsWith("world")) { return new dWorld(entity.getWorld()) .getAttribute(attribute.fulfill(1)); } ///////////////////// // STATE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_pickup_items> // @returns Element(Boolean) // @description // Returns whether the entity can pick up items. // --> if (attribute.startsWith("can_pickup_items")) return new Element(getLivingEntity().getCanPickupItems()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_distance> // @returns Element(Decimal) // @description // Returns how far the entity has fallen. // --> if (attribute.startsWith("fall_distance")) return new Element(entity.getFallDistance()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_time> // @returns Duration // @description // Returns the duration for which the entity will remain on fire // --> if (attribute.startsWith("fire_time")) return new Duration(entity.getFireTicks() / 20) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_leash_holder> // @returns dPlayer // @description // Returns the leash holder of entity. // --> if (attribute.startsWith("get_leash_holder")) { if (isLivingEntity() && getLivingEntity().isLeashed()) { return new dEntity(getLivingEntity().getLeashHolder()) .getAttribute(attribute.fulfill(1)); } else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_passenger> // @returns dEntity // @description // If the entity has a passenger, returns the passenger as a dEntity. // Otherwise, returns null. // --> if (attribute.startsWith("get_passenger")) { if (!entity.isEmpty()) return new dEntity(entity.getPassenger()) .getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_shooter> // @returns dEntity // @description // If the entity is a projectile with a shooter, gets its shooter // Otherwise, returns null. // --> if (attribute.startsWith("get_shooter") || attribute.startsWith("shooter")) { if (isProjectile() && hasShooter()) return getShooter().getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_vehicle> // @returns dEntity // @description // If the entity is in a vehicle, returns the vehicle as a dEntity. // Otherwise, returns null. // --> if (attribute.startsWith("get_vehicle")) { if (entity.isInsideVehicle()) return new dEntity(entity.getVehicle()) .getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_effect[<effect>]> // @returns Element(Boolean) // @description // Returns whether the entity has a specified effect. // If no effect is specified, returns whether the entity has any effect. // --> // TODO: add list_effects ? if (attribute.startsWith("has_effect")) { Boolean returnElement = false; if (attribute.hasContext(1)) for (org.bukkit.potion.PotionEffect effect : getLivingEntity().getActivePotionEffects()) if (effect.getType().equals(PotionEffectType.getByName(attribute.getContext(1)))) returnElement = true; else if (!getLivingEntity().getActivePotionEffects().isEmpty()) returnElement = true; return new Element(returnElement).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns a formatted value of the player's current health level. // May be 'dying', 'seriously wounded', 'injured', 'scraped', or 'healthy'. // --> if (attribute.startsWith("health.formatted")) { double maxHealth = getLivingEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHealth = attribute.getIntContext(2); if ((float) getLivingEntity().getHealth() / maxHealth < .10) return new Element("dying").getAttribute(attribute.fulfill(2)); else if ((float) getLivingEntity().getHealth() / maxHealth < .40) return new Element("seriously wounded").getAttribute(attribute.fulfill(2)); else if ((float) getLivingEntity().getHealth() / maxHealth < .75) return new Element("injured").getAttribute(attribute.fulfill(2)); else if ((float) getLivingEntity().getHealth() / maxHealth < 1) return new Element("scraped").getAttribute(attribute.fulfill(2)); else return new Element("healthy").getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the maximum health of the entity. // --> if (attribute.startsWith("health.max")) return new Element(getLivingEntity().getMaxHealth()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the entity's current health as a percentage. // --> if (attribute.startsWith("health.percentage")) { double maxHealth = getLivingEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHealth = attribute.getIntContext(2); return new Element((getLivingEntity().getHealth() / maxHealth) * 100) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the current health of the entity. // --> if (attribute.startsWith("health")) return new Element(getLivingEntity().getHealth()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_empty> // @returns Element(Boolean) // @description // Returns whether the entity does not have a passenger. // --> if (attribute.startsWith("is_empty")) return new Element(entity.isEmpty()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_inside_vehicle> // @returns Element(Boolean) // @description // Returns whether the entity is inside a vehicle. // --> if (attribute.startsWith("is_inside_vehicle")) return new Element(entity.isInsideVehicle()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_leashed> // @returns Element(Boolean) // @description // Returns whether the entity is leashed. // --> if (attribute.startsWith("is_leashed")) { if (isLivingEntity()) return new Element(getLivingEntity().isLeashed()) .getAttribute(attribute.fulfill(1)); else return Element.FALSE .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_on_ground> // @returns Element(Boolean) // @description // Returns whether the entity is supported by a block. // --> if (attribute.startsWith("is_on_ground")) return new Element(entity.isOnGround()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_persistent> // @returns Element(Boolean) // @description // Returns whether the entity will not be removed completely when far away from players. // --> if (attribute.startsWith("is_persistent")) { if (isLivingEntity()) return new Element(!getLivingEntity().getRemoveWhenFarAway()) .getAttribute(attribute.fulfill(1)); else return Element.FALSE .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_spawned> // @returns Element(Boolean) // @description // Returns whether the entity is spawned. // --> if (attribute.startsWith("is_spawned")) { return new Element(isSpawned()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dPlayer // @description // Returns the player that last killed the entity. // --> if (attribute.startsWith("killer")) return new dPlayer(getLivingEntity().getKiller()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_damage.amount> // @returns Element(Decimal) // @description // Returns the amount of the last damage taken by the entity. // --> if (attribute.startsWith("last_damage.amount")) return new Element(getLivingEntity().getLastDamage()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_damage.cause> // @returns Element // @description // Returns the cause of the last damage taken by the entity. // --> if (attribute.startsWith("last_damage.cause")) return new Element(entity.getLastDamageCause().getCause().name()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_damage.duration> // @returns Duration // @description // Returns the duration of the last damage taken by the entity. // --> if (attribute.startsWith("last_damage.duration")) return new Duration((long) getLivingEntity().getNoDamageTicks()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Duration // @description // Returns the maximum duration of oxygen the entity can have. // --> if (attribute.startsWith("oxygen.max")) return new Duration((long) getLivingEntity().getMaximumAir()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Duration // @description // Returns the duration of oxygen the entity has left. // --> if (attribute.startsWith("oxygen")) return new Duration((long) getLivingEntity().getRemainingAir()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_when_far> // @returns Element(Boolean) // @description // Returns if the entity despawns when away from players. // --> if (attribute.startsWith("remove_when_far")) return new Element(getLivingEntity().getRemoveWhenFarAway()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_lived> // @returns Duration // @description // Returns how long the entity has lived. // --> if (attribute.startsWith("time_lived")) return new Duration(entity.getTicksLived() / 20) .getAttribute(attribute.fulfill(1)); ///////////////////// // TYPE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_type> // @returns Element // @description // Returns the type of the entity. // --> if (attribute.startsWith("entity_type")) { return new Element(entity_type.name()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_living> // @returns Element(Boolean) // @description // Returns whether the entity is a living entity. // --> if (attribute.startsWith("is_living")) { return new Element(isLivingEntity()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_mob> // @returns Element(Boolean) // @description // Returns whether the entity is a mob (Not a player or NPC). // --> if (attribute.startsWith("is_mob")) { if (!isPlayer() && !isNPC()) return Element.TRUE.getAttribute(attribute.fulfill(1)); else return Element.FALSE.getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_npc> // @returns Element(Boolean) // @description // Returns whether the entity is an NPC. // --> if (attribute.startsWith("is_npc")) { return new Element(isNPC()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_player> // @returns Element(Boolean) // @description // Returns whether the entity is a player. // --> if (attribute.startsWith("is_player")) { return new Element(isPlayer()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_projectile> // @returns Element(Boolean) // @description // Returns whether the entity is a projectile. // --> if (attribute.startsWith("is_projectile")) { return new Element(isProjectile()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_tameable> // @returns Element(Boolean) // @description // Returns whether the entity is tameable. // If this returns true, it will enable access to: // <@link mechanism dEntity.tame>, <@link mechanism dEntity.owner>, // <@link tag [email protected]_tamed>, and <@link tag [email protected]_owner> // --> if (attribute.startsWith("is_tameable")) return new Element(EntityTame.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_ageable> // @returns Element(Boolean) // @description // Returns whether the entity is ageable. // If this returns true, it will enable access to: // <@link mechanism dEntity.age>, <@link mechanism dEntity.age_lock>, // <@link tag [email protected]_baby>, <@link tag [email protected]>, // and <@link tag [email protected]_age_locked> // --> if (attribute.startsWith("is_ageable")) return new Element(EntityAge.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_frame> // @returns Element(Boolean) // @description // Returns whether the entity can hold a framed item. // If this returns true, it will enable access to: // <@link mechanism dEntity.framed>, <@link tag [email protected]_item>, // <@link tag [email protected]_framed_item>, and <@link tag [email protected]_item_rotation> // --> if (attribute.startsWith("is_frame")) return new Element(EntityFramed.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_colorable> // @returns Element(Boolean) // @description // Returns whether the entity can be colored. // If this returns true, it will enable access to: // <@link mechanism dEntity.color> and <@link tag [email protected]> // --> if (attribute.startsWith("is_colorable")) return new Element(EntityColor.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_powerable> // @returns Element(Boolean) // @description // Returns whether the entity can be powered. // If this returns true, it will enable access to: // <@link mechanism dEntity.powered> and <@link tag [email protected]> // --> if (attribute.startsWith("is_powerable")) return new Element(EntityPowered.describes(this)) .getAttribute(attribute.fulfill(1)); ///////////////////// // PROPERTY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Boolean) // @description // Returns the entity's full description, including all properties. // --> if (attribute.startsWith("describe")) return new Element("e@" + getEntityType().name().toLowerCase() + PropertyParser.getPropertiesString(this)) .getAttribute(attribute.fulfill(1)); // Iterate through this object's properties' attributes for (Property property : PropertyParser.getProperties(this)) { String returned = property.getAttribute(attribute); if (returned != null) return returned; } return new Element(identify()).getAttribute(attribute); }
public String getAttribute(Attribute attribute) { if (attribute == null) return null; if (entity == null) { dB.echoError("dEntity has returned null."); return Element.NULL.getAttribute(attribute); } ///////////////////// // DEBUG ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Boolean) // @description // Debugs the entity in the log and returns true. // --> if (attribute.startsWith("debug.log")) { dB.log(debug()); return new Element(Boolean.TRUE.toString()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_color> // @returns Element // @description // Returns the entity's debug with no color. // --> if (attribute.startsWith("debug.no_color")) { return new Element(ChatColor.stripColor(debug())) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the entity's debug. // --> if (attribute.startsWith("debug")) { return new Element(debug()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the prefix of the entity. // --> if (attribute.startsWith("prefix")) return new Element(prefix) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns 'Entity', the type of this dObject. // --> if (attribute.startsWith("type")) { return new Element(getObjectType()) .getAttribute(attribute.fulfill(1)); } ///////////////////// // IDENTIFICATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_id> // @returns dScript/Element // @description // If the entity has a script ID, returns the dScript of that ID. // Otherwise, returns the name of the entity type. // --> if (attribute.startsWith("custom_id")) { if (CustomNBT.hasCustomNBT(getLivingEntity(), "denizen-script-id")) return new dScript(CustomNBT.getCustomNBT(getLivingEntity(), "denizen-script-id")) .getAttribute(attribute.fulfill(1)); else return new Element(entity.getType().name()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_name> // @returns Element // @description // If the entity has a custom name, returns the name as an Element. // Otherwise, returns null. // --> if (attribute.startsWith("custom_name")) { if (getLivingEntity().getCustomName() == null) return "null"; return new Element(getLivingEntity().getCustomName()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_name.visible> // @returns Element(Boolean) // @description // Returns true if the entity's custom name is visible. // --> if (attribute.startsWith("custom_name.visible")) return new Element(getLivingEntity().isCustomNameVisible()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Number) // @description // Returns the entity's temporary server entity ID. // --> if (attribute.startsWith("eid")) return new Element(entity.getEntityId()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the name of the entity. // --> if (attribute.startsWith("name")) { if (isNPC()) return new Element(getNPC().getName()) .getAttribute(attribute.fulfill(1)); if (entity instanceof Player) return new Element(((Player) entity).getName()) .getAttribute(attribute.fulfill(1)); return new Element(entity.getType().getName()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_reason> // @returns String // @description // Returns the reason an entity was spawned. // --> if (attribute.startsWith("spawn_reason")) { if (entity.getMetadata("spawnreason").size() == 0) return "null"; return new Element(entity.getMetadata("spawnreason").get(0).asString()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns the permanent unique ID of the entity. // --> if (attribute.startsWith("uuid")) return new Element(getUUID().toString()) .getAttribute(attribute.fulfill(1)); ///////////////////// // INVENTORY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as boots, or null // if none. // --> if (attribute.startsWith("equipment.boots")) { if (getLivingEntity().getEquipment().getBoots() != null) { return new dItem(getLivingEntity().getEquipment().getBoots()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as a chestplate, or null // if none. // --> else if (attribute.startsWith("equipment.chestplate") || attribute.startsWith("equipment.chest")) { if (getLivingEntity().getEquipment().getChestplate() != null) { return new dItem(getLivingEntity().getEquipment().getChestplate()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as a helmet, or null // if none. // --> else if (attribute.startsWith("equipment.helmet") || attribute.startsWith("equipment.head")) { if (getLivingEntity().getEquipment().getHelmet() != null) { return new dItem(getLivingEntity().getEquipment().getHelmet()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dItem // @description // returns the item the entity is wearing as leggings, or null // if none. // --> else if (attribute.startsWith("equipment.leggings") || attribute.startsWith("equipment.legs")) { if (getLivingEntity().getEquipment().getLeggings() != null) { return new dItem(getLivingEntity().getEquipment().getLeggings()) .getAttribute(attribute.fulfill(2)); } } // <--[tag] // @attribute <[email protected]> // @returns dInventory // @description // returns a dInventory containing the entity's equipment. // --> else if (attribute.startsWith("equipment")) { // The only way to return correct size for dInventory // created from equipment is to use a CRAFTING type // that has the expected 4 slots return getEquipment().getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_in_hand> // @returns dItem // @description // returns the item the entity is holding, or i@air // if none. // --> if (attribute.startsWith("item_in_hand") || attribute.startsWith("iteminhand")) return new dItem(getLivingEntity().getEquipment().getItemInHand()) .getAttribute(attribute.fulfill(1)); ///////////////////// // LOCATION ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_see[<entity>]> // @returns Element(Boolean) // @description // Returns whether the entity can see the specified other entity. // --> if (attribute.startsWith("can_see")) { if (attribute.hasContext(1) && dEntity.matches(attribute.getContext(1))) { dEntity toEntity = dEntity.valueOf(attribute.getContext(1)); return new Element(getLivingEntity().hasLineOfSight(toEntity.getBukkitEntity())).getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <[email protected]_location> // @returns dLocation // @description // returns the location of the entity's eyes. // --> if (attribute.startsWith("eye_location")) return new dLocation(getEyeLocation()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_eye_height> // @returns Element(Boolean) // @description // Returns the height of the entity's eyes above its location. // --> if (attribute.startsWith("get_eye_height")) { if (isLivingEntity()) return new Element(getLivingEntity().getEyeHeight()) .getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_on[<range>]> // @returns dLocation // @description // Returns the location of the block the entity is looking at. // Optionally, specify a maximum range to find the location from. // --> if (attribute.startsWith("location.cursor_on")) { int range = attribute.getIntContext(2); if (range < 1) range = 50; return new dLocation(getLivingEntity().getTargetBlock(null, range).getLocation().clone()) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]_on> // @returns dLocation // @description // Returns the location of what the entity is standing on. // --> if (attribute.startsWith("location.standing_on")) return new dLocation(entity.getLocation().clone().add(0, -1, 0)) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the location of the entity. // --> if (attribute.startsWith("location")) { return new dLocation(entity.getLocation()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dLocation // @description // Returns the movement velocity of the entity. // Note: Does not accurately calculate player clientside movement velocity. // --> if (attribute.startsWith("velocity")) { return new dLocation(entity.getVelocity().toLocation(entity.getWorld())) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dWorld // @description // Returns the world the entity is in. // --> if (attribute.startsWith("world")) { return new dWorld(entity.getWorld()) .getAttribute(attribute.fulfill(1)); } ///////////////////// // STATE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_pickup_items> // @returns Element(Boolean) // @description // Returns whether the entity can pick up items. // --> if (attribute.startsWith("can_pickup_items")) return new Element(getLivingEntity().getCanPickupItems()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_distance> // @returns Element(Decimal) // @description // Returns how far the entity has fallen. // --> if (attribute.startsWith("fall_distance")) return new Element(entity.getFallDistance()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_time> // @returns Duration // @description // Returns the duration for which the entity will remain on fire // --> if (attribute.startsWith("fire_time")) return new Duration(entity.getFireTicks() / 20) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_leash_holder> // @returns dPlayer // @description // Returns the leash holder of entity. // --> if (attribute.startsWith("get_leash_holder")) { if (isLivingEntity() && getLivingEntity().isLeashed()) { return new dEntity(getLivingEntity().getLeashHolder()) .getAttribute(attribute.fulfill(1)); } else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_passenger> // @returns dEntity // @description // If the entity has a passenger, returns the passenger as a dEntity. // Otherwise, returns null. // --> if (attribute.startsWith("get_passenger")) { if (!entity.isEmpty()) return new dEntity(entity.getPassenger()) .getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_shooter> // @returns dEntity // @description // If the entity is a projectile with a shooter, gets its shooter // Otherwise, returns null. // --> if (attribute.startsWith("get_shooter") || attribute.startsWith("shooter")) { if (isProjectile() && hasShooter()) return getShooter().getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_vehicle> // @returns dEntity // @description // If the entity is in a vehicle, returns the vehicle as a dEntity. // Otherwise, returns null. // --> if (attribute.startsWith("get_vehicle")) { if (entity.isInsideVehicle()) return new dEntity(entity.getVehicle()) .getAttribute(attribute.fulfill(1)); else return new Element("null") .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_effect[<effect>]> // @returns Element(Boolean) // @description // Returns whether the entity has a specified effect. // If no effect is specified, returns whether the entity has any effect. // --> // TODO: add list_effects ? if (attribute.startsWith("has_effect")) { Boolean returnElement = false; if (attribute.hasContext(1)) { for (org.bukkit.potion.PotionEffect effect : getLivingEntity().getActivePotionEffects()) if (effect.getType().equals(PotionEffectType.getByName(attribute.getContext(1)))) returnElement = true; } else if (!getLivingEntity().getActivePotionEffects().isEmpty()) returnElement = true; return new Element(returnElement).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns Element // @description // Returns a formatted value of the player's current health level. // May be 'dying', 'seriously wounded', 'injured', 'scraped', or 'healthy'. // --> if (attribute.startsWith("health.formatted")) { double maxHealth = getLivingEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHealth = attribute.getIntContext(2); if ((float) getLivingEntity().getHealth() / maxHealth < .10) return new Element("dying").getAttribute(attribute.fulfill(2)); else if ((float) getLivingEntity().getHealth() / maxHealth < .40) return new Element("seriously wounded").getAttribute(attribute.fulfill(2)); else if ((float) getLivingEntity().getHealth() / maxHealth < .75) return new Element("injured").getAttribute(attribute.fulfill(2)); else if ((float) getLivingEntity().getHealth() / maxHealth < 1) return new Element("scraped").getAttribute(attribute.fulfill(2)); else return new Element("healthy").getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the maximum health of the entity. // --> if (attribute.startsWith("health.max")) return new Element(getLivingEntity().getMaxHealth()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the entity's current health as a percentage. // --> if (attribute.startsWith("health.percentage")) { double maxHealth = getLivingEntity().getMaxHealth(); if (attribute.hasContext(2)) maxHealth = attribute.getIntContext(2); return new Element((getLivingEntity().getHealth() / maxHealth) * 100) .getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <[email protected]> // @returns Element(Decimal) // @description // Returns the current health of the entity. // --> if (attribute.startsWith("health")) return new Element(getLivingEntity().getHealth()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_empty> // @returns Element(Boolean) // @description // Returns whether the entity does not have a passenger. // --> if (attribute.startsWith("is_empty")) return new Element(entity.isEmpty()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_inside_vehicle> // @returns Element(Boolean) // @description // Returns whether the entity is inside a vehicle. // --> if (attribute.startsWith("is_inside_vehicle")) return new Element(entity.isInsideVehicle()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_leashed> // @returns Element(Boolean) // @description // Returns whether the entity is leashed. // --> if (attribute.startsWith("is_leashed")) { if (isLivingEntity()) return new Element(getLivingEntity().isLeashed()) .getAttribute(attribute.fulfill(1)); else return Element.FALSE .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_on_ground> // @returns Element(Boolean) // @description // Returns whether the entity is supported by a block. // --> if (attribute.startsWith("is_on_ground")) return new Element(entity.isOnGround()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_persistent> // @returns Element(Boolean) // @description // Returns whether the entity will not be removed completely when far away from players. // --> if (attribute.startsWith("is_persistent")) { if (isLivingEntity()) return new Element(!getLivingEntity().getRemoveWhenFarAway()) .getAttribute(attribute.fulfill(1)); else return Element.FALSE .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_spawned> // @returns Element(Boolean) // @description // Returns whether the entity is spawned. // --> if (attribute.startsWith("is_spawned")) { return new Element(isSpawned()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]> // @returns dPlayer // @description // Returns the player that last killed the entity. // --> if (attribute.startsWith("killer")) return new dPlayer(getLivingEntity().getKiller()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_damage.amount> // @returns Element(Decimal) // @description // Returns the amount of the last damage taken by the entity. // --> if (attribute.startsWith("last_damage.amount")) return new Element(getLivingEntity().getLastDamage()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_damage.cause> // @returns Element // @description // Returns the cause of the last damage taken by the entity. // --> if (attribute.startsWith("last_damage.cause")) return new Element(entity.getLastDamageCause().getCause().name()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]_damage.duration> // @returns Duration // @description // Returns the duration of the last damage taken by the entity. // --> if (attribute.startsWith("last_damage.duration")) return new Duration((long) getLivingEntity().getNoDamageTicks()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <[email protected]> // @returns Duration // @description // Returns the maximum duration of oxygen the entity can have. // --> if (attribute.startsWith("oxygen.max")) return new Duration((long) getLivingEntity().getMaximumAir()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]> // @returns Duration // @description // Returns the duration of oxygen the entity has left. // --> if (attribute.startsWith("oxygen")) return new Duration((long) getLivingEntity().getRemainingAir()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_when_far> // @returns Element(Boolean) // @description // Returns if the entity despawns when away from players. // --> if (attribute.startsWith("remove_when_far")) return new Element(getLivingEntity().getRemoveWhenFarAway()) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_lived> // @returns Duration // @description // Returns how long the entity has lived. // --> if (attribute.startsWith("time_lived")) return new Duration(entity.getTicksLived() / 20) .getAttribute(attribute.fulfill(1)); ///////////////////// // TYPE ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]_type> // @returns Element // @description // Returns the type of the entity. // --> if (attribute.startsWith("entity_type")) { return new Element(entity_type.name()).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_living> // @returns Element(Boolean) // @description // Returns whether the entity is a living entity. // --> if (attribute.startsWith("is_living")) { return new Element(isLivingEntity()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_mob> // @returns Element(Boolean) // @description // Returns whether the entity is a mob (Not a player or NPC). // --> if (attribute.startsWith("is_mob")) { if (!isPlayer() && !isNPC()) return Element.TRUE.getAttribute(attribute.fulfill(1)); else return Element.FALSE.getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_npc> // @returns Element(Boolean) // @description // Returns whether the entity is an NPC. // --> if (attribute.startsWith("is_npc")) { return new Element(isNPC()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_player> // @returns Element(Boolean) // @description // Returns whether the entity is a player. // --> if (attribute.startsWith("is_player")) { return new Element(isPlayer()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_projectile> // @returns Element(Boolean) // @description // Returns whether the entity is a projectile. // --> if (attribute.startsWith("is_projectile")) { return new Element(isProjectile()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <[email protected]_tameable> // @returns Element(Boolean) // @description // Returns whether the entity is tameable. // If this returns true, it will enable access to: // <@link mechanism dEntity.tame>, <@link mechanism dEntity.owner>, // <@link tag [email protected]_tamed>, and <@link tag [email protected]_owner> // --> if (attribute.startsWith("is_tameable")) return new Element(EntityTame.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_ageable> // @returns Element(Boolean) // @description // Returns whether the entity is ageable. // If this returns true, it will enable access to: // <@link mechanism dEntity.age>, <@link mechanism dEntity.age_lock>, // <@link tag [email protected]_baby>, <@link tag [email protected]>, // and <@link tag [email protected]_age_locked> // --> if (attribute.startsWith("is_ageable")) return new Element(EntityAge.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_frame> // @returns Element(Boolean) // @description // Returns whether the entity can hold a framed item. // If this returns true, it will enable access to: // <@link mechanism dEntity.framed>, <@link tag [email protected]_item>, // <@link tag [email protected]_framed_item>, and <@link tag [email protected]_item_rotation> // --> if (attribute.startsWith("is_frame")) return new Element(EntityFramed.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_colorable> // @returns Element(Boolean) // @description // Returns whether the entity can be colored. // If this returns true, it will enable access to: // <@link mechanism dEntity.color> and <@link tag [email protected]> // --> if (attribute.startsWith("is_colorable")) return new Element(EntityColor.describes(this)) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <[email protected]_powerable> // @returns Element(Boolean) // @description // Returns whether the entity can be powered. // If this returns true, it will enable access to: // <@link mechanism dEntity.powered> and <@link tag [email protected]> // --> if (attribute.startsWith("is_powerable")) return new Element(EntityPowered.describes(this)) .getAttribute(attribute.fulfill(1)); ///////////////////// // PROPERTY ATTRIBUTES ///////////////// // <--[tag] // @attribute <[email protected]> // @returns Element(Boolean) // @description // Returns the entity's full description, including all properties. // --> if (attribute.startsWith("describe")) return new Element("e@" + getEntityType().name().toLowerCase() + PropertyParser.getPropertiesString(this)) .getAttribute(attribute.fulfill(1)); // Iterate through this object's properties' attributes for (Property property : PropertyParser.getProperties(this)) { String returned = property.getAttribute(attribute); if (returned != null) return returned; } return new Element(identify()).getAttribute(attribute); }
diff --git a/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/keyboard/KeyboardTest.java b/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/keyboard/KeyboardTest.java index 143eb44..546625a 100644 --- a/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/keyboard/KeyboardTest.java +++ b/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/keyboard/KeyboardTest.java @@ -1,263 +1,263 @@ /******************************************************************************* * Copyright (c) 2009 Ketan Padegaonkar and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Ketan Padegaonkar - initial API and implementation *******************************************************************************/ package org.eclipse.swtbot.swt.finder.keyboard; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jface.bindings.keys.KeyStroke; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.finders.AbstractSWTTestCase; import org.eclipse.swtbot.swt.finder.widgets.SWTBotStyledText; import org.eclipse.swtbot.swt.finder.widgets.SWTBotText; import org.junit.Test; /** * @author Ketan Padegaonkar &lt;KetanPadegaonkar [at] gmail [dot] com&gt; * @version $Id$ */ public class KeyboardTest extends AbstractSWTTestCase { private SWTBotStyledText styledText; private SWTBotText listeners; private Keyboard keyboard; @Test public void canTypeShiftKey() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=332938450 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=332938540 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canTypeCTRLKey() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334095974 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334096084 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canTypeAltKey() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337927063 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337927163 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canType_CTRL_SHIFT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334163451 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334163611 data=null character='\\0' keyCode=131072 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334163782 data=null character='\\0' keyCode=131072 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334163832 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canType_SHIFT_CTRL_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT, Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334173686 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334173996 data=null character='\\0' keyCode=262144 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334174277 data=null character='\\0' keyCode=262144 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334174347 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canType_CTRL_ALT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334364901 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334365191 data=null character='\\0' keyCode=65536 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334365331 data=null character='\\0' keyCode=65536 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334365492 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canType_ALT_CTRL_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT, Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334374164 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334374324 data=null character='\\0' keyCode=262144 stateMask=65536 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334374475 data=null character='\\0' keyCode=262144 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334374495 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canType_SHIFT_ALT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT, Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334403126 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334403236 data=null character='\\0' keyCode=65536 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334403366 data=null character='\\0' keyCode=65536 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334403426 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canType_ALT_SHIFT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT, Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334417126 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334417456 data=null character='\\0' keyCode=131072 stateMask=65536 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334417526 data=null character='\\0' keyCode=131072 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334417577 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canType_SHIFT_CTRL_ALT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT, Keystrokes.CTRL, Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=336998217 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=336998548 data=null character='\\0' keyCode=262144 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=336998858 data=null character='\\0' keyCode=65536 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=336998938 data=null character='\\0' keyCode=65536 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337000000 data=null character='\\0' keyCode=262144 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337000330 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canType_SHIFT_ALT_CTRL_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT, Keystrokes.ALT, Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337024085 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337024595 data=null character='\\0' keyCode=65536 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337025316 data=null character='\\0' keyCode=262144 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337026738 data=null character='\\0' keyCode=262144 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337027700 data=null character='\\0' keyCode=65536 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337028090 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canType_CTRL_SHIFT_ALT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.SHIFT, Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337073666 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337074086 data=null character='\\0' keyCode=131072 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337074527 data=null character='\\0' keyCode=65536 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337074928 data=null character='\\0' keyCode=65536 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337075999 data=null character='\\0' keyCode=131072 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337076370 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canType_CTRL_ALT_SHIFT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.ALT, Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337084111 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337084592 data=null character='\\0' keyCode=65536 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337085162 data=null character='\\0' keyCode=131072 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337085753 data=null character='\\0' keyCode=131072 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337086184 data=null character='\\0' keyCode=65536 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337086584 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canType_ALT_CTRL_SHIFT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT, Keystrokes.CTRL, Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337516292 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337516753 data=null character='\\0' keyCode=262144 stateMask=65536 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337517113 data=null character='\\0' keyCode=131072 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337517985 data=null character='\\0' keyCode=131072 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337518335 data=null character='\\0' keyCode=262144 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337518686 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canType_ALT_SHIFT_CTRL_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT, Keystrokes.SHIFT, Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337527028 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337527649 data=null character='\\0' keyCode=131072 stateMask=65536 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337528209 data=null character='\\0' keyCode=262144 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337531534 data=null character='\\0' keyCode=262144 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337532275 data=null character='\\0' keyCode=131072 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337532666 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canTypeCTRL_SHIFT_T() throws Exception { styledText.setFocus(); keyboard.pressShortcut(keys(Keystrokes.CTRL, Keystrokes.SHIFT, Keystrokes.create('t'))); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=356391804 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=356392194 data=null character='\\0' keyCode=131072 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=356393156 data=null character='' keyCode=116 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=356392495 data=null character='' keyCode=116 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=356393987 data=null character='\\0' keyCode=131072 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=356394307 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canTypeSmallCharacters() throws Exception { styledText.setFocus(); keyboard.typeText("ab"); assertEventMatches(listeners.getText(), "Verify [25]: VerifyEvent{StyledText {} time=358259489 data=null character='\\0' keyCode=0 stateMask=0 doit=true start=0 end=0 text=a}"); assertEventMatches(listeners.getText(), "Modify [24]: ModifyEvent{StyledText {} time=358259489 data=null}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=358259489 data=null character='a' keyCode=97 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=358259560 data=null character='a' keyCode=97 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "Verify [25]: VerifyEvent{StyledText {} time=358264617 data=null character='\\0' keyCode=0 stateMask=0 doit=true start=1 end=1 text=b}"); assertEventMatches(listeners.getText(), "Modify [24]: ModifyEvent{StyledText {} time=358264617 data=null}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=358264617 data=null character='b' keyCode=98 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=358259810 data=null character='b' keyCode=98 stateMask=0 doit=true}"); } @Test public void canTypeCapitalCharacters() throws Exception { styledText.setFocus(); keyboard.typeText("A"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=359800165 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "Verify [25]: VerifyEvent{StyledText {} time=359800285 data=null character='\\0' keyCode=0 stateMask=0 doit=true start=0 end=0 text=A}"); assertEventMatches(listeners.getText(), "Modify [24]: ModifyEvent{StyledText {} time=359800285 data=null}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=359800285 data=null character='A' keyCode=97 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=359800405 data=null character='A' keyCode=97 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=359800485 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canTypeCTRL_SPACE() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.create(' ')[0]); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=41517702 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "Modify [24]: ModifyEvent{StyledText {} time=41517983 data=null}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=41517983 data=null character=' ' keyCode=32 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=41518070 data=null character=' ' keyCode=32 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=41518278 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } private List<KeyStroke> keys(KeyStroke ctrl, KeyStroke shift, KeyStroke[] keyStrokes) { List<KeyStroke> keys = new ArrayList<KeyStroke>(); keys.add(ctrl); keys.add(shift); keys.addAll(Arrays.asList(keyStrokes)); return keys; } public void setUp() throws Exception { super.setUp(); bot = new SWTBot(); - keyboard = new Keyboard(display); + keyboard = new Keyboard(); bot.shell("SWT Custom Controls").activate(); bot.tabItem("StyledText").activate(); bot.checkBox("Horizontal Fill").select(); bot.checkBox("Vertical Fill").select(); bot.checkBox("Listen").deselect(); bot.checkBox("Listen").select(); styledText = bot.styledTextInGroup("StyledText"); styledText.setText(""); bot.button("Clear").click(); listeners = bot.textInGroup("Listeners"); } }
true
true
public void setUp() throws Exception { super.setUp(); bot = new SWTBot(); keyboard = new Keyboard(display); bot.shell("SWT Custom Controls").activate(); bot.tabItem("StyledText").activate(); bot.checkBox("Horizontal Fill").select(); bot.checkBox("Vertical Fill").select(); bot.checkBox("Listen").deselect(); bot.checkBox("Listen").select(); styledText = bot.styledTextInGroup("StyledText"); styledText.setText(""); bot.button("Clear").click(); listeners = bot.textInGroup("Listeners"); }
public void setUp() throws Exception { super.setUp(); bot = new SWTBot(); keyboard = new Keyboard(); bot.shell("SWT Custom Controls").activate(); bot.tabItem("StyledText").activate(); bot.checkBox("Horizontal Fill").select(); bot.checkBox("Vertical Fill").select(); bot.checkBox("Listen").deselect(); bot.checkBox("Listen").select(); styledText = bot.styledTextInGroup("StyledText"); styledText.setText(""); bot.button("Clear").click(); listeners = bot.textInGroup("Listeners"); }
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/config/DeploymentsResolver.java b/container/openejb-core/src/main/java/org/apache/openejb/config/DeploymentsResolver.java index 14eaa1fdd9..f095b07334 100644 --- a/container/openejb-core/src/main/java/org/apache/openejb/config/DeploymentsResolver.java +++ b/container/openejb-core/src/main/java/org/apache/openejb/config/DeploymentsResolver.java @@ -1,302 +1,302 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.config; import org.apache.openejb.config.sys.Deployments; import org.apache.openejb.config.sys.JaxbOpenejb; import org.apache.openejb.loader.FileUtils; import org.apache.openejb.loader.SystemInstance; import org.apache.openejb.util.Logger; import org.apache.xbean.finder.UrlSet; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; /** * @version $Rev$ $Date$ */ public class DeploymentsResolver { private static final String CLASSPATH_INCLUDE = "openejb.deployments.classpath.include"; private static final String CLASSPATH_EXCLUDE = "openejb.deployments.classpath.exclude"; private static final String CLASSPATH_REQUIRE_DESCRIPTOR = "openejb.deployments.classpath.require.descriptor"; private static final String CLASSPATH_FILTER_DESCRIPTORS = "openejb.deployments.classpath.filter.descriptors"; private static final String CLASSPATH_FILTER_SYSTEMAPPS = "openejb.deployments.classpath.filter.systemapps"; private static final Logger logger = DeploymentLoader.logger; private static void loadFrom(Deployments dep, FileUtils path, List<String> jarList) { //////////////////////////////// // // Expand the path of a jar // //////////////////////////////// if (dep.getDir() == null && dep.getJar() != null) { try { File jar = path.getFile(dep.getJar(), false); if (!jarList.contains(jar.getAbsolutePath())) { jarList.add(jar.getAbsolutePath()); } } catch (Exception ignored) { } return; } File dir = null; try { dir = path.getFile(dep.getDir(), false); } catch (Exception ignored) { } if (dir == null || !dir.isDirectory()) return; //////////////////////////////// // // Unpacked "Jar" directory // //////////////////////////////// File ejbJarXml = new File(dir, "META-INF" + File.separator + "ejb-jar.xml"); if (ejbJarXml.exists()) { if (!jarList.contains(dir.getAbsolutePath())) { jarList.add(dir.getAbsolutePath()); } return; } File appXml = new File(dir, "META-INF" + File.separator + "application.xml"); if (appXml.exists()) { if (!jarList.contains(dir.getAbsolutePath())) { jarList.add(dir.getAbsolutePath()); } return; } HashMap<String, URL> files = new HashMap<String, URL>(); DeploymentLoader.scanDir(dir, files, ""); for (String fileName : files.keySet()) { if (fileName.endsWith(".class")) { if (!jarList.contains(dir.getAbsolutePath())) { jarList.add(dir.getAbsolutePath()); } return; } } //////////////////////////////// // // Directory contains Jar files // //////////////////////////////// for (String fileName : files.keySet()) { if (fileName.endsWith(".jar") || fileName.endsWith(".ear")) { File jar = new File(dir, fileName); if (jarList.contains(jar.getAbsolutePath())) continue; jarList.add(jar.getAbsolutePath()); } } } public static List<String> resolveAppLocations(List<Deployments> deployments) { // make a copy of the list because we update it deployments = new ArrayList<Deployments>(deployments); //// getOption ///////////////////////////////// BEGIN //////////////////// String flag = SystemInstance.get().getProperty("openejb.deployments.classpath", "true").toLowerCase(); boolean searchClassPath = flag.equals("true"); //// getOption ///////////////////////////////// END //////////////////// if (searchClassPath) { Deployments deployment = JaxbOpenejb.createDeployments(); deployment.setClasspath(Thread.currentThread().getContextClassLoader()); deployments.add(deployment); } // resolve jar locations ////////////////////////////////////// BEGIN /////// FileUtils base = SystemInstance.get().getBase(); List<String> jarList = new ArrayList<String>(deployments.size()); try { for (Deployments deployment : deployments) { if (deployment.getClasspath() != null) { loadFromClasspath(base, jarList, deployment.getClasspath()); } else { loadFrom(deployment, base, jarList); } } } catch (SecurityException ignored) { } return jarList; } /** * The algorithm of OpenEJB deployments class-path inclusion and exclusion is implemented as follows: * 1- If the string value of the resource URL matches the include class-path pattern * Then load this resource * 2- If the string value of the resource URL matches the exclude class-path pattern * Then ignore this resource * 3- If the include and exclude class-path patterns are not defined * Then load this resource * <p/> * The previous steps are based on the following points: * 1- Include class-path pattern has the highst priority * This helps in case both patterns are defined using the same values. * This appears in step 1 and 2 of the above algorithm. * 2- Loading the resource is the default behaviour in case of not defining a value for any class-path pattern * This appears in step 3 of the above algorithm. */ private static void loadFromClasspath(FileUtils base, List<String> jarList, ClassLoader classLoader) { Deployments deployment = null; String include = null; String exclude = null; String path = null; include = SystemInstance.get().getProperty(CLASSPATH_INCLUDE, ""); exclude = SystemInstance.get().getProperty(CLASSPATH_EXCLUDE, ".*"); boolean requireDescriptors = SystemInstance.get().getProperty(CLASSPATH_REQUIRE_DESCRIPTOR, "false").equalsIgnoreCase("true"); boolean filterDescriptors = SystemInstance.get().getProperty(CLASSPATH_FILTER_DESCRIPTORS, "false").equalsIgnoreCase("true"); boolean filterSystemApps = SystemInstance.get().getProperty(CLASSPATH_FILTER_SYSTEMAPPS, "true").equalsIgnoreCase("true"); logger.debug("Using "+CLASSPATH_INCLUDE+" '"+include+"'"); logger.debug("Using "+CLASSPATH_EXCLUDE+" '"+exclude+"'"); logger.debug("Using "+CLASSPATH_FILTER_SYSTEMAPPS+" '"+filterSystemApps+"'"); logger.debug("Using "+CLASSPATH_FILTER_DESCRIPTORS+" '"+filterDescriptors+"'"); logger.debug("Using "+CLASSPATH_REQUIRE_DESCRIPTOR+" '"+requireDescriptors+"'"); try { UrlSet urlSet = new UrlSet(classLoader); UrlSet includes = urlSet.matching(include); urlSet = urlSet.exclude(ClassLoader.getSystemClassLoader().getParent()); urlSet = urlSet.excludeJavaExtDirs(); urlSet = urlSet.excludeJavaEndorsedDirs(); urlSet = urlSet.excludeJavaHome(); urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", "")); urlSet = urlSet.exclude(".*/JavaVM.framework/.*"); UrlSet prefiltered = urlSet; urlSet = urlSet.exclude(exclude); urlSet = urlSet.include(includes); if (filterSystemApps){ urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); } List<URL> urls = urlSet.getUrls(); int size = urls.size(); if (size == 0 && include.length() > 0) { logger.warning("No classpath URLs matched. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); return; } else if (size == 0 && (!filterDescriptors && prefiltered.getUrls().size() == 0)) { return; } else if (size < 10) { logger.debug("Inspecting classpath for applications: " + urls.size() + " urls."); } else if (size < 50 && !requireDescriptors) { logger.info("Inspecting classpath for applications: " + urls.size() + " urls. Consider adjusting your exclude/include. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } else if (!requireDescriptors) { logger.warning("Inspecting classpath for applications: " + urls.size() + " urls."); logger.warning("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } long begin = System.currentTimeMillis(); processUrls(urls, classLoader, !requireDescriptors, base, jarList); long end = System.currentTimeMillis(); long time = end - begin; UrlSet unchecked = new UrlSet(); if (!filterDescriptors){ unchecked = prefiltered.exclude(urlSet); if (filterSystemApps){ - urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); + unchecked = unchecked.exclude(".*/openejb-[^/]+(.(jar|ear|war)(./)?|/target/classes/?)"); } processUrls(unchecked.getUrls(), classLoader, false, base, jarList); } if (logger.isDebugEnabled()) { logger.debug("URLs after filtering: "+urlSet.getUrls().size() + unchecked.getUrls().size()); for (URL url : urlSet.getUrls()) { logger.debug("Annotations path: " + url); } for (URL url : unchecked.getUrls()) { logger.debug("Descriptors path: " + url); } } if (urls.size() == 0) return; if (time < 1000) { logger.debug("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 4000 || urls.size() < 3) { logger.info("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 10000) { logger.warning("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); logger.warning("Consider adjusting your " + CLASSPATH_EXCLUDE + " and " + CLASSPATH_INCLUDE + " settings. Current settings: exclude='" + exclude + "', include='" + include + "'"); } else { logger.fatal("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url. TOO LONG!"); logger.fatal("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); List<String> list = new ArrayList<String>(); for (URL url : urls) { list.add(url.toExternalForm()); } Collections.sort(list); for (String url : list) { logger.info("Matched: " + url); } } } catch (IOException e1) { e1.printStackTrace(); logger.warning("Unable to search classpath for modules: Received Exception: " + e1.getClass().getName() + " " + e1.getMessage(), e1); } } private static void processUrls(List<URL> urls, ClassLoader classLoader, boolean desc, FileUtils base, List<String> jarList) { Deployments deployment; String path; for (URL url : urls) { try { Class moduleType = DeploymentLoader.discoverModuleType(url, classLoader, desc); if (AppModule.class.isAssignableFrom(moduleType) || EjbModule.class.isAssignableFrom(moduleType)) { deployment = JaxbOpenejb.createDeployments(); if (url.getProtocol().equals("jar")) { url = new URL(url.getFile().replaceFirst("!.*$", "")); File file = new File(url.getFile()); path = file.getAbsolutePath(); deployment.setJar(path); } else if (url.getProtocol().equals("file")) { File file = new File(url.getFile()); path = file.getAbsolutePath(); deployment.setDir(path); } else { logger.warning("Not loading " + moduleType.getSimpleName() + ". Unknown protocol " + url.getProtocol()); continue; } logger.info("Found " + moduleType.getSimpleName() + " in classpath: " + path); loadFrom(deployment, base, jarList); } } catch (IOException e) { logger.warning("Unable to determine the module type of " + url.toExternalForm() + ": Exception: " + e.getMessage(), e); } catch (UnknownModuleTypeException ignore) { } } } }
true
true
private static void loadFromClasspath(FileUtils base, List<String> jarList, ClassLoader classLoader) { Deployments deployment = null; String include = null; String exclude = null; String path = null; include = SystemInstance.get().getProperty(CLASSPATH_INCLUDE, ""); exclude = SystemInstance.get().getProperty(CLASSPATH_EXCLUDE, ".*"); boolean requireDescriptors = SystemInstance.get().getProperty(CLASSPATH_REQUIRE_DESCRIPTOR, "false").equalsIgnoreCase("true"); boolean filterDescriptors = SystemInstance.get().getProperty(CLASSPATH_FILTER_DESCRIPTORS, "false").equalsIgnoreCase("true"); boolean filterSystemApps = SystemInstance.get().getProperty(CLASSPATH_FILTER_SYSTEMAPPS, "true").equalsIgnoreCase("true"); logger.debug("Using "+CLASSPATH_INCLUDE+" '"+include+"'"); logger.debug("Using "+CLASSPATH_EXCLUDE+" '"+exclude+"'"); logger.debug("Using "+CLASSPATH_FILTER_SYSTEMAPPS+" '"+filterSystemApps+"'"); logger.debug("Using "+CLASSPATH_FILTER_DESCRIPTORS+" '"+filterDescriptors+"'"); logger.debug("Using "+CLASSPATH_REQUIRE_DESCRIPTOR+" '"+requireDescriptors+"'"); try { UrlSet urlSet = new UrlSet(classLoader); UrlSet includes = urlSet.matching(include); urlSet = urlSet.exclude(ClassLoader.getSystemClassLoader().getParent()); urlSet = urlSet.excludeJavaExtDirs(); urlSet = urlSet.excludeJavaEndorsedDirs(); urlSet = urlSet.excludeJavaHome(); urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", "")); urlSet = urlSet.exclude(".*/JavaVM.framework/.*"); UrlSet prefiltered = urlSet; urlSet = urlSet.exclude(exclude); urlSet = urlSet.include(includes); if (filterSystemApps){ urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); } List<URL> urls = urlSet.getUrls(); int size = urls.size(); if (size == 0 && include.length() > 0) { logger.warning("No classpath URLs matched. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); return; } else if (size == 0 && (!filterDescriptors && prefiltered.getUrls().size() == 0)) { return; } else if (size < 10) { logger.debug("Inspecting classpath for applications: " + urls.size() + " urls."); } else if (size < 50 && !requireDescriptors) { logger.info("Inspecting classpath for applications: " + urls.size() + " urls. Consider adjusting your exclude/include. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } else if (!requireDescriptors) { logger.warning("Inspecting classpath for applications: " + urls.size() + " urls."); logger.warning("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } long begin = System.currentTimeMillis(); processUrls(urls, classLoader, !requireDescriptors, base, jarList); long end = System.currentTimeMillis(); long time = end - begin; UrlSet unchecked = new UrlSet(); if (!filterDescriptors){ unchecked = prefiltered.exclude(urlSet); if (filterSystemApps){ urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); } processUrls(unchecked.getUrls(), classLoader, false, base, jarList); } if (logger.isDebugEnabled()) { logger.debug("URLs after filtering: "+urlSet.getUrls().size() + unchecked.getUrls().size()); for (URL url : urlSet.getUrls()) { logger.debug("Annotations path: " + url); } for (URL url : unchecked.getUrls()) { logger.debug("Descriptors path: " + url); } } if (urls.size() == 0) return; if (time < 1000) { logger.debug("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 4000 || urls.size() < 3) { logger.info("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 10000) { logger.warning("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); logger.warning("Consider adjusting your " + CLASSPATH_EXCLUDE + " and " + CLASSPATH_INCLUDE + " settings. Current settings: exclude='" + exclude + "', include='" + include + "'"); } else { logger.fatal("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url. TOO LONG!"); logger.fatal("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); List<String> list = new ArrayList<String>(); for (URL url : urls) { list.add(url.toExternalForm()); } Collections.sort(list); for (String url : list) { logger.info("Matched: " + url); } } } catch (IOException e1) { e1.printStackTrace(); logger.warning("Unable to search classpath for modules: Received Exception: " + e1.getClass().getName() + " " + e1.getMessage(), e1); } }
private static void loadFromClasspath(FileUtils base, List<String> jarList, ClassLoader classLoader) { Deployments deployment = null; String include = null; String exclude = null; String path = null; include = SystemInstance.get().getProperty(CLASSPATH_INCLUDE, ""); exclude = SystemInstance.get().getProperty(CLASSPATH_EXCLUDE, ".*"); boolean requireDescriptors = SystemInstance.get().getProperty(CLASSPATH_REQUIRE_DESCRIPTOR, "false").equalsIgnoreCase("true"); boolean filterDescriptors = SystemInstance.get().getProperty(CLASSPATH_FILTER_DESCRIPTORS, "false").equalsIgnoreCase("true"); boolean filterSystemApps = SystemInstance.get().getProperty(CLASSPATH_FILTER_SYSTEMAPPS, "true").equalsIgnoreCase("true"); logger.debug("Using "+CLASSPATH_INCLUDE+" '"+include+"'"); logger.debug("Using "+CLASSPATH_EXCLUDE+" '"+exclude+"'"); logger.debug("Using "+CLASSPATH_FILTER_SYSTEMAPPS+" '"+filterSystemApps+"'"); logger.debug("Using "+CLASSPATH_FILTER_DESCRIPTORS+" '"+filterDescriptors+"'"); logger.debug("Using "+CLASSPATH_REQUIRE_DESCRIPTOR+" '"+requireDescriptors+"'"); try { UrlSet urlSet = new UrlSet(classLoader); UrlSet includes = urlSet.matching(include); urlSet = urlSet.exclude(ClassLoader.getSystemClassLoader().getParent()); urlSet = urlSet.excludeJavaExtDirs(); urlSet = urlSet.excludeJavaEndorsedDirs(); urlSet = urlSet.excludeJavaHome(); urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", "")); urlSet = urlSet.exclude(".*/JavaVM.framework/.*"); UrlSet prefiltered = urlSet; urlSet = urlSet.exclude(exclude); urlSet = urlSet.include(includes); if (filterSystemApps){ urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); } List<URL> urls = urlSet.getUrls(); int size = urls.size(); if (size == 0 && include.length() > 0) { logger.warning("No classpath URLs matched. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); return; } else if (size == 0 && (!filterDescriptors && prefiltered.getUrls().size() == 0)) { return; } else if (size < 10) { logger.debug("Inspecting classpath for applications: " + urls.size() + " urls."); } else if (size < 50 && !requireDescriptors) { logger.info("Inspecting classpath for applications: " + urls.size() + " urls. Consider adjusting your exclude/include. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } else if (!requireDescriptors) { logger.warning("Inspecting classpath for applications: " + urls.size() + " urls."); logger.warning("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } long begin = System.currentTimeMillis(); processUrls(urls, classLoader, !requireDescriptors, base, jarList); long end = System.currentTimeMillis(); long time = end - begin; UrlSet unchecked = new UrlSet(); if (!filterDescriptors){ unchecked = prefiltered.exclude(urlSet); if (filterSystemApps){ unchecked = unchecked.exclude(".*/openejb-[^/]+(.(jar|ear|war)(./)?|/target/classes/?)"); } processUrls(unchecked.getUrls(), classLoader, false, base, jarList); } if (logger.isDebugEnabled()) { logger.debug("URLs after filtering: "+urlSet.getUrls().size() + unchecked.getUrls().size()); for (URL url : urlSet.getUrls()) { logger.debug("Annotations path: " + url); } for (URL url : unchecked.getUrls()) { logger.debug("Descriptors path: " + url); } } if (urls.size() == 0) return; if (time < 1000) { logger.debug("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 4000 || urls.size() < 3) { logger.info("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 10000) { logger.warning("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); logger.warning("Consider adjusting your " + CLASSPATH_EXCLUDE + " and " + CLASSPATH_INCLUDE + " settings. Current settings: exclude='" + exclude + "', include='" + include + "'"); } else { logger.fatal("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url. TOO LONG!"); logger.fatal("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); List<String> list = new ArrayList<String>(); for (URL url : urls) { list.add(url.toExternalForm()); } Collections.sort(list); for (String url : list) { logger.info("Matched: " + url); } } } catch (IOException e1) { e1.printStackTrace(); logger.warning("Unable to search classpath for modules: Received Exception: " + e1.getClass().getName() + " " + e1.getMessage(), e1); } }
diff --git a/src/com/leppie/dhd/PSCalibrator.java b/src/com/leppie/dhd/PSCalibrator.java index 18b17b7..91f10e5 100644 --- a/src/com/leppie/dhd/PSCalibrator.java +++ b/src/com/leppie/dhd/PSCalibrator.java @@ -1,340 +1,340 @@ package com.leppie.dhd; import java.util.*; import java.io.*; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.hardware.*; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; import android.widget.SeekBar.OnSeekBarChangeListener; class Calibration { static final String ps_kadc = "/sys/devices/virtual/optical_sensors/proximity/ps_kadc"; static int lt = -1; static int ht = -1; static int x = -1; static int a = -1; public static void applyAndSave(Context ctx, int lt, int ht) { SharedPreferences prefs = ctx.getSharedPreferences("PSCalibration", 0); Editor edit = prefs.edit(); edit.putInt("LT", lt); edit.putInt("HT", ht); edit.commit(); Log.i("saving values:", lt + " " + ht); apply(lt, ht); } static void apply(int ltv, int htv) { // save to static fields here lt = ltv; ht = htv; Log.i("Calibration", lt + " " + ht); int p1 = (0x5053 << 16) + ((lt & 0xff) << 8) + (ht & 0xff); int p2 = (a << 24) + (x << 16) + ((lt & 0xff) << 8) + (ht & 0xff); String output = "0x" + Integer.toHexString(p1) + " 0x" + Integer.toHexString(p2); Log.i("Writing", output); FileWriter fw; try { fw = new FileWriter(ps_kadc); fw.write(output); fw.write("\n"); fw.flush(); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static void applyAndNotify(Context ctx, int lt, int ht) { apply(lt, ht); Toast.makeText(ctx, "Proximity sensor recalibrated: LT=" + lt + " HT=" + ht, Toast.LENGTH_LONG).show(); } public static void applySaved(Context ctx) { SharedPreferences prefs = ctx.getSharedPreferences("PSCalibration", 0); int lt = prefs.getInt("LT", -1); int ht = prefs.getInt("HT", -1); Log.i("loading values:", lt + " " + ht); if (!(lt < 0 || ht < 0)) { applyAndNotify(ctx, lt, ht); } } public static int getLT() { if (lt < 0 || ht < 0) { getValues(); } return lt; } public static int getHT() { if (lt < 0 || ht < 0) { getValues(); } return ht; } @SuppressWarnings("unused") static void getValues() { try { FileReader fr = new FileReader(ps_kadc); char[] buf = new char[256]; int len = fr.read(buf); StringTokenizer tokens = new StringTokenizer(new String(buf, 0, len), "="); tokens.nextToken(); String values = tokens.nextToken().trim(); values = values.substring(1, values.length() - 1); tokens = new StringTokenizer(values, ", "); String B_value, C_value, A_value, X_value, THL, THH; B_value = tokens.nextToken(); C_value = tokens.nextToken(); A_value = tokens.nextToken(); X_value = tokens.nextToken(); THL = tokens.nextToken(); THH = tokens.nextToken(); a = Integer.parseInt(A_value.substring(2), 16) & 0xff; x = Integer.parseInt(X_value.substring(2), 16) & 0xff; lt = Integer.parseInt(THL.substring(2), 16); ht = Integer.parseInt(THH.substring(2), 16); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class PSCalibrator extends Activity implements SensorEventListener { SensorManager sensormanager; Sensor ps; SensorEventListener psevent; Context context; boolean running = false; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); context = getApplicationContext(); psevent = this; sensormanager = (SensorManager)getSystemService(SENSOR_SERVICE); ps = sensormanager.getDefaultSensor(Sensor.TYPE_PROXIMITY); final Button applybut = (Button) findViewById(R.id.applyBut); applybut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (running) { sensormanager.unregisterListener(psevent); setPSStatus("Not running"); applybut.setText("Start"); } else { sensormanager.registerListener(psevent, ps, SensorManager.SENSOR_DELAY_FASTEST); setPSStatus("Waiting for reading"); applybut.setText("Stop"); } running = !running; } }); final SeekBar ltslider = (SeekBar) findViewById(R.id.lt_slider); final SeekBar htslider = (SeekBar) findViewById(R.id.ht_slider); final TextView lt_value = (TextView) findViewById(R.id.lt_value); final TextView ht_value = (TextView) findViewById(R.id.ht_value); ltslider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { lt_value.setText(new Integer(progress).toString()); if (progress >= (htslider.getProgress() - 1)) { htslider.setProgress(progress + 1); } } }); htslider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { ht_value.setText(new Integer(progress).toString()); if (progress <= (ltslider.getProgress() + 1)) { ltslider.setProgress(progress - 1); } } }); ZoomControls ltzoom = (ZoomControls) findViewById(R.id.ltZoom); ZoomControls htzoom = (ZoomControls) findViewById(R.id.htZoom); ltzoom.setOnZoomInClickListener(new OnClickListener() { @Override public void onClick(View v) { ltslider.setProgress(ltslider.getProgress() + 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); ltzoom.setOnZoomOutClickListener(new OnClickListener() { @Override public void onClick(View v) { ltslider.setProgress(ltslider.getProgress() - 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); htzoom.setOnZoomInClickListener(new OnClickListener() { @Override public void onClick(View v) { htslider.setProgress(htslider.getProgress() + 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); htzoom.setOnZoomOutClickListener(new OnClickListener() { @Override public void onClick(View v) { htslider.setProgress(htslider.getProgress() - 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); Button b = (Button) findViewById(R.id.beerbut); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&[email protected]" + - "&item_name=DHD%20Proximity%20Recalibrator&no_shipping=1&currency_code=USD" ); + "&item_name=DHD%20Proximity%20Recalibrator&no_shipping=1&amount=2&currency_code=USD" ); startActivity(new Intent( Intent.ACTION_VIEW, uri ) ); } }); int lt = Calibration.getLT(); int ht = Calibration.getHT(); lt_value.setText(new Integer(lt).toString()); ht_value.setText(new Integer(ht).toString()); ltslider.setProgress(lt); htslider.setProgress(ht); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } void setPSStatus(String val) { TextView psstatus = (TextView) findViewById(R.id.ps_status); psstatus.setText(val); } @Override public void onSensorChanged(SensorEvent event) { String pval = event.values[0] == 0.0 ? "NEAR" : "FAR"; Log.i("Proximity changed", pval); setPSStatus(pval); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); context = getApplicationContext(); psevent = this; sensormanager = (SensorManager)getSystemService(SENSOR_SERVICE); ps = sensormanager.getDefaultSensor(Sensor.TYPE_PROXIMITY); final Button applybut = (Button) findViewById(R.id.applyBut); applybut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (running) { sensormanager.unregisterListener(psevent); setPSStatus("Not running"); applybut.setText("Start"); } else { sensormanager.registerListener(psevent, ps, SensorManager.SENSOR_DELAY_FASTEST); setPSStatus("Waiting for reading"); applybut.setText("Stop"); } running = !running; } }); final SeekBar ltslider = (SeekBar) findViewById(R.id.lt_slider); final SeekBar htslider = (SeekBar) findViewById(R.id.ht_slider); final TextView lt_value = (TextView) findViewById(R.id.lt_value); final TextView ht_value = (TextView) findViewById(R.id.ht_value); ltslider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { lt_value.setText(new Integer(progress).toString()); if (progress >= (htslider.getProgress() - 1)) { htslider.setProgress(progress + 1); } } }); htslider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { ht_value.setText(new Integer(progress).toString()); if (progress <= (ltslider.getProgress() + 1)) { ltslider.setProgress(progress - 1); } } }); ZoomControls ltzoom = (ZoomControls) findViewById(R.id.ltZoom); ZoomControls htzoom = (ZoomControls) findViewById(R.id.htZoom); ltzoom.setOnZoomInClickListener(new OnClickListener() { @Override public void onClick(View v) { ltslider.setProgress(ltslider.getProgress() + 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); ltzoom.setOnZoomOutClickListener(new OnClickListener() { @Override public void onClick(View v) { ltslider.setProgress(ltslider.getProgress() - 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); htzoom.setOnZoomInClickListener(new OnClickListener() { @Override public void onClick(View v) { htslider.setProgress(htslider.getProgress() + 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); htzoom.setOnZoomOutClickListener(new OnClickListener() { @Override public void onClick(View v) { htslider.setProgress(htslider.getProgress() - 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); Button b = (Button) findViewById(R.id.beerbut); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&[email protected]" + "&item_name=DHD%20Proximity%20Recalibrator&no_shipping=1&currency_code=USD" ); startActivity(new Intent( Intent.ACTION_VIEW, uri ) ); } }); int lt = Calibration.getLT(); int ht = Calibration.getHT(); lt_value.setText(new Integer(lt).toString()); ht_value.setText(new Integer(ht).toString()); ltslider.setProgress(lt); htslider.setProgress(ht); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); context = getApplicationContext(); psevent = this; sensormanager = (SensorManager)getSystemService(SENSOR_SERVICE); ps = sensormanager.getDefaultSensor(Sensor.TYPE_PROXIMITY); final Button applybut = (Button) findViewById(R.id.applyBut); applybut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (running) { sensormanager.unregisterListener(psevent); setPSStatus("Not running"); applybut.setText("Start"); } else { sensormanager.registerListener(psevent, ps, SensorManager.SENSOR_DELAY_FASTEST); setPSStatus("Waiting for reading"); applybut.setText("Stop"); } running = !running; } }); final SeekBar ltslider = (SeekBar) findViewById(R.id.lt_slider); final SeekBar htslider = (SeekBar) findViewById(R.id.ht_slider); final TextView lt_value = (TextView) findViewById(R.id.lt_value); final TextView ht_value = (TextView) findViewById(R.id.ht_value); ltslider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { lt_value.setText(new Integer(progress).toString()); if (progress >= (htslider.getProgress() - 1)) { htslider.setProgress(progress + 1); } } }); htslider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { ht_value.setText(new Integer(progress).toString()); if (progress <= (ltslider.getProgress() + 1)) { ltslider.setProgress(progress - 1); } } }); ZoomControls ltzoom = (ZoomControls) findViewById(R.id.ltZoom); ZoomControls htzoom = (ZoomControls) findViewById(R.id.htZoom); ltzoom.setOnZoomInClickListener(new OnClickListener() { @Override public void onClick(View v) { ltslider.setProgress(ltslider.getProgress() + 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); ltzoom.setOnZoomOutClickListener(new OnClickListener() { @Override public void onClick(View v) { ltslider.setProgress(ltslider.getProgress() - 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); htzoom.setOnZoomInClickListener(new OnClickListener() { @Override public void onClick(View v) { htslider.setProgress(htslider.getProgress() + 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); htzoom.setOnZoomOutClickListener(new OnClickListener() { @Override public void onClick(View v) { htslider.setProgress(htslider.getProgress() - 1); Calibration.applyAndSave(context, ltslider.getProgress(), htslider.getProgress()); } }); Button b = (Button) findViewById(R.id.beerbut); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("https://www.paypal.com/cgi-bin/webscr?cmd=_donations&[email protected]" + "&item_name=DHD%20Proximity%20Recalibrator&no_shipping=1&amount=2&currency_code=USD" ); startActivity(new Intent( Intent.ACTION_VIEW, uri ) ); } }); int lt = Calibration.getLT(); int ht = Calibration.getHT(); lt_value.setText(new Integer(lt).toString()); ht_value.setText(new Integer(ht).toString()); ltslider.setProgress(lt); htslider.setProgress(ht); }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/push/PushOperationUI.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/push/PushOperationUI.java index 15e0ec7c..7d96b554 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/push/PushOperationUI.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/push/PushOperationUI.java @@ -1,211 +1,211 @@ /******************************************************************************* * Copyright (c) 2011 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mathias Kinzler (SAP AG) - initial implementation *******************************************************************************/ package org.eclipse.egit.ui.internal.push; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.egit.core.op.PushOperation; import org.eclipse.egit.core.op.PushOperationResult; import org.eclipse.egit.core.op.PushOperationSpecification; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.JobFamilies; import org.eclipse.egit.ui.UIText; import org.eclipse.jgit.errors.NotSupportedException; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.Transport; import org.eclipse.jgit.transport.URIish; import org.eclipse.osgi.util.NLS; /** * UI Wrapper for {@link PushOperation} */ public class PushOperationUI { /** The default RefSpec */ public static final RefSpec DEFAULT_PUSH_REF_SPEC = new RefSpec( "refs/heads/*:refs/heads/*"); //$NON-NLS-1$ private final Repository repository; private final int timeout; private final boolean dryRun; private final String destinationString; private final RemoteConfig config; private PushOperationSpecification spec; private CredentialsProvider credentialsProvider; private PushOperation op; /** * @param repository * @param config * @param timeout * @param dryRun * */ public PushOperationUI(Repository repository, RemoteConfig config, int timeout, boolean dryRun) { this.repository = repository; this.spec = null; this.config = config; this.timeout = timeout; this.dryRun = dryRun; destinationString = NLS.bind("{0} - {1}", repository.getDirectory() //$NON-NLS-1$ .getParentFile().getName(), config.getName()); } /** * @param repository * @param spec * @param timeout * @param dryRun */ public PushOperationUI(Repository repository, PushOperationSpecification spec, int timeout, boolean dryRun) { this.repository = repository; this.spec = spec; this.config = null; this.timeout = timeout; this.dryRun = dryRun; if (spec.getURIsNumber() == 1) destinationString = spec.getURIs().iterator().next() .toPrivateString(); else destinationString = NLS.bind( UIText.PushOperationUI_MultiRepositoriesDestinationString, Integer.valueOf(spec.getURIsNumber())); } /** * @param credentialsProvider */ public void setCredentialsProvider(CredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; } /** * Executes this directly, without showing a confirmation dialog * * @param monitor * @return the result of the operation * @throws CoreException */ public PushOperationResult execute(IProgressMonitor monitor) throws CoreException { if (spec == null) { // we don't use the configuration directly, as it may contain // unsaved changes and as we may need // to add the default push RefSpec here spec = new PushOperationSpecification(); List<URIish> urisToPush = new ArrayList<URIish>(); for (URIish uri : config.getPushURIs()) urisToPush.add(uri); if (urisToPush.isEmpty() && !config.getURIs().isEmpty()) urisToPush.add(config.getURIs().get(0)); List<RefSpec> pushRefSpecs = new ArrayList<RefSpec>(); pushRefSpecs.addAll(config.getPushRefSpecs()); if (pushRefSpecs.isEmpty()) // default push to all branches pushRefSpecs.add(DEFAULT_PUSH_REF_SPEC); for (URIish uri : urisToPush) { try { spec.addURIRefUpdates(uri, Transport.open(repository, uri) .findRemoteRefUpdatesFor(pushRefSpecs)); } catch (NotSupportedException e) { - throw new CoreException(Activator.createErrorStatus(e - .getCause().getMessage(), e.getCause())); + throw new CoreException(Activator.createErrorStatus( + e.getMessage(), e)); } catch (IOException e) { - throw new CoreException(Activator.createErrorStatus(e - .getCause().getMessage(), e.getCause())); + throw new CoreException(Activator.createErrorStatus( + e.getMessage(), e)); } } } op = new PushOperation(repository, spec, dryRun, timeout); if (credentialsProvider != null) op.setCredentialsProvider(credentialsProvider); try { op.run(monitor); return op.getOperationResult(); } catch (InvocationTargetException e) { throw new CoreException(Activator.createErrorStatus(e.getCause() .getMessage(), e.getCause())); } } /** * Starts the operation asynchronously showing a confirmation dialog after * completion */ public void start() { Job job = new Job(NLS.bind(UIText.PushOperationUI_PushJobName, destinationString)) { @Override protected IStatus run(IProgressMonitor monitor) { try { execute(monitor); } catch (CoreException e) { return Activator.createErrorStatus(e.getStatus() .getMessage(), e); } return Status.OK_STATUS; } @Override public boolean belongsTo(Object family) { if (JobFamilies.PUSH.equals(family)) return true; return super.belongsTo(family); } }; job.setUser(true); job.schedule(); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { if (event.getResult().isOK()) PushResultDialog.show(repository, op.getOperationResult(), destinationString); else Activator.handleError(event.getResult().getMessage(), event .getResult().getException(), true); } }); } /** * @return the string denoting the remote source */ public String getDestinationString() { return destinationString; } }
false
true
public PushOperationResult execute(IProgressMonitor monitor) throws CoreException { if (spec == null) { // we don't use the configuration directly, as it may contain // unsaved changes and as we may need // to add the default push RefSpec here spec = new PushOperationSpecification(); List<URIish> urisToPush = new ArrayList<URIish>(); for (URIish uri : config.getPushURIs()) urisToPush.add(uri); if (urisToPush.isEmpty() && !config.getURIs().isEmpty()) urisToPush.add(config.getURIs().get(0)); List<RefSpec> pushRefSpecs = new ArrayList<RefSpec>(); pushRefSpecs.addAll(config.getPushRefSpecs()); if (pushRefSpecs.isEmpty()) // default push to all branches pushRefSpecs.add(DEFAULT_PUSH_REF_SPEC); for (URIish uri : urisToPush) { try { spec.addURIRefUpdates(uri, Transport.open(repository, uri) .findRemoteRefUpdatesFor(pushRefSpecs)); } catch (NotSupportedException e) { throw new CoreException(Activator.createErrorStatus(e .getCause().getMessage(), e.getCause())); } catch (IOException e) { throw new CoreException(Activator.createErrorStatus(e .getCause().getMessage(), e.getCause())); } } } op = new PushOperation(repository, spec, dryRun, timeout); if (credentialsProvider != null) op.setCredentialsProvider(credentialsProvider); try { op.run(monitor); return op.getOperationResult(); } catch (InvocationTargetException e) { throw new CoreException(Activator.createErrorStatus(e.getCause() .getMessage(), e.getCause())); } }
public PushOperationResult execute(IProgressMonitor monitor) throws CoreException { if (spec == null) { // we don't use the configuration directly, as it may contain // unsaved changes and as we may need // to add the default push RefSpec here spec = new PushOperationSpecification(); List<URIish> urisToPush = new ArrayList<URIish>(); for (URIish uri : config.getPushURIs()) urisToPush.add(uri); if (urisToPush.isEmpty() && !config.getURIs().isEmpty()) urisToPush.add(config.getURIs().get(0)); List<RefSpec> pushRefSpecs = new ArrayList<RefSpec>(); pushRefSpecs.addAll(config.getPushRefSpecs()); if (pushRefSpecs.isEmpty()) // default push to all branches pushRefSpecs.add(DEFAULT_PUSH_REF_SPEC); for (URIish uri : urisToPush) { try { spec.addURIRefUpdates(uri, Transport.open(repository, uri) .findRemoteRefUpdatesFor(pushRefSpecs)); } catch (NotSupportedException e) { throw new CoreException(Activator.createErrorStatus( e.getMessage(), e)); } catch (IOException e) { throw new CoreException(Activator.createErrorStatus( e.getMessage(), e)); } } } op = new PushOperation(repository, spec, dryRun, timeout); if (credentialsProvider != null) op.setCredentialsProvider(credentialsProvider); try { op.run(monitor); return op.getOperationResult(); } catch (InvocationTargetException e) { throw new CoreException(Activator.createErrorStatus(e.getCause() .getMessage(), e.getCause())); } }
diff --git a/ttools/src/main/uk/ac/starlink/ttools/task/SkyMatch2Mapper.java b/ttools/src/main/uk/ac/starlink/ttools/task/SkyMatch2Mapper.java index 14b9525e0..fe0e84a36 100644 --- a/ttools/src/main/uk/ac/starlink/ttools/task/SkyMatch2Mapper.java +++ b/ttools/src/main/uk/ac/starlink/ttools/task/SkyMatch2Mapper.java @@ -1,110 +1,115 @@ package uk.ac.starlink.ttools.task; import uk.ac.starlink.table.JoinFixAction; import uk.ac.starlink.table.join.HEALPixMatchEngine; import uk.ac.starlink.table.join.JoinType; import uk.ac.starlink.table.join.MatchEngine; import uk.ac.starlink.task.ChoiceParameter; import uk.ac.starlink.task.DoubleParameter; import uk.ac.starlink.task.Environment; import uk.ac.starlink.task.Parameter; import uk.ac.starlink.task.ParameterValueException; import uk.ac.starlink.task.TaskException; import uk.ac.starlink.ttools.func.Coords; /** * TableMapper which does the work for sky-specific pair matching (tskymatch2). * * @author Mark Taylor * @since 2 Nov 2007 */ public class SkyMatch2Mapper implements TableMapper { private final Parameter[] raParams_; private final Parameter[] decParams_; private final DoubleParameter errorParam_; private final JoinTypeParameter joinParam_; private final FindModeParameter modeParam_; /** * Constructor. */ public SkyMatch2Mapper() { raParams_ = new Parameter[ 2 ]; decParams_ = new Parameter[ 2 ]; for ( int i = 0; i < 2; i++ ) { int i1 = i + 1; Parameter raParam = new Parameter( "ra" + i1 ); Parameter decParam = new Parameter( "dec" + i1 ); raParam.setPrompt( "<expr/degs>" ); decParam.setPrompt( "<expr/degs>" ); raParam.setPrompt( "Expression for table " + i1 + " right ascension in degrees" ); decParam.setPrompt( "Expression for table " + i1 + " declination in degrees" ); raParam.setDescription( new String[] { "<p>Value in degrees for the right ascension of positions in", "table " + i1 + " to be matched.", "This may simply be a column name, or it may be an", "algebraic expression calculated from columns as explained", "in <ref id='jel'/>.", "</p>", } ); decParam.setDescription( new String[] { "<p>Value in degrees for the declination of positions in", "table " + i1 + " to be matched.", "This may simply be a column name, or it may be an", "algebraic expression calculated from columns as explained", "in <ref id='jel'/>.", } ); raParams_[ i ] = raParam; decParams_[ i ] = decParam; } errorParam_ = new DoubleParameter( "error" ); errorParam_.setUsage( "<arcsec>" ); errorParam_.setPrompt( "Maximum separation in arcsec" ); + errorParam_.setDescription( new String[] { + "<p>The maximum separation permitted between two objects", + "for them to count as a match. Units are arc seconds.", + "</p>", + } ); joinParam_ = new JoinTypeParameter( "join" ); modeParam_ = new FindModeParameter( "find" ); } public Parameter[] getParameters() { return new Parameter[] { raParams_[ 0 ], decParams_[ 0 ], raParams_[ 1 ], decParams_[ 1 ], errorParam_, joinParam_, modeParam_, }; } public TableMapping createMapping( Environment env, int nin ) throws TaskException { String ra1 = raParams_[ 0 ].stringValue( env ); String dec1 = decParams_[ 0 ].stringValue( env ); String ra2 = raParams_[ 1 ].stringValue( env ); String dec2 = decParams_[ 1 ].stringValue( env ); double error = errorParam_.doubleValue( env ) * Coords.ARC_SECOND; if ( error < 0 ) { throw new ParameterValueException( errorParam_, "Negative value illegal" ); } JoinType join = joinParam_.joinTypeValue( env ); boolean bestOnly = modeParam_.bestOnlyValue( env ); MatchEngine engine = new HumanMatchEngine( new HEALPixMatchEngine( error, false ) ); JoinFixAction fixact1 = JoinFixAction.makeRenameDuplicatesAction( "_1", false, true ); JoinFixAction fixact2 = JoinFixAction.makeRenameDuplicatesAction( "_2", false, true ); return new Match2Mapping( engine, new String[] { ra1, dec1, }, new String[] { ra2, dec2, }, join, bestOnly, fixact1, fixact2, env.getErrorStream() ); } }
true
true
public SkyMatch2Mapper() { raParams_ = new Parameter[ 2 ]; decParams_ = new Parameter[ 2 ]; for ( int i = 0; i < 2; i++ ) { int i1 = i + 1; Parameter raParam = new Parameter( "ra" + i1 ); Parameter decParam = new Parameter( "dec" + i1 ); raParam.setPrompt( "<expr/degs>" ); decParam.setPrompt( "<expr/degs>" ); raParam.setPrompt( "Expression for table " + i1 + " right ascension in degrees" ); decParam.setPrompt( "Expression for table " + i1 + " declination in degrees" ); raParam.setDescription( new String[] { "<p>Value in degrees for the right ascension of positions in", "table " + i1 + " to be matched.", "This may simply be a column name, or it may be an", "algebraic expression calculated from columns as explained", "in <ref id='jel'/>.", "</p>", } ); decParam.setDescription( new String[] { "<p>Value in degrees for the declination of positions in", "table " + i1 + " to be matched.", "This may simply be a column name, or it may be an", "algebraic expression calculated from columns as explained", "in <ref id='jel'/>.", } ); raParams_[ i ] = raParam; decParams_[ i ] = decParam; } errorParam_ = new DoubleParameter( "error" ); errorParam_.setUsage( "<arcsec>" ); errorParam_.setPrompt( "Maximum separation in arcsec" ); joinParam_ = new JoinTypeParameter( "join" ); modeParam_ = new FindModeParameter( "find" ); }
public SkyMatch2Mapper() { raParams_ = new Parameter[ 2 ]; decParams_ = new Parameter[ 2 ]; for ( int i = 0; i < 2; i++ ) { int i1 = i + 1; Parameter raParam = new Parameter( "ra" + i1 ); Parameter decParam = new Parameter( "dec" + i1 ); raParam.setPrompt( "<expr/degs>" ); decParam.setPrompt( "<expr/degs>" ); raParam.setPrompt( "Expression for table " + i1 + " right ascension in degrees" ); decParam.setPrompt( "Expression for table " + i1 + " declination in degrees" ); raParam.setDescription( new String[] { "<p>Value in degrees for the right ascension of positions in", "table " + i1 + " to be matched.", "This may simply be a column name, or it may be an", "algebraic expression calculated from columns as explained", "in <ref id='jel'/>.", "</p>", } ); decParam.setDescription( new String[] { "<p>Value in degrees for the declination of positions in", "table " + i1 + " to be matched.", "This may simply be a column name, or it may be an", "algebraic expression calculated from columns as explained", "in <ref id='jel'/>.", } ); raParams_[ i ] = raParam; decParams_[ i ] = decParam; } errorParam_ = new DoubleParameter( "error" ); errorParam_.setUsage( "<arcsec>" ); errorParam_.setPrompt( "Maximum separation in arcsec" ); errorParam_.setDescription( new String[] { "<p>The maximum separation permitted between two objects", "for them to count as a match. Units are arc seconds.", "</p>", } ); joinParam_ = new JoinTypeParameter( "join" ); modeParam_ = new FindModeParameter( "find" ); }
diff --git a/exporting-server/java/highcharts-export/highcharts-export-convert/src/main/java/com/highcharts/export/pool/ServerObjectFactory.java b/exporting-server/java/highcharts-export/highcharts-export-convert/src/main/java/com/highcharts/export/pool/ServerObjectFactory.java index 66847d080..173356f19 100644 --- a/exporting-server/java/highcharts-export/highcharts-export-convert/src/main/java/com/highcharts/export/pool/ServerObjectFactory.java +++ b/exporting-server/java/highcharts-export/highcharts-export-convert/src/main/java/com/highcharts/export/pool/ServerObjectFactory.java @@ -1,201 +1,201 @@ 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.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.io.IOUtils; public class ServerObjectFactory implements ObjectFactory<Server> { public String exec; public String script; private String host; private int basePort; private int readTimeout; private int connectTimeout; private int maxTimeout; private static HashMap<Integer, PortStatus> portUsage = new HashMap<Integer, PortStatus>(); 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(); portUsage.put(port, PortStatus.BUSY); return new Server(exec, script, host, port, connectTimeout, readTimeout, maxTimeout); } @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() { for (Map.Entry<Integer, PortStatus> entry : portUsage.entrySet()) { if (PortStatus.FREE == entry.getValue()) { // return available port logger.debug("Portusage " + portUsage.toString()); return entry.getKey(); } } // if no port is free logger.debug("Nothing free in Portusage " + portUsage.toString()); return basePort + portUsage.size(); } /*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; } @PostConstruct public void afterBeanInit() { - String jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); + String jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().getPath().split("!")[0].replace("file:/", ""); try { jarLocation = URLDecoder.decode(jarLocation, "utf-8"); // get filesystem depend path jarLocation = new File(jarLocation).getCanonicalPath(); } catch (UnsupportedEncodingException ueex) { logger.error(ueex); } catch (IOException ioex) { logger.error(ioex); } try { JarFile jar = new JarFile(jarLocation); for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.startsWith("phantomjs/")) { Path path = Paths.get(TempDir.getTmpDir().toString(), name); if (name.endsWith("/")) { Files.createDirectories(path); } else { File file = Files.createFile(path).toFile(); InputStream in = jar.getInputStream(entry); IOUtils.copy(in, new FileOutputStream(file)); } } } } catch (IOException ioex) { logger.error(ioex); } } }
true
true
public void afterBeanInit() { String jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); try { jarLocation = URLDecoder.decode(jarLocation, "utf-8"); // get filesystem depend path jarLocation = new File(jarLocation).getCanonicalPath(); } catch (UnsupportedEncodingException ueex) { logger.error(ueex); } catch (IOException ioex) { logger.error(ioex); } try { JarFile jar = new JarFile(jarLocation); for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.startsWith("phantomjs/")) { Path path = Paths.get(TempDir.getTmpDir().toString(), name); if (name.endsWith("/")) { Files.createDirectories(path); } else { File file = Files.createFile(path).toFile(); InputStream in = jar.getInputStream(entry); IOUtils.copy(in, new FileOutputStream(file)); } } } } catch (IOException ioex) { logger.error(ioex); } }
public void afterBeanInit() { String jarLocation = getClass().getProtectionDomain().getCodeSource().getLocation().getPath().split("!")[0].replace("file:/", ""); try { jarLocation = URLDecoder.decode(jarLocation, "utf-8"); // get filesystem depend path jarLocation = new File(jarLocation).getCanonicalPath(); } catch (UnsupportedEncodingException ueex) { logger.error(ueex); } catch (IOException ioex) { logger.error(ioex); } try { JarFile jar = new JarFile(jarLocation); for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.startsWith("phantomjs/")) { Path path = Paths.get(TempDir.getTmpDir().toString(), name); if (name.endsWith("/")) { Files.createDirectories(path); } else { File file = Files.createFile(path).toFile(); InputStream in = jar.getInputStream(entry); IOUtils.copy(in, new FileOutputStream(file)); } } } } catch (IOException ioex) { logger.error(ioex); } }
diff --git a/src/armitage/ArmitageApplication.java b/src/armitage/ArmitageApplication.java index 5da7dab..ed702fd 100644 --- a/src/armitage/ArmitageApplication.java +++ b/src/armitage/ArmitageApplication.java @@ -1,209 +1,209 @@ package armitage; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class ArmitageApplication extends JFrame { protected JTabbedPane tabs = new JTabbedPane(); protected JSplitPane split = null; protected JMenuBar menus = new JMenuBar(); public void addMenu(JMenuItem menu) { menus.add(menu); } public JMenuBar getJMenuBar() { return menus; } public void _removeTab(JComponent component) { tabs.remove(component); tabs.validate(); } public void removeTab(final JComponent tab) { if (SwingUtilities.isEventDispatchThread()) { _removeTab(tab); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { _removeTab(tab); } }); } } public void setTop(final JComponent top) { if (SwingUtilities.isEventDispatchThread()) { _setTop(top); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { _setTop(top); } }); } } public void _setTop(JComponent top) { split.setTopComponent(top); split.setDividerLocation(0.50); split.setResizeWeight(0.50); split.revalidate(); } public void addTab(final String title, final JComponent tab, final ActionListener removeListener) { if (SwingUtilities.isEventDispatchThread()) { _addTab(title, tab, removeListener); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { _addTab(title, tab, removeListener); } }); } } private static class ApplicationTab { public String title; public JComponent component; public ActionListener removeListener; public String toString() { return title; } } protected LinkedList apptabs = new LinkedList(); public void addAppTab(String title, JComponent component, ActionListener removeListener) { ApplicationTab t = new ApplicationTab(); t.title = title; t.component = component; t.removeListener = removeListener; apptabs.add(t); } public void popAppTab(Component tab) { Iterator i = apptabs.iterator(); while (i.hasNext()) { final ApplicationTab t = (ApplicationTab)i.next(); if (t.component == tab) { tabs.remove(t.component); i.remove(); /* pop goes the tab! */ JFrame r = new JFrame(t.title); r.setIconImages(getIconImages()); r.setLayout(new BorderLayout()); r.add(t.component, BorderLayout.CENTER); r.pack(); r.setVisible(true); r.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent ev) { if (t.removeListener != null) t.removeListener.actionPerformed(new ActionEvent(ev.getSource(), 0, "close")); } }); } } } public void removeAppTab(Component tab, String title, ActionEvent ev) { Iterator i = apptabs.iterator(); while (i.hasNext()) { ApplicationTab t = (ApplicationTab)i.next(); if (t.component == tab || t.title.equals(title)) { tabs.remove(t.component); if (t.removeListener != null) t.removeListener.actionPerformed(ev); i.remove(); } } } public void _addTab(final String title, JComponent tab, final ActionListener removeListener) { final Component component = tabs.add("", tab); final JLabel label = new JLabel(title + " "); JPanel control = new JPanel(); control.setOpaque(false); control.setLayout(new BorderLayout()); control.add(label, BorderLayout.CENTER); if (tab instanceof Activity) { ((Activity)tab).registerLabel(label); } JButton close = new JButton("X"); close.setOpaque(false); close.setContentAreaFilled(false); close.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); control.add(close, BorderLayout.EAST); int index = tabs.indexOfComponent(component); tabs.setTabComponentAt(index, control); addAppTab(title, tab, removeListener); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if ((ev.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { popAppTab(component); } - if ((ev.getModifiers() & ActionEvent.SHIFT_MASK) == ActionEvent.SHIFT_MASK) { + else if ((ev.getModifiers() & ActionEvent.SHIFT_MASK) == ActionEvent.SHIFT_MASK) { removeAppTab(null, title, ev); } else { removeAppTab(component, null, ev); } System.gc(); } }); component.addComponentListener(new ComponentAdapter() { public void componentShown(ComponentEvent ev) { if (component instanceof Activity) { ((Activity)component).resetNotification(); } component.requestFocusInWindow(); System.gc(); } }); tabs.setSelectedIndex(index); component.requestFocusInWindow(); } public ArmitageApplication() { super("Armitage"); setLayout(new BorderLayout()); /* place holder */ JPanel panel = new JPanel(); /* add our menubar */ add(menus, BorderLayout.NORTH); split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel, tabs); split.setOneTouchExpandable(true); /* add our tabbed pane */ add(split, BorderLayout.CENTER); /* ... */ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
true
true
public void _addTab(final String title, JComponent tab, final ActionListener removeListener) { final Component component = tabs.add("", tab); final JLabel label = new JLabel(title + " "); JPanel control = new JPanel(); control.setOpaque(false); control.setLayout(new BorderLayout()); control.add(label, BorderLayout.CENTER); if (tab instanceof Activity) { ((Activity)tab).registerLabel(label); } JButton close = new JButton("X"); close.setOpaque(false); close.setContentAreaFilled(false); close.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); control.add(close, BorderLayout.EAST); int index = tabs.indexOfComponent(component); tabs.setTabComponentAt(index, control); addAppTab(title, tab, removeListener); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if ((ev.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { popAppTab(component); } if ((ev.getModifiers() & ActionEvent.SHIFT_MASK) == ActionEvent.SHIFT_MASK) { removeAppTab(null, title, ev); } else { removeAppTab(component, null, ev); } System.gc(); } }); component.addComponentListener(new ComponentAdapter() { public void componentShown(ComponentEvent ev) { if (component instanceof Activity) { ((Activity)component).resetNotification(); } component.requestFocusInWindow(); System.gc(); } }); tabs.setSelectedIndex(index); component.requestFocusInWindow(); }
public void _addTab(final String title, JComponent tab, final ActionListener removeListener) { final Component component = tabs.add("", tab); final JLabel label = new JLabel(title + " "); JPanel control = new JPanel(); control.setOpaque(false); control.setLayout(new BorderLayout()); control.add(label, BorderLayout.CENTER); if (tab instanceof Activity) { ((Activity)tab).registerLabel(label); } JButton close = new JButton("X"); close.setOpaque(false); close.setContentAreaFilled(false); close.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); control.add(close, BorderLayout.EAST); int index = tabs.indexOfComponent(component); tabs.setTabComponentAt(index, control); addAppTab(title, tab, removeListener); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { if ((ev.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { popAppTab(component); } else if ((ev.getModifiers() & ActionEvent.SHIFT_MASK) == ActionEvent.SHIFT_MASK) { removeAppTab(null, title, ev); } else { removeAppTab(component, null, ev); } System.gc(); } }); component.addComponentListener(new ComponentAdapter() { public void componentShown(ComponentEvent ev) { if (component instanceof Activity) { ((Activity)component).resetNotification(); } component.requestFocusInWindow(); System.gc(); } }); tabs.setSelectedIndex(index); component.requestFocusInWindow(); }
diff --git a/grisu-core/src/main/java/grisu/backend/model/FileSystemCache.java b/grisu-core/src/main/java/grisu/backend/model/FileSystemCache.java index f051007c..cd140872 100644 --- a/grisu-core/src/main/java/grisu/backend/model/FileSystemCache.java +++ b/grisu-core/src/main/java/grisu/backend/model/FileSystemCache.java @@ -1,203 +1,203 @@ package grisu.backend.model; import grisu.model.MountPoint; import grisu.settings.ServerPropertiesManager; import grith.jgrith.cred.AbstractCred; import grith.jgrith.cred.Cred; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystem; import org.apache.commons.vfs.FileSystemException; import org.apache.commons.vfs.FileSystemOptions; import org.apache.commons.vfs.impl.DefaultFileSystemManager; import org.apache.commons.vfs.provider.gridftp.cogjglobus.GridFtpFileSystemConfigBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.dl.escience.vfs.util.VFSUtil; public class FileSystemCache { private static AtomicInteger COUNTER = new AtomicInteger(); private static Logger myLogger = LoggerFactory .getLogger(FileSystemCache.class.getName()); private Map<MountPoint, FileSystem> cachedFilesystems = new HashMap<MountPoint, FileSystem>(); private DefaultFileSystemManager fsm = null; private final User user; private final String id; public FileSystemCache(User user) { id = "FILESYSTEM_CACHE_" + UUID.randomUUID().toString() + ": "; final int i = COUNTER.addAndGet(1); // X.p("Opening filesystemmanager: " + i); this.user = user; try { // String tmp = System.getProperty("java.io.tmpdir"); // if (StringUtils.isBlank(tmp)) { // tmp = "/tmp/grisu-fs-tmp"; // } else { // myLogger.debug("Using " + tmp // + "/grisu-fs-tmp for temporary directory..."); // // } myLogger.debug(user.getDn() + ": Creating FS manager for user..."); fsm = VFSUtil.createNewFsManager(false, false, true, true, true, true, true, "/tmp"); } catch (final FileSystemException e) { throw new RuntimeException(e); } } public void addFileSystem(MountPoint mp, FileSystem fs) { cachedFilesystems.put(mp, fs); } public void close() { cachedFilesystems = new HashMap<MountPoint, FileSystem>(); if (!ServerPropertiesManager.closeFileSystemsInBackground()) { myLogger.debug(id + "Closing filesystem. Currently open filesystems: " + COUNTER); fsm.close(); final int i = COUNTER.decrementAndGet(); myLogger.debug(id + "Filesystemm closed. Remaining open filesystems: " + i); } else { final Thread t = new Thread() { @Override public void run() { myLogger.debug(id + "Closing filesystem. Currently open filesystems: " + COUNTER); fsm.close(); final int i = COUNTER.decrementAndGet(); myLogger.debug(id + "Filesystemm closed. Remaining open filesystems: " + i); } }; t.setName("FS_CLOSE_" + new Date().getTime()); t.start(); } } private FileSystem createFileSystem(String rootUrl, Cred credToUse) throws FileSystemException { final FileSystemOptions opts = new FileSystemOptions(); FileObject fileRoot; try { if (rootUrl.startsWith("gsiftp")) { // myLogger.debug("Url \"" + rootUrl // + "\" is gsiftp url, using gridftpfilesystembuilder..."); final GridFtpFileSystemConfigBuilder builder = GridFtpFileSystemConfigBuilder .getInstance(); builder.setGSSCredential(opts, credToUse.getGSSCredential()); builder.setTimeout(opts, ServerPropertiesManager.getFileSystemConnectTimeout()); // builder.setUserDirIsRoot(opts, true); } fileRoot = fsm.resolveFile(rootUrl, opts); } catch (final FileSystemException e) { myLogger.error("Can't connect to filesystem: " + rootUrl + " using VO: " + credToUse.getFqan()); throw new FileSystemException("Can't connect to filesystem " + rootUrl + ": " + e.getLocalizedMessage(), e); } FileSystem fileBase = null; fileBase = fileRoot.getFileSystem(); return fileBase; } public FileSystem getFileSystem(MountPoint mp) { return cachedFilesystems.get(mp); } public FileSystem getFileSystem(final String rootUrl, String fqan) throws FileSystemException { synchronized (rootUrl) { Cred credToUse = null; MountPoint temp = null; try { String tmp = fqan; System.out.println(tmp); temp = user.getResponsibleMountpointForAbsoluteFile(rootUrl); } catch (final IllegalStateException e) { e.printStackTrace(); - myLogger.debug("Can't get mountpoint.",e); + myLogger.debug("Can't get mountpoint, mountpoints not set yet."); } if ((fqan == null) && (temp != null) && (temp.getFqan() != null)) { fqan = temp.getFqan(); } // get the right credential for this mountpoint if (fqan != null) { credToUse = user.getCredential(fqan); } else { credToUse = user.getCredential(); } FileSystem fileBase = null; if (temp == null) { // means we have to figure out how to connect to this. I.e. // which fqan to use... // throw new FileSystemException( // "Could not find mountpoint for url " + rootUrl); // creating a filesystem... myLogger.debug("Creating filesystem without mountpoint..."); return createFileSystem(rootUrl, credToUse); } else { // great, we can re-use this filesystem if (getFileSystem(temp) == null) { fileBase = createFileSystem(temp.getRootUrl(), credToUse); if (temp != null) { addFileSystem(temp, fileBase); } } else { fileBase = getFileSystem(temp); } } return fileBase; } } public DefaultFileSystemManager getFileSystemManager() { return fsm; } public Map<MountPoint, FileSystem> getFileSystems() { return cachedFilesystems; } }
true
true
public FileSystem getFileSystem(final String rootUrl, String fqan) throws FileSystemException { synchronized (rootUrl) { Cred credToUse = null; MountPoint temp = null; try { String tmp = fqan; System.out.println(tmp); temp = user.getResponsibleMountpointForAbsoluteFile(rootUrl); } catch (final IllegalStateException e) { e.printStackTrace(); myLogger.debug("Can't get mountpoint.",e); } if ((fqan == null) && (temp != null) && (temp.getFqan() != null)) { fqan = temp.getFqan(); } // get the right credential for this mountpoint if (fqan != null) { credToUse = user.getCredential(fqan); } else { credToUse = user.getCredential(); } FileSystem fileBase = null; if (temp == null) { // means we have to figure out how to connect to this. I.e. // which fqan to use... // throw new FileSystemException( // "Could not find mountpoint for url " + rootUrl); // creating a filesystem... myLogger.debug("Creating filesystem without mountpoint..."); return createFileSystem(rootUrl, credToUse); } else { // great, we can re-use this filesystem if (getFileSystem(temp) == null) { fileBase = createFileSystem(temp.getRootUrl(), credToUse); if (temp != null) { addFileSystem(temp, fileBase); } } else { fileBase = getFileSystem(temp); } } return fileBase; } }
public FileSystem getFileSystem(final String rootUrl, String fqan) throws FileSystemException { synchronized (rootUrl) { Cred credToUse = null; MountPoint temp = null; try { String tmp = fqan; System.out.println(tmp); temp = user.getResponsibleMountpointForAbsoluteFile(rootUrl); } catch (final IllegalStateException e) { e.printStackTrace(); myLogger.debug("Can't get mountpoint, mountpoints not set yet."); } if ((fqan == null) && (temp != null) && (temp.getFqan() != null)) { fqan = temp.getFqan(); } // get the right credential for this mountpoint if (fqan != null) { credToUse = user.getCredential(fqan); } else { credToUse = user.getCredential(); } FileSystem fileBase = null; if (temp == null) { // means we have to figure out how to connect to this. I.e. // which fqan to use... // throw new FileSystemException( // "Could not find mountpoint for url " + rootUrl); // creating a filesystem... myLogger.debug("Creating filesystem without mountpoint..."); return createFileSystem(rootUrl, credToUse); } else { // great, we can re-use this filesystem if (getFileSystem(temp) == null) { fileBase = createFileSystem(temp.getRootUrl(), credToUse); if (temp != null) { addFileSystem(temp, fileBase); } } else { fileBase = getFileSystem(temp); } } return fileBase; } }
diff --git a/controllers/SupervisorController/SupervisorController.java b/controllers/SupervisorController/SupervisorController.java index ef87824..a59eed5 100644 --- a/controllers/SupervisorController/SupervisorController.java +++ b/controllers/SupervisorController/SupervisorController.java @@ -1,583 +1,583 @@ import com.cyberbotics.webots.controller.*; import nn.NeuralNetwork; import utils.FilesFunctions; import utils.Util; import java.io.*; import java.util.Random; /** * Created with IntelliJ IDEA. * User: annapawlicka * Date: 09/03/2013 * Time: 14:27 * Supervisor controller. Controls the evolution of e-puck. Supervisor can reset position of the epuck. * Communication with e-puck is done via emitters/receivers. Separate devices for game and neural communication. * Evolution is done by elitism, crossover and mutation. * Fitness function of agents is how well they learn the games. */ //TODO Test reading best indiv public class SupervisorController extends Supervisor { // Devices private Emitter emitter; private Emitter gameEmitter; private Receiver receiver; private Receiver gameReceiver; private Node epuck; private Field fldTranslation; private double[] initTranslation; private Display groundDisplay; private int width, height; private double GROUND_X = 0.9; private double GROUND_Z = 0.9; private int WHITE = 0xFFFFFF; private int BLACK = 0x000000; private double[] translation; private ImageRef toStore; private final int TIME_STEP = 128; // [ms] // Evolution private int NN_POP_SIZE; private int GAME_POP_SIZE; private int NB_INPUTS; private int NB_OUTPUTS; private int NB_GENES; private NeuralNetwork[] populationOfNN; private double[] fitnessNN; private double[][] sortedfitnessNN; // Population sorted by fitness private double ELITISM_RATIO = 0.1; private double REPRODUCTION_RATIO = 0.4; // If not using roulette wheel (truncation selection), we need reproduction ratio private double CROSSOVER_PROBABILITY = 0.5; // Probability of having a crossover private double MUTATION_PROBABILITY = 0.1; // Probability of mutating each weight-value in a genome private int GENE_MIN = -1; // Range of genes: minimum value private int GENE_MAX = 1; // Range of genes: maximum value private double MUTATION_SIGMA = 0.2; // Mutations follow a Box-Muller distribution from the gene with this sigma private int evaluatedNN = 0; // Evaluated individuals private int generation = 0; // Generation counter //If 1, evolution takes place. If 0, then the best individual obtained during the previous evolution is tested for an undetermined amount of time. private int EVOLVING = 1; private int TESTING = 0; private int ROULETTE_WHEEL = 1; //Log variables private double minFitNN = 0.0, avgFitNN = 0.0, bestFitNN = 0.0, absBestFitNN = -10000; private int bestNN = -1, absBestNN = -1; private BufferedWriter out1, out2, out3; private BufferedReader in1, in2, in3; private FileWriter file1, file2, file3; private BufferedReader reader1, reader3; private Random random = new Random(); public SupervisorController() { super(); } /** * This method exits only when simulation is closed/reversed. */ public void run() { while (step(TIME_STEP) != -1) { byte[] nnFit; float finished = -1; drawRobotsPosition(); // As long as individual is being evaluated, print current fitness and return int n = receiver.getQueueLength(); if (n > 0) { nnFit = receiver.getData(); // Convert bytes into floats if (nnFit.length == 12) { byte[] currFitness = new byte[4]; for (int i = 0; i < 4; i++) { currFitness[i] = nnFit[i]; } byte[] indivNo = new byte[4]; int m = 0; for (int k = 4; k < 8; k++) { indivNo[m] = nnFit[k]; m++; } byte[] flag = new byte[4]; int l = 0; for (int j = 8; j < 12; j++) { flag[l] = nnFit[j]; l++; } int indIndex = (int) Util.bytearray2float(indivNo); fitnessNN[indIndex] = Util.bytearray2float(currFitness); finished = Util.bytearray2float(flag); receiver.nextPacket(); } else if (nnFit.length == 4) { byte[] flag = new byte[4]; for (int j = 0; j < 4; j++) { flag[j] = nnFit[j]; } finished = Util.bytearray2float(flag); receiver.nextPacket(); } } // When evaluation is done, an extra flag is returned in the message if (finished == 1.0f) { if (EVOLVING == 1) { //System.out.println("Evaluated individual " + evaluatedNN); //normaliseFitnessScore(fitnessNN); // Normalise fitness scores // Sort populationOfNN by fitness sortPopulation(sortedfitnessNN, fitnessNN); // Find and log current and absolute best individual bestFitNN = sortedfitnessNN[0][0]; minFitNN = sortedfitnessNN[NN_POP_SIZE - 1][0]; bestNN = (int) sortedfitnessNN[0][1]; avgFitNN = Util.mean(fitnessNN); if (bestFitNN > absBestFitNN) { absBestFitNN = bestFitNN; absBestNN = bestNN; FilesFunctions.logBest(out3, generation, NB_GENES, absBestNN, populationOfNN); } System.out.println("Best fitness score: \n" + bestFitNN); System.out.println("Average fitness score: \n" + avgFitNN); System.out.println("Worst fitness score: \n" + minFitNN); // Write data to files FilesFunctions.logPopulation(out1, avgFitNN, generation, fitnessNN, bestFitNN, minFitNN, NB_GENES, populationOfNN, bestNN); FilesFunctions.logAllActorFitnesses(out2, generation, fitnessNN); // Log the generation data - stores weights try { FilesFunctions.logLastGeneration(populationOfNN); } catch (IOException e) { e.getMessage(); } // Log best individual try { - FilesFunctions.logBestIndiv(populationOfNN, bestNN); + FilesFunctions.logBestIndiv(populationOfNN, absBestNN); } catch (IOException e) { System.err.println(e.getMessage()); } // Rank populationOfNN, select best individuals and create new generation createNewPopulation(); generation++; System.out.println("\nGENERATION \n" + generation); evaluatedNN = 0; avgFitNN = 0.0; bestFitNN = 0; bestNN = 0; minFitNN = 0; resetRobotPosition(); // Evolve games every 4 NN generations (gives them time to learn) if (generation % 5 == 0) { // Send flag to start evolution of games byte[] flag = {1}; gameEmitter.send(flag); } // Send new weights byte[] msgInBytes = Util.float2Byte(populationOfNN[evaluatedNN].getWeights()); emitter.send(msgInBytes); } } else if (finished == 0.0) { if ((evaluatedNN + 1) < NN_POP_SIZE) { storeImage(evaluatedNN); resetDisplay(); evaluatedNN++; System.out.println("Evaluated individual " + evaluatedNN); // Send next genome to experiment resetRobotPosition(); byte[] msgInBytes = Util.float2Byte(populationOfNN[evaluatedNN].getWeights()); emitter.send(msgInBytes); } } } } /** * Store screenshot of display node into an image file, append current individual's index to file's name * @param indivIndex */ private void storeImage(int indivIndex){ toStore = groundDisplay.imageCopy(0,0,width,height); groundDisplay.imageSave(toStore,"screenshot"+indivIndex+".png"); groundDisplay.imageDelete(toStore); } /** * Draw current robot's position on the display */ private void drawRobotsPosition(){ translation = fldTranslation.getSFVec3f(); groundDisplay.setOpacity(0.03); groundDisplay.setColor(BLACK); groundDisplay.fillOval( (int) (height * (translation[2] + GROUND_Z / 2) / GROUND_Z), (int) (width * (translation[0] + GROUND_X / 2) / GROUND_X), 2, 2); } /** * Reset display node by repainting the background */ private void resetDisplay(){ groundDisplay.setOpacity(1.0); groundDisplay.setColor(WHITE); groundDisplay.fillRectangle(0, 0, width, height); translation = fldTranslation.getSFVec3f(); } private void normaliseFitnessScore(double[] fitnessScores) { double min, max; // Find min and max - takes two additional runs that don't change time complexity min = Util.min(fitnessScores); max = Util.max(fitnessScores); for (int i = 0; i < fitnessScores.length; i++) { double temp = 0; try { temp = Util.normalize(min, max, fitnessScores[i]); // add buffer of 0.5 } catch (Exception e) { System.err.println("Error while normalizing: " + e.getMessage()); } fitnessScores[i] = temp; } } /** * The reset function is called at the beginning of an evolution. */ public void reset() { int i; for (i = 0; i < NN_POP_SIZE; i++) fitnessNN[i] = -1; if (EVOLVING == 1) { // Initialise weights randomly initializePopulation(); System.out.println("NEW EVOLUTION\n"); System.out.println("GENERATION 0\n"); resetRobotPosition(); // Then, send weights of NNs to experiment byte[] msgInBytes = Util.float2Byte(populationOfNN[evaluatedNN].getWeights()); emitter.send(msgInBytes); } int counter = 0; String strLine; if (TESTING == 1) { // Test last recorded generation try { while ((strLine = reader3.readLine()) != null && counter < 50) { String[] weightsStr = strLine.split(","); for (i = 0; i < populationOfNN[counter].getWeightsNo(); i++) { populationOfNN[counter].setWeights(i, Float.parseFloat(weightsStr[i])); } counter++; } } catch (IOException e) { e.getMessage(); } System.out.println("TESTING LAST GENERATION \n"); } if (TESTING == 2) { // Test best individual - whole population will be filled with the same individual's weights try { while ((strLine = reader1.readLine()) != null) { // Only one line in a file. TODO check if doesn't throw exception String[] weightsStr = strLine.split(","); for (i = 0; i < NN_POP_SIZE; i++) { for (int j = 0; j < populationOfNN[i].getWeightsNo(); j++) { populationOfNN[i].setWeights(j, Float.parseFloat(weightsStr[j])); } } } } catch (IOException e) { System.err.println(e.getMessage()); } } } /** * Initiate genes of all individuals randomly */ private void initializePopulation() { int i, j; for (i = 0; i < NN_POP_SIZE; i++) { for (j = 0; j < NB_GENES; j++) { // all genes must be in the range of [-1, 1] populationOfNN[i].setWeights(j, (float) ((GENE_MAX - GENE_MIN) * random.nextFloat() - (GENE_MAX - GENE_MIN) / 2.0)); } } } /** * Based on the fitness of the last generation, generate a new population of genomes for the next generation. */ private void createNewPopulation() { NeuralNetwork[] newpop = new NeuralNetwork[NN_POP_SIZE]; for (int i = 0; i < newpop.length; i++) { newpop[i] = new NeuralNetwork(NB_INPUTS, NB_OUTPUTS); } double elitism_counter = NN_POP_SIZE * ELITISM_RATIO; double total_fitness = 0; // Find minimum fitness to subtract it from sum double min_fitness = sortedfitnessNN[NN_POP_SIZE - 1][0]; //if (min_fitness < 0) min_fitness = 0; // Causes an issue if scores are below 0 int i, j; // Calculate total of fitness, used for roulette wheel selection for (i = 0; i < NN_POP_SIZE; i++) total_fitness += fitnessNN[i]; total_fitness -= min_fitness * NN_POP_SIZE; // Create new population for (i = 0; i < NN_POP_SIZE; i++) { // The elitism_counter best individuals are simply copied to the new populationOfNN if (i < elitism_counter) { for (j = 0; j < NB_GENES; j++) newpop[i].setWeights(j, populationOfNN[(int) sortedfitnessNN[i][1]].getWeights()[j]); } // The other individuals are generated through the crossover of two parents else { // Select non-elitist individual int ind1 = 0; float r = random.nextFloat(); double fitness_counter = (sortedfitnessNN[ind1][0] - min_fitness) / total_fitness; while (r > fitness_counter && ind1 < NN_POP_SIZE - 1) { ind1++; fitness_counter += (sortedfitnessNN[ind1][0] - min_fitness) / total_fitness; if (ind1 == NN_POP_SIZE - 1) break; } // If we will do crossover, select a second individual if (random.nextFloat() < CROSSOVER_PROBABILITY) { int ind2 = 0; do { r = random.nextFloat(); fitness_counter = (sortedfitnessNN[ind2][0] - min_fitness) / total_fitness; while (r > fitness_counter && ind2 < NN_POP_SIZE - 1) { ind2++; fitness_counter += (sortedfitnessNN[ind2][0] - min_fitness) / total_fitness; if (ind2 == NN_POP_SIZE - 1) break; } } while (ind1 == ind2); ind1 = (int) sortedfitnessNN[ind1][1]; ind2 = (int) sortedfitnessNN[ind2][1]; newpop[i].crossover(ind1, ind2, newpop[i], NB_GENES, populationOfNN); } else { //if no crossover was done, just copy selected individual directly for (j = 0; j < NB_GENES; j++) newpop[i].setWeights(j, populationOfNN[(int) sortedfitnessNN[ind1][1]].getWeights()[j]); } } } // Mutate new populationOfNN and copy back to pop for (i = 0; i < NN_POP_SIZE; i++) { if (i < elitism_counter) { //no mutation for elitists for (j = 0; j < NB_GENES; j++) { populationOfNN[i].copy(newpop[i]); } } else { // Mutate others with probability per gene for (j = 0; j < NB_GENES; j++) if (random.nextFloat() < MUTATION_PROBABILITY) populationOfNN[i].setWeights(j, populationOfNN[i].mutate(GENE_MIN, GENE_MAX, newpop[i].getWeights()[j], MUTATION_SIGMA)); else populationOfNN[i].copy(newpop[i]); } // Reset fitness fitnessNN[i] = 0; } } /** * Sort whole population according to fitness score of each individual. Uses quickSort. */ private void sortPopulation(double[][] sortedfitness, double[] fitness) { int i; //sort populationOfNN by fitness for (i = 0; i < sortedfitness.length; i++) { sortedfitness[i][0] = fitness[i]; sortedfitness[i][1] = (float) i; //keep index } quickSort(sortedfitness, 0, sortedfitness.length - 1); } /** * Standard fast algorithm to sort populationOfNN by fitness * * @param fitness Array that stores fitness and index of each individual. * @param left Min index of the array * @param right Max index of the array */ private void quickSort(double fitness[][], int left, int right) { double[] pivot = new double[2]; int l_hold, r_hold; l_hold = left; r_hold = right; pivot[0] = fitness[left][0]; pivot[1] = fitness[left][1]; while (left < right) { while ((fitness[right][0] <= pivot[0]) && (left < right)) right--; if (left != right) { fitness[left][0] = fitness[right][0]; fitness[left][1] = fitness[right][1]; left++; } while ((fitness[left][0] >= pivot[0]) && (left < right)) left++; if (left != right) { fitness[right][0] = fitness[left][0]; fitness[right][1] = fitness[left][1]; right--; } } fitness[left][0] = pivot[0]; fitness[left][1] = pivot[1]; pivot[0] = left; left = l_hold; right = r_hold; if (left < (int) pivot[0]) quickSort(fitness, left, (int) pivot[0] - 1); if (right > (int) pivot[0]) quickSort(fitness, (int) pivot[0] + 1, right); } /** * Resets the position of the epuck before each generation's trials */ private void resetRobotPosition() { fldTranslation.setSFVec3f(initTranslation); } private void initialise() { int i, j; /* Population/Evolution parameters */ NN_POP_SIZE = 50; GAME_POP_SIZE = 10; // Neural Networks NB_INPUTS = 7; NB_OUTPUTS = 2; NB_GENES = 10; populationOfNN = new NeuralNetwork[NN_POP_SIZE]; for (i = 0; i < NN_POP_SIZE; i++) populationOfNN[i] = new NeuralNetwork(NB_INPUTS, NB_OUTPUTS); fitnessNN = new double[NN_POP_SIZE]; for (i = 0; i < NN_POP_SIZE; i++) fitnessNN[i] = 0.0; sortedfitnessNN = new double[NN_POP_SIZE][2]; for (i = 0; i < sortedfitnessNN.length; i++) { for (j = 0; j < 2; j++) { sortedfitnessNN[i][j] = 0.0; } } // Nodes receiver = getReceiver("receiver"); receiver.enable(TIME_STEP); emitter = getEmitter("emitter"); epuck = getFromDef("EPUCK"); fldTranslation = epuck.getField("translation"); gameEmitter = getEmitter("gamesemittersuper"); gameEmitter.setChannel(1); gameReceiver = getReceiver("gamesreceiversuper"); gameReceiver.setChannel(1); gameReceiver.enable(TIME_STEP); // Initialise gps coordinates arrays initTranslation = new double[3]; initTranslation = fldTranslation.getSFVec3f(); // Display groundDisplay = getDisplay("ground_display"); width = groundDisplay.getWidth(); height = groundDisplay.getHeight(); // paint the display's background resetDisplay(); // Logging try { file1 = new FileWriter("results:fitness.txt"); } catch (IOException e) { System.out.println("Cannot open fitness.txt file."); } out1 = new BufferedWriter(file1); try { out1.write("generation , average fitness, worst fitness, best fitness"); out1.write("\n"); } catch (IOException e) { System.out.println("" + e.getMessage()); } try { file2 = new FileWriter("all_actor_fit.txt"); } catch (IOException e) { System.err.println("Error while opening file: all_actor_fit.txt " + e.getMessage()); } out2 = new BufferedWriter(file2); try { out2.write("generation"); for (i = 0; i < NN_POP_SIZE; i++) { out2.write(",Actor" + i + ","); } out2.write("\n"); } catch (IOException e) { System.out.println("" + e.getMessage()); } try { file3 = new FileWriter("results:bestgenome.txt"); } catch (IOException e) { System.out.println("Cannot open bestgenome.txt file."); } out3 = new BufferedWriter(file3); /* Reading from file - for testing purposes */ try { reader3 = new BufferedReader(new FileReader("results:genomes.txt")); } catch (FileNotFoundException e) { System.out.println("Cannot read from file: results:genomes.txt"); System.out.println(e.getMessage()); } try { reader1 = new BufferedReader(new FileReader("best_actor.txt")); } catch (FileNotFoundException e) { System.out.println("Cannot read from file: best_actor.txt"); System.out.println(e.getMessage()); } System.out.println("Supervisor has been initialised."); } public static void main(String[] args) { SupervisorController supervisorController = new SupervisorController(); supervisorController.initialise(); supervisorController.reset(); supervisorController.run(); } }
true
true
public void run() { while (step(TIME_STEP) != -1) { byte[] nnFit; float finished = -1; drawRobotsPosition(); // As long as individual is being evaluated, print current fitness and return int n = receiver.getQueueLength(); if (n > 0) { nnFit = receiver.getData(); // Convert bytes into floats if (nnFit.length == 12) { byte[] currFitness = new byte[4]; for (int i = 0; i < 4; i++) { currFitness[i] = nnFit[i]; } byte[] indivNo = new byte[4]; int m = 0; for (int k = 4; k < 8; k++) { indivNo[m] = nnFit[k]; m++; } byte[] flag = new byte[4]; int l = 0; for (int j = 8; j < 12; j++) { flag[l] = nnFit[j]; l++; } int indIndex = (int) Util.bytearray2float(indivNo); fitnessNN[indIndex] = Util.bytearray2float(currFitness); finished = Util.bytearray2float(flag); receiver.nextPacket(); } else if (nnFit.length == 4) { byte[] flag = new byte[4]; for (int j = 0; j < 4; j++) { flag[j] = nnFit[j]; } finished = Util.bytearray2float(flag); receiver.nextPacket(); } } // When evaluation is done, an extra flag is returned in the message if (finished == 1.0f) { if (EVOLVING == 1) { //System.out.println("Evaluated individual " + evaluatedNN); //normaliseFitnessScore(fitnessNN); // Normalise fitness scores // Sort populationOfNN by fitness sortPopulation(sortedfitnessNN, fitnessNN); // Find and log current and absolute best individual bestFitNN = sortedfitnessNN[0][0]; minFitNN = sortedfitnessNN[NN_POP_SIZE - 1][0]; bestNN = (int) sortedfitnessNN[0][1]; avgFitNN = Util.mean(fitnessNN); if (bestFitNN > absBestFitNN) { absBestFitNN = bestFitNN; absBestNN = bestNN; FilesFunctions.logBest(out3, generation, NB_GENES, absBestNN, populationOfNN); } System.out.println("Best fitness score: \n" + bestFitNN); System.out.println("Average fitness score: \n" + avgFitNN); System.out.println("Worst fitness score: \n" + minFitNN); // Write data to files FilesFunctions.logPopulation(out1, avgFitNN, generation, fitnessNN, bestFitNN, minFitNN, NB_GENES, populationOfNN, bestNN); FilesFunctions.logAllActorFitnesses(out2, generation, fitnessNN); // Log the generation data - stores weights try { FilesFunctions.logLastGeneration(populationOfNN); } catch (IOException e) { e.getMessage(); } // Log best individual try { FilesFunctions.logBestIndiv(populationOfNN, bestNN); } catch (IOException e) { System.err.println(e.getMessage()); } // Rank populationOfNN, select best individuals and create new generation createNewPopulation(); generation++; System.out.println("\nGENERATION \n" + generation); evaluatedNN = 0; avgFitNN = 0.0; bestFitNN = 0; bestNN = 0; minFitNN = 0; resetRobotPosition(); // Evolve games every 4 NN generations (gives them time to learn) if (generation % 5 == 0) { // Send flag to start evolution of games byte[] flag = {1}; gameEmitter.send(flag); } // Send new weights byte[] msgInBytes = Util.float2Byte(populationOfNN[evaluatedNN].getWeights()); emitter.send(msgInBytes); } } else if (finished == 0.0) { if ((evaluatedNN + 1) < NN_POP_SIZE) { storeImage(evaluatedNN); resetDisplay(); evaluatedNN++; System.out.println("Evaluated individual " + evaluatedNN); // Send next genome to experiment resetRobotPosition(); byte[] msgInBytes = Util.float2Byte(populationOfNN[evaluatedNN].getWeights()); emitter.send(msgInBytes); } } } }
public void run() { while (step(TIME_STEP) != -1) { byte[] nnFit; float finished = -1; drawRobotsPosition(); // As long as individual is being evaluated, print current fitness and return int n = receiver.getQueueLength(); if (n > 0) { nnFit = receiver.getData(); // Convert bytes into floats if (nnFit.length == 12) { byte[] currFitness = new byte[4]; for (int i = 0; i < 4; i++) { currFitness[i] = nnFit[i]; } byte[] indivNo = new byte[4]; int m = 0; for (int k = 4; k < 8; k++) { indivNo[m] = nnFit[k]; m++; } byte[] flag = new byte[4]; int l = 0; for (int j = 8; j < 12; j++) { flag[l] = nnFit[j]; l++; } int indIndex = (int) Util.bytearray2float(indivNo); fitnessNN[indIndex] = Util.bytearray2float(currFitness); finished = Util.bytearray2float(flag); receiver.nextPacket(); } else if (nnFit.length == 4) { byte[] flag = new byte[4]; for (int j = 0; j < 4; j++) { flag[j] = nnFit[j]; } finished = Util.bytearray2float(flag); receiver.nextPacket(); } } // When evaluation is done, an extra flag is returned in the message if (finished == 1.0f) { if (EVOLVING == 1) { //System.out.println("Evaluated individual " + evaluatedNN); //normaliseFitnessScore(fitnessNN); // Normalise fitness scores // Sort populationOfNN by fitness sortPopulation(sortedfitnessNN, fitnessNN); // Find and log current and absolute best individual bestFitNN = sortedfitnessNN[0][0]; minFitNN = sortedfitnessNN[NN_POP_SIZE - 1][0]; bestNN = (int) sortedfitnessNN[0][1]; avgFitNN = Util.mean(fitnessNN); if (bestFitNN > absBestFitNN) { absBestFitNN = bestFitNN; absBestNN = bestNN; FilesFunctions.logBest(out3, generation, NB_GENES, absBestNN, populationOfNN); } System.out.println("Best fitness score: \n" + bestFitNN); System.out.println("Average fitness score: \n" + avgFitNN); System.out.println("Worst fitness score: \n" + minFitNN); // Write data to files FilesFunctions.logPopulation(out1, avgFitNN, generation, fitnessNN, bestFitNN, minFitNN, NB_GENES, populationOfNN, bestNN); FilesFunctions.logAllActorFitnesses(out2, generation, fitnessNN); // Log the generation data - stores weights try { FilesFunctions.logLastGeneration(populationOfNN); } catch (IOException e) { e.getMessage(); } // Log best individual try { FilesFunctions.logBestIndiv(populationOfNN, absBestNN); } catch (IOException e) { System.err.println(e.getMessage()); } // Rank populationOfNN, select best individuals and create new generation createNewPopulation(); generation++; System.out.println("\nGENERATION \n" + generation); evaluatedNN = 0; avgFitNN = 0.0; bestFitNN = 0; bestNN = 0; minFitNN = 0; resetRobotPosition(); // Evolve games every 4 NN generations (gives them time to learn) if (generation % 5 == 0) { // Send flag to start evolution of games byte[] flag = {1}; gameEmitter.send(flag); } // Send new weights byte[] msgInBytes = Util.float2Byte(populationOfNN[evaluatedNN].getWeights()); emitter.send(msgInBytes); } } else if (finished == 0.0) { if ((evaluatedNN + 1) < NN_POP_SIZE) { storeImage(evaluatedNN); resetDisplay(); evaluatedNN++; System.out.println("Evaluated individual " + evaluatedNN); // Send next genome to experiment resetRobotPosition(); byte[] msgInBytes = Util.float2Byte(populationOfNN[evaluatedNN].getWeights()); emitter.send(msgInBytes); } } } }
diff --git a/sonar-python-plugin/src/test/java/org/sonar/plugins/python/pylint/PylintConfigurationTest.java b/sonar-python-plugin/src/test/java/org/sonar/plugins/python/pylint/PylintConfigurationTest.java index 0dfdfb0a..4a835eb8 100644 --- a/sonar-python-plugin/src/test/java/org/sonar/plugins/python/pylint/PylintConfigurationTest.java +++ b/sonar-python-plugin/src/test/java/org/sonar/plugins/python/pylint/PylintConfigurationTest.java @@ -1,58 +1,59 @@ /* * Sonar Python Plugin * Copyright (C) 2011 Waleri Enns * [email protected] * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.python.pylint; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.junit.Test; import org.sonar.api.resources.Project; import org.sonar.api.resources.ProjectFileSystem; import java.io.File; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PylintConfigurationTest { @Test public void shouldGetCorrectPylintPath() { Configuration conf = new BaseConfiguration(); PylintConfiguration pylintConfiguration = new PylintConfiguration(conf); ProjectFileSystem pfs = mock(ProjectFileSystem.class); when(pfs.getBasedir()).thenReturn(new File("/projectroot")); Project project = new Project("foo"); project.setFileSystem(pfs); assertThat(pylintConfiguration.getPylintConfigPath(project)).isNull(); conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, ""); assertThat(pylintConfiguration.getPylintConfigPath(project)).isNull(); conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, ".pylintrc"); assertThat(pylintConfiguration.getPylintConfigPath(project)).isEqualTo(new File("/projectroot/.pylintrc").getAbsolutePath()); - conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, "/absolute/.pylintrc"); - assertThat(pylintConfiguration.getPylintConfigPath(project)).isEqualTo(new File("/absolute/.pylintrc").getAbsolutePath()); + String absolutePath = new File("/absolute/.pylintrc").getAbsolutePath(); + conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, absolutePath); + assertThat(pylintConfiguration.getPylintConfigPath(project)).isEqualTo(absolutePath); } }
true
true
public void shouldGetCorrectPylintPath() { Configuration conf = new BaseConfiguration(); PylintConfiguration pylintConfiguration = new PylintConfiguration(conf); ProjectFileSystem pfs = mock(ProjectFileSystem.class); when(pfs.getBasedir()).thenReturn(new File("/projectroot")); Project project = new Project("foo"); project.setFileSystem(pfs); assertThat(pylintConfiguration.getPylintConfigPath(project)).isNull(); conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, ""); assertThat(pylintConfiguration.getPylintConfigPath(project)).isNull(); conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, ".pylintrc"); assertThat(pylintConfiguration.getPylintConfigPath(project)).isEqualTo(new File("/projectroot/.pylintrc").getAbsolutePath()); conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, "/absolute/.pylintrc"); assertThat(pylintConfiguration.getPylintConfigPath(project)).isEqualTo(new File("/absolute/.pylintrc").getAbsolutePath()); }
public void shouldGetCorrectPylintPath() { Configuration conf = new BaseConfiguration(); PylintConfiguration pylintConfiguration = new PylintConfiguration(conf); ProjectFileSystem pfs = mock(ProjectFileSystem.class); when(pfs.getBasedir()).thenReturn(new File("/projectroot")); Project project = new Project("foo"); project.setFileSystem(pfs); assertThat(pylintConfiguration.getPylintConfigPath(project)).isNull(); conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, ""); assertThat(pylintConfiguration.getPylintConfigPath(project)).isNull(); conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, ".pylintrc"); assertThat(pylintConfiguration.getPylintConfigPath(project)).isEqualTo(new File("/projectroot/.pylintrc").getAbsolutePath()); String absolutePath = new File("/absolute/.pylintrc").getAbsolutePath(); conf.setProperty(PylintConfiguration.PYLINT_CONFIG_KEY, absolutePath); assertThat(pylintConfiguration.getPylintConfigPath(project)).isEqualTo(absolutePath); }
diff --git a/src/java/org/wings/plaf/css/IconTextCompound.java b/src/java/org/wings/plaf/css/IconTextCompound.java index c0babbf9..c3026968 100644 --- a/src/java/org/wings/plaf/css/IconTextCompound.java +++ b/src/java/org/wings/plaf/css/IconTextCompound.java @@ -1,99 +1,99 @@ /* * $Id$ * Copyright 2000,2005 wingS development team. * * This file is part of wingS (http://www.j-wings.org). * * wingS is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * Please see COPYING for the complete licence. */ package org.wings.plaf.css; import org.wings.SComponent; import org.wings.SConstants; import org.wings.SDimension; import org.wings.io.Device; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; /** * @author hengels * @version $Revision$ */ public abstract class IconTextCompound { private final static transient Log log = LogFactory.getLog(IconTextCompound.class); public void writeCompound(Device device, SComponent component, int horizontal, int vertical) throws IOException { if (horizontal == SConstants.NO_ALIGN) horizontal = SConstants.RIGHT; if (vertical == SConstants.NO_ALIGN) vertical = SConstants.CENTER; boolean order = vertical == SConstants.TOP || (vertical == SConstants.CENTER && horizontal == SConstants.LEFT); device.print("<table class=\"SLayout\""); SDimension prefSize = component.getPreferredSize(); if (prefSize != null && (prefSize.getWidth() != null || prefSize.getHeight() != null)) { device.print(" style=\"width:100%;height:100%\""); } device.print(">"); if (vertical == SConstants.TOP && horizontal == SConstants.LEFT || vertical == SConstants.BOTTOM && horizontal == SConstants.RIGHT) { device.print("<tr><td align=\"left\" valign=\"top\" class=\"SLayout\">"); first(device, order); device.print("</td><td class=\"SLayout\"></td></tr><tr><td class=\"SLayout\"></td><td align=\"right\" valign=\"bottom\" class=\"SLayout\">"); last(device, order); device.print("</td></tr>"); } else if (vertical == SConstants.TOP && horizontal == SConstants.RIGHT || vertical == SConstants.BOTTOM && horizontal == SConstants.LEFT) { device.print("<tr><td class=\"SLayout\"></td><td align=\"right\" valign=\"top\" class=\"SLayout\">"); first(device, order); device.print("</td></tr><tr><td align=\"left\" valign=\"bottom\" class=\"SLayout\">"); last(device, order); device.print("</td><td class=\"SLayout\"></td></tr>"); } else if (vertical == SConstants.TOP && horizontal == SConstants.CENTER || vertical == SConstants.BOTTOM && horizontal == SConstants.CENTER) { device.print("<tr><td align=\"center\" valign=\"top\" class=\"SLayout\">"); first(device, order); - device.print("</td></tr><tr><td align=\"center\" valign=\"bottom\"> class=\"SLayout\""); + device.print("</td></tr><tr><td align=\"center\" valign=\"bottom\" class=\"SLayout\">"); last(device, order); device.print("</td></tr>"); } else if (vertical == SConstants.CENTER && horizontal == SConstants.LEFT || vertical == SConstants.CENTER && horizontal == SConstants.RIGHT) { device.print("<tr><td align=\"left\" class=\"SLayout\">"); first(device, order); device.print("</td><td align=\"right\" class=\"SLayout\">"); last(device, order); device.print("</td></tr>"); } else { log.warn("horizontal = " + horizontal); log.warn("vertical = " + vertical); } device.print("</table>"); } private void first(Device d, boolean order) throws IOException { if (order) text(d); else icon(d); } private void last(Device d, boolean order) throws IOException { if (!order) text(d); else icon(d); } protected abstract void text(Device d) throws IOException; protected abstract void icon(Device d) throws IOException; }
true
true
public void writeCompound(Device device, SComponent component, int horizontal, int vertical) throws IOException { if (horizontal == SConstants.NO_ALIGN) horizontal = SConstants.RIGHT; if (vertical == SConstants.NO_ALIGN) vertical = SConstants.CENTER; boolean order = vertical == SConstants.TOP || (vertical == SConstants.CENTER && horizontal == SConstants.LEFT); device.print("<table class=\"SLayout\""); SDimension prefSize = component.getPreferredSize(); if (prefSize != null && (prefSize.getWidth() != null || prefSize.getHeight() != null)) { device.print(" style=\"width:100%;height:100%\""); } device.print(">"); if (vertical == SConstants.TOP && horizontal == SConstants.LEFT || vertical == SConstants.BOTTOM && horizontal == SConstants.RIGHT) { device.print("<tr><td align=\"left\" valign=\"top\" class=\"SLayout\">"); first(device, order); device.print("</td><td class=\"SLayout\"></td></tr><tr><td class=\"SLayout\"></td><td align=\"right\" valign=\"bottom\" class=\"SLayout\">"); last(device, order); device.print("</td></tr>"); } else if (vertical == SConstants.TOP && horizontal == SConstants.RIGHT || vertical == SConstants.BOTTOM && horizontal == SConstants.LEFT) { device.print("<tr><td class=\"SLayout\"></td><td align=\"right\" valign=\"top\" class=\"SLayout\">"); first(device, order); device.print("</td></tr><tr><td align=\"left\" valign=\"bottom\" class=\"SLayout\">"); last(device, order); device.print("</td><td class=\"SLayout\"></td></tr>"); } else if (vertical == SConstants.TOP && horizontal == SConstants.CENTER || vertical == SConstants.BOTTOM && horizontal == SConstants.CENTER) { device.print("<tr><td align=\"center\" valign=\"top\" class=\"SLayout\">"); first(device, order); device.print("</td></tr><tr><td align=\"center\" valign=\"bottom\"> class=\"SLayout\""); last(device, order); device.print("</td></tr>"); } else if (vertical == SConstants.CENTER && horizontal == SConstants.LEFT || vertical == SConstants.CENTER && horizontal == SConstants.RIGHT) { device.print("<tr><td align=\"left\" class=\"SLayout\">"); first(device, order); device.print("</td><td align=\"right\" class=\"SLayout\">"); last(device, order); device.print("</td></tr>"); } else { log.warn("horizontal = " + horizontal); log.warn("vertical = " + vertical); } device.print("</table>"); }
public void writeCompound(Device device, SComponent component, int horizontal, int vertical) throws IOException { if (horizontal == SConstants.NO_ALIGN) horizontal = SConstants.RIGHT; if (vertical == SConstants.NO_ALIGN) vertical = SConstants.CENTER; boolean order = vertical == SConstants.TOP || (vertical == SConstants.CENTER && horizontal == SConstants.LEFT); device.print("<table class=\"SLayout\""); SDimension prefSize = component.getPreferredSize(); if (prefSize != null && (prefSize.getWidth() != null || prefSize.getHeight() != null)) { device.print(" style=\"width:100%;height:100%\""); } device.print(">"); if (vertical == SConstants.TOP && horizontal == SConstants.LEFT || vertical == SConstants.BOTTOM && horizontal == SConstants.RIGHT) { device.print("<tr><td align=\"left\" valign=\"top\" class=\"SLayout\">"); first(device, order); device.print("</td><td class=\"SLayout\"></td></tr><tr><td class=\"SLayout\"></td><td align=\"right\" valign=\"bottom\" class=\"SLayout\">"); last(device, order); device.print("</td></tr>"); } else if (vertical == SConstants.TOP && horizontal == SConstants.RIGHT || vertical == SConstants.BOTTOM && horizontal == SConstants.LEFT) { device.print("<tr><td class=\"SLayout\"></td><td align=\"right\" valign=\"top\" class=\"SLayout\">"); first(device, order); device.print("</td></tr><tr><td align=\"left\" valign=\"bottom\" class=\"SLayout\">"); last(device, order); device.print("</td><td class=\"SLayout\"></td></tr>"); } else if (vertical == SConstants.TOP && horizontal == SConstants.CENTER || vertical == SConstants.BOTTOM && horizontal == SConstants.CENTER) { device.print("<tr><td align=\"center\" valign=\"top\" class=\"SLayout\">"); first(device, order); device.print("</td></tr><tr><td align=\"center\" valign=\"bottom\" class=\"SLayout\">"); last(device, order); device.print("</td></tr>"); } else if (vertical == SConstants.CENTER && horizontal == SConstants.LEFT || vertical == SConstants.CENTER && horizontal == SConstants.RIGHT) { device.print("<tr><td align=\"left\" class=\"SLayout\">"); first(device, order); device.print("</td><td align=\"right\" class=\"SLayout\">"); last(device, order); device.print("</td></tr>"); } else { log.warn("horizontal = " + horizontal); log.warn("vertical = " + vertical); } device.print("</table>"); }
diff --git a/src/main/java/org/jenkinsci/plugins/rallyBuild/RallyBuild.java b/src/main/java/org/jenkinsci/plugins/rallyBuild/RallyBuild.java index 1718430..c2ac757 100644 --- a/src/main/java/org/jenkinsci/plugins/rallyBuild/RallyBuild.java +++ b/src/main/java/org/jenkinsci/plugins/rallyBuild/RallyBuild.java @@ -1,394 +1,393 @@ package org.jenkinsci.plugins.rallyBuild; import hudson.EnvVars; import hudson.Extension; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Descriptor; import hudson.model.AbstractDescribableImpl; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import java.io.IOException; import java.io.Serializable; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Logger; import net.sf.json.JSONObject; import org.jenkinsci.plugins.rallyBuild.rallyActions.Action; import org.jenkinsci.plugins.rallyBuild.rallyActions.CommentAction; import org.jenkinsci.plugins.rallyBuild.rallyActions.DefectStateAction; import org.jenkinsci.plugins.rallyBuild.rallyActions.ReadyAction; import org.jenkinsci.plugins.rallyBuild.rallyActions.StateAction; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import com.rallydev.rest.RallyRestApi; public class RallyBuild extends Builder { public final String issueString; public final Boolean updateOnce; public String issueRallyState; public String defectRallyState; public String commentText; public Boolean issueReady; public String preCommentText; public String preIssueRallyState; public Boolean preReadyState; public Boolean changeRallyState =false; public Boolean changeDefectRallyState= false; public Boolean createComment =false; public Boolean changeReady =false; public Boolean preComment =false; public Boolean preReady =false; public Set<String> updatedIssues = new HashSet<String>(); private static final Logger logger = Logger.getLogger(RallyBuild.class.getName()); public List<PreRallyState> preRallyState; //Fields in config.jelly must match the parameter names in the "DataBoundConstructor" @DataBoundConstructor public RallyBuild(List<PreRallyState> preRallyState, String issueString, Boolean updateOnce, PreCommentBlock preComment, PreReadyBlock preReady, EnableReadyBlock changeReady,CreateCommentBlock createComment, ChangeStateBlock changeRallyState, ChangeDefectStateBlock changeDefectRallyState) { this.issueString = issueString; this.updateOnce=updateOnce; this.preRallyState=preRallyState; if(changeDefectRallyState!=null){ this.changeDefectRallyState=true; this.defectRallyState=changeDefectRallyState.getIssueState(); } if(changeRallyState!=null){ this.changeRallyState=true; this.issueRallyState=changeRallyState.getIssueState(); } if(createComment!=null){ this.createComment=true; this.commentText=createComment.getComment(); } if(changeReady!=null){ this.changeReady=true; this.issueReady=changeReady.getIssueReady(); } if(preComment!=null){ this.preComment=true; this.preCommentText = preComment.getComment(); } if(preReady!=null){ this.preReady=true; this.preReadyState=preReady.getIssueReady(); } } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { EnvVars env = build.getEnvironment(listener); String expandedCommentText = env.expand(commentText); String expandedPreConditionText = env.expand(preCommentText); String expandedIssueString = env.expand(issueString); List<Action> rallyActions = new ArrayList<Action>(); List<Action> preConditions = new ArrayList<Action>(); List<StateAction> preStates = new ArrayList<StateAction>(); Rally rally = null; try { logger.info("Server "+getDescriptor().getRallyServer()); RallyRestApi api = new RallyRestApi(new URI(getDescriptor().getRallyServer()), getDescriptor().getRallyUser(), getDescriptor().getRallyPassword()); rally = new Rally(api,listener); } catch (URISyntaxException e) { e.printStackTrace(); } if(rally!=null){ logger.info("Pre Condition Comment "+createComment); if(preComment){ CommentAction comment = new CommentAction(expandedPreConditionText); preConditions.add(comment); } logger.info("Pre Condition Ready "+changeReady); if(preReady){ ReadyAction ready = new ReadyAction(preReadyState); preConditions.add(ready); } - logger.info("Pre RallyStates "+preRallyState.size()); if(preRallyState!=null && preRallyState.size()>0){ for(PreRallyState rallyState :preRallyState){ StateAction action = new StateAction(rallyState.getStateName()); preStates.add(action); } } logger.info("Create Comment "+createComment); if(createComment){ CommentAction comment = new CommentAction(expandedCommentText); rallyActions.add(comment); } logger.info("Mark ready "+changeReady); if(changeReady){ ReadyAction ready = new ReadyAction(issueReady); rallyActions.add(ready); } logger.info("Change State "+changeRallyState); if(changeRallyState){ StateAction state = new StateAction(issueRallyState); rallyActions.add(state); } logger.info("Change State "+changeDefectRallyState); if(changeDefectRallyState){ DefectStateAction defectState = new DefectStateAction(defectRallyState); rallyActions.add(defectState); } HashSet<String> issues = rally.getIssues(expandedIssueString); rally.updateIssues(issues,preConditions,preStates,rallyActions,updateOnce); } return true; } public static class EnableReadyBlock { private Boolean issueReady; @DataBoundConstructor public EnableReadyBlock(Boolean issueReady) { this.issueReady = issueReady; } public Boolean getIssueReady() { return issueReady; } } public static class ChangeStateBlock { private String issueRallyState; @DataBoundConstructor public ChangeStateBlock(String issueRallyState) { this.issueRallyState = issueRallyState; } public String getIssueState() { return issueRallyState; } } public static class ChangeDefectStateBlock { private String defectRallyState; @DataBoundConstructor public ChangeDefectStateBlock(String defectRallyState) { this.defectRallyState = defectRallyState; } public String getIssueState() { return defectRallyState; } } public static final class PreRallyState extends AbstractDescribableImpl<PreRallyState> implements Serializable{ /** * */ private static final long serialVersionUID = 147571780733339453L; private String stateName; @DataBoundConstructor public PreRallyState(String stateName){ this.stateName=stateName; } public String getStateName() { return stateName; } @Extension public static class DescriptorImpl extends Descriptor<PreRallyState> { public String getDisplayName() { return ""; } } } public static class CreateCommentBlock { private String commentText; @DataBoundConstructor public CreateCommentBlock(String commentText) { this.commentText = commentText; } public String getComment() { return commentText; } } public static class PreCommentBlock { private String preCommentText; @DataBoundConstructor public PreCommentBlock(String preCommentText) { this.preCommentText = preCommentText; } public String getComment() { return preCommentText; } } public static class PreReadyBlock { private Boolean preReadyState; @DataBoundConstructor public PreReadyBlock(Boolean preReadyState) { this.preReadyState = preReadyState; } public Boolean getIssueReady() { return preReadyState; } } public static class PreRallyStateBlock { private String preIssueRallyState; @DataBoundConstructor public PreRallyStateBlock(String preIssueRallyState) { this.preIssueRallyState = preIssueRallyState; } public String getIssueState() { return preIssueRallyState; } } // Overridden for better type safety. // If your plugin doesn't really define any property on Descriptor, // you don't have to do this. @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl)super.getDescriptor(); } @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { /** * To persist global configuration information, * simply store it in a field and call save(). * * <p> * If you don't want fields to be persisted, use <tt>transient</tt>. */ private String rallyServer; private String rallyPassword; private String rallyUser; public DescriptorImpl(){ load(); } public boolean isApplicable(Class<? extends AbstractProject> aClass) { // Indicates that this builder can be used with all kinds of project types return true; } /** * This human readable name is used in the configuration screen. */ public String getDisplayName() { return "Rally Builder"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { // To persist global configuration information, // set that to properties and call save(). //name = formData.getString("name"); rallyServer = formData.getString("rallyServer"); rallyUser = formData.getString("rallyUser"); rallyPassword = formData.getString("rallyPassword"); // ^Can also use req.bindJSON(this, formData); // (easier when there are many fields; need set* methods for this, like setUseFrench) save(); return super.configure(req,formData); } /** * This method returns true if the global configuration says we should speak French. * * The method name is bit awkward because global.jelly calls this method to determine * the initial state of the checkbox by the naming convention. */ public String getRallyServer(){ return rallyServer; } public String getRallyUser(){ return rallyUser; } public String getRallyPassword(){ return rallyPassword; } } }
true
true
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { EnvVars env = build.getEnvironment(listener); String expandedCommentText = env.expand(commentText); String expandedPreConditionText = env.expand(preCommentText); String expandedIssueString = env.expand(issueString); List<Action> rallyActions = new ArrayList<Action>(); List<Action> preConditions = new ArrayList<Action>(); List<StateAction> preStates = new ArrayList<StateAction>(); Rally rally = null; try { logger.info("Server "+getDescriptor().getRallyServer()); RallyRestApi api = new RallyRestApi(new URI(getDescriptor().getRallyServer()), getDescriptor().getRallyUser(), getDescriptor().getRallyPassword()); rally = new Rally(api,listener); } catch (URISyntaxException e) { e.printStackTrace(); } if(rally!=null){ logger.info("Pre Condition Comment "+createComment); if(preComment){ CommentAction comment = new CommentAction(expandedPreConditionText); preConditions.add(comment); } logger.info("Pre Condition Ready "+changeReady); if(preReady){ ReadyAction ready = new ReadyAction(preReadyState); preConditions.add(ready); } logger.info("Pre RallyStates "+preRallyState.size()); if(preRallyState!=null && preRallyState.size()>0){ for(PreRallyState rallyState :preRallyState){ StateAction action = new StateAction(rallyState.getStateName()); preStates.add(action); } } logger.info("Create Comment "+createComment); if(createComment){ CommentAction comment = new CommentAction(expandedCommentText); rallyActions.add(comment); } logger.info("Mark ready "+changeReady); if(changeReady){ ReadyAction ready = new ReadyAction(issueReady); rallyActions.add(ready); } logger.info("Change State "+changeRallyState); if(changeRallyState){ StateAction state = new StateAction(issueRallyState); rallyActions.add(state); } logger.info("Change State "+changeDefectRallyState); if(changeDefectRallyState){ DefectStateAction defectState = new DefectStateAction(defectRallyState); rallyActions.add(defectState); } HashSet<String> issues = rally.getIssues(expandedIssueString); rally.updateIssues(issues,preConditions,preStates,rallyActions,updateOnce); } return true; }
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { EnvVars env = build.getEnvironment(listener); String expandedCommentText = env.expand(commentText); String expandedPreConditionText = env.expand(preCommentText); String expandedIssueString = env.expand(issueString); List<Action> rallyActions = new ArrayList<Action>(); List<Action> preConditions = new ArrayList<Action>(); List<StateAction> preStates = new ArrayList<StateAction>(); Rally rally = null; try { logger.info("Server "+getDescriptor().getRallyServer()); RallyRestApi api = new RallyRestApi(new URI(getDescriptor().getRallyServer()), getDescriptor().getRallyUser(), getDescriptor().getRallyPassword()); rally = new Rally(api,listener); } catch (URISyntaxException e) { e.printStackTrace(); } if(rally!=null){ logger.info("Pre Condition Comment "+createComment); if(preComment){ CommentAction comment = new CommentAction(expandedPreConditionText); preConditions.add(comment); } logger.info("Pre Condition Ready "+changeReady); if(preReady){ ReadyAction ready = new ReadyAction(preReadyState); preConditions.add(ready); } if(preRallyState!=null && preRallyState.size()>0){ for(PreRallyState rallyState :preRallyState){ StateAction action = new StateAction(rallyState.getStateName()); preStates.add(action); } } logger.info("Create Comment "+createComment); if(createComment){ CommentAction comment = new CommentAction(expandedCommentText); rallyActions.add(comment); } logger.info("Mark ready "+changeReady); if(changeReady){ ReadyAction ready = new ReadyAction(issueReady); rallyActions.add(ready); } logger.info("Change State "+changeRallyState); if(changeRallyState){ StateAction state = new StateAction(issueRallyState); rallyActions.add(state); } logger.info("Change State "+changeDefectRallyState); if(changeDefectRallyState){ DefectStateAction defectState = new DefectStateAction(defectRallyState); rallyActions.add(defectState); } HashSet<String> issues = rally.getIssues(expandedIssueString); rally.updateIssues(issues,preConditions,preStates,rallyActions,updateOnce); } return true; }
diff --git a/src/main/java/org/drpowell/xlifyvcf/XLifyVcf.java b/src/main/java/org/drpowell/xlifyvcf/XLifyVcf.java index 97377b9..8bcd3ef 100644 --- a/src/main/java/org/drpowell/xlifyvcf/XLifyVcf.java +++ b/src/main/java/org/drpowell/xlifyvcf/XLifyVcf.java @@ -1,265 +1,265 @@ package org.drpowell.xlifyvcf; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.Map; import java.util.zip.GZIPInputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.drpowell.varitas.VCFMeta; import org.drpowell.varitas.VCFParser; import org.drpowell.varitas.VCFVariant; public class XLifyVcf { public final Workbook workbook; public final VCFParser vcfParser; private final CreationHelper createHelper; private final Map<String, VCFMeta> infos; private final Map<String, VCFMeta> formats; private final String [] samples; private final String [] headers; private final Sheet dataSheet; private short rowNum = 0; private BitSet numericColumns; private CellStyle hlink_style; private Map<Integer, HyperlinkColumn> columnsToHyperlink; private enum HyperlinkColumn { GENE("http://www.ncbi.nlm.nih.gov/gene?term=%s"), SNP("http://www.ncbi.nlm.nih.gov/projects/SNP/snp_ref.cgi?rs=%s"), OMIM("http://omim.org/search?search=%s"), GENETESTS("http://www.ncbi.nlm.nih.gov/sites/GeneTests/review/gene/%s?db=genetests&search_param=begins_with"); public final String url; HyperlinkColumn(String url) { this.url = url; }; } public XLifyVcf(VCFParser input) { workbook = new HSSFWorkbook(); createHelper = workbook.getCreationHelper(); vcfParser = input; formats = vcfParser.formats(); infos = vcfParser.infos(); samples = vcfParser.samples(); headers = makeHeaders(); makeMetaSheet(); dataSheet = setupDataSheet(); } private String [] makeHeaders() { numericColumns = new BitSet(); ArrayList<String> out = new ArrayList<String>(Arrays.asList(vcfParser.getColHeaderLine().split("\t", -1))); numericColumns.set(1); numericColumns.set(5); for (VCFMeta m: infos.values()) { if ("1".equals(m.getValue("Number"))) { String type = m.getValue("Type"); if ("Integer".equals(type) || "Float".equals(type)) { numericColumns.set(out.size()); } } out.add(m.getId()); } for (String s : samples) { for (VCFMeta m: formats.values()) { if ("1".equals(m.getValue("Number"))) { String type = m.getValue("Type"); if ("Integer".equals(type) || "Float".equals(type)) { numericColumns.set(out.size()); } } out.add(s + "_" + m.getId()); } } return out.toArray(new String[out.size()]); } private void mapHeadersToHyperlinks() { Map<String, HyperlinkColumn> acceptableHeaders = new HashMap<String, HyperlinkColumn>(); columnsToHyperlink = new HashMap<Integer, HyperlinkColumn>(16); acceptableHeaders.put("gene", HyperlinkColumn.GENE); acceptableHeaders.put("gene_name", HyperlinkColumn.GENE); acceptableHeaders.put("id", HyperlinkColumn.SNP); acceptableHeaders.put("in_omim", HyperlinkColumn.OMIM); acceptableHeaders.put("omim", HyperlinkColumn.OMIM); acceptableHeaders.put("in_genetests", HyperlinkColumn.GENETESTS); acceptableHeaders.put("genetests", HyperlinkColumn.GENETESTS); for (int i = 0; i < headers.length; i++) { HyperlinkColumn hc = acceptableHeaders.get(headers[i].toLowerCase()); if (hc != null) { columnsToHyperlink.put(i, hc); } } } private Sheet setupDataSheet() { Sheet data = workbook.createSheet("data"); Row r = data.createRow(rowNum); for (int c = 0; c < headers.length; c++) { r.createCell(c).setCellValue(headers[c]); } hlink_style = workbook.createCellStyle(); Font hlink_font = workbook.createFont(); hlink_font.setUnderline(Font.U_SINGLE); hlink_font.setColor(IndexedColors.BLUE.getIndex()); hlink_style.setFont(hlink_font); mapHeadersToHyperlinks(); return data; } private void makeMetaSheet() { Sheet metaSheet = workbook.createSheet("metadata"); String [] headers = vcfParser.getMetaHeaders().split("\n"); for (int i = 0; i < headers.length; i++) { metaSheet.createRow(i).createCell(0).setCellValue(headers[i]); } } private boolean filterAF(VCFVariant v, String key, double cutoff) { String afString = v.getInfoField(key); if (afString == null || afString.isEmpty() || ".".equals(afString)) return true; try { double d = Double.valueOf(afString); return d <= cutoff; } catch (NumberFormatException nfe) { // nothing to do } return true; } private boolean filter(VCFVariant v) { String vFilter = v.getFilter(); double cutoff = 0.01; return ("PASS".equals(vFilter) || ".".equals(vFilter) && filterAF(v, "NIEHSAF", cutoff) && filterAF(v, "NIEHSIAF", cutoff) && filterAF(v, "TGAF", cutoff) ); } private void writeRow(VCFVariant v) { rowNum++; ArrayList<String> data = new ArrayList<String>(headers.length); Row r = dataSheet.createRow(rowNum); data.addAll(Arrays.asList(v.toString().split("\t", -1))); for (String i : vcfParser.infos().keySet()) { data.add(v.getInfoField(i)); } String [] calls = v.getCalls(); String [] callFormat = v.getFormat().split(":", -1); Map<String, Integer> formatIndices = new HashMap<String, Integer>(callFormat.length * 2); for (int i = 0; i < callFormat.length; i++) { formatIndices.put(callFormat[i], i); } if (calls.length == samples.length) { for (String call: calls) { String [] subfields = call.split(":"); for (String k: formats.keySet()) { Integer i = formatIndices.get(k); - if (i == null) { + if (i == null || i >= subfields.length) { data.add(""); } else { data.add(subfields[i]); } } } } else { throw new RuntimeException("Problem with VCF line: " + v.toString()); } for (int i = 0; i < data.size(); i++) { String d = data.get(i); if (d != null && !".".equals(d)) { Cell c = r.createCell(i); if (numericColumns.get(i)) { try { Double db = new Double(d); c.setCellValue(db.doubleValue()); } catch (NumberFormatException nfe) { // FIXME - maybe I should log this, maybe not c.setCellValue(d); } } else { c.setCellValue(d); } } } makeHyperlinks(r); } private void makeHyperlinks(Row r) { DataFormatter df = new DataFormatter(); Cell chromosomeCell = r.getCell(0); String chr = df.formatCellValue(chromosomeCell); long pos = Math.round(r.getCell(1).getNumericCellValue()); Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL); link.setAddress(String.format("http://genome.ucsc.edu/cgi-bin/hgTracks?db=hg19&position=chr%s:%d-%d", chr, pos-100, pos+100)); chromosomeCell.setHyperlink(link); chromosomeCell.setCellStyle(hlink_style); for (Map.Entry<Integer, HyperlinkColumn> kv : columnsToHyperlink.entrySet()) { Cell c = r.getCell(kv.getKey()); if (c != null) { link = createHelper.createHyperlink(Hyperlink.LINK_URL); link.setAddress(String.format(kv.getValue().url, df.formatCellValue(c))); c.setHyperlink(link); c.setCellStyle(hlink_style); } } } public void doWork() { for (VCFVariant variant : vcfParser) { if (filter(variant)) { writeRow(variant); // TODO: progress } } } public void writeOutput(OutputStream out) throws IOException { workbook.write(out); } /** * @param args */ public static void main(String[] args) throws IOException { FileOutputStream output = new FileOutputStream(args[0]); BufferedReader input; if (args.length > 1) { if (args[1].endsWith(".gz")) { input = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(args[1])))); } else { input = new BufferedReader(new FileReader(args[1])); } } else { input = new BufferedReader(new InputStreamReader(System.in)); } XLifyVcf xlv = new XLifyVcf(new VCFParser(input)); xlv.doWork(); xlv.writeOutput(output); } }
true
true
private void writeRow(VCFVariant v) { rowNum++; ArrayList<String> data = new ArrayList<String>(headers.length); Row r = dataSheet.createRow(rowNum); data.addAll(Arrays.asList(v.toString().split("\t", -1))); for (String i : vcfParser.infos().keySet()) { data.add(v.getInfoField(i)); } String [] calls = v.getCalls(); String [] callFormat = v.getFormat().split(":", -1); Map<String, Integer> formatIndices = new HashMap<String, Integer>(callFormat.length * 2); for (int i = 0; i < callFormat.length; i++) { formatIndices.put(callFormat[i], i); } if (calls.length == samples.length) { for (String call: calls) { String [] subfields = call.split(":"); for (String k: formats.keySet()) { Integer i = formatIndices.get(k); if (i == null) { data.add(""); } else { data.add(subfields[i]); } } } } else { throw new RuntimeException("Problem with VCF line: " + v.toString()); } for (int i = 0; i < data.size(); i++) { String d = data.get(i); if (d != null && !".".equals(d)) { Cell c = r.createCell(i); if (numericColumns.get(i)) { try { Double db = new Double(d); c.setCellValue(db.doubleValue()); } catch (NumberFormatException nfe) { // FIXME - maybe I should log this, maybe not c.setCellValue(d); } } else { c.setCellValue(d); } } } makeHyperlinks(r); }
private void writeRow(VCFVariant v) { rowNum++; ArrayList<String> data = new ArrayList<String>(headers.length); Row r = dataSheet.createRow(rowNum); data.addAll(Arrays.asList(v.toString().split("\t", -1))); for (String i : vcfParser.infos().keySet()) { data.add(v.getInfoField(i)); } String [] calls = v.getCalls(); String [] callFormat = v.getFormat().split(":", -1); Map<String, Integer> formatIndices = new HashMap<String, Integer>(callFormat.length * 2); for (int i = 0; i < callFormat.length; i++) { formatIndices.put(callFormat[i], i); } if (calls.length == samples.length) { for (String call: calls) { String [] subfields = call.split(":"); for (String k: formats.keySet()) { Integer i = formatIndices.get(k); if (i == null || i >= subfields.length) { data.add(""); } else { data.add(subfields[i]); } } } } else { throw new RuntimeException("Problem with VCF line: " + v.toString()); } for (int i = 0; i < data.size(); i++) { String d = data.get(i); if (d != null && !".".equals(d)) { Cell c = r.createCell(i); if (numericColumns.get(i)) { try { Double db = new Double(d); c.setCellValue(db.doubleValue()); } catch (NumberFormatException nfe) { // FIXME - maybe I should log this, maybe not c.setCellValue(d); } } else { c.setCellValue(d); } } } makeHyperlinks(r); }
diff --git a/src/microcontroller/threads/PresenceThread.java b/src/microcontroller/threads/PresenceThread.java index b31030a..b30d281 100644 --- a/src/microcontroller/threads/PresenceThread.java +++ b/src/microcontroller/threads/PresenceThread.java @@ -1,81 +1,83 @@ package microcontroller.threads; import java.util.LinkedList; import java.util.TimerTask; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Semaphore; import microcontroller.interfaces.Database; import microcontroller.interfaces.Presence; public class PresenceThread extends TimerTask { protected Presence presence; protected Database db; protected BlockingQueue<String> messagesToPublish; protected LinkedList<String> nearbyUsers; protected LinkedList<String> staticNearbyUsers; protected Semaphore nearbyUsersSemaphore; public PresenceThread(Presence presence, Database db, BlockingQueue<String> messagesToPublish, LinkedList<String> nearbyUsers, Semaphore nearbyUsersSemaphore) { super(); this.presence = presence; this.db = db; this.messagesToPublish = messagesToPublish; this.nearbyUsers = nearbyUsers; this.nearbyUsersSemaphore = nearbyUsersSemaphore; this.staticNearbyUsers = new LinkedList<String>(); this.staticNearbyUsers.add("1CB0940951E7"); } @Override public void run() { while (true) { try { System.out.println("Presence service is running"); LinkedList<String> previousNearbyUsers = new LinkedList<String>(); /* * Find out current devices in the room */ this.nearbyUsersSemaphore.acquire(); if (!this.nearbyUsers.isEmpty()) { previousNearbyUsers.addAll(this.nearbyUsers); this.nearbyUsers.clear(); } this.presence.resetDevs(); this.presence.detectDevs(); this.nearbyUsers.addAll(this.presence.getDevs()); for(String deviceId: staticNearbyUsers) { if(!nearbyUsers.contains(deviceId)) { this.nearbyUsers.add(deviceId); } } /* * Which devices left the room? */ previousNearbyUsers.removeAll(this.nearbyUsers); /* * TODO: Decide if this is necessary. Might make things ugly. */ /* * Publish the users that present in the previous sweep but not * in this one */ for (String userDeviceId : previousNearbyUsers) { String twitterName = db.getTwitterNameFromDeviceId(userDeviceId); + if(twitterName == null) + continue; db.logOutUserWithDeviceId(userDeviceId); this.messagesToPublish.add(String.format("@%s left the room.", twitterName)); } this.nearbyUsersSemaphore.release(); break; } catch (InterruptedException e) { } } } }
true
true
public void run() { while (true) { try { System.out.println("Presence service is running"); LinkedList<String> previousNearbyUsers = new LinkedList<String>(); /* * Find out current devices in the room */ this.nearbyUsersSemaphore.acquire(); if (!this.nearbyUsers.isEmpty()) { previousNearbyUsers.addAll(this.nearbyUsers); this.nearbyUsers.clear(); } this.presence.resetDevs(); this.presence.detectDevs(); this.nearbyUsers.addAll(this.presence.getDevs()); for(String deviceId: staticNearbyUsers) { if(!nearbyUsers.contains(deviceId)) { this.nearbyUsers.add(deviceId); } } /* * Which devices left the room? */ previousNearbyUsers.removeAll(this.nearbyUsers); /* * TODO: Decide if this is necessary. Might make things ugly. */ /* * Publish the users that present in the previous sweep but not * in this one */ for (String userDeviceId : previousNearbyUsers) { String twitterName = db.getTwitterNameFromDeviceId(userDeviceId); db.logOutUserWithDeviceId(userDeviceId); this.messagesToPublish.add(String.format("@%s left the room.", twitterName)); } this.nearbyUsersSemaphore.release(); break; } catch (InterruptedException e) { } } }
public void run() { while (true) { try { System.out.println("Presence service is running"); LinkedList<String> previousNearbyUsers = new LinkedList<String>(); /* * Find out current devices in the room */ this.nearbyUsersSemaphore.acquire(); if (!this.nearbyUsers.isEmpty()) { previousNearbyUsers.addAll(this.nearbyUsers); this.nearbyUsers.clear(); } this.presence.resetDevs(); this.presence.detectDevs(); this.nearbyUsers.addAll(this.presence.getDevs()); for(String deviceId: staticNearbyUsers) { if(!nearbyUsers.contains(deviceId)) { this.nearbyUsers.add(deviceId); } } /* * Which devices left the room? */ previousNearbyUsers.removeAll(this.nearbyUsers); /* * TODO: Decide if this is necessary. Might make things ugly. */ /* * Publish the users that present in the previous sweep but not * in this one */ for (String userDeviceId : previousNearbyUsers) { String twitterName = db.getTwitterNameFromDeviceId(userDeviceId); if(twitterName == null) continue; db.logOutUserWithDeviceId(userDeviceId); this.messagesToPublish.add(String.format("@%s left the room.", twitterName)); } this.nearbyUsersSemaphore.release(); break; } catch (InterruptedException e) { } } }
diff --git a/src/main/java/org/candlepin/resource/DistributorVersionResource.java b/src/main/java/org/candlepin/resource/DistributorVersionResource.java index 37d265274..4cfefdd37 100644 --- a/src/main/java/org/candlepin/resource/DistributorVersionResource.java +++ b/src/main/java/org/candlepin/resource/DistributorVersionResource.java @@ -1,125 +1,125 @@ /** * Copyright (c) 2009 - 2012 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.candlepin.resource; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.candlepin.auth.Principal; import org.candlepin.exceptions.BadRequestException; import org.candlepin.exceptions.NotFoundException; import org.candlepin.model.DistributorVersion; import org.candlepin.model.DistributorVersionCurator; import org.xnap.commons.i18n.I18n; import com.google.inject.Inject; /** * DistributorVersionResource */ @Path("/distributor_versions") public class DistributorVersionResource { private I18n i18n; private DistributorVersionCurator curator; @Inject public DistributorVersionResource(I18n i18n, DistributorVersionCurator curator) { this.i18n = i18n; this.curator = curator; } /** * @return a DistributorVersion list * @httpcode 200 */ @GET @Produces(MediaType.APPLICATION_JSON) public List<DistributorVersion> getVersions() { return curator.findAll(); } /** * @httpcode 400 * @httpcode 404 * @httpcode 200 */ @DELETE @Path("/{id}") public void delete(@PathParam("id") String id, @Context Principal principal) { DistributorVersion dv = curator.findById(id); if (dv != null) { curator.delete(dv); } } /** * @return a DistributorVersion * @httpcode 200 */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public DistributorVersion create(DistributorVersion dv, @Context Principal principal) { DistributorVersion existing = curator.findByName(dv.getName()); if (existing != null) { throw new BadRequestException( - i18n.tr("A distributor version with name {0}" + + i18n.tr("A distributor version with name {0} " + "already exists", dv.getName())); } return curator.create(dv); } /** * @return a DistributorVersion * @httpcode 200 */ @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") public DistributorVersion update(@PathParam("id") String id, DistributorVersion dv, @Context Principal principal) { DistributorVersion existing = verifyAndLookupDistributorVersion(id); existing.setDisplayName(dv.getDisplayName()); existing.setCapabilities(dv.getCapabilities()); curator.merge(existing); return existing; } private DistributorVersion verifyAndLookupDistributorVersion(String id) { DistributorVersion dv = curator.findById(id); if (dv == null) { throw new NotFoundException(i18n.tr("No such distributor version: {0}", id)); } return dv; } }
true
true
public DistributorVersion create(DistributorVersion dv, @Context Principal principal) { DistributorVersion existing = curator.findByName(dv.getName()); if (existing != null) { throw new BadRequestException( i18n.tr("A distributor version with name {0}" + "already exists", dv.getName())); } return curator.create(dv); }
public DistributorVersion create(DistributorVersion dv, @Context Principal principal) { DistributorVersion existing = curator.findByName(dv.getName()); if (existing != null) { throw new BadRequestException( i18n.tr("A distributor version with name {0} " + "already exists", dv.getName())); } return curator.create(dv); }
diff --git a/src/net/slipcor/pvparena/commands/PAG_Join.java b/src/net/slipcor/pvparena/commands/PAG_Join.java index 307ef265..e1fbfe97 100644 --- a/src/net/slipcor/pvparena/commands/PAG_Join.java +++ b/src/net/slipcor/pvparena/commands/PAG_Join.java @@ -1,71 +1,74 @@ package net.slipcor.pvparena.commands; import net.slipcor.pvparena.arena.Arena; import net.slipcor.pvparena.arena.ArenaPlayer; import net.slipcor.pvparena.classes.PACheck; import net.slipcor.pvparena.core.Help; import net.slipcor.pvparena.core.Language; import net.slipcor.pvparena.core.Help.HELP; import net.slipcor.pvparena.core.Language.MSG; import net.slipcor.pvparena.managers.ConfigurationManager; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * <pre>PVP Arena JOIN Command class</pre> * * A command to join an arena * * @author slipcor * * @version v0.9.4 */ public class PAG_Join extends PAA__Command { public PAG_Join() { super(new String[] {"pvparena.user"}); } @Override public void commit(Arena arena, CommandSender sender, String[] args) { if (!this.hasPerms(sender, arena)) { return; } if (!this.argCountValid(sender, arena, args, new Integer[]{0,1})) { return; } if (!(sender instanceof Player)) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ONLY_PLAYERS)); return; } String error = ConfigurationManager.isSetup(arena); if (error != null) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ERROR, error)); return; } ArenaPlayer ap = ArenaPlayer.parsePlayer(sender.getName()); - if (ap.getArena() != null || arena.hasAlreadyPlayed(ap.getName())) { + if (ap.getArena() != null) { Arena a = ap.getArena(); a.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, a.getName())); return; + } else if (arena.hasAlreadyPlayed(ap.getName())) { + arena.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, arena.getName())); + return; } PACheck.handleJoin(arena, sender, args); } @Override public String getName() { return this.getClass().getName(); } @Override public void displayHelp(CommandSender sender) { Arena.pmsg(sender, Help.parse(HELP.JOIN)); } }
false
true
public void commit(Arena arena, CommandSender sender, String[] args) { if (!this.hasPerms(sender, arena)) { return; } if (!this.argCountValid(sender, arena, args, new Integer[]{0,1})) { return; } if (!(sender instanceof Player)) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ONLY_PLAYERS)); return; } String error = ConfigurationManager.isSetup(arena); if (error != null) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ERROR, error)); return; } ArenaPlayer ap = ArenaPlayer.parsePlayer(sender.getName()); if (ap.getArena() != null || arena.hasAlreadyPlayed(ap.getName())) { Arena a = ap.getArena(); a.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, a.getName())); return; } PACheck.handleJoin(arena, sender, args); }
public void commit(Arena arena, CommandSender sender, String[] args) { if (!this.hasPerms(sender, arena)) { return; } if (!this.argCountValid(sender, arena, args, new Integer[]{0,1})) { return; } if (!(sender instanceof Player)) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ONLY_PLAYERS)); return; } String error = ConfigurationManager.isSetup(arena); if (error != null) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ERROR, error)); return; } ArenaPlayer ap = ArenaPlayer.parsePlayer(sender.getName()); if (ap.getArena() != null) { Arena a = ap.getArena(); a.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, a.getName())); return; } else if (arena.hasAlreadyPlayed(ap.getName())) { arena.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, arena.getName())); return; } PACheck.handleJoin(arena, sender, args); }
diff --git a/backend/skynet_backend/src/main/java/toctep/skynet/backend/dal/dao/impl/mysql/UserDaoImpl.java b/backend/skynet_backend/src/main/java/toctep/skynet/backend/dal/dao/impl/mysql/UserDaoImpl.java index 4010c9c..8ac0358 100644 --- a/backend/skynet_backend/src/main/java/toctep/skynet/backend/dal/dao/impl/mysql/UserDaoImpl.java +++ b/backend/skynet_backend/src/main/java/toctep/skynet/backend/dal/dao/impl/mysql/UserDaoImpl.java @@ -1,94 +1,94 @@ package toctep.skynet.backend.dal.dao.impl.mysql; import java.sql.ResultSet; import java.sql.SQLException; import toctep.skynet.backend.dal.dao.UserDao; import toctep.skynet.backend.dal.domain.User; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class UserDaoImpl implements UserDao { @Override public User selectUser(String name) { Connection conn = DaoConnectionImpl.getInstance().getConnection(); User user = null; Statement stmt = null; ResultSet rs = null; try { stmt = (Statement) conn.createStatement(); rs = stmt.executeQuery("SELECT name FROM twitter_user WHERE name = '" + name + "'"); rs.first(); - user = new User(rs.getString("name")); + user = new User(rs.getInt("id"), rs.getString("name")); } catch (SQLException e) { e.printStackTrace(); } finally { try { stmt.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } return user; } @Override public void insertUser(User user) { Connection conn = DaoConnectionImpl.getInstance().getConnection(); Statement stmt = null; try { stmt = (Statement) conn.createStatement(); stmt.executeUpdate( "INSERT INTO twitter_user" + "(name)" + "VALUES " + "('" + user.getName() + "')"); } catch (SQLException e) { e.printStackTrace(); } finally { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } @Override public void updateUser(User user) { // TODO Auto-generated method stub } @Override public void deleteUser(User user) { Connection conn = DaoConnectionImpl.getInstance().getConnection(); Statement stmt = null; try { stmt = (Statement) conn.createStatement(); stmt.executeUpdate( "DELETE FROM twitter_tweet" + "WHERE id=" + user.getId()); } catch (SQLException e) { e.printStackTrace(); } finally { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
true
true
public User selectUser(String name) { Connection conn = DaoConnectionImpl.getInstance().getConnection(); User user = null; Statement stmt = null; ResultSet rs = null; try { stmt = (Statement) conn.createStatement(); rs = stmt.executeQuery("SELECT name FROM twitter_user WHERE name = '" + name + "'"); rs.first(); user = new User(rs.getString("name")); } catch (SQLException e) { e.printStackTrace(); } finally { try { stmt.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } return user; }
public User selectUser(String name) { Connection conn = DaoConnectionImpl.getInstance().getConnection(); User user = null; Statement stmt = null; ResultSet rs = null; try { stmt = (Statement) conn.createStatement(); rs = stmt.executeQuery("SELECT name FROM twitter_user WHERE name = '" + name + "'"); rs.first(); user = new User(rs.getInt("id"), rs.getString("name")); } catch (SQLException e) { e.printStackTrace(); } finally { try { stmt.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } return user; }
diff --git a/syncronizer/src/org/sync/MainEntry.java b/syncronizer/src/org/sync/MainEntry.java index b35684e..1151009 100644 --- a/syncronizer/src/org/sync/MainEntry.java +++ b/syncronizer/src/org/sync/MainEntry.java @@ -1,197 +1,198 @@ /***************************************************************************** This file is part of Git-Starteam. Git-Starteam is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Git-Starteam is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Git-Starteam. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.sync; import java.io.Console; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import com.starbase.starteam.Project; import com.starbase.starteam.Server; import com.starbase.starteam.View; import jargs.gnu.CmdLineParser; import jargs.gnu.CmdLineParser.IllegalOptionValueException; import jargs.gnu.CmdLineParser.UnknownOptionException; public class MainEntry { /** * @param args */ public static void main(String[] args) { CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option selectHost = parser.addStringOption('h', "host"); CmdLineParser.Option selectPort = parser.addIntegerOption('P', "port"); CmdLineParser.Option selectProject = parser.addStringOption('p', "project"); CmdLineParser.Option selectView = parser.addStringOption('v', "view"); CmdLineParser.Option selectTimeBasedImport = parser.addBooleanOption('T', "time-based"); CmdLineParser.Option selectTime = parser.addStringOption('t', "time"); CmdLineParser.Option selectFolder = parser.addStringOption('f', "folder"); CmdLineParser.Option selectDomain = parser.addStringOption('d', "domain"); CmdLineParser.Option isExpandKeywords = parser.addBooleanOption('k', "keyword"); CmdLineParser.Option selectUser = parser.addStringOption('U', "user"); CmdLineParser.Option isResume = parser.addBooleanOption('R', "resume"); CmdLineParser.Option selectHead = parser.addStringOption('H', "head"); CmdLineParser.Option selectPath = parser.addStringOption('X', "path-to-program"); CmdLineParser.Option isCreateRepo = parser.addBooleanOption('c', "create-new-repo"); CmdLineParser.Option selectPassword = parser.addStringOption("password"); CmdLineParser.Option dumpToFile = parser.addStringOption('D', "dump"); CmdLineParser.Option isVerbose = parser.addBooleanOption("verbose"); try { parser.parse(args); } catch (IllegalOptionValueException e) { System.err.println(e.getMessage()); printHelp(); System.exit(1); } catch (UnknownOptionException e) { System.err.println(e.getMessage()); printHelp(); System.exit(2); } String host = (String) parser.getOptionValue(selectHost); Integer port = (Integer) parser.getOptionValue(selectPort); String project = (String) parser.getOptionValue(selectProject); String view = (String) parser.getOptionValue(selectView); String time = (String) parser.getOptionValue(selectTime); Boolean timeBased = (Boolean) parser.getOptionValue(selectTimeBasedImport); String folder = (String) parser.getOptionValue(selectFolder); String domain = (String) parser.getOptionValue(selectDomain); Boolean keyword = (Boolean) parser.getOptionValue(isExpandKeywords); String user = (String) parser.getOptionValue(selectUser); Boolean resume = (Boolean) parser.getOptionValue(isResume); String head = (String) parser.getOptionValue(selectHead); String pathToProgram = (String) parser.getOptionValue(selectPath); Boolean createNewRepo = (Boolean) parser.getOptionValue(isCreateRepo); String password = (String) parser.getOptionValue(selectPassword); String dumpTo = (String) parser.getOptionValue(dumpToFile); - boolean verbose = (Boolean) parser.getOptionValue(isVerbose); + Boolean verboseFlag = (Boolean) parser.getOptionValue(isVerbose); + boolean verbose = verboseFlag != null && verboseFlag; if(host == null || port == null || project == null || view == null) { printHelp(); System.exit(3); } if(null != folder && !folder.endsWith("/")) { folder = folder + "/"; } Date date = null; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(null != time) { try { date = dateFormat.parse(time); } catch (Exception ex) { System.out.println(ex.getMessage()); System.exit(3); } } if(null == domain) { domain = "cie.com"; } RepositoryHelperFactory.getFactory().setPreferedPath(pathToProgram); RepositoryHelperFactory.getFactory().setCreateRepo((null != createNewRepo)); Server starteam = new Server(host, port); starteam.connect(); Console con = System.console(); if(null == user) { user = con.readLine("Username:"); } if(null == password) { password = new String(con.readPassword("Password:")); } int userid = starteam.logOn(user, password); if(userid > 0) { boolean projectFound = false; for(Project p : starteam.getProjects()) { if(p.getName().equalsIgnoreCase(project)) { projectFound = true; if(null == keyword) { p.setExpandKeywords(false); } else { p.setExpandKeywords(true); } GitImporter g = new GitImporter(starteam, p); if(null != head) { g.setHeadName(head); } if(null != resume) { g.setResume(resume); } if(null != dumpTo) { g.setDumpFile(new File(dumpTo)); } g.setVerbose(verbose); boolean viewFound = false; for(View v : p.getViews()) { if(v.getName().equalsIgnoreCase(view)) { viewFound = true; if(null != timeBased && timeBased) { g.generateDayByDayImport(v, date, folder, domain); } else { g.generateFastImportStream(v, folder, domain); } // process is finished we can close now. g.dispose(); break; } else if(verbose) { System.err.println("Not view: " + v.getName()); } } if (!viewFound) { System.err.println("View not found: " + view); } break; } else if(verbose) { System.err.println("Not project: " + p.getName()); } } if (!projectFound) { System.err.println("Project not found: " + project); } } else { System.err.println("Could not log in user: " + user); } } public static void printHelp() { System.out.println("-h <host>\t\tDefine on which host the server is hosted"); System.out.println("-P <port>\t\tDefine the port used to connect to the starteam server"); System.out.println("-p <project>\t\tSelect the project to import from"); System.out.println("-v <view>\t\tSelect the view used for importation"); System.out.println("-t <time>\t\tSelect the time (format like \"2012-07-11 23:59:59\") to import from"); System.out.println("-f <folder>\t\tSelect the folder (format like Src/apps/vlc2android/) to import from"); System.out.println("-d <domain>\t\tSelect the email domain (format like gmail.com) of the user"); System.out.println("[-T]\t\t\tDo a day by day importation of the starteam view"); System.out.println("[-k]\t\t\tSet to enable keyword expansion in text files"); System.out.println("[-U <user>]\t\tPreselect the user login"); System.out.println("[-R]\t\t\tResume the file history importation for branch view"); System.out.println("[-H <head>]\t\tSelect the name of the head to use"); System.out.println("[-X <path to dvcs>]\tSelect the path where to find the dvcs executable"); System.out.println("[-c]\t\t\tCreate a new repository if one does not exist"); System.out.println("[--password]\t\t\tStarTeam password"); System.out.println("-D <dump file>\t\t\tDump fast-import data to file"); System.out.println("[--verbose]\t\t\tVerbose output"); System.out.println("java -jar Syncronizer.jar -h localhost -P 23456 -p Alpha -v MAIN -U you"); } }
true
true
public static void main(String[] args) { CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option selectHost = parser.addStringOption('h', "host"); CmdLineParser.Option selectPort = parser.addIntegerOption('P', "port"); CmdLineParser.Option selectProject = parser.addStringOption('p', "project"); CmdLineParser.Option selectView = parser.addStringOption('v', "view"); CmdLineParser.Option selectTimeBasedImport = parser.addBooleanOption('T', "time-based"); CmdLineParser.Option selectTime = parser.addStringOption('t', "time"); CmdLineParser.Option selectFolder = parser.addStringOption('f', "folder"); CmdLineParser.Option selectDomain = parser.addStringOption('d', "domain"); CmdLineParser.Option isExpandKeywords = parser.addBooleanOption('k', "keyword"); CmdLineParser.Option selectUser = parser.addStringOption('U', "user"); CmdLineParser.Option isResume = parser.addBooleanOption('R', "resume"); CmdLineParser.Option selectHead = parser.addStringOption('H', "head"); CmdLineParser.Option selectPath = parser.addStringOption('X', "path-to-program"); CmdLineParser.Option isCreateRepo = parser.addBooleanOption('c', "create-new-repo"); CmdLineParser.Option selectPassword = parser.addStringOption("password"); CmdLineParser.Option dumpToFile = parser.addStringOption('D', "dump"); CmdLineParser.Option isVerbose = parser.addBooleanOption("verbose"); try { parser.parse(args); } catch (IllegalOptionValueException e) { System.err.println(e.getMessage()); printHelp(); System.exit(1); } catch (UnknownOptionException e) { System.err.println(e.getMessage()); printHelp(); System.exit(2); } String host = (String) parser.getOptionValue(selectHost); Integer port = (Integer) parser.getOptionValue(selectPort); String project = (String) parser.getOptionValue(selectProject); String view = (String) parser.getOptionValue(selectView); String time = (String) parser.getOptionValue(selectTime); Boolean timeBased = (Boolean) parser.getOptionValue(selectTimeBasedImport); String folder = (String) parser.getOptionValue(selectFolder); String domain = (String) parser.getOptionValue(selectDomain); Boolean keyword = (Boolean) parser.getOptionValue(isExpandKeywords); String user = (String) parser.getOptionValue(selectUser); Boolean resume = (Boolean) parser.getOptionValue(isResume); String head = (String) parser.getOptionValue(selectHead); String pathToProgram = (String) parser.getOptionValue(selectPath); Boolean createNewRepo = (Boolean) parser.getOptionValue(isCreateRepo); String password = (String) parser.getOptionValue(selectPassword); String dumpTo = (String) parser.getOptionValue(dumpToFile); boolean verbose = (Boolean) parser.getOptionValue(isVerbose); if(host == null || port == null || project == null || view == null) { printHelp(); System.exit(3); } if(null != folder && !folder.endsWith("/")) { folder = folder + "/"; } Date date = null; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(null != time) { try { date = dateFormat.parse(time); } catch (Exception ex) { System.out.println(ex.getMessage()); System.exit(3); } } if(null == domain) { domain = "cie.com"; } RepositoryHelperFactory.getFactory().setPreferedPath(pathToProgram); RepositoryHelperFactory.getFactory().setCreateRepo((null != createNewRepo)); Server starteam = new Server(host, port); starteam.connect(); Console con = System.console(); if(null == user) { user = con.readLine("Username:"); } if(null == password) { password = new String(con.readPassword("Password:")); } int userid = starteam.logOn(user, password); if(userid > 0) { boolean projectFound = false; for(Project p : starteam.getProjects()) { if(p.getName().equalsIgnoreCase(project)) { projectFound = true; if(null == keyword) { p.setExpandKeywords(false); } else { p.setExpandKeywords(true); } GitImporter g = new GitImporter(starteam, p); if(null != head) { g.setHeadName(head); } if(null != resume) { g.setResume(resume); } if(null != dumpTo) { g.setDumpFile(new File(dumpTo)); } g.setVerbose(verbose); boolean viewFound = false; for(View v : p.getViews()) { if(v.getName().equalsIgnoreCase(view)) { viewFound = true; if(null != timeBased && timeBased) { g.generateDayByDayImport(v, date, folder, domain); } else { g.generateFastImportStream(v, folder, domain); } // process is finished we can close now. g.dispose(); break; } else if(verbose) { System.err.println("Not view: " + v.getName()); } } if (!viewFound) { System.err.println("View not found: " + view); } break; } else if(verbose) { System.err.println("Not project: " + p.getName()); } } if (!projectFound) { System.err.println("Project not found: " + project); } } else { System.err.println("Could not log in user: " + user); } }
public static void main(String[] args) { CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option selectHost = parser.addStringOption('h', "host"); CmdLineParser.Option selectPort = parser.addIntegerOption('P', "port"); CmdLineParser.Option selectProject = parser.addStringOption('p', "project"); CmdLineParser.Option selectView = parser.addStringOption('v', "view"); CmdLineParser.Option selectTimeBasedImport = parser.addBooleanOption('T', "time-based"); CmdLineParser.Option selectTime = parser.addStringOption('t', "time"); CmdLineParser.Option selectFolder = parser.addStringOption('f', "folder"); CmdLineParser.Option selectDomain = parser.addStringOption('d', "domain"); CmdLineParser.Option isExpandKeywords = parser.addBooleanOption('k', "keyword"); CmdLineParser.Option selectUser = parser.addStringOption('U', "user"); CmdLineParser.Option isResume = parser.addBooleanOption('R', "resume"); CmdLineParser.Option selectHead = parser.addStringOption('H', "head"); CmdLineParser.Option selectPath = parser.addStringOption('X', "path-to-program"); CmdLineParser.Option isCreateRepo = parser.addBooleanOption('c', "create-new-repo"); CmdLineParser.Option selectPassword = parser.addStringOption("password"); CmdLineParser.Option dumpToFile = parser.addStringOption('D', "dump"); CmdLineParser.Option isVerbose = parser.addBooleanOption("verbose"); try { parser.parse(args); } catch (IllegalOptionValueException e) { System.err.println(e.getMessage()); printHelp(); System.exit(1); } catch (UnknownOptionException e) { System.err.println(e.getMessage()); printHelp(); System.exit(2); } String host = (String) parser.getOptionValue(selectHost); Integer port = (Integer) parser.getOptionValue(selectPort); String project = (String) parser.getOptionValue(selectProject); String view = (String) parser.getOptionValue(selectView); String time = (String) parser.getOptionValue(selectTime); Boolean timeBased = (Boolean) parser.getOptionValue(selectTimeBasedImport); String folder = (String) parser.getOptionValue(selectFolder); String domain = (String) parser.getOptionValue(selectDomain); Boolean keyword = (Boolean) parser.getOptionValue(isExpandKeywords); String user = (String) parser.getOptionValue(selectUser); Boolean resume = (Boolean) parser.getOptionValue(isResume); String head = (String) parser.getOptionValue(selectHead); String pathToProgram = (String) parser.getOptionValue(selectPath); Boolean createNewRepo = (Boolean) parser.getOptionValue(isCreateRepo); String password = (String) parser.getOptionValue(selectPassword); String dumpTo = (String) parser.getOptionValue(dumpToFile); Boolean verboseFlag = (Boolean) parser.getOptionValue(isVerbose); boolean verbose = verboseFlag != null && verboseFlag; if(host == null || port == null || project == null || view == null) { printHelp(); System.exit(3); } if(null != folder && !folder.endsWith("/")) { folder = folder + "/"; } Date date = null; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(null != time) { try { date = dateFormat.parse(time); } catch (Exception ex) { System.out.println(ex.getMessage()); System.exit(3); } } if(null == domain) { domain = "cie.com"; } RepositoryHelperFactory.getFactory().setPreferedPath(pathToProgram); RepositoryHelperFactory.getFactory().setCreateRepo((null != createNewRepo)); Server starteam = new Server(host, port); starteam.connect(); Console con = System.console(); if(null == user) { user = con.readLine("Username:"); } if(null == password) { password = new String(con.readPassword("Password:")); } int userid = starteam.logOn(user, password); if(userid > 0) { boolean projectFound = false; for(Project p : starteam.getProjects()) { if(p.getName().equalsIgnoreCase(project)) { projectFound = true; if(null == keyword) { p.setExpandKeywords(false); } else { p.setExpandKeywords(true); } GitImporter g = new GitImporter(starteam, p); if(null != head) { g.setHeadName(head); } if(null != resume) { g.setResume(resume); } if(null != dumpTo) { g.setDumpFile(new File(dumpTo)); } g.setVerbose(verbose); boolean viewFound = false; for(View v : p.getViews()) { if(v.getName().equalsIgnoreCase(view)) { viewFound = true; if(null != timeBased && timeBased) { g.generateDayByDayImport(v, date, folder, domain); } else { g.generateFastImportStream(v, folder, domain); } // process is finished we can close now. g.dispose(); break; } else if(verbose) { System.err.println("Not view: " + v.getName()); } } if (!viewFound) { System.err.println("View not found: " + view); } break; } else if(verbose) { System.err.println("Not project: " + p.getName()); } } if (!projectFound) { System.err.println("Project not found: " + project); } } else { System.err.println("Could not log in user: " + user); } }
diff --git a/AndroidRally/src/se/chalmers/dryleafsoftware/androidrally/controller/AIRobotController.java b/AndroidRally/src/se/chalmers/dryleafsoftware/androidrally/controller/AIRobotController.java index 2e1ae78..053fae2 100644 --- a/AndroidRally/src/se/chalmers/dryleafsoftware/androidrally/controller/AIRobotController.java +++ b/AndroidRally/src/se/chalmers/dryleafsoftware/androidrally/controller/AIRobotController.java @@ -1,460 +1,460 @@ package se.chalmers.dryleafsoftware.androidrally.controller; import java.util.ArrayList; import java.util.Collections; import java.util.List; import se.chalmers.dryleafsoftware.androidrally.model.cards.Card; import se.chalmers.dryleafsoftware.androidrally.model.gameBoard.BoardElement; import se.chalmers.dryleafsoftware.androidrally.model.cards.Move; import se.chalmers.dryleafsoftware.androidrally.model.cards.Turn; import se.chalmers.dryleafsoftware.androidrally.model.cards.TurnType; import se.chalmers.dryleafsoftware.androidrally.model.gameBoard.GameBoard; import se.chalmers.dryleafsoftware.androidrally.model.gameBoard.Hole; import se.chalmers.dryleafsoftware.androidrally.model.robots.Robot; /** * This is a simple AI class which can choose cards for robots. * <p> * This class will not be able to guide robots through maps which is to tricky. The only * boardelements which this class will take into account is Holes and walls which it will * attempt to run around, other boardelements such as conveyor belt will not be considered. * * * @author * */ public class AIRobotController { private GameBoard gb; private List<Card> chosenCards; private Robot robot; private int x; private int y; private int direction; private int nextCheckPoint; private int[] checkpointPosition; private List<Card> cards; private List<Move> moveForwardCards; private List<Move> moveBackwardCards; private List<Card> leftTurnCards; private List<Card> rightTurnCards; private List<Card> uTurnCards; /** * Creates a new AI which will make moves according to the gameboard provided. * @param gb */ public AIRobotController(GameBoard gb) { this.gb = gb; } /** * Cards will be chosen for the robot provided. Cards will be chosen with the * goal of reaching the next checkpoint for the robot. * @param robot the robot to choose cards for. */ @SuppressWarnings("unchecked") public void makeMove(Robot robot) { cards = new ArrayList<Card>(); moveForwardCards = new ArrayList<Move>(); moveBackwardCards = new ArrayList<Move>(); leftTurnCards = new ArrayList<Card>(); rightTurnCards = new ArrayList<Card>(); uTurnCards = new ArrayList<Card>(); chosenCards = new ArrayList<Card>(); cards.addAll(robot.getCards()); //Put the cards of the robot in the correct lists for (Card card : cards) { if (card instanceof Turn) { if(((Turn)card).getTurn() == TurnType.LEFT){ leftTurnCards.add((Turn)card); }else if(((Turn)card).getTurn() == TurnType.RIGHT){ rightTurnCards.add((Turn)card); }else { uTurnCards.add((Turn)card); } } } for (Card card : cards) { if (card instanceof Move) { if (((Move)card).getDistance() > 0) { moveForwardCards.add((Move)card); } else { moveBackwardCards.add((Move)card); } } } Collections.sort(moveForwardCards); // These values will be needed through the class. x = robot.getX(); y = robot.getY(); direction = robot.getDirection(); nextCheckPoint = robot.getLastCheckPoint() + 1; checkpointPosition = nextCheckPoint(); placeCards(); robot.setChosenCards(chosenCards); } /** * This method will choose the cards for the robot. In most cases it will choose one * card and then call itself. */ private void placeCards() { if (chosenCards.size() == 5) { return; } boolean isRightDirection = false; for (Integer direction : getDirections()) { // Check if the robot stand in a correct direction - if (this.direction == direction) { + if (this.direction == direction.intValue()) { isRightDirection = true; } } if (isRightDirection) { if (moveForwardCards.size() != 0) { // Move forward with a fitting distance if(direction == GameBoard.NORTH || direction == GameBoard.SOUTH){ addMoveCard(Math.abs(getDY())); }else{ addMoveCard(Math.abs(getDX())); } } else { //check if there are other good combinations of cards if(chosenCards.size() <= 1 && moveBackwardCards.size() >= 2 && uTurnCards.size() >= 2) { //turn around, walk backwards 2 steps and turn around again addChosenCard(uTurnCards.get(0)); addChosenCard(moveBackwardCards.get(0)); addChosenCard(moveBackwardCards.get(0)); addChosenCard(uTurnCards.get(0)); } else if (chosenCards.size() <= 2 && moveBackwardCards.size() >= 1 && uTurnCards.size() >= 2) { //turn around, walk backwards 1 step and turn around again addChosenCard(uTurnCards.get(0)); addChosenCard(moveBackwardCards.get(0)); addChosenCard(uTurnCards.get(0)); } else {// if there are none -> random card - randomizeCard(); //maybe randomize between turn-cards? TODO + randomizeCard(); } } } else { // If the robot is turned towards a wrong direction. if (rightTurnCards.size() != 0 || leftTurnCards.size() != 0 || uTurnCards.size() != 0) { // Try turn towards a correct direction boolean cardAdded = false; for(Integer i : getDirections()){ int turnDifference = ((i.intValue() - direction)+4)%4; if(turnDifference == 3){ if(leftTurnCards.size() != 0){ addChosenCard(leftTurnCards.get(0)); cardAdded = true; break; } }else if(turnDifference == 2){ if(uTurnCards.size() != 0){ addChosenCard(uTurnCards.get(0)); cardAdded = true; break; } }else if(turnDifference == 1){ if(rightTurnCards.size() != 0){ addChosenCard(rightTurnCards.get(0)); cardAdded = true; break; } } } if(!cardAdded){ for(int j = 0; j<cards.size(); j++){ if(!(cards.get(j) instanceof Move)){ addChosenCard(cards.get(j)); cardAdded = true; break; } } if(!cardAdded){ randomizeCard(); } } } else { // No turn cards -> random card randomizeCard(); } } placeCards(); } /** * Add a card to chosenCards and changes instance variables accordingly. * @param card */ private void addChosenCard(Card card){ chosenCards.add(card); removeCardFromLists(card); changeCalculatedPosition(card); } /** * After one card is chosen this method can be called to update the instance variables * which will make it possible to choose a good next card. * @param card the card which will change the calculated position. */ private void changeCalculatedPosition(Card card){ if(card instanceof Move){ if(direction == GameBoard.NORTH){ y = y - ((Move)card).getDistance(); }else if(direction == GameBoard.EAST){ x = x + ((Move)card).getDistance(); }else if(direction == GameBoard.SOUTH){ y = y + ((Move)card).getDistance(); }else if(direction == GameBoard.WEST){ x = x - ((Move)card).getDistance(); } }else if(card instanceof Turn){ if(((Turn)card).getTurn() == TurnType.LEFT){ direction = (direction + 3) % 4; }else if(((Turn)card).getTurn() == TurnType.RIGHT){ direction = (direction + 1) % 4; }else{ // UTurn direction = (direction + 2) % 4; } } } /** * Returns the next checkpoint for the robot. * @param robot the robot to find the next checkpoint for. * @return the next checkpoint for the robot in the form [posX][posY]. */ private int[] nextCheckPoint() { int[] xy = new int[2]; for(int i = 0; i <= 1; i++) { xy[i] = gb.getCheckPoints().get(nextCheckPoint)[i]; } return xy; } /** * Will return a list of good directions for the robot to walk. The list * will contain directions which would move the robot closer to the next * checkpoint. If such a direction would lead the robot towards a hole, a wall * or outside the map the direction will be removed. In case the last direction * was removed two perpendicular directions will be added. * @return a list of good directions for the robot to walk. */ private List<Integer> getDirections(){ List<Integer> directions = new ArrayList<Integer>(); int dx = getDX(); int dy = getDY(); if (x == checkpointPosition[0] && y == checkpointPosition[1]) { nextCheckPoint++; if (nextCheckPoint > gb.getCheckPoints().size()) { for (int i = chosenCards.size(); i < 5; i++) { randomizeCard(); } } else { checkpointPosition = gb.getCheckPoints().get(nextCheckPoint); dx = getDX(); dy = getDY(); } } if(dx < 0){ directions.add(Integer.valueOf(GameBoard.EAST)); }else if(dx > 0){ directions.add(Integer.valueOf(GameBoard.WEST)); } if(dy < 0){ directions.add(Integer.valueOf(GameBoard.SOUTH)); }else if(dy > 0){ directions.add(Integer.valueOf(GameBoard.NORTH)); } removeBadDirections(directions); // The direction which distance towards the checkpoint is // longest should be first in the list. if(directions.size() == 2){ if(Math.abs(dx) < Math.abs(dy)){ directions.add(directions.remove(0)); } } return directions; } /** * Removes a direction from a list. If the direction removed is the last, two * perpendicular directions will be added. * @param directions the list to remove a direction from. * @param indexToRemove the index of the direction to remove. */ private void removeDirection(List<Integer> directions, int indexToRemove){ if(directions.size() == 1){ directions.add(((indexToRemove + 1) % 4)); directions.add(((indexToRemove + 3) % 4)); } directions.remove(indexToRemove); } /** * Will remove directions which will not be good for the robot. If the robot * have a hole, wall or the map ends within <code>Math.min(3, Math.abs(getDY()))</code> * the direction will be removed. * @param directions the list to check for badDirections. */ private void removeBadDirections(List<Integer> directions){ if(x<0 || x>(gb.getWidth()-1) || y<0 || y>(gb.getHeight()-1)){ return; } for(int i = 0; i < directions.size(); i++){ if(directions.get(i).intValue() == GameBoard.NORTH){ for(int j = 0; j < Math.min(3, Math.abs(getDY())); j++){ if((y-j) >= 0 && !gb.getTile(x, y-j).getNorthWall()){ if (gb.getTile(x, y-j).getBoardElements() != null) { for(BoardElement boardElement : gb.getTile(x, (y-j)).getBoardElements()){ if(boardElement instanceof Hole){ removeDirection(directions, i); break; } } } }else{ removeDirection(directions, i); break; } } }else if(directions.get(i).intValue() == GameBoard.EAST){ for(int j = 0; j < Math.min(3, Math.abs(getDX())); j++){ if((x+j) < gb.getWidth() && !gb.getTile(x+j, y).getEastWall()){ if (gb.getTile(x+j, y).getBoardElements() != null) { for(BoardElement boardElement : gb.getTile((x+j), y).getBoardElements()){ if(boardElement instanceof Hole){ removeDirection(directions, i); break; } } } }else{ removeDirection(directions, i); break; } } }else if(directions.get(i).intValue() == GameBoard.SOUTH){ for(int j = 0; j < Math.min(3, Math.abs(getDY())); j++){ if((y+j) < gb.getHeight() && !gb.getTile(x, y+j).getSouthWall()){ if (gb.getTile(x, y+j).getBoardElements() != null) { for(BoardElement boardElement : gb.getTile(x, (y+j)).getBoardElements()){ if(boardElement instanceof Hole){ removeDirection(directions, i); break; } } } }else{ removeDirection(directions, i); break; } } }else if(directions.get(i).intValue() == GameBoard.WEST){ for(int j = 0; j < Math.min(3, Math.abs(getDX())); j++){ if((x-j) >= 0 && !gb.getTile(x-j, y).getWestWall()){ if (gb.getTile(x-j, y).getBoardElements() != null) { for(BoardElement boardElement : gb.getTile((x-j), y).getBoardElements()){ if(boardElement instanceof Hole){ removeDirection(directions, i); break; } } } }else{ removeDirection(directions, i); break; } } } } } /** * Adds a move card to chosenCards. The move card chosen will be the move card * biggest move distance <= distance. * @param distance the distance the robot should try to move. */ private void addMoveCard(int distance){ for(Move card : moveForwardCards){// the list is sorted with longest distance first. if(card.getDistance() <= distance){ addChosenCard(card); return; } } randomizeCard(); } /** * The difference in the x-axis between the next checkpoint and the * robots calculated position. * @return The difference in the x-axis between the next checkpoint and the * robots calculated position. */ private int getDX(){ return (x - checkpointPosition[0]); } /** * The difference in the y-axis between the next checkpoint and the * robots calculated position. * @return The difference in the y-axis between the next checkpoint and the * robots calculated position. */ private int getDY(){ return (y - checkpointPosition[1]); } /** * Removes a card from all lists in this class except chosenCards. * @param card the card to be removed. */ private void removeCardFromLists(Card card) { cards.remove(card); if (card instanceof Move) { if (((Move)card).getDistance() > 0) { moveForwardCards.remove(card); } else { moveBackwardCards.remove(card); } } else if (card instanceof Turn) { if (((Turn) card).getTurn() == TurnType.LEFT) { leftTurnCards.remove(card); } else if (((Turn) card).getTurn() == TurnType.UTURN) { uTurnCards.remove(card); } else if (((Turn) card).getTurn() == TurnType.RIGHT) { rightTurnCards.remove(card); } } } /** * Will choose a "random" card. Will try to add cards in the order turnLeft, turnRight, uTurn, * any other card. */ private void randomizeCard() { if(addCardFromList(leftTurnCards)){ }else if(addCardFromList(rightTurnCards)){ }else if(addCardFromList(uTurnCards)){ }else{ addCardFromList(cards); } } /** * Will add the first card from a list to chosenCards. * @param cards the list to add a card from. * @return true if a card was found in the list, false otherwise. */ private boolean addCardFromList(List<Card> cards){ for(Card card : cards){ addChosenCard(card); return true; } return false;//empty list } }
false
true
private void placeCards() { if (chosenCards.size() == 5) { return; } boolean isRightDirection = false; for (Integer direction : getDirections()) { // Check if the robot stand in a correct direction if (this.direction == direction) { isRightDirection = true; } } if (isRightDirection) { if (moveForwardCards.size() != 0) { // Move forward with a fitting distance if(direction == GameBoard.NORTH || direction == GameBoard.SOUTH){ addMoveCard(Math.abs(getDY())); }else{ addMoveCard(Math.abs(getDX())); } } else { //check if there are other good combinations of cards if(chosenCards.size() <= 1 && moveBackwardCards.size() >= 2 && uTurnCards.size() >= 2) { //turn around, walk backwards 2 steps and turn around again addChosenCard(uTurnCards.get(0)); addChosenCard(moveBackwardCards.get(0)); addChosenCard(moveBackwardCards.get(0)); addChosenCard(uTurnCards.get(0)); } else if (chosenCards.size() <= 2 && moveBackwardCards.size() >= 1 && uTurnCards.size() >= 2) { //turn around, walk backwards 1 step and turn around again addChosenCard(uTurnCards.get(0)); addChosenCard(moveBackwardCards.get(0)); addChosenCard(uTurnCards.get(0)); } else {// if there are none -> random card randomizeCard(); //maybe randomize between turn-cards? TODO } } } else { // If the robot is turned towards a wrong direction. if (rightTurnCards.size() != 0 || leftTurnCards.size() != 0 || uTurnCards.size() != 0) { // Try turn towards a correct direction boolean cardAdded = false; for(Integer i : getDirections()){ int turnDifference = ((i.intValue() - direction)+4)%4; if(turnDifference == 3){ if(leftTurnCards.size() != 0){ addChosenCard(leftTurnCards.get(0)); cardAdded = true; break; } }else if(turnDifference == 2){ if(uTurnCards.size() != 0){ addChosenCard(uTurnCards.get(0)); cardAdded = true; break; } }else if(turnDifference == 1){ if(rightTurnCards.size() != 0){ addChosenCard(rightTurnCards.get(0)); cardAdded = true; break; } } } if(!cardAdded){ for(int j = 0; j<cards.size(); j++){ if(!(cards.get(j) instanceof Move)){ addChosenCard(cards.get(j)); cardAdded = true; break; } } if(!cardAdded){ randomizeCard(); } } } else { // No turn cards -> random card randomizeCard(); } } placeCards(); }
private void placeCards() { if (chosenCards.size() == 5) { return; } boolean isRightDirection = false; for (Integer direction : getDirections()) { // Check if the robot stand in a correct direction if (this.direction == direction.intValue()) { isRightDirection = true; } } if (isRightDirection) { if (moveForwardCards.size() != 0) { // Move forward with a fitting distance if(direction == GameBoard.NORTH || direction == GameBoard.SOUTH){ addMoveCard(Math.abs(getDY())); }else{ addMoveCard(Math.abs(getDX())); } } else { //check if there are other good combinations of cards if(chosenCards.size() <= 1 && moveBackwardCards.size() >= 2 && uTurnCards.size() >= 2) { //turn around, walk backwards 2 steps and turn around again addChosenCard(uTurnCards.get(0)); addChosenCard(moveBackwardCards.get(0)); addChosenCard(moveBackwardCards.get(0)); addChosenCard(uTurnCards.get(0)); } else if (chosenCards.size() <= 2 && moveBackwardCards.size() >= 1 && uTurnCards.size() >= 2) { //turn around, walk backwards 1 step and turn around again addChosenCard(uTurnCards.get(0)); addChosenCard(moveBackwardCards.get(0)); addChosenCard(uTurnCards.get(0)); } else {// if there are none -> random card randomizeCard(); } } } else { // If the robot is turned towards a wrong direction. if (rightTurnCards.size() != 0 || leftTurnCards.size() != 0 || uTurnCards.size() != 0) { // Try turn towards a correct direction boolean cardAdded = false; for(Integer i : getDirections()){ int turnDifference = ((i.intValue() - direction)+4)%4; if(turnDifference == 3){ if(leftTurnCards.size() != 0){ addChosenCard(leftTurnCards.get(0)); cardAdded = true; break; } }else if(turnDifference == 2){ if(uTurnCards.size() != 0){ addChosenCard(uTurnCards.get(0)); cardAdded = true; break; } }else if(turnDifference == 1){ if(rightTurnCards.size() != 0){ addChosenCard(rightTurnCards.get(0)); cardAdded = true; break; } } } if(!cardAdded){ for(int j = 0; j<cards.size(); j++){ if(!(cards.get(j) instanceof Move)){ addChosenCard(cards.get(j)); cardAdded = true; break; } } if(!cardAdded){ randomizeCard(); } } } else { // No turn cards -> random card randomizeCard(); } } placeCards(); }
diff --git a/citations-impl/impl/src/java/org/sakaiproject/citation/impl/CitationListAccessServlet.java b/citations-impl/impl/src/java/org/sakaiproject/citation/impl/CitationListAccessServlet.java index 4c831e5..a8bb988 100644 --- a/citations-impl/impl/src/java/org/sakaiproject/citation/impl/CitationListAccessServlet.java +++ b/citations-impl/impl/src/java/org/sakaiproject/citation/impl/CitationListAccessServlet.java @@ -1,453 +1,450 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.citation.impl; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.citation.api.Citation; import org.sakaiproject.citation.api.CitationCollection; import org.sakaiproject.citation.api.CitationHelper; import org.sakaiproject.citation.api.Schema; import org.sakaiproject.citation.api.Schema.Field; import org.sakaiproject.citation.cover.CitationService; import org.sakaiproject.citation.cover.ConfigurationService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.cover.ContentHostingService; import org.sakaiproject.entity.api.EntityAccessOverloadException; import org.sakaiproject.entity.api.EntityCopyrightException; import org.sakaiproject.entity.api.EntityNotDefinedException; import org.sakaiproject.entity.api.EntityPermissionException; import org.sakaiproject.entity.api.HttpAccess; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.ServerOverloadException; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.Validator; import org.sakaiproject.cheftool.VmServlet; /** * */ public class CitationListAccessServlet implements HttpAccess { public static final String LIST_TEMPLATE = "/vm/citationList.vm"; /** Messages, for the http access. */ protected static ResourceLoader rb = new ResourceLoader("citations"); /** Our logger. */ private static Log m_log = LogFactory.getLog(CitationListAccessServlet.class); /** * Handle an HTTP request for access. The request and response objects are provider.<br /> * The access is for the referenced entity.<br /> * Use the response object to send the headers, length, content type, and bytes of the response in whatever manner needed.<br /> * Make the response ONLY if it is permitted and exists and otherwise valid. Use the exceptions for any error handling. * * @param req * The request object. * @param res * The response object. * @param ref * The entity reference * @param copyrightAcceptedRefs * The collection (entity reference String) of entities that the end user in this session have already accepted the copyright for. * @throws EntityPermissionException * Throw this if the current user does not have permission for the access. * @throws EntityNotDefinedException * Throw this if the ref is not supported or the entity is not available for access in any way. * @throws EntityAccessOverloadException * Throw this if you are rejecting an otherwise valid request because of some sort of server resource shortage or limit. * @throws EntityCopyrightException * Throw this if you are rejecting an otherwise valid request because the user needs to agree to the copyright and has not yet done so. */ public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref, Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException, EntityAccessOverloadException, EntityCopyrightException { String subtype = ref.getSubType(); if(org.sakaiproject.citation.api.CitationService.REF_TYPE_EXPORT_RIS_SEL.equals(subtype) || org.sakaiproject.citation.api.CitationService.REF_TYPE_EXPORT_RIS_ALL.equals(subtype)) { handleExportRequest(req, res, ref, org.sakaiproject.citation.api.CitationService.RIS_FORMAT, subtype); } else if(org.sakaiproject.citation.api.CitationService.REF_TYPE_VIEW_LIST.equals(subtype)) { handleViewRequest(req, res, ref); } else { throw new EntityNotDefinedException(ref.getReference()); } } // handleAccess protected void handleExportRequest(HttpServletRequest req, HttpServletResponse res, Reference ref, String format, String subtype) throws EntityNotDefinedException, EntityAccessOverloadException { if(org.sakaiproject.citation.api.CitationService.RIS_FORMAT.equals(format)) { String collectionId = req.getParameter("collectionId"); List<String> citationIds = new java.util.ArrayList<String>(); CitationCollection collection = null; try { collection = CitationService.getCollection(collectionId); } catch (IdUnusedException e) { throw new EntityNotDefinedException(ref.getReference()); } // decide whether to export selected or entire list if( org.sakaiproject.citation.api.CitationService.REF_TYPE_EXPORT_RIS_SEL.equals(subtype) ) { // export selected String[] paramCitationIds = req.getParameterValues("citationId"); if( paramCitationIds == null || paramCitationIds.length < 1 ) { // none selected - do not continue return; } citationIds.addAll(Arrays.asList(paramCitationIds)); } else { // export all // iterate through ids List<Citation> citations = collection.getCitations(); if( citations == null || citations.size() < 1 ) { // no citations to export - do not continue return; } for( Citation citation : citations ) { citationIds.add( citation.getId() ); } } // We need to write to a temporary stream for better speed, plus // so we can get a byte count. Internet Explorer has problems // if we don't make the setContentLength() call. StringBuilder buffer = new StringBuilder(4096); // StringBuilder contentType = new StringBuilder(); try { collection.exportRis(buffer, citationIds); } catch (IOException e) { throw new EntityAccessOverloadException(ref.getReference()); } // Set the mime type for a RIS file res.addHeader("Content-Disposition", "attachment; filename=\"citations.RIS\""); res.setContentType("application/x-Research-Info-Systems"); res.setContentLength(buffer.length()); if (buffer.length() > 0) { // Increase the buffer size for more speed. res.setBufferSize(buffer.length()); } OutputStream out = null; try { out = res.getOutputStream(); if (buffer.length() > 0) { out.write(buffer.toString().getBytes()); } out.flush(); out.close(); } catch (Throwable ignore) { } finally { if (out != null) { try { out.close(); } catch (Throwable ignore) { } } } } } // handleExportRequest protected void handleViewRequest(HttpServletRequest req, HttpServletResponse res, Reference ref) throws EntityPermissionException, EntityAccessOverloadException, EntityNotDefinedException { if(! ContentHostingService.allowGetResource(ref.getId())) { String user = ""; if(req.getUserPrincipal() != null) { user = req.getUserPrincipal().getName(); } throw new EntityPermissionException(user, ContentHostingService.EVENT_RESOURCE_READ, ref.getReference()); } try { ContentResource resource = (ContentResource) ref.getEntity(); // ContentHostingService.getResource(ref.getId()); ResourceProperties properties = resource.getProperties(); String title = properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME); String description = properties.getProperty( ResourceProperties.PROP_DESCRIPTION ); String citationCollectionId = new String( resource.getContent() ); CitationCollection collection = CitationService.getCollection(citationCollectionId); res.setContentType("text/html; charset=UTF-8"); PrintWriter out = res.getWriter(); out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n" + "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" + "<title>" + rb.getString("list.title") + ": " + Validator.escapeHtml(title) + "</title>\n" + "<link href=\"/library/skin/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<link href=\"/library/skin/default/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<script type=\"text/javascript\" src=\"/sakai-citations-tool/js/citationscript.js\"></script>\n" + "<script type=\"text/javascript\" src=\"/library/juice/jquery-1.3.2.min.js\"></script>\n" - + "<script type=\"text/javascript\">\n" - + "jQuery.noConflict();\n" - + "</script>\n" + "<script type=\"text/javascript\" src=\"/library/juice/juice.js\"></script>\n" + "<script type=\"text/javascript\" src=\"/library/juice/juice-weblearn.js\"></script>\n" + "</head>\n<body>" ); List<Citation> citations = collection.getCitations(); out.println("<div class=\"portletBody\">\n\t<div class=\"indnt1\">"); out.println("\t<h3>" + rb.getString("list.title") + ": " + Validator.escapeHtml(title) + "</h3>"); if( description != null && !description.trim().equals("") ) { out.println("\t<p>" + description + "</p>"); } if( citations.size() > 0 ) { Object[] args = { ConfigurationService.getSiteConfigOpenUrlLabel() }; out.println("\t<p class=\"instruction\">" + rb.getFormattedMessage("cite.subtitle", args) + "</p>"); } out.println("\t<table class=\"listHier lines nolines\" summary=\"citations table\" cellpadding=\"0\" cellspacing=\"0\">"); out.println("\t<tbody>"); out.println("\t<tr><th colspan=\"2\">"); out.println("\t\t<div class=\"viewNav\" style=\"padding: 0pt;\"><strong>" + rb.getString("listing.title") + "</strong> (" + collection.size() + ")" ); out.println("\t\t</div>"); out.println("\t</th></tr>"); if( citations.size() > 0 ) { out.println("\t<tr class=\"exclude\"><td colspan=\"2\">"); out.println("\t\t<div class=\"itemAction\">"); out.println("\t\t\t<a href=\"#\" onclick=\"showAllDetails( '" + rb.getString("link.hide.results") + "' ); return false;\">" + rb.getString("link.show.readonly") + "</a> |" ); out.println("\t\t\t<a href=\"#\" onclick=\"hideAllDetails( '" + rb.getString("link.show.readonly") + "' ); return false;\">" + rb.getString("link.hide.results") + "</a>" ); out.println("\t\t</div>\n\t</td></tr>"); } for( Citation citation : citations ) { String escapedId = citation.getId().replace( '-', 'x' ); // toggle image out.println("\t\t<tr>"); out.println("\t\t\t<td class=\"attach\">"); out.println("\t\t\t\t<img onclick=\"toggleDetails( '" + escapedId + "', '" + rb.getString("link.show.readonly") + "', '" + rb.getString("link.hide.results") + "' );\"" ); out.println("\t\t\t\tid=\"toggle_" + escapedId + "\" class=\"toggleIcon\"" ); out.println("\t\t\t\tstyle=\"cursor: pointer;\" src=\"/library/image/sakai/expand.gif?panel=Main\""); out.println("\t\t\t\talt=\"" + rb.getString("link.show.readonly") + "\" align=\"top\"" ); out.println("\t\t\t\tborder=\"0\" height=\"13\" width=\"13\" />" ); out.println("\t\t\t</td>"); // preferred URL? String href = citation.hasPreferredUrl() ? citation.getCustomUrl(citation.getPreferredUrlId()) : citation.getOpenurl(); out.println("\t\t<td headers=\"details\">"); out.println("\t\t\t<a href=\"" + Validator.escapeHtml(href) + "\" target=\"_blank\">" + Validator.escapeHtml( (String)citation.getCitationProperty( Schema.TITLE ) ) + "</a><br />"); out.println("\t\t\t\t" + Validator.escapeHtml( citation.getCreator() ) ); out.println("\t\t\t\t" + Validator.escapeHtml( citation.getSource() ) ); out.println("\t\t\t<div class=\"itemAction\">"); if( citation.hasCustomUrls() ) { List<String> customUrlIds = citation.getCustomUrlIds(); for( String urlId : customUrlIds ) { if (!citation.hasPreferredUrl() || (citation.hasPreferredUrl() && (!citation.getPreferredUrlId().equals(urlId)))) { String urlLabel = ( citation.getCustomUrlLabel( urlId ) == null || citation.getCustomUrlLabel( urlId ).trim().equals("") ) ? rb.getString( "nullUrlLabel.view" ) : Validator.escapeHtml( citation.getCustomUrlLabel( urlId ) ); out.println("\t\t\t\t<a href=\"" + Validator.escapeHtml(citation.getCustomUrl( urlId )) + "\" target=\"_blank\">" + urlLabel + "</a>"); out.println("\t\t\t\t |"); } } } out.println("\t\t\t\t<a href=\"" + citation.getOpenurl() + "\" target=\"_blank\">" + ConfigurationService.getSiteConfigOpenUrlLabel() + "</a>"); /* not using view citation link - using toggle triangle out.println("\t\t\t\t<a id=\"link_" + escapedId + "\" href=\"#\" onclick=\"viewFullCitation('" + escapedId + "'); return false;\">" + rb.getString( "action.view" ) + "</a>" ); */ // TODO This doesn't need any Inline HTTP Transport. out.println("\t\t\t\t<span class=\"Z3988\" title=\""+ citation.getOpenurlParameters().substring(1).replace("&", "&amp;")+ "\"></span>"); out.println("\t\t\t</div>"); // show detailed info out.println("\t\t<div id=\"details_" + escapedId + "\" class=\"citationDetails\" style=\"display: none;\">"); out.println("\t\t\t<table class=\"listHier lines nolines\" style=\"margin-left: 2em;\" cellpadding=\"0\" cellspacing=\"0\">"); Schema schema = citation.getSchema(); if(schema == null) { m_log.warn("CLAS.handleViewRequest() Schema is null: " + citation); continue; } List fields = schema.getFields(); Iterator fieldIt = fields.iterator(); while(fieldIt.hasNext()) { Field field = (Field) fieldIt.next(); if(field.isMultivalued()) { // don't want to repeat authors if( !Schema.CREATOR.equals(field.getIdentifier()) ) { List values = (List) citation.getCitationProperty(field.getIdentifier()); Iterator valueIt = values.iterator(); boolean first = true; while(valueIt.hasNext()) { String value = (String) valueIt.next(); if( value != null && !value.trim().equals("") ) { if(first) { String label = rb.getString(schema.getIdentifier() + "." + field.getIdentifier(), field.getIdentifier()); out.println("\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"attach\"><strong>" + label + "</strong></td>\n\t\t\t\t\t<td>" + Validator.escapeHtml(value) + "</td>\n\t\t\t\t</tr>"); } else { out.println("\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"attach\">&nbsp;</td>\n\t\t\t\t\t<td>" + Validator.escapeHtml(value) + "</td>\n\t\t\t\t</tr>\n"); } } first = false; } } } else { String value = (String) citation.getCitationProperty(field.getIdentifier()); if(value != null && ! value.trim().equals("")) { String label = rb.getString(schema.getIdentifier() + "." + field.getIdentifier(), field.getIdentifier()); /* leaving out "Find It!" link for now as we're not using it anywhere else anymore if(Schema.TITLE.equals(field.getIdentifier())) { value += " [<a href=\"" + citation.getOpenurl() + "\" target=\"_blank\">" + openUrlLabel + "</a>]"; } */ // don't want to repeat titles if( !Schema.TITLE.equals(field.getIdentifier()) ) { out.println("\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"attach\"><strong>" + label + "</strong></td>\n\t\t\t\t\t<td>" + Validator.escapeHtml(value) + "</td>\n\t\t\t\t</tr>"); } } } } out.println("\t\t\t</table>"); out.println("\t\t</div>"); out.println("\t\t</td>"); out.println("\t\t</tr>"); } if( citations.size() > 0 ) { out.println("\t<tr class=\"exclude\"><td colspan=\"2\">"); out.println("\t\t<div class=\"itemAction\">"); out.println("\t\t\t<a href=\"#\" onclick=\"showAllDetails( '" + rb.getString("link.hide.results") + "' ); return false;\">" + rb.getString("link.show.readonly") + "</a> |" ); out.println("\t\t\t<a href=\"#\" onclick=\"hideAllDetails( '" + rb.getString("link.show.readonly") + "' ); return false;\">" + rb.getString("link.hide.results") + "</a>" ); out.println("\t\t</div>\n\t</td></tr>"); out.println("\t<tr><th colspan=\"2\">"); out.println("\t\t<div class=\"viewNav\" style=\"padding: 0pt;\"><strong>" + rb.getString("listing.title") + "</strong> (" + collection.size() + ")" ); out.println("\t\t</div>"); out.println("\t</th></tr>"); out.println("\t</tbody>"); out.println("\t</table>"); out.println("</div></div>"); out.println("</body></html>"); } } catch (IOException e) { throw new EntityAccessOverloadException(ref.getReference()); } catch (ServerOverloadException e) { throw new EntityAccessOverloadException(ref.getReference()); } catch (IdUnusedException e) { throw new EntityNotDefinedException(ref.getReference()); } } }
true
true
protected void handleViewRequest(HttpServletRequest req, HttpServletResponse res, Reference ref) throws EntityPermissionException, EntityAccessOverloadException, EntityNotDefinedException { if(! ContentHostingService.allowGetResource(ref.getId())) { String user = ""; if(req.getUserPrincipal() != null) { user = req.getUserPrincipal().getName(); } throw new EntityPermissionException(user, ContentHostingService.EVENT_RESOURCE_READ, ref.getReference()); } try { ContentResource resource = (ContentResource) ref.getEntity(); // ContentHostingService.getResource(ref.getId()); ResourceProperties properties = resource.getProperties(); String title = properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME); String description = properties.getProperty( ResourceProperties.PROP_DESCRIPTION ); String citationCollectionId = new String( resource.getContent() ); CitationCollection collection = CitationService.getCollection(citationCollectionId); res.setContentType("text/html; charset=UTF-8"); PrintWriter out = res.getWriter(); out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n" + "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" + "<title>" + rb.getString("list.title") + ": " + Validator.escapeHtml(title) + "</title>\n" + "<link href=\"/library/skin/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<link href=\"/library/skin/default/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<script type=\"text/javascript\" src=\"/sakai-citations-tool/js/citationscript.js\"></script>\n" + "<script type=\"text/javascript\" src=\"/library/juice/jquery-1.3.2.min.js\"></script>\n" + "<script type=\"text/javascript\">\n" + "jQuery.noConflict();\n" + "</script>\n" + "<script type=\"text/javascript\" src=\"/library/juice/juice.js\"></script>\n" + "<script type=\"text/javascript\" src=\"/library/juice/juice-weblearn.js\"></script>\n" + "</head>\n<body>" ); List<Citation> citations = collection.getCitations(); out.println("<div class=\"portletBody\">\n\t<div class=\"indnt1\">"); out.println("\t<h3>" + rb.getString("list.title") + ": " + Validator.escapeHtml(title) + "</h3>"); if( description != null && !description.trim().equals("") ) { out.println("\t<p>" + description + "</p>"); } if( citations.size() > 0 ) { Object[] args = { ConfigurationService.getSiteConfigOpenUrlLabel() }; out.println("\t<p class=\"instruction\">" + rb.getFormattedMessage("cite.subtitle", args) + "</p>"); } out.println("\t<table class=\"listHier lines nolines\" summary=\"citations table\" cellpadding=\"0\" cellspacing=\"0\">"); out.println("\t<tbody>"); out.println("\t<tr><th colspan=\"2\">"); out.println("\t\t<div class=\"viewNav\" style=\"padding: 0pt;\"><strong>" + rb.getString("listing.title") + "</strong> (" + collection.size() + ")" ); out.println("\t\t</div>"); out.println("\t</th></tr>"); if( citations.size() > 0 ) { out.println("\t<tr class=\"exclude\"><td colspan=\"2\">"); out.println("\t\t<div class=\"itemAction\">"); out.println("\t\t\t<a href=\"#\" onclick=\"showAllDetails( '" + rb.getString("link.hide.results") + "' ); return false;\">" + rb.getString("link.show.readonly") + "</a> |" ); out.println("\t\t\t<a href=\"#\" onclick=\"hideAllDetails( '" + rb.getString("link.show.readonly") + "' ); return false;\">" + rb.getString("link.hide.results") + "</a>" ); out.println("\t\t</div>\n\t</td></tr>"); } for( Citation citation : citations ) { String escapedId = citation.getId().replace( '-', 'x' ); // toggle image out.println("\t\t<tr>"); out.println("\t\t\t<td class=\"attach\">"); out.println("\t\t\t\t<img onclick=\"toggleDetails( '" + escapedId + "', '" + rb.getString("link.show.readonly") + "', '" + rb.getString("link.hide.results") + "' );\"" ); out.println("\t\t\t\tid=\"toggle_" + escapedId + "\" class=\"toggleIcon\"" ); out.println("\t\t\t\tstyle=\"cursor: pointer;\" src=\"/library/image/sakai/expand.gif?panel=Main\""); out.println("\t\t\t\talt=\"" + rb.getString("link.show.readonly") + "\" align=\"top\"" ); out.println("\t\t\t\tborder=\"0\" height=\"13\" width=\"13\" />" ); out.println("\t\t\t</td>"); // preferred URL? String href = citation.hasPreferredUrl() ? citation.getCustomUrl(citation.getPreferredUrlId()) : citation.getOpenurl(); out.println("\t\t<td headers=\"details\">"); out.println("\t\t\t<a href=\"" + Validator.escapeHtml(href) + "\" target=\"_blank\">" + Validator.escapeHtml( (String)citation.getCitationProperty( Schema.TITLE ) ) + "</a><br />"); out.println("\t\t\t\t" + Validator.escapeHtml( citation.getCreator() ) ); out.println("\t\t\t\t" + Validator.escapeHtml( citation.getSource() ) ); out.println("\t\t\t<div class=\"itemAction\">"); if( citation.hasCustomUrls() ) { List<String> customUrlIds = citation.getCustomUrlIds(); for( String urlId : customUrlIds ) { if (!citation.hasPreferredUrl() || (citation.hasPreferredUrl() && (!citation.getPreferredUrlId().equals(urlId)))) { String urlLabel = ( citation.getCustomUrlLabel( urlId ) == null || citation.getCustomUrlLabel( urlId ).trim().equals("") ) ? rb.getString( "nullUrlLabel.view" ) : Validator.escapeHtml( citation.getCustomUrlLabel( urlId ) ); out.println("\t\t\t\t<a href=\"" + Validator.escapeHtml(citation.getCustomUrl( urlId )) + "\" target=\"_blank\">" + urlLabel + "</a>"); out.println("\t\t\t\t |"); } } } out.println("\t\t\t\t<a href=\"" + citation.getOpenurl() + "\" target=\"_blank\">" + ConfigurationService.getSiteConfigOpenUrlLabel() + "</a>"); /* not using view citation link - using toggle triangle out.println("\t\t\t\t<a id=\"link_" + escapedId + "\" href=\"#\" onclick=\"viewFullCitation('" + escapedId + "'); return false;\">" + rb.getString( "action.view" ) + "</a>" ); */ // TODO This doesn't need any Inline HTTP Transport. out.println("\t\t\t\t<span class=\"Z3988\" title=\""+ citation.getOpenurlParameters().substring(1).replace("&", "&amp;")+ "\"></span>"); out.println("\t\t\t</div>"); // show detailed info out.println("\t\t<div id=\"details_" + escapedId + "\" class=\"citationDetails\" style=\"display: none;\">"); out.println("\t\t\t<table class=\"listHier lines nolines\" style=\"margin-left: 2em;\" cellpadding=\"0\" cellspacing=\"0\">"); Schema schema = citation.getSchema(); if(schema == null) { m_log.warn("CLAS.handleViewRequest() Schema is null: " + citation); continue; } List fields = schema.getFields(); Iterator fieldIt = fields.iterator(); while(fieldIt.hasNext()) { Field field = (Field) fieldIt.next(); if(field.isMultivalued()) { // don't want to repeat authors if( !Schema.CREATOR.equals(field.getIdentifier()) ) { List values = (List) citation.getCitationProperty(field.getIdentifier()); Iterator valueIt = values.iterator(); boolean first = true; while(valueIt.hasNext()) { String value = (String) valueIt.next(); if( value != null && !value.trim().equals("") ) { if(first) { String label = rb.getString(schema.getIdentifier() + "." + field.getIdentifier(), field.getIdentifier()); out.println("\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"attach\"><strong>" + label + "</strong></td>\n\t\t\t\t\t<td>" + Validator.escapeHtml(value) + "</td>\n\t\t\t\t</tr>"); } else { out.println("\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"attach\">&nbsp;</td>\n\t\t\t\t\t<td>" + Validator.escapeHtml(value) + "</td>\n\t\t\t\t</tr>\n"); } } first = false; } } } else { String value = (String) citation.getCitationProperty(field.getIdentifier()); if(value != null && ! value.trim().equals("")) { String label = rb.getString(schema.getIdentifier() + "." + field.getIdentifier(), field.getIdentifier()); /* leaving out "Find It!" link for now as we're not using it anywhere else anymore if(Schema.TITLE.equals(field.getIdentifier())) { value += " [<a href=\"" + citation.getOpenurl() + "\" target=\"_blank\">" + openUrlLabel + "</a>]"; } */ // don't want to repeat titles if( !Schema.TITLE.equals(field.getIdentifier()) ) { out.println("\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"attach\"><strong>" + label + "</strong></td>\n\t\t\t\t\t<td>" + Validator.escapeHtml(value) + "</td>\n\t\t\t\t</tr>"); } } } } out.println("\t\t\t</table>"); out.println("\t\t</div>"); out.println("\t\t</td>"); out.println("\t\t</tr>"); } if( citations.size() > 0 ) { out.println("\t<tr class=\"exclude\"><td colspan=\"2\">"); out.println("\t\t<div class=\"itemAction\">"); out.println("\t\t\t<a href=\"#\" onclick=\"showAllDetails( '" + rb.getString("link.hide.results") + "' ); return false;\">" + rb.getString("link.show.readonly") + "</a> |" ); out.println("\t\t\t<a href=\"#\" onclick=\"hideAllDetails( '" + rb.getString("link.show.readonly") + "' ); return false;\">" + rb.getString("link.hide.results") + "</a>" ); out.println("\t\t</div>\n\t</td></tr>"); out.println("\t<tr><th colspan=\"2\">"); out.println("\t\t<div class=\"viewNav\" style=\"padding: 0pt;\"><strong>" + rb.getString("listing.title") + "</strong> (" + collection.size() + ")" ); out.println("\t\t</div>"); out.println("\t</th></tr>"); out.println("\t</tbody>"); out.println("\t</table>"); out.println("</div></div>"); out.println("</body></html>"); } } catch (IOException e) { throw new EntityAccessOverloadException(ref.getReference()); } catch (ServerOverloadException e) { throw new EntityAccessOverloadException(ref.getReference()); } catch (IdUnusedException e) { throw new EntityNotDefinedException(ref.getReference()); } }
protected void handleViewRequest(HttpServletRequest req, HttpServletResponse res, Reference ref) throws EntityPermissionException, EntityAccessOverloadException, EntityNotDefinedException { if(! ContentHostingService.allowGetResource(ref.getId())) { String user = ""; if(req.getUserPrincipal() != null) { user = req.getUserPrincipal().getName(); } throw new EntityPermissionException(user, ContentHostingService.EVENT_RESOURCE_READ, ref.getReference()); } try { ContentResource resource = (ContentResource) ref.getEntity(); // ContentHostingService.getResource(ref.getId()); ResourceProperties properties = resource.getProperties(); String title = properties.getProperty(ResourceProperties.PROP_DISPLAY_NAME); String description = properties.getProperty( ResourceProperties.PROP_DESCRIPTION ); String citationCollectionId = new String( resource.getContent() ); CitationCollection collection = CitationService.getCollection(citationCollectionId); res.setContentType("text/html; charset=UTF-8"); PrintWriter out = res.getWriter(); out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n" + "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" + "<title>" + rb.getString("list.title") + ": " + Validator.escapeHtml(title) + "</title>\n" + "<link href=\"/library/skin/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<link href=\"/library/skin/default/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<script type=\"text/javascript\" src=\"/sakai-citations-tool/js/citationscript.js\"></script>\n" + "<script type=\"text/javascript\" src=\"/library/juice/jquery-1.3.2.min.js\"></script>\n" + "<script type=\"text/javascript\" src=\"/library/juice/juice.js\"></script>\n" + "<script type=\"text/javascript\" src=\"/library/juice/juice-weblearn.js\"></script>\n" + "</head>\n<body>" ); List<Citation> citations = collection.getCitations(); out.println("<div class=\"portletBody\">\n\t<div class=\"indnt1\">"); out.println("\t<h3>" + rb.getString("list.title") + ": " + Validator.escapeHtml(title) + "</h3>"); if( description != null && !description.trim().equals("") ) { out.println("\t<p>" + description + "</p>"); } if( citations.size() > 0 ) { Object[] args = { ConfigurationService.getSiteConfigOpenUrlLabel() }; out.println("\t<p class=\"instruction\">" + rb.getFormattedMessage("cite.subtitle", args) + "</p>"); } out.println("\t<table class=\"listHier lines nolines\" summary=\"citations table\" cellpadding=\"0\" cellspacing=\"0\">"); out.println("\t<tbody>"); out.println("\t<tr><th colspan=\"2\">"); out.println("\t\t<div class=\"viewNav\" style=\"padding: 0pt;\"><strong>" + rb.getString("listing.title") + "</strong> (" + collection.size() + ")" ); out.println("\t\t</div>"); out.println("\t</th></tr>"); if( citations.size() > 0 ) { out.println("\t<tr class=\"exclude\"><td colspan=\"2\">"); out.println("\t\t<div class=\"itemAction\">"); out.println("\t\t\t<a href=\"#\" onclick=\"showAllDetails( '" + rb.getString("link.hide.results") + "' ); return false;\">" + rb.getString("link.show.readonly") + "</a> |" ); out.println("\t\t\t<a href=\"#\" onclick=\"hideAllDetails( '" + rb.getString("link.show.readonly") + "' ); return false;\">" + rb.getString("link.hide.results") + "</a>" ); out.println("\t\t</div>\n\t</td></tr>"); } for( Citation citation : citations ) { String escapedId = citation.getId().replace( '-', 'x' ); // toggle image out.println("\t\t<tr>"); out.println("\t\t\t<td class=\"attach\">"); out.println("\t\t\t\t<img onclick=\"toggleDetails( '" + escapedId + "', '" + rb.getString("link.show.readonly") + "', '" + rb.getString("link.hide.results") + "' );\"" ); out.println("\t\t\t\tid=\"toggle_" + escapedId + "\" class=\"toggleIcon\"" ); out.println("\t\t\t\tstyle=\"cursor: pointer;\" src=\"/library/image/sakai/expand.gif?panel=Main\""); out.println("\t\t\t\talt=\"" + rb.getString("link.show.readonly") + "\" align=\"top\"" ); out.println("\t\t\t\tborder=\"0\" height=\"13\" width=\"13\" />" ); out.println("\t\t\t</td>"); // preferred URL? String href = citation.hasPreferredUrl() ? citation.getCustomUrl(citation.getPreferredUrlId()) : citation.getOpenurl(); out.println("\t\t<td headers=\"details\">"); out.println("\t\t\t<a href=\"" + Validator.escapeHtml(href) + "\" target=\"_blank\">" + Validator.escapeHtml( (String)citation.getCitationProperty( Schema.TITLE ) ) + "</a><br />"); out.println("\t\t\t\t" + Validator.escapeHtml( citation.getCreator() ) ); out.println("\t\t\t\t" + Validator.escapeHtml( citation.getSource() ) ); out.println("\t\t\t<div class=\"itemAction\">"); if( citation.hasCustomUrls() ) { List<String> customUrlIds = citation.getCustomUrlIds(); for( String urlId : customUrlIds ) { if (!citation.hasPreferredUrl() || (citation.hasPreferredUrl() && (!citation.getPreferredUrlId().equals(urlId)))) { String urlLabel = ( citation.getCustomUrlLabel( urlId ) == null || citation.getCustomUrlLabel( urlId ).trim().equals("") ) ? rb.getString( "nullUrlLabel.view" ) : Validator.escapeHtml( citation.getCustomUrlLabel( urlId ) ); out.println("\t\t\t\t<a href=\"" + Validator.escapeHtml(citation.getCustomUrl( urlId )) + "\" target=\"_blank\">" + urlLabel + "</a>"); out.println("\t\t\t\t |"); } } } out.println("\t\t\t\t<a href=\"" + citation.getOpenurl() + "\" target=\"_blank\">" + ConfigurationService.getSiteConfigOpenUrlLabel() + "</a>"); /* not using view citation link - using toggle triangle out.println("\t\t\t\t<a id=\"link_" + escapedId + "\" href=\"#\" onclick=\"viewFullCitation('" + escapedId + "'); return false;\">" + rb.getString( "action.view" ) + "</a>" ); */ // TODO This doesn't need any Inline HTTP Transport. out.println("\t\t\t\t<span class=\"Z3988\" title=\""+ citation.getOpenurlParameters().substring(1).replace("&", "&amp;")+ "\"></span>"); out.println("\t\t\t</div>"); // show detailed info out.println("\t\t<div id=\"details_" + escapedId + "\" class=\"citationDetails\" style=\"display: none;\">"); out.println("\t\t\t<table class=\"listHier lines nolines\" style=\"margin-left: 2em;\" cellpadding=\"0\" cellspacing=\"0\">"); Schema schema = citation.getSchema(); if(schema == null) { m_log.warn("CLAS.handleViewRequest() Schema is null: " + citation); continue; } List fields = schema.getFields(); Iterator fieldIt = fields.iterator(); while(fieldIt.hasNext()) { Field field = (Field) fieldIt.next(); if(field.isMultivalued()) { // don't want to repeat authors if( !Schema.CREATOR.equals(field.getIdentifier()) ) { List values = (List) citation.getCitationProperty(field.getIdentifier()); Iterator valueIt = values.iterator(); boolean first = true; while(valueIt.hasNext()) { String value = (String) valueIt.next(); if( value != null && !value.trim().equals("") ) { if(first) { String label = rb.getString(schema.getIdentifier() + "." + field.getIdentifier(), field.getIdentifier()); out.println("\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"attach\"><strong>" + label + "</strong></td>\n\t\t\t\t\t<td>" + Validator.escapeHtml(value) + "</td>\n\t\t\t\t</tr>"); } else { out.println("\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"attach\">&nbsp;</td>\n\t\t\t\t\t<td>" + Validator.escapeHtml(value) + "</td>\n\t\t\t\t</tr>\n"); } } first = false; } } } else { String value = (String) citation.getCitationProperty(field.getIdentifier()); if(value != null && ! value.trim().equals("")) { String label = rb.getString(schema.getIdentifier() + "." + field.getIdentifier(), field.getIdentifier()); /* leaving out "Find It!" link for now as we're not using it anywhere else anymore if(Schema.TITLE.equals(field.getIdentifier())) { value += " [<a href=\"" + citation.getOpenurl() + "\" target=\"_blank\">" + openUrlLabel + "</a>]"; } */ // don't want to repeat titles if( !Schema.TITLE.equals(field.getIdentifier()) ) { out.println("\t\t\t\t<tr>\n\t\t\t\t\t<td class=\"attach\"><strong>" + label + "</strong></td>\n\t\t\t\t\t<td>" + Validator.escapeHtml(value) + "</td>\n\t\t\t\t</tr>"); } } } } out.println("\t\t\t</table>"); out.println("\t\t</div>"); out.println("\t\t</td>"); out.println("\t\t</tr>"); } if( citations.size() > 0 ) { out.println("\t<tr class=\"exclude\"><td colspan=\"2\">"); out.println("\t\t<div class=\"itemAction\">"); out.println("\t\t\t<a href=\"#\" onclick=\"showAllDetails( '" + rb.getString("link.hide.results") + "' ); return false;\">" + rb.getString("link.show.readonly") + "</a> |" ); out.println("\t\t\t<a href=\"#\" onclick=\"hideAllDetails( '" + rb.getString("link.show.readonly") + "' ); return false;\">" + rb.getString("link.hide.results") + "</a>" ); out.println("\t\t</div>\n\t</td></tr>"); out.println("\t<tr><th colspan=\"2\">"); out.println("\t\t<div class=\"viewNav\" style=\"padding: 0pt;\"><strong>" + rb.getString("listing.title") + "</strong> (" + collection.size() + ")" ); out.println("\t\t</div>"); out.println("\t</th></tr>"); out.println("\t</tbody>"); out.println("\t</table>"); out.println("</div></div>"); out.println("</body></html>"); } } catch (IOException e) { throw new EntityAccessOverloadException(ref.getReference()); } catch (ServerOverloadException e) { throw new EntityAccessOverloadException(ref.getReference()); } catch (IdUnusedException e) { throw new EntityNotDefinedException(ref.getReference()); } }
diff --git a/application/src/main/java/org/mifos/customers/office/business/OfficeBO.java b/application/src/main/java/org/mifos/customers/office/business/OfficeBO.java index 673a20434..8d762e040 100644 --- a/application/src/main/java/org/mifos/customers/office/business/OfficeBO.java +++ b/application/src/main/java/org/mifos/customers/office/business/OfficeBO.java @@ -1,687 +1,690 @@ /* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.customers.office.business; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.mifos.application.holiday.business.HolidayBO; import org.mifos.application.master.business.CustomFieldDto; import org.mifos.application.master.persistence.MasterPersistence; import org.mifos.customers.center.struts.action.OfficeHierarchyDto; import org.mifos.customers.office.exceptions.OfficeException; import org.mifos.customers.office.exceptions.OfficeValidationException; import org.mifos.customers.office.persistence.OfficePersistence; import org.mifos.customers.office.util.helpers.OfficeConstants; import org.mifos.customers.office.util.helpers.OfficeLevel; import org.mifos.customers.office.util.helpers.OfficeStatus; import org.mifos.customers.office.util.helpers.OperationMode; import org.mifos.framework.business.AbstractBusinessObject; import org.mifos.framework.business.util.Address; import org.mifos.framework.exceptions.PersistenceException; import org.mifos.framework.exceptions.PropertyNotFoundException; import org.mifos.framework.util.helpers.Constants; import org.mifos.framework.util.helpers.FilePaths; import org.mifos.security.authorization.HierarchyManager; import org.mifos.security.util.EventManger; import org.mifos.security.util.OfficeSearch; import org.mifos.security.util.SecurityConstants; import org.mifos.security.util.UserContext; public class OfficeBO extends AbstractBusinessObject implements Comparable<OfficeBO> { private final Short officeId; private final Short operationMode; @SuppressWarnings("unused") // see .hbm.xml file private Integer maxChildCount = Integer.valueOf(0); private String officeName; private String shortName; private String globalOfficeNum; private String searchId; private OfficeLevelEntity level; private OfficeBO parentOffice; private OfficeStatusEntity status; private OfficeAddressEntity address; private Set<OfficeCustomFieldEntity> customFields; private Set<OfficeBO> children; private Set<HolidayBO> holidays; public static List<OfficeHierarchyDto> convertToBranchOnlyHierarchyWithParentsOfficeHierarchy( List<OfficeBO> branchParents) { List<OfficeHierarchyDto> hierarchy = new ArrayList<OfficeHierarchyDto>(); for (OfficeBO officeBO : branchParents) { List<OfficeHierarchyDto> children = new ArrayList<OfficeHierarchyDto>(); Set<OfficeBO> branchOnlyChildren = officeBO.getBranchOnlyChildren(); if (branchOnlyChildren != null && !branchOnlyChildren.isEmpty()) { children = convertToBranchOnlyHierarchyWithParentsOfficeHierarchy(new ArrayList<OfficeBO>( branchOnlyChildren)); } OfficeHierarchyDto officeHierarchy = new OfficeHierarchyDto(officeBO.getOfficeId(), officeBO .getOfficeName(), officeBO.getSearchId(), officeBO.isActive(), children); hierarchy.add(officeHierarchy); } return hierarchy; } /** * default constructor for hibernate usuage */ public OfficeBO() { this(null, null, null, null); status = new OfficeStatusEntity(OfficeStatus.ACTIVE); address = new OfficeAddressEntity(); } /** * minimal legal constructor * @param officeId */ public OfficeBO(Short officeId, final String name, final String shortName, String globalOfficeNum, OfficeBO parentOffice, OfficeLevel officeLevel, String searchId, OfficeStatus status) { this.officeId = officeId; this.officeName = name; this.shortName = shortName; this.globalOfficeNum = globalOfficeNum; this.searchId = searchId; this.parentOffice = parentOffice; this.level = new OfficeLevelEntity(officeLevel); this.operationMode = OperationMode.REMOTE_SERVER.getValue(); this.status = new OfficeStatusEntity(status); this.address = null; } /** * For tests. Does not require that the names in question actually exist in the database. */ public static OfficeBO makeForTest(final UserContext userContext, final OfficeLevel level, final OfficeBO parentOffice, final String searchId, final List<CustomFieldDto> customFields, final String officeName, final String shortName, final Address address, final OperationMode operationMode, final OfficeStatus status) throws OfficeException { return new OfficeBO(userContext, null, level, parentOffice, searchId, customFields, officeName, shortName, address, operationMode, status); } public static OfficeBO makeForTest(final UserContext userContext, final Short officeId, final String officeName, final String shortName) throws OfficeException { return new OfficeBO(userContext, officeId, OfficeLevel.AREAOFFICE, null, null, null, officeName, shortName, null, OperationMode.LOCAL_SERVER, OfficeStatus.ACTIVE); } /** * Construct an object without validating it against the database. */ private OfficeBO(final UserContext userContext, final Short officeId, final OfficeLevel level, final OfficeBO parentOffice, final String searchId, final List<CustomFieldDto> customFields, final String officeName, final String shortName, final Address address, final OperationMode operationMode, final OfficeStatus status) throws OfficeValidationException { super(userContext); verifyFieldsNoDatabase(level, operationMode); setCreateDetails(); this.globalOfficeNum = null; this.operationMode = operationMode.getValue(); this.searchId = searchId; this.officeId = officeId; this.level = new OfficeLevelEntity(level); this.status = new OfficeStatusEntity(status); this.parentOffice = parentOffice; + if (parentOffice != null && parentOffice.getHolidays() != null) { + this.setHolidays(new HashSet<HolidayBO>(parentOffice.getHolidays())); + } this.officeName = officeName; this.shortName = shortName; if (address != null) { this.address = new OfficeAddressEntity(this, address); } this.customFields = new HashSet<OfficeCustomFieldEntity>(); if (customFields != null) { for (CustomFieldDto view : customFields) { this.customFields.add(new OfficeCustomFieldEntity(view.getFieldValue(), view.getFieldId(), this)); } } } /** * @throws OfficeValidationException * Thrown when there's a validation error * @throws PersistenceException * Thrown when there's a problem with the persistence layer */ public OfficeBO(final UserContext userContext, final OfficeLevel level, final OfficeBO parentOffice, final List<CustomFieldDto> customFields, final String officeName, final String shortName, final Address address, final OperationMode operationMode) throws OfficeValidationException, PersistenceException { this(userContext, null, level, parentOffice, null, customFields, officeName, shortName, address, operationMode, OfficeStatus.ACTIVE); verifyFields(officeName, shortName, parentOffice); } public OfficeBO(final Short officeId, final String officeName, final Integer maxChildCount, final Short operationMode) { super(); this.officeId = officeId; this.officeName = officeName; this.maxChildCount = maxChildCount; this.operationMode = operationMode; } @Override public void setCreatedDate(final Date createdDate) { this.createdDate = createdDate; } public String getGlobalOfficeNum() { return globalOfficeNum; } public OfficeLevel getOfficeLevel() { return OfficeLevel.getOfficeLevel(level.getId()); } public OfficeStatus getOfficeStatus() throws OfficeException { try { return OfficeStatus.getOfficeStatus(status.getId()); } catch (PropertyNotFoundException e) { throw new OfficeException(e); } } public OfficeStatusEntity getStatus() { return this.status; } public OfficeLevelEntity getLevel() { return this.level; } public String getOfficeName() { return officeName; } void setOfficeName(final String officeName) { this.officeName = officeName; } public Short getOfficeId() { return officeId; } public OperationMode getMode() { return OperationMode.fromInt(operationMode); } public OfficeBO getParentOffice() { return parentOffice; } void setParentOffice(final OfficeBO parentOffice) { this.parentOffice = parentOffice; } public String getSearchId() { return searchId; } public String getShortName() { return shortName; } void setShortName(final String shortName) { this.shortName = shortName; } @Override public void setUpdatedDate(final Date updatedDate) { this.updatedDate = updatedDate; } public OfficeAddressEntity getAddress() { return address; } public Set<OfficeCustomFieldEntity> getCustomFields() { return customFields; } public void setCustomFields(final Set<OfficeCustomFieldEntity> customFields) { if (customFields != null) { this.customFields = customFields; } } public void setAddress(final OfficeAddressEntity address) { this.address = address; } public void setChildren(final Set<OfficeBO> children) { this.children = children; } public void setHolidays(final Set<HolidayBO> holidays) { this.holidays = holidays; } void setGlobalOfficeNum(final String globalOfficeNum) { this.globalOfficeNum = globalOfficeNum; } void setLevel(final OfficeLevelEntity level) { this.level = level; } void setSearchId(final String searchId) { this.searchId = searchId; } void setStatus(final OfficeStatusEntity status) { this.status = status; } public Set<OfficeBO> getChildren() { return children; } public Set<HolidayBO> getHolidays() { return holidays; } private void removeChild(final OfficeBO office) { Set<OfficeBO> childerns = null; if (getChildren() != null && getChildren().size() > 0) { childerns = getChildren(); childerns.remove(office); } setChildren(childerns); } private void addChild(final OfficeBO office) { Set<OfficeBO> childerns = null; if (getChildren() == null) { childerns = new HashSet<OfficeBO>(); } else { childerns = getChildren(); } office.setParentOffice(this); childerns.add(office); setChildren(childerns); } // Changed this method signature so that it throws the PersistenceExcpetion // instead of wrapping in an OfficeExcpetion. The idea being that we are // seperating validation exceptions from PersistenceExceptions, which should // ultimately be runtime errors because they occurr, most likely, from // configuration/binding problems which are exceptions that we shouldn't // be catching. private void verifyFields(final String officeName, final String shortName, final OfficeBO parentOffice) throws OfficeValidationException, PersistenceException { OfficePersistence officePersistence = new OfficePersistence(); if (StringUtils.isBlank(officeName)) { throw new OfficeValidationException(OfficeConstants.ERRORMANDATORYFIELD, new Object[] { getLocaleString(OfficeConstants.OFFICE_NAME) }); } if (officePersistence.isOfficeNameExist(officeName)) { throw new OfficeValidationException(OfficeConstants.OFFICENAMEEXIST); } if (StringUtils.isBlank(shortName)) { throw new OfficeValidationException(OfficeConstants.ERRORMANDATORYFIELD, new Object[] { getLocaleString(OfficeConstants.OFFICESHORTNAME) }); } if (officePersistence.isOfficeShortNameExist(shortName)) { throw new OfficeValidationException(OfficeConstants.OFFICESHORTNAMEEXIST); } if (parentOffice == null) { throw new OfficeValidationException(OfficeConstants.ERRORMANDATORYFIELD, new Object[] { getLocaleString(OfficeConstants.PARENTOFFICE) }); } } private void verifyFieldsNoDatabase(final OfficeLevel level, final OperationMode operationMode) throws OfficeValidationException { if (level == null) { throw new OfficeValidationException(OfficeConstants.ERRORMANDATORYFIELD, new Object[] { getLocaleString(OfficeConstants.OFFICELEVEL) }); } if (operationMode == null) { throw new OfficeValidationException(OfficeConstants.ERRORMANDATORYFIELD, new Object[] { getLocaleString(OfficeConstants.OFFICEOPERATIONMODE) }); } } private String getLocaleString(final String key) { ResourceBundle resourceBundle = ResourceBundle.getBundle(FilePaths.OFFICERESOURCEPATH, userContext .getPreferredLocale()); return resourceBundle.getString(key); } private String generateOfficeGlobalNo() throws OfficeException { try { /* * TODO: Why not auto-increment? Fetching the max and adding one would seem to have a race condition. */ String officeGlobelNo = String.valueOf(new OfficePersistence().getMaxOfficeId().intValue() + 1); if (officeGlobelNo.length() > 4) { throw new OfficeException(OfficeConstants.MAXOFFICELIMITREACHED); } StringBuilder temp = new StringBuilder(""); for (int i = officeGlobelNo.length(); i < 4; i++) { temp.append("0"); } return officeGlobelNo = temp.append(officeGlobelNo).toString(); } catch (PersistenceException e) { throw new OfficeException(e); } } private String generateSearchId() throws OfficeException { Integer noOfChildern; try { noOfChildern = new OfficePersistence().getChildCount(parentOffice.getOfficeId()); } catch (PersistenceException e) { throw new OfficeException(e); } String parentSearchId = HierarchyManager.getInstance().getSearchId(parentOffice.getOfficeId()); parentSearchId += ++noOfChildern; parentSearchId += "."; return parentSearchId; } public void save() throws OfficeException { this.globalOfficeNum = generateOfficeGlobalNo(); this.searchId = generateSearchId(); try { new OfficePersistence().createOrUpdate(this); } catch (PersistenceException e) { throw new OfficeException(e); } // if we are here it means office created sucessfully // we need to update hierarchy manager cache OfficeSearch os = new OfficeSearch(getOfficeId(), getSearchId(), getParentOffice().getOfficeId()); List<OfficeSearch> osList = new ArrayList<OfficeSearch>(); osList.add(os); EventManger.postEvent(Constants.CREATE, osList, SecurityConstants.OFFICECHANGEEVENT); } private void changeStatus(final OfficeStatus status) throws OfficeException { if (!this.status.getId().equals(status.getValue())) { if (status == OfficeStatus.INACTIVE) { canInactivateOffice(); } else { canActivateOffice(); } try { this.status = (OfficeStatusEntity) new MasterPersistence().getPersistentObject( OfficeStatusEntity.class, status.getValue()); } catch (PersistenceException e) { throw new OfficeException(e); } } } private void canInactivateOffice() throws OfficeException { OfficePersistence officePersistence = new OfficePersistence(); try { if (officePersistence.hasActiveChildern(this.officeId)) { throw new OfficeException(OfficeConstants.KEYHASACTIVECHILDREN); } if (officePersistence.hasActivePeronnel(this.officeId)) { throw new OfficeException(OfficeConstants.KEYHASACTIVEPERSONNEL); } } catch (PersistenceException e) { throw new OfficeException(e); } } private void canActivateOffice() throws OfficeException { if (parentOffice.getOfficeStatus().equals(OfficeStatus.INACTIVE)) { throw new OfficeException(OfficeConstants.KEYPARENTNOTACTIVE); } } public boolean isActive() { return getStatus().getId().equals(OfficeStatus.ACTIVE.getValue()); } public void update(final String newName, final String newShortName, final OfficeStatus newStatus, final OfficeLevel newLevel, final OfficeBO newParent, final Address address, final List<CustomFieldDto> customFileds) throws OfficeException { changeOfficeName(newName); changeOfficeShortName(newShortName); updateLevel(newLevel); if (!this.getOfficeLevel().equals(OfficeLevel.HEADOFFICE)) { updateParent(newParent); } changeStatus(newStatus); updateAddress(address); updateCustomFields(customFileds); setUpdateDetails(); try { new OfficePersistence().createOrUpdate(this); } catch (PersistenceException e) { throw new OfficeException(e); } } private void changeOfficeName(final String newName) throws OfficeException { if (!this.officeName.equalsIgnoreCase(newName)) { try { if (new OfficePersistence().isOfficeNameExist(newName)) { throw new OfficeException(OfficeConstants.OFFICENAMEEXIST); } } catch (PersistenceException e) { throw new OfficeException(e); } this.officeName = newName; } } private void changeOfficeShortName(final String newShortName) throws OfficeException { if (!this.shortName.equalsIgnoreCase(newShortName)) { try { if (new OfficePersistence().isOfficeShortNameExist(newShortName)) { throw new OfficeException(OfficeConstants.OFFICESHORTNAMEEXIST); } } catch (PersistenceException e) { throw new OfficeException(e); } this.shortName = newShortName; } } private void updateParent(final OfficeBO newParent) throws OfficeException { if (newParent != null) { if (this.getParentOffice() != null) { if (!this.getParentOffice().getOfficeId().equals(newParent.getOfficeId())) { OfficeBO oldParent = this.getParentOffice(); if (this.getOfficeLevel().getValue().shortValue() < newParent.getOfficeLevel().getValue() .shortValue()) { throw new OfficeException(OfficeConstants.ERROR_INVLID_PARENT); } OfficeBO oldParent1 = getIfChildPresent(newParent, oldParent); if (oldParent1 == null) { oldParent1 = oldParent; } oldParent1.removeChild(this); OfficeBO newParent1 = getIfChildPresent(oldParent, newParent); if (newParent1 == null) { newParent1 = newParent; } newParent1.addChild(this); newParent1.updateSearchId(newParent1.getSearchId()); oldParent1.updateSearchId(oldParent1.getSearchId()); } } } } private void updateSearchId(final String searchId) { this.setSearchId(searchId); int i = 1; if (this.getChildren() != null) { Iterator<OfficeBO> iter = this.getChildren().iterator(); while (iter.hasNext()) { OfficeBO element = iter.next(); element.updateSearchId(this.getSearchId() + i + "."); i++; } } } private void updateLevel(final OfficeLevel level) throws OfficeException { if (this.getOfficeLevel() != level) { if (!canUpdateLevel(level)) { throw new OfficeException(OfficeConstants.ERROR_INVALID_LEVEL); } try { this.level = (OfficeLevelEntity) new MasterPersistence().getPersistentObject(OfficeLevelEntity.class, level.getValue()); } catch (PersistenceException e) { throw new OfficeException(e); } } } private boolean canUpdateLevel(final OfficeLevel level) { if (this.getOfficeLevel().getValue() > level.getValue()) { return true; } for (OfficeBO office : this.children) { if (office.getLevel().getId() <= level.getValue()) { return false; } } return true; } private void updateAddress(final Address address) { if (this.address != null && address != null) { this.address.setAddress(address); } else if (this.address == null && address != null) { this.address = new OfficeAddressEntity(this, address); } } private void updateCustomFields(final List<CustomFieldDto> customfields) { if (this.customFields != null && customfields != null) { for (CustomFieldDto fieldView : customfields) { for (OfficeCustomFieldEntity fieldEntity : this.customFields) { if (fieldView.getFieldId().equals(fieldEntity.getFieldId())) { fieldEntity.setFieldValue(fieldView.getFieldValue()); } } } } else if (this.customFields == null && customfields != null) { this.customFields = new HashSet<OfficeCustomFieldEntity>(); for (CustomFieldDto view : customfields) { this.customFields.add(new OfficeCustomFieldEntity(view.getFieldValue(), view.getFieldId(), this)); } } } public Set<OfficeBO> getBranchOnlyChildren() { Set<OfficeBO> offices = new HashSet<OfficeBO>(); if (getChildren() != null) { for (OfficeBO office : getChildren()) { if (office.getOfficeLevel().equals(OfficeLevel.BRANCHOFFICE)) { offices.add(office); } } } return offices; } /* FIXME: we also need to implement hashCode() */ @Override public boolean equals(final Object o) { return officeId.equals(((OfficeBO) o).getOfficeId()); } public int compareTo(final OfficeBO o) { return officeId.compareTo(o.getOfficeId()); } public OfficeBO getIfChildPresent(final OfficeBO parent, final OfficeBO child) { if (parent.getChildren() != null) { for (OfficeBO childl : parent.getChildren()) { if (childl.getOfficeId().equals(child.getOfficeId())) { return childl; } return getIfChildPresent(childl, child); } } return null; } public boolean isParent(final OfficeBO child) { boolean isParent = false; if (getChildren() != null) { for (OfficeBO children : getChildren()) { if (children.equals(child)) { return true; } isParent = children.isParent(child); if (isParent) { return true; } } } return isParent; } public void addHoliday(HolidayBO holiday){ getHolidays().add(holiday); } }
true
true
private OfficeBO(final UserContext userContext, final Short officeId, final OfficeLevel level, final OfficeBO parentOffice, final String searchId, final List<CustomFieldDto> customFields, final String officeName, final String shortName, final Address address, final OperationMode operationMode, final OfficeStatus status) throws OfficeValidationException { super(userContext); verifyFieldsNoDatabase(level, operationMode); setCreateDetails(); this.globalOfficeNum = null; this.operationMode = operationMode.getValue(); this.searchId = searchId; this.officeId = officeId; this.level = new OfficeLevelEntity(level); this.status = new OfficeStatusEntity(status); this.parentOffice = parentOffice; this.officeName = officeName; this.shortName = shortName; if (address != null) { this.address = new OfficeAddressEntity(this, address); } this.customFields = new HashSet<OfficeCustomFieldEntity>(); if (customFields != null) { for (CustomFieldDto view : customFields) { this.customFields.add(new OfficeCustomFieldEntity(view.getFieldValue(), view.getFieldId(), this)); } } }
private OfficeBO(final UserContext userContext, final Short officeId, final OfficeLevel level, final OfficeBO parentOffice, final String searchId, final List<CustomFieldDto> customFields, final String officeName, final String shortName, final Address address, final OperationMode operationMode, final OfficeStatus status) throws OfficeValidationException { super(userContext); verifyFieldsNoDatabase(level, operationMode); setCreateDetails(); this.globalOfficeNum = null; this.operationMode = operationMode.getValue(); this.searchId = searchId; this.officeId = officeId; this.level = new OfficeLevelEntity(level); this.status = new OfficeStatusEntity(status); this.parentOffice = parentOffice; if (parentOffice != null && parentOffice.getHolidays() != null) { this.setHolidays(new HashSet<HolidayBO>(parentOffice.getHolidays())); } this.officeName = officeName; this.shortName = shortName; if (address != null) { this.address = new OfficeAddressEntity(this, address); } this.customFields = new HashSet<OfficeCustomFieldEntity>(); if (customFields != null) { for (CustomFieldDto view : customFields) { this.customFields.add(new OfficeCustomFieldEntity(view.getFieldValue(), view.getFieldId(), this)); } } }
diff --git a/Server/VoiceServer.java b/Server/VoiceServer.java index f022aca..0ba4c4a 100644 --- a/Server/VoiceServer.java +++ b/Server/VoiceServer.java @@ -1,82 +1,81 @@ import java.util.*; import java.io.*; import java.net.*; public class VoiceServer implements Runnable { private int _port = 0; ArrayList<VoiceServerConnection> _connections = null; VoiceServer(int port) { _port = port; _connections = new ArrayList<VoiceServerConnection>(); } public void run() { System.out.println("Voice Server started."); try { // create a socket for handling incoming requests DatagramSocket serverSocket = new DatagramSocket(_port); while(true) { // receive the incoming packet byte[] buffer = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length); serverSocket.receive(receivePacket); // extract the byte stream data buffer = receivePacket.getData(); // extract the IP address and port number InetAddress ipAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); // if this is a new connection, store it in our list VoiceServerConnection target = null; for (VoiceServerConnection c : _connections) { - if ((c.getIPAddress() == ipAddress) && + if ((c.getIPAddress().toString(ipAddress)) && (c.getPort() == port)) { target = c; break; } } if (target == null) { VoiceServerConnection vsc = new VoiceServerConnection(ipAddress, port); _connections.add(vsc); } // send the packet data for (VoiceServerConnection c : _connections) { try { - if ((c.getIPAddress() != ipAddress) || - (c.getPort() != port)) // we don't need to hear our own audio + if (!(c.getIPAddress().toString(ipAddress))) // we don't need to hear our own audio { DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, c.getIPAddress(), c.getPort()); serverSocket.send(sendPacket); } } catch (IOException ex) { // TODO: handle this exception } } } } catch (IOException ex) { // TODO: handle this exception } } }
false
true
public void run() { System.out.println("Voice Server started."); try { // create a socket for handling incoming requests DatagramSocket serverSocket = new DatagramSocket(_port); while(true) { // receive the incoming packet byte[] buffer = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length); serverSocket.receive(receivePacket); // extract the byte stream data buffer = receivePacket.getData(); // extract the IP address and port number InetAddress ipAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); // if this is a new connection, store it in our list VoiceServerConnection target = null; for (VoiceServerConnection c : _connections) { if ((c.getIPAddress() == ipAddress) && (c.getPort() == port)) { target = c; break; } } if (target == null) { VoiceServerConnection vsc = new VoiceServerConnection(ipAddress, port); _connections.add(vsc); } // send the packet data for (VoiceServerConnection c : _connections) { try { if ((c.getIPAddress() != ipAddress) || (c.getPort() != port)) // we don't need to hear our own audio { DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, c.getIPAddress(), c.getPort()); serverSocket.send(sendPacket); } } catch (IOException ex) { // TODO: handle this exception } } } } catch (IOException ex) { // TODO: handle this exception } }
public void run() { System.out.println("Voice Server started."); try { // create a socket for handling incoming requests DatagramSocket serverSocket = new DatagramSocket(_port); while(true) { // receive the incoming packet byte[] buffer = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length); serverSocket.receive(receivePacket); // extract the byte stream data buffer = receivePacket.getData(); // extract the IP address and port number InetAddress ipAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); // if this is a new connection, store it in our list VoiceServerConnection target = null; for (VoiceServerConnection c : _connections) { if ((c.getIPAddress().toString(ipAddress)) && (c.getPort() == port)) { target = c; break; } } if (target == null) { VoiceServerConnection vsc = new VoiceServerConnection(ipAddress, port); _connections.add(vsc); } // send the packet data for (VoiceServerConnection c : _connections) { try { if (!(c.getIPAddress().toString(ipAddress))) // we don't need to hear our own audio { DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, c.getIPAddress(), c.getPort()); serverSocket.send(sendPacket); } } catch (IOException ex) { // TODO: handle this exception } } } } catch (IOException ex) { // TODO: handle this exception } }
diff --git a/JsTestDriver/src/com/google/jstestdriver/config/DefaultConfiguration.java b/JsTestDriver/src/com/google/jstestdriver/config/DefaultConfiguration.java index 5058fdf..d811020 100644 --- a/JsTestDriver/src/com/google/jstestdriver/config/DefaultConfiguration.java +++ b/JsTestDriver/src/com/google/jstestdriver/config/DefaultConfiguration.java @@ -1,65 +1,65 @@ /* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.jstestdriver.config; import com.google.jstestdriver.FileInfo; import com.google.jstestdriver.Flags; import com.google.jstestdriver.PathResolver; import com.google.jstestdriver.Plugin; import com.google.jstestdriver.model.HandlerPathPrefix; import java.util.Collections; import java.util.List; import java.util.Set; /** * @author [email protected] (Cory Smith) */ public class DefaultConfiguration implements Configuration{ public static final long DEFAULT_TEST_TIMEOUT = 2 * 60 * 60; public Set<FileInfo> getFilesList() { return Collections.<FileInfo>emptySet(); } public List<Plugin> getPlugins() { return Collections.<Plugin>emptyList(); } public String getServer(String flagValue, int port, HandlerPathPrefix handlerPrefix) { if (flagValue != null && !flagValue.isEmpty()) { return handlerPrefix.suffixServer(flagValue); } if (port == -1) { throw new RuntimeException("Oh Snap! No server defined!"); } - return handlerPrefix.suffixServer(String.format("http://%s:%d", "127.0.0.1")); + return handlerPrefix.suffixServer(String.format("http://%s:%d", "127.0.0.1", port)); } public Configuration resolvePaths(PathResolver resolver, Flags flags) { return this; } public long getTestSuiteTimeout() { return DEFAULT_TEST_TIMEOUT; // two hours. Should be enough to debug. } public List<FileInfo> getTests() { return Collections.<FileInfo>emptyList(); } }
true
true
public String getServer(String flagValue, int port, HandlerPathPrefix handlerPrefix) { if (flagValue != null && !flagValue.isEmpty()) { return handlerPrefix.suffixServer(flagValue); } if (port == -1) { throw new RuntimeException("Oh Snap! No server defined!"); } return handlerPrefix.suffixServer(String.format("http://%s:%d", "127.0.0.1")); }
public String getServer(String flagValue, int port, HandlerPathPrefix handlerPrefix) { if (flagValue != null && !flagValue.isEmpty()) { return handlerPrefix.suffixServer(flagValue); } if (port == -1) { throw new RuntimeException("Oh Snap! No server defined!"); } return handlerPrefix.suffixServer(String.format("http://%s:%d", "127.0.0.1", port)); }
diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/scan/spi/AbstractScannerImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/scan/spi/AbstractScannerImpl.java index da5af94f25..3d2c441370 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/scan/spi/AbstractScannerImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/scan/spi/AbstractScannerImpl.java @@ -1,302 +1,302 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2013, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.jpa.boot.scan.spi; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.hibernate.jpa.boot.archive.spi.ArchiveContext; import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptor; import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptorFactory; import org.hibernate.jpa.boot.archive.spi.ArchiveEntry; import org.hibernate.jpa.boot.archive.spi.ArchiveEntryHandler; import org.hibernate.jpa.boot.internal.ClassDescriptorImpl; import org.hibernate.jpa.boot.internal.MappingFileDescriptorImpl; import org.hibernate.jpa.boot.internal.PackageDescriptorImpl; import org.hibernate.jpa.boot.spi.ClassDescriptor; import org.hibernate.jpa.boot.spi.MappingFileDescriptor; import org.hibernate.jpa.boot.spi.PackageDescriptor; import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor; /** * @author Steve Ebersole */ public abstract class AbstractScannerImpl implements Scanner { private final ArchiveDescriptorFactory archiveDescriptorFactory; private final Map<URL, ArchiveDescriptorInfo> archiveDescriptorCache = new HashMap<URL, ArchiveDescriptorInfo>(); protected AbstractScannerImpl(ArchiveDescriptorFactory archiveDescriptorFactory) { this.archiveDescriptorFactory = archiveDescriptorFactory; } @Override public ScanResult scan(PersistenceUnitDescriptor persistenceUnit, ScanOptions scanOptions) { final ResultCollector resultCollector = new ResultCollector( scanOptions ); if ( persistenceUnit.getJarFileUrls() != null ) { for ( URL url : persistenceUnit.getJarFileUrls() ) { final ArchiveDescriptor descriptor = buildArchiveDescriptor( url, false, scanOptions ); final ArchiveContext context = buildArchiveContext( persistenceUnit, false, resultCollector ); descriptor.visitArchive( context ); } } if ( persistenceUnit.getPersistenceUnitRootUrl() != null ) { final ArchiveDescriptor descriptor = buildArchiveDescriptor( persistenceUnit.getPersistenceUnitRootUrl(), true, scanOptions ); - final ArchiveContext context = buildArchiveContext( persistenceUnit, false, resultCollector ); + final ArchiveContext context = buildArchiveContext( persistenceUnit, true, resultCollector ); descriptor.visitArchive( context ); } return ScanResultImpl.from( resultCollector ); } private ArchiveContext buildArchiveContext( PersistenceUnitDescriptor persistenceUnit, boolean isRoot, ArchiveEntryHandlers entryHandlers) { return new ArchiveContextImpl( persistenceUnit, isRoot, entryHandlers ); } protected static interface ArchiveEntryHandlers { public ArchiveEntryHandler getClassFileHandler(); public ArchiveEntryHandler getPackageInfoHandler(); public ArchiveEntryHandler getFileHandler(); } private ArchiveDescriptor buildArchiveDescriptor(URL url, boolean isRootUrl, ScanOptions scanOptions) { final ArchiveDescriptor descriptor; final ArchiveDescriptorInfo descriptorInfo = archiveDescriptorCache.get( url ); if ( descriptorInfo == null ) { descriptor = archiveDescriptorFactory.buildArchiveDescriptor( url ); archiveDescriptorCache.put( url, new ArchiveDescriptorInfo( descriptor, isRootUrl, scanOptions ) ); } else { validateReuse( descriptorInfo, isRootUrl, scanOptions ); descriptor = descriptorInfo.archiveDescriptor; } return descriptor; } public static class ResultCollector implements ArchiveEntryHandlers, PackageInfoArchiveEntryHandler.Callback, ClassFileArchiveEntryHandler.Callback, NonClassFileArchiveEntryHandler.Callback { private final ClassFileArchiveEntryHandler classFileHandler; private final PackageInfoArchiveEntryHandler packageInfoHandler; private final NonClassFileArchiveEntryHandler fileHandler; private final Set<PackageDescriptor> packageDescriptorSet = new HashSet<PackageDescriptor>(); private final Set<ClassDescriptor> classDescriptorSet = new HashSet<ClassDescriptor>(); private final Set<MappingFileDescriptor> mappingFileSet = new HashSet<MappingFileDescriptor>(); public ResultCollector(ScanOptions scanOptions) { this.classFileHandler = new ClassFileArchiveEntryHandler( scanOptions, this ); this.packageInfoHandler = new PackageInfoArchiveEntryHandler( scanOptions, this ); this.fileHandler = new NonClassFileArchiveEntryHandler( scanOptions, this ); } @Override public ArchiveEntryHandler getClassFileHandler() { return classFileHandler; } @Override public ArchiveEntryHandler getPackageInfoHandler() { return packageInfoHandler; } @Override public ArchiveEntryHandler getFileHandler() { return fileHandler; } @Override public void locatedPackage(PackageDescriptor packageDescriptor) { if ( PackageDescriptorImpl.class.isInstance( packageDescriptor ) ) { packageDescriptorSet.add( packageDescriptor ); } else { // to make sure we have proper equals/hashcode packageDescriptorSet.add( new PackageDescriptorImpl( packageDescriptor.getName(), packageDescriptor.getStreamAccess() ) ); } } @Override public void locatedClass(ClassDescriptor classDescriptor) { if ( ClassDescriptorImpl.class.isInstance( classDescriptor ) ) { classDescriptorSet.add( classDescriptor ); } else { // to make sure we have proper equals/hashcode classDescriptorSet.add( new ClassDescriptorImpl( classDescriptor.getName(), classDescriptor.getStreamAccess() ) ); } } @Override public void locatedMappingFile(MappingFileDescriptor mappingFileDescriptor) { if ( MappingFileDescriptorImpl.class.isInstance( mappingFileDescriptor ) ) { mappingFileSet.add( mappingFileDescriptor ); } else { // to make sure we have proper equals/hashcode mappingFileSet.add( new MappingFileDescriptorImpl( mappingFileDescriptor.getName(), mappingFileDescriptor.getStreamAccess() ) ); } } public Set<PackageDescriptor> getPackageDescriptorSet() { return packageDescriptorSet; } public Set<ClassDescriptor> getClassDescriptorSet() { return classDescriptorSet; } public Set<MappingFileDescriptor> getMappingFileSet() { return mappingFileSet; } } private static class ArchiveDescriptorInfo { private final ArchiveDescriptor archiveDescriptor; private final boolean isRoot; private final ScanOptions scanOptions; private ArchiveDescriptorInfo( ArchiveDescriptor archiveDescriptor, boolean isRoot, ScanOptions scanOptions) { this.archiveDescriptor = archiveDescriptor; this.isRoot = isRoot; this.scanOptions = scanOptions; } } protected void validateReuse(ArchiveDescriptorInfo descriptor, boolean root, ScanOptions options) { // is it really reasonable that a single url be processed multiple times? // for now, throw an exception, mainly because I am interested in situations where this might happen throw new IllegalStateException( "ArchiveDescriptor reused; can URLs be processed multiple times?" ); } public static class ArchiveContextImpl implements ArchiveContext { private final PersistenceUnitDescriptor persistenceUnitDescriptor; private final boolean isRootUrl; private final ArchiveEntryHandlers entryHandlers; public ArchiveContextImpl( PersistenceUnitDescriptor persistenceUnitDescriptor, boolean isRootUrl, ArchiveEntryHandlers entryHandlers) { this.persistenceUnitDescriptor = persistenceUnitDescriptor; this.isRootUrl = isRootUrl; this.entryHandlers = entryHandlers; } @Override public PersistenceUnitDescriptor getPersistenceUnitDescriptor() { return persistenceUnitDescriptor; } @Override public boolean isRootUrl() { return isRootUrl; } @Override public ArchiveEntryHandler obtainArchiveEntryHandler(ArchiveEntry entry) { final String nameWithinArchive = entry.getNameWithinArchive(); if ( nameWithinArchive.endsWith( "package-info.class" ) ) { return entryHandlers.getPackageInfoHandler(); } else if ( nameWithinArchive.endsWith( ".class" ) ) { return entryHandlers.getClassFileHandler(); } else { return entryHandlers.getFileHandler(); } } } private static class ScanResultImpl implements ScanResult { private final Set<PackageDescriptor> packageDescriptorSet; private final Set<ClassDescriptor> classDescriptorSet; private final Set<MappingFileDescriptor> mappingFileSet; private ScanResultImpl( Set<PackageDescriptor> packageDescriptorSet, Set<ClassDescriptor> classDescriptorSet, Set<MappingFileDescriptor> mappingFileSet) { this.packageDescriptorSet = packageDescriptorSet; this.classDescriptorSet = classDescriptorSet; this.mappingFileSet = mappingFileSet; } private static ScanResult from(ResultCollector resultCollector) { return new ScanResultImpl( Collections.unmodifiableSet( resultCollector.packageDescriptorSet ), Collections.unmodifiableSet( resultCollector.classDescriptorSet ), Collections.unmodifiableSet( resultCollector.mappingFileSet ) ); } @Override public Set<PackageDescriptor> getLocatedPackages() { return packageDescriptorSet; } @Override public Set<ClassDescriptor> getLocatedClasses() { return classDescriptorSet; } @Override public Set<MappingFileDescriptor> getLocatedMappingFiles() { return mappingFileSet; } } }
true
true
public ScanResult scan(PersistenceUnitDescriptor persistenceUnit, ScanOptions scanOptions) { final ResultCollector resultCollector = new ResultCollector( scanOptions ); if ( persistenceUnit.getJarFileUrls() != null ) { for ( URL url : persistenceUnit.getJarFileUrls() ) { final ArchiveDescriptor descriptor = buildArchiveDescriptor( url, false, scanOptions ); final ArchiveContext context = buildArchiveContext( persistenceUnit, false, resultCollector ); descriptor.visitArchive( context ); } } if ( persistenceUnit.getPersistenceUnitRootUrl() != null ) { final ArchiveDescriptor descriptor = buildArchiveDescriptor( persistenceUnit.getPersistenceUnitRootUrl(), true, scanOptions ); final ArchiveContext context = buildArchiveContext( persistenceUnit, false, resultCollector ); descriptor.visitArchive( context ); } return ScanResultImpl.from( resultCollector ); }
public ScanResult scan(PersistenceUnitDescriptor persistenceUnit, ScanOptions scanOptions) { final ResultCollector resultCollector = new ResultCollector( scanOptions ); if ( persistenceUnit.getJarFileUrls() != null ) { for ( URL url : persistenceUnit.getJarFileUrls() ) { final ArchiveDescriptor descriptor = buildArchiveDescriptor( url, false, scanOptions ); final ArchiveContext context = buildArchiveContext( persistenceUnit, false, resultCollector ); descriptor.visitArchive( context ); } } if ( persistenceUnit.getPersistenceUnitRootUrl() != null ) { final ArchiveDescriptor descriptor = buildArchiveDescriptor( persistenceUnit.getPersistenceUnitRootUrl(), true, scanOptions ); final ArchiveContext context = buildArchiveContext( persistenceUnit, true, resultCollector ); descriptor.visitArchive( context ); } return ScanResultImpl.from( resultCollector ); }
diff --git a/issues/jira/src/main/java/uk/org/sappho/code/heatmap/issues/jira/JiraService.java b/issues/jira/src/main/java/uk/org/sappho/code/heatmap/issues/jira/JiraService.java index a0ed733..6119ff1 100644 --- a/issues/jira/src/main/java/uk/org/sappho/code/heatmap/issues/jira/JiraService.java +++ b/issues/jira/src/main/java/uk/org/sappho/code/heatmap/issues/jira/JiraService.java @@ -1,144 +1,150 @@ package uk.org.sappho.code.heatmap.issues.jira; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import com.atlassian.jira.rpc.soap.client.JiraSoapService; import com.atlassian.jira.rpc.soap.client.JiraSoapServiceServiceLocator; import com.atlassian.jira.rpc.soap.client.RemoteIssue; import com.google.inject.Inject; import com.google.inject.Singleton; import uk.org.sappho.code.heatmap.config.Configuration; import uk.org.sappho.code.heatmap.issues.IssueManagement; import uk.org.sappho.code.heatmap.issues.IssueManagementException; import uk.org.sappho.code.heatmap.issues.IssueWrapper; @Singleton public class JiraService implements IssueManagement { protected JiraSoapService jiraSoapService = null; protected String JiraSoapServiceToken = null; protected Map<String, IssueWrapper> allowedIssues = new HashMap<String, IssueWrapper>(); protected Map<String, String> issueTypes = new HashMap<String, String>(); protected Map<String, Integer> issueTypeWeightMultipliers = new HashMap<String, Integer>(); protected Configuration config; protected static final Pattern SIMPLE_JIRA_REGEX = Pattern.compile("^([a-zA-Z]{2,}-\\d+):.*$"); private static final Logger LOG = Logger.getLogger(JiraService.class); @Inject public JiraService(Configuration config) throws IssueManagementException { LOG.info("Using Jira issue management plugin"); this.config = config; connect(); getAllowedIssues(); } protected void connect() throws IssueManagementException { String url = config.getProperty("jira.url", "http://example.com"); String username = config.getProperty("jira.username", "nobody"); String password = config.getProperty("jira.password", "nopassword"); LOG.info("Connecting to " + url + " as " + username); try { jiraSoapService = new JiraSoapServiceServiceLocator().getJirasoapserviceV2(new URL(url + "/rpc/soap/jirasoapservice-v2")); JiraSoapServiceToken = jiraSoapService.login(username, password); } catch (Throwable t) { throw new IssueManagementException("Unable to log in to Jira at " + url + " as user " + username, t); } } protected void getAllowedIssues() throws IssueManagementException { /** * note: this is a bit rubbish but because jira's soap interface doesn't have a getParent function it's the only way to fake it * making this better will require an installed plugin * **/ LOG.info("Getting list of allowed issues"); try { // get all tasks we're prepared to deal with - RemoteIssue[] remoteIssues = jiraSoapService.getIssuesFromJqlSearch(JiraSoapServiceToken, config - .getProperty("jira.filter.issues.allowed"), 1000); + String jql = config.getProperty("jira.filter.issues.allowed"); + LOG.info("Running Jira query: " + jql); + RemoteIssue[] remoteIssues = jiraSoapService.getIssuesFromJqlSearch(JiraSoapServiceToken, jql, 5000); + LOG.info("Processing " + remoteIssues.length + " issues returned by query"); // map all subtasks back to their parents Map<String, RemoteIssue> mappedRemoteIssues = new HashMap<String, RemoteIssue>(); Map<String, String> subTaskParents = new HashMap<String, String>(); for (RemoteIssue remoteIssue : remoteIssues) { String issueKey = remoteIssue.getKey(); - mappedRemoteIssues.put(issueKey, remoteIssue); + if (mappedRemoteIssues.get(issueKey) == null) { + mappedRemoteIssues.put(issueKey, remoteIssue); + } RemoteIssue[] subTasks = jiraSoapService.getIssuesFromJqlSearch(JiraSoapServiceToken, "parent = " + issueKey, 200); for (RemoteIssue subTask : subTasks) { String subTaskKey = subTask.getKey(); LOG.info("Mapping " + subTaskKey + " to parent issue " + issueKey); if (mappedRemoteIssues.get(subTaskKey) == null) { mappedRemoteIssues.put(subTaskKey, subTask); } subTaskParents.put(subTaskKey, issueKey); } } + LOG.info("Processed " + mappedRemoteIssues.size() + + " issues - added subtasks might have inflated this figure"); // create issue wrappers for all allowed root (non-subtask) issues for (String issueKey : mappedRemoteIssues.keySet()) { String parentKey = subTaskParents.get(issueKey); IssueWrapper issueWrapper = parentKey != null ? createIssueWrapper(mappedRemoteIssues.get(parentKey), issueKey) : createIssueWrapper(mappedRemoteIssues.get(issueKey), null); allowedIssues.put(issueKey, issueWrapper); } } catch (Throwable t) { throw new IssueManagementException("Unable to get list of allowed issues", t); } } protected IssueWrapper createIssueWrapper(RemoteIssue issue, String subTaskKey) throws IssueManagementException { String typeId = issue.getType(); String typeName = issueTypes.get(typeId); if (typeName == null) { typeName = config.getProperty("jira.type.map.id." + typeId, "housekeeping"); LOG.info("Mapping raw issue type " + typeId + " to " + typeName); issueTypes.put(typeId, typeName); } Integer weight = issueTypeWeightMultipliers.get(typeName); if (weight == null) { String typeNameKey = "jira.type.multiplier." + typeName; try { weight = Integer.parseInt(config.getProperty(typeNameKey, "0")); } catch (Throwable t) { throw new IssueManagementException( "Issue type weight configuration \"" + typeNameKey + "\" is invalid", t); } LOG.info("Weight of issue type " + typeName + " is " + weight); issueTypeWeightMultipliers.put(typeName, weight); } return new JiraIssueWrapper(issue, subTaskKey, weight); } protected String getIssueKeyFromCommitComment(String commitComment) { String key = null; Matcher matcher = SIMPLE_JIRA_REGEX.matcher(commitComment.split("\n")[0]); if (matcher.matches()) { key = matcher.group(1); } else { LOG.info("No issue ID found in commit comment: " + commitComment); } return key; } public IssueWrapper getIssue(String commitComment) { IssueWrapper issue = null; String key = getIssueKeyFromCommitComment(commitComment); if (key != null) { issue = allowedIssues.get(key); } return issue; } }
false
true
protected void getAllowedIssues() throws IssueManagementException { /** * note: this is a bit rubbish but because jira's soap interface doesn't have a getParent function it's the only way to fake it * making this better will require an installed plugin * **/ LOG.info("Getting list of allowed issues"); try { // get all tasks we're prepared to deal with RemoteIssue[] remoteIssues = jiraSoapService.getIssuesFromJqlSearch(JiraSoapServiceToken, config .getProperty("jira.filter.issues.allowed"), 1000); // map all subtasks back to their parents Map<String, RemoteIssue> mappedRemoteIssues = new HashMap<String, RemoteIssue>(); Map<String, String> subTaskParents = new HashMap<String, String>(); for (RemoteIssue remoteIssue : remoteIssues) { String issueKey = remoteIssue.getKey(); mappedRemoteIssues.put(issueKey, remoteIssue); RemoteIssue[] subTasks = jiraSoapService.getIssuesFromJqlSearch(JiraSoapServiceToken, "parent = " + issueKey, 200); for (RemoteIssue subTask : subTasks) { String subTaskKey = subTask.getKey(); LOG.info("Mapping " + subTaskKey + " to parent issue " + issueKey); if (mappedRemoteIssues.get(subTaskKey) == null) { mappedRemoteIssues.put(subTaskKey, subTask); } subTaskParents.put(subTaskKey, issueKey); } } // create issue wrappers for all allowed root (non-subtask) issues for (String issueKey : mappedRemoteIssues.keySet()) { String parentKey = subTaskParents.get(issueKey); IssueWrapper issueWrapper = parentKey != null ? createIssueWrapper(mappedRemoteIssues.get(parentKey), issueKey) : createIssueWrapper(mappedRemoteIssues.get(issueKey), null); allowedIssues.put(issueKey, issueWrapper); } } catch (Throwable t) { throw new IssueManagementException("Unable to get list of allowed issues", t); } }
protected void getAllowedIssues() throws IssueManagementException { /** * note: this is a bit rubbish but because jira's soap interface doesn't have a getParent function it's the only way to fake it * making this better will require an installed plugin * **/ LOG.info("Getting list of allowed issues"); try { // get all tasks we're prepared to deal with String jql = config.getProperty("jira.filter.issues.allowed"); LOG.info("Running Jira query: " + jql); RemoteIssue[] remoteIssues = jiraSoapService.getIssuesFromJqlSearch(JiraSoapServiceToken, jql, 5000); LOG.info("Processing " + remoteIssues.length + " issues returned by query"); // map all subtasks back to their parents Map<String, RemoteIssue> mappedRemoteIssues = new HashMap<String, RemoteIssue>(); Map<String, String> subTaskParents = new HashMap<String, String>(); for (RemoteIssue remoteIssue : remoteIssues) { String issueKey = remoteIssue.getKey(); if (mappedRemoteIssues.get(issueKey) == null) { mappedRemoteIssues.put(issueKey, remoteIssue); } RemoteIssue[] subTasks = jiraSoapService.getIssuesFromJqlSearch(JiraSoapServiceToken, "parent = " + issueKey, 200); for (RemoteIssue subTask : subTasks) { String subTaskKey = subTask.getKey(); LOG.info("Mapping " + subTaskKey + " to parent issue " + issueKey); if (mappedRemoteIssues.get(subTaskKey) == null) { mappedRemoteIssues.put(subTaskKey, subTask); } subTaskParents.put(subTaskKey, issueKey); } } LOG.info("Processed " + mappedRemoteIssues.size() + " issues - added subtasks might have inflated this figure"); // create issue wrappers for all allowed root (non-subtask) issues for (String issueKey : mappedRemoteIssues.keySet()) { String parentKey = subTaskParents.get(issueKey); IssueWrapper issueWrapper = parentKey != null ? createIssueWrapper(mappedRemoteIssues.get(parentKey), issueKey) : createIssueWrapper(mappedRemoteIssues.get(issueKey), null); allowedIssues.put(issueKey, issueWrapper); } } catch (Throwable t) { throw new IssueManagementException("Unable to get list of allowed issues", t); } }
diff --git a/HBaseAdapter/src/main/java/com/nearinfinity/hbaseclient/ColumnInfo.java b/HBaseAdapter/src/main/java/com/nearinfinity/hbaseclient/ColumnInfo.java index c70d9cd8..735b0dbd 100644 --- a/HBaseAdapter/src/main/java/com/nearinfinity/hbaseclient/ColumnInfo.java +++ b/HBaseAdapter/src/main/java/com/nearinfinity/hbaseclient/ColumnInfo.java @@ -1,36 +1,36 @@ package com.nearinfinity.hbaseclient; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created with IntelliJ IDEA. * User: jedstrom * Date: 7/25/12 * Time: 2:06 PM * To change this template use File | Settings | File Templates. */ public class ColumnInfo { private long id; private String name; private ColumnMetadata metadata; public ColumnInfo(long id, String name, ColumnMetadata metadata) { this.id = id; this.name = name; - this.metadata = new ColumnMetadata(); + this.metadata = metadata; } public long getId() { return this.id; } public String getName() { return this.name; } public ColumnMetadata getMetadata() { return this.metadata; } }
true
true
public ColumnInfo(long id, String name, ColumnMetadata metadata) { this.id = id; this.name = name; this.metadata = new ColumnMetadata(); }
public ColumnInfo(long id, String name, ColumnMetadata metadata) { this.id = id; this.name = name; this.metadata = metadata; }
diff --git a/cadpageTest/src/net/anei/cadpage/parsers/PA/PANorthamptonCountyParserTest.java b/cadpageTest/src/net/anei/cadpage/parsers/PA/PANorthamptonCountyParserTest.java index 83e955fc9..b58ea9a78 100644 --- a/cadpageTest/src/net/anei/cadpage/parsers/PA/PANorthamptonCountyParserTest.java +++ b/cadpageTest/src/net/anei/cadpage/parsers/PA/PANorthamptonCountyParserTest.java @@ -1,238 +1,238 @@ package net.anei.cadpage.parsers.PA; import net.anei.cadpage.parsers.BaseParserTest; import net.anei.cadpage.parsers.PA.PANorthamptonCountyParser; import org.junit.Test; public class PANorthamptonCountyParserTest extends BaseParserTest { public PANorthamptonCountyParserTest() { setParser(new PANorthamptonCountyParser(), "NORTHAMPTON COUNTY", "PA"); } @Test public void testParser() { doTest("T1", "[e49]ALS >ADVANCED LIFE SUPPORT CALL 602 E 21ST ST Apt: 119 Bldg NORTHAMPTON DIANE ECK Map: Grids:0,0 Cad: 2011-0000086714", "UNIT:e49", "CALL:ADVANCED LIFE SUPPORT", "ADDR:602 E 21ST ST", "APT:119 Bldg", "CITY:NORTHAMPTON", "NAME:DIANE ECK", "ID:2011-0000086714"); doTest("T2", "[e49]BLS >BASIC LIFE SUPPORT CALL 1323 NEWPORT AVE Apt: REAR Bldg NORTHAMPTON TONY FERRERA Map: Grids:0,0 Cad: 2011-00000", "UNIT:e49", "CALL:BASIC LIFE SUPPORT", "ADDR:1323 NEWPORT AVE", "APT:REAR Bldg", "CITY:NORTHAMPTON", "NAME:TONY FERRERA", "ID:2011-00000"); doTest("T3", "[e49]MVAI >MVA WITH INJURIES 248 AT PENNSVILLE LIGHT LEHIGH TWP NATALIE BRODIANO Cad: 2011-0000086361", "UNIT:e49", "CALL:MVA WITH INJURIES", "ADDR:248 AT PENNSVILLE LIGHT", "CITY:LEHIGH TWP", "NAME:NATALIE BRODIANO", "ID:2011-0000086361"); doTest("T4", "[e49]ALS >ADVANCED LIFE SUPPORT CALL 612 E 10TH ST NORTHAMPTON ROBERTS PAMELA Map: Grids:0,0 Cad: 2011-0000086262", "UNIT:e49", "CALL:ADVANCED LIFE SUPPORT", "ADDR:612 E 10TH ST", "CITY:NORTHAMPTON", "NAME:ROBERTS PAMELA", "ID:2011-0000086262"); doTest("T5", "[e49]BLS >BASIC LIFE SUPPORT CALL 1001 WASHINGTON AVE Apt: 105 Bldg NORTHAMPTON MEGAN MOREY Map: Grids:0,0 Cad: 2011-000008", "UNIT:e49", "CALL:BASIC LIFE SUPPORT", "ADDR:1001 WASHINGTON AVE", "APT:105 Bldg", "CITY:NORTHAMPTON", "NAME:MEGAN MOREY", "ID:2011-000008"); doTest("T6", "[e49]ALS >ADVANCED LIFE SUPPORT CALL 5962 KEYSTONE DR EAST ALLEN CHRISTINA WIGMER Map: Grids:0,0 Cad: 2011-0000086103", "UNIT:e49", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5962 KEYSTONE DR", "CITY:EAST ALLEN", "NAME:CHRISTINA WIGMER", "ID:2011-0000086103"); doTest("T7", "[e49]BLS >BASIC LIFE SUPPORT CALL 1323 NEWPORT AVE NORTHAMPTON TONY CABRERA Map: Grids:0,0 Cad: 2011-0000086010", "UNIT:e49", "CALL:BASIC LIFE SUPPORT", "ADDR:1323 NEWPORT AVE", "CITY:NORTHAMPTON", "NAME:TONY CABRERA", "ID:2011-0000086010"); } @Test public void testParser2() { doTest("T1", "Subject:#6550\n[f14]MVAU >MVA WITH UNKNOW INJUIRIES WILLOW PARK RD BETHLEHEM TWP P1736 Map: Grids:0,0 Cad: 2011-0000131105", "UNIT:f14", "CALL:MVA WITH UNKNOW INJUIRIES", "ADDR:WILLOW PARK RD", "CITY:BETHLEHEM TWP", "NAME:P1736", "ID:2011-0000131105"); } public void testParsaer3() { doTest("T1", "*3750: *[email protected] / / [f25]ODOR >ODOR / OTHER THAN SMOKE ARNDT RD FORKS Map: Grids:0,0 Cad: 2011-0000171220 <20110000171220>", "UNIT:f25", "CALL:ODOR/OTHER THAN SMOKE", "ADDR:ARNDT RD", "NAME:FORKS", "ID:2011-0000171220 <20110000171220>"); } @Test public void testActive911() { doTest("T1", "[#8ICT Northampton County PA CAD] [e46]BLS >BASIC LIFE SUPPORT CALL 6303 HANOVERVILLE RD EAST ALLEN SARA HILBERT Map: Grids:0,0 Cad: 2012-0000098761\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397037&c=f5d0d for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:BASIC LIFE SUPPORT", "ADDR:6303 HANOVERVILLE RD", "CITY:EAST ALLEN", "NAME:SARA HILBERT", "ID:2012-0000098761"); doTest("T2", "[#8IJN Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 5516 LOIS LN EAST ALLEN HOSER, CHRISTINE Map: Grids:0,0 Cad: 2012-0000099349\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397283&c=8e4b8 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5516 LOIS LN", "CITY:EAST ALLEN", "NAME:HOSER, CHRISTINE", "ID:2012-0000099349"); doTest("T3", "[#8IKZ Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 251 S GREENBRIAR DR EAST ALLEN HORTON, ROBERT Map: Grids:0,0 Cad: 2012-0000099450\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397331&c=4e113 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:251 S GREENBRIAR DR", "CITY:EAST ALLEN", "NAME:HORTON, ROBERT", "ID:2012-0000099450"); doTest("T4", "[#8IMN Northampton County PA CAD] [e46]MVA >MVA NONE INJURY AIRPORT RD EAST ALLEN 4676 Map: Grids:0,0 Cad: 2012-0000099584\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397391&c=b9536 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", - "CALL:MVA NON INJURY", + "CALL:MVA NONE INJURY", "ADDR:AIRPORT RD", "CITY:EAST ALLEN", "NAME:4676", "ID:2012-0000099584"); doTest("T5", "[#8IXF Northampton County PA CAD] [e46]BLS >BASIC LIFE SUPPORT CALL 478 BLUE MOUNTAIN DR LEHIGH KARMONICK, TERRY Map: Grids:0,0 Cad: 2012-0000100411\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397779&c=77340 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:BASIC LIFE SUPPORT", "ADDR:478 BLUE MOUNTAIN DR", "NAME:LEHIGH KARMONICK, TERRY", "ID:2012-0000100411"); doTest("T6", "[#8J0R Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 5701 COLONY DR EAST ALLEN MARY JOE DEEGAN Map: Grids:0,0 Cad: 2012-0000100593\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397899&c=90443 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5701 COLONY DR", "CITY:EAST ALLEN", "NAME:MARY JOE DEEGAN", "ID:2012-0000100593"); doTest("T7", "[#8J2X Northampton County PA CAD] [e46]BLS >BASIC LIFE SUPPORT CALL 5745 COLONY DR EAST ALLEN WENGRYN HELEN Map: Grids:0,0 Cad: 2012-0000100697\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397977&c=2f09b for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:BASIC LIFE SUPPORT", "ADDR:5745 COLONY DR", "CITY:EAST ALLEN", "NAME:WENGRYN HELEN", "ID:2012-0000100697"); doTest("T8", "[#8J6H Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 5897 LEHIGH LN EAST ALLEN WALTON, CECELIA Map: Grids:0,0 Cad: 2012-0000100946\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=398105&c=61154 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5897 LEHIGH LN", "CITY:EAST ALLEN", "NAME:WALTON, CECELIA", "ID:2012-0000100946"); } public static void main(String[] args) { new PANorthamptonCountyParserTest().generateTests("T1", "UNIT CALL ADDR APT CITY NAME MAP ID"); } }
true
true
public void testActive911() { doTest("T1", "[#8ICT Northampton County PA CAD] [e46]BLS >BASIC LIFE SUPPORT CALL 6303 HANOVERVILLE RD EAST ALLEN SARA HILBERT Map: Grids:0,0 Cad: 2012-0000098761\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397037&c=f5d0d for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:BASIC LIFE SUPPORT", "ADDR:6303 HANOVERVILLE RD", "CITY:EAST ALLEN", "NAME:SARA HILBERT", "ID:2012-0000098761"); doTest("T2", "[#8IJN Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 5516 LOIS LN EAST ALLEN HOSER, CHRISTINE Map: Grids:0,0 Cad: 2012-0000099349\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397283&c=8e4b8 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5516 LOIS LN", "CITY:EAST ALLEN", "NAME:HOSER, CHRISTINE", "ID:2012-0000099349"); doTest("T3", "[#8IKZ Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 251 S GREENBRIAR DR EAST ALLEN HORTON, ROBERT Map: Grids:0,0 Cad: 2012-0000099450\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397331&c=4e113 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:251 S GREENBRIAR DR", "CITY:EAST ALLEN", "NAME:HORTON, ROBERT", "ID:2012-0000099450"); doTest("T4", "[#8IMN Northampton County PA CAD] [e46]MVA >MVA NONE INJURY AIRPORT RD EAST ALLEN 4676 Map: Grids:0,0 Cad: 2012-0000099584\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397391&c=b9536 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:MVA NON INJURY", "ADDR:AIRPORT RD", "CITY:EAST ALLEN", "NAME:4676", "ID:2012-0000099584"); doTest("T5", "[#8IXF Northampton County PA CAD] [e46]BLS >BASIC LIFE SUPPORT CALL 478 BLUE MOUNTAIN DR LEHIGH KARMONICK, TERRY Map: Grids:0,0 Cad: 2012-0000100411\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397779&c=77340 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:BASIC LIFE SUPPORT", "ADDR:478 BLUE MOUNTAIN DR", "NAME:LEHIGH KARMONICK, TERRY", "ID:2012-0000100411"); doTest("T6", "[#8J0R Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 5701 COLONY DR EAST ALLEN MARY JOE DEEGAN Map: Grids:0,0 Cad: 2012-0000100593\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397899&c=90443 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5701 COLONY DR", "CITY:EAST ALLEN", "NAME:MARY JOE DEEGAN", "ID:2012-0000100593"); doTest("T7", "[#8J2X Northampton County PA CAD] [e46]BLS >BASIC LIFE SUPPORT CALL 5745 COLONY DR EAST ALLEN WENGRYN HELEN Map: Grids:0,0 Cad: 2012-0000100697\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397977&c=2f09b for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:BASIC LIFE SUPPORT", "ADDR:5745 COLONY DR", "CITY:EAST ALLEN", "NAME:WENGRYN HELEN", "ID:2012-0000100697"); doTest("T8", "[#8J6H Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 5897 LEHIGH LN EAST ALLEN WALTON, CECELIA Map: Grids:0,0 Cad: 2012-0000100946\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=398105&c=61154 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5897 LEHIGH LN", "CITY:EAST ALLEN", "NAME:WALTON, CECELIA", "ID:2012-0000100946"); }
public void testActive911() { doTest("T1", "[#8ICT Northampton County PA CAD] [e46]BLS >BASIC LIFE SUPPORT CALL 6303 HANOVERVILLE RD EAST ALLEN SARA HILBERT Map: Grids:0,0 Cad: 2012-0000098761\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397037&c=f5d0d for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:BASIC LIFE SUPPORT", "ADDR:6303 HANOVERVILLE RD", "CITY:EAST ALLEN", "NAME:SARA HILBERT", "ID:2012-0000098761"); doTest("T2", "[#8IJN Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 5516 LOIS LN EAST ALLEN HOSER, CHRISTINE Map: Grids:0,0 Cad: 2012-0000099349\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397283&c=8e4b8 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5516 LOIS LN", "CITY:EAST ALLEN", "NAME:HOSER, CHRISTINE", "ID:2012-0000099349"); doTest("T3", "[#8IKZ Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 251 S GREENBRIAR DR EAST ALLEN HORTON, ROBERT Map: Grids:0,0 Cad: 2012-0000099450\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397331&c=4e113 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:251 S GREENBRIAR DR", "CITY:EAST ALLEN", "NAME:HORTON, ROBERT", "ID:2012-0000099450"); doTest("T4", "[#8IMN Northampton County PA CAD] [e46]MVA >MVA NONE INJURY AIRPORT RD EAST ALLEN 4676 Map: Grids:0,0 Cad: 2012-0000099584\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397391&c=b9536 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:MVA NONE INJURY", "ADDR:AIRPORT RD", "CITY:EAST ALLEN", "NAME:4676", "ID:2012-0000099584"); doTest("T5", "[#8IXF Northampton County PA CAD] [e46]BLS >BASIC LIFE SUPPORT CALL 478 BLUE MOUNTAIN DR LEHIGH KARMONICK, TERRY Map: Grids:0,0 Cad: 2012-0000100411\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397779&c=77340 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:BASIC LIFE SUPPORT", "ADDR:478 BLUE MOUNTAIN DR", "NAME:LEHIGH KARMONICK, TERRY", "ID:2012-0000100411"); doTest("T6", "[#8J0R Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 5701 COLONY DR EAST ALLEN MARY JOE DEEGAN Map: Grids:0,0 Cad: 2012-0000100593\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397899&c=90443 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5701 COLONY DR", "CITY:EAST ALLEN", "NAME:MARY JOE DEEGAN", "ID:2012-0000100593"); doTest("T7", "[#8J2X Northampton County PA CAD] [e46]BLS >BASIC LIFE SUPPORT CALL 5745 COLONY DR EAST ALLEN WENGRYN HELEN Map: Grids:0,0 Cad: 2012-0000100697\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=397977&c=2f09b for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:BASIC LIFE SUPPORT", "ADDR:5745 COLONY DR", "CITY:EAST ALLEN", "NAME:WENGRYN HELEN", "ID:2012-0000100697"); doTest("T8", "[#8J6H Northampton County PA CAD] [e46]ALS >ADVANCED LIFE SUPPORT CALL 5897 LEHIGH LN EAST ALLEN WALTON, CECELIA Map: Grids:0,0 Cad: 2012-0000100946\n" + "Sent by Northampton County Alert Network powered by Cooper Notification's Roam Secure Alert Network\n" + "Visit https://www.notifync.org/am.php?a=398105&c=61154 for the map of the area\n" + "--\n" + "You received this message because you registered on Northampton County Alert Network . To change your alerting preferences go to www.notifync.org/mygroups.php\n" + "Tell a friend/co-worker about Northampton County Alert Network! Forward this message to them and have them register for this free service at www.notifync.org \n", "UNIT:e46", "CALL:ADVANCED LIFE SUPPORT", "ADDR:5897 LEHIGH LN", "CITY:EAST ALLEN", "NAME:WALTON, CECELIA", "ID:2012-0000100946"); }
diff --git a/src/main/java/net/dockter/infoguide/gui/GUIGuide.java b/src/main/java/net/dockter/infoguide/gui/GUIGuide.java index 38dc3e8..f58dae4 100644 --- a/src/main/java/net/dockter/infoguide/gui/GUIGuide.java +++ b/src/main/java/net/dockter/infoguide/gui/GUIGuide.java @@ -1,334 +1,334 @@ /** * This file is part of InfoGuide. * * Copyright Dockter 2012 <mcsnetworks.com> InfoGuide is licensed under the GNU * General Public License. * * InfoGuide is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * As an exception, all classes which do not reference GPL licensed code are * hereby licensed under the GNU Lesser Public License, as described in GNU * General Public License. * * InfoGuide is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License, the GNU * Lesser Public License (for classes that fulfill the exception) and the GNU * General Public License along with this program. If not, see * <http://www.gnu.org/licenses/> for the GNU General Public License and the GNU * Lesser Public License. */ package net.dockter.infoguide.gui; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; import net.dockter.infoguide.Main; import net.dockter.infoguide.guide.Guide; import net.dockter.infoguide.guide.GuideManager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.getspout.spoutapi.gui.CheckBox; import org.getspout.spoutapi.gui.Color; import org.getspout.spoutapi.gui.ComboBox; import org.getspout.spoutapi.gui.GenericButton; import org.getspout.spoutapi.gui.GenericLabel; import org.getspout.spoutapi.gui.GenericPopup; import org.getspout.spoutapi.gui.GenericTextField; import org.getspout.spoutapi.gui.GenericTexture; import org.getspout.spoutapi.gui.RenderPriority; import org.getspout.spoutapi.gui.Screen; import org.getspout.spoutapi.gui.WidgetAnchor; import org.getspout.spoutapi.player.SpoutPlayer; public class GUIGuide extends GenericPopup { final GenericTextField guideField, guideInvisible; final GenericLabel guideName, guideDate, pagelabel; final public static HashMap<Player, Guide> map = new HashMap<Player, Guide>(); public int pageno = 1; final GenericButton close, newb, saveb, deleteb, pd, pu; final ComboBox box; final CheckBox checkBox; private final SpoutPlayer player; public final Logger log = Logger.getLogger("Minecraft"); public GUIGuide(SpoutPlayer player) { super(); this.player = player; GenericLabel label = new GenericLabel(); label.setText(Main.getInstance().getConfig().getString("PromptTitle")); label.setAnchor(WidgetAnchor.CENTER_CENTER); label.shiftXPos(-35).shiftYPos(-122); label.setPriority(RenderPriority.Highest); label.setWidth(-1).setHeight(-1); guideName = new GenericLabel("TheGuideNameHere"); guideName.setWidth(-1).setHeight(-1); guideName.setAnchor(WidgetAnchor.CENTER_CENTER); guideName.shiftXPos(-200).shiftYPos(-105); guideInvisible = new GenericTextField(); guideInvisible.setWidth(150).setHeight(18); guideInvisible.setAnchor(WidgetAnchor.CENTER_CENTER); guideInvisible.shiftXPos(-200).shiftYPos(-110); guideInvisible.setMaximumCharacters(30); guideInvisible.setMaximumLines(1); guideInvisible.setVisible(false); guideDate = new GenericLabel("Updated: " + new SimpleDateFormat("HH:mm dd-MM").format(Calendar.getInstance().getTime())); guideDate.setWidth(-1).setHeight(-1); guideDate.setAnchor(WidgetAnchor.CENTER_CENTER); guideDate.shiftXPos(-200).shiftYPos(90); box = new MyCombo(this); - box.setText("Guides"); + box.setText("Guides - Click Here"); box.setAnchor(WidgetAnchor.CENTER_CENTER); box.setWidth(GenericLabel.getStringWidth("12345678901234567890123459")); box.setHeight(18); box.shiftXPos(25).shiftYPos(-110); box.setAuto(true); box.setPriority(RenderPriority.Low); refreshItems(); GenericTexture border = new GenericTexture("http://www.almuramc.com/images/sguide.png"); border.setAnchor(WidgetAnchor.CENTER_CENTER); border.setPriority(RenderPriority.High); border.setWidth(626).setHeight(240); border.shiftXPos(-220).shiftYPos(-128); guideField = new GenericTextField(); guideField.setText("first guide goes here"); // The default text guideField.setAnchor(WidgetAnchor.CENTER_CENTER); guideField.setBorderColor(new Color(1.0F, 1.0F, 1.0F, 1.0F)); // White border guideField.setMaximumCharacters(1000); guideField.setMaximumLines(13); guideField.setHeight(160).setWidth(377); guideField.shiftXPos(-195).shiftYPos(-83); guideField.setMargin(0); close = new CloseButton(this); close.setAuto(true); close.setAnchor(WidgetAnchor.CENTER_CENTER); close.setHeight(18).setWidth(40); close.shiftXPos(142).shiftYPos(87); pu = new PageUpButton(this); pu.setAuto(true).setText("<<<"); pu.setAnchor(WidgetAnchor.CENTER_CENTER); pu.setHeight(18).setWidth(40); pu.shiftXPos(17).shiftYPos(87); pagelabel = new GenericLabel(); pagelabel.setText(Integer.toString(pageno)); pagelabel.setAnchor(WidgetAnchor.CENTER_CENTER); pagelabel.shiftXPos(66).shiftYPos(92); pagelabel.setPriority(RenderPriority.Normal); pagelabel.setWidth(5).setHeight(18); pd = new PageDownButton(this); pd.setAuto(true).setText(">>>"); pd.setAnchor(WidgetAnchor.CENTER_CENTER); pd.setHeight(18).setWidth(40); pd.shiftXPos(82).shiftYPos(87); checkBox = new BypassCheckBox(player, this); checkBox.setText("Bypass"); checkBox.setAnchor(WidgetAnchor.CENTER_CENTER); checkBox.setHeight(20).setWidth(19); checkBox.shiftXPos(-52).shiftYPos(87); checkBox.setAuto(true); this.setTransparent(true); attachWidgets(Main.getInstance(), border, label); this.setTransparent(true); attachWidget(Main.getInstance(), label); attachWidget(Main.getInstance(), border); attachWidget(Main.getInstance(), guideField); attachWidget(Main.getInstance(), close); attachWidget(Main.getInstance(), pu); attachWidget(Main.getInstance(), pagelabel); attachWidget(Main.getInstance(), pd); attachWidget(Main.getInstance(), guideName); attachWidget(Main.getInstance(), guideInvisible); attachWidget(Main.getInstance(), guideDate); attachWidget(Main.getInstance(), box); if (Main.getInstance().canBypass(player.getName()) || player.hasPermission("infoguide.bypass") || player.hasPermission("infoguide.admin")) { attachWidget(Main.getInstance(), checkBox); } if (player.hasPermission("infoguide.edit") || player.hasPermission("infoguide.admin")) { saveb = new SaveButton(this); saveb.setAnchor(WidgetAnchor.CENTER_CENTER); saveb.setAuto(true).setHeight(18).setWidth(40).shiftXPos(-145).shiftYPos(87); attachWidget(Main.getInstance(), saveb); } else { saveb = null; } if (player.hasPermission("infoguide.create") || player.hasPermission("infoguide.edit") || player.hasPermission("infoguide.admin")) { guideDate.setVisible(false); newb = new NewButton(this); newb.setAuto(true); newb.setAnchor(WidgetAnchor.CENTER_CENTER); newb.setAuto(true).setHeight(18).setWidth(40).shiftXPos(-190).shiftYPos(87); attachWidget(Main.getInstance(), newb); } else { newb = null; guideDate.setVisible(true); } if (player.hasPermission("infoguide.delete") || player.hasPermission("infoguide.admin")) { deleteb = new DeleteButton(this); deleteb.setAnchor(WidgetAnchor.CENTER_CENTER); deleteb.setAuto(true).setHeight(18).setWidth(40).shiftXPos(-100).shiftYPos(87); attachWidget(Main.getInstance(), deleteb); } else { deleteb = null; } if (player.hasPermission("infoguide.moderatorguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("ModeratorGuide"))); return; } else if (player.hasPermission("infoguide.supermemberguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("SuperMemberGuide"))); return; } else if (player.hasPermission("infoguide.memberguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("MemberGuide"))); return; } else if (player.hasPermission("infoguide.guestguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("GuestGuide"))); return; } else { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("DefaultGuide"))); } } private Guide guide; public void setGuide(Guide guide) { if (guide == null) { return; } this.guide = guide; guideDate.setText("Updated: " + guide.getDate()); guideName.setText(guide.getName()).setWidth(-1); map.put(player, guide); pageno = 1; pagelabel.setText(Integer.toString(pageno)); guideField.setText(guide.getPage(1)); if (pageno == guide.getPages() && player.hasPermission("infoguide.edit")) { pd.setText("+"); pd.setDirty(true); } } public void pageUp() { pageno = pageno - 1; if (pageno == 0) { pageno = 1; } Guide gguide = map.get(player); if (pageno == gguide.getPages() - 1) { pd.setText(">>>"); pd.setDirty(true); } guideField.setText(gguide.getPage(pageno)); pagelabel.setText(Integer.toString(pageno)); } public void pageDown() { pageno++; Guide gguide = map.get(player); if (pageno == gguide.getPages() + 1) { if (player.hasPermission("infoguide.edit") || player.hasPermission("infoguide.admin")) { gguide.addPage(); pd.setText(">>>"); } pd.setDirty(true); pageno--; } if (pageno == gguide.getPages() && (player.hasPermission("infoguide.edit") || player.hasPermission("infoguide.admin"))) { pd.setText("+"); pd.setDirty(true); } guideField.setText(gguide.getPage(pageno)); pagelabel.setText(Integer.toString(pageno)); } public void onNewClick() { setGuide(new Guide("", "", new ArrayList<String>())); guideName.setVisible(false); guideInvisible.setVisible(true); } void onSaveClick(String playerName) { Guide gguide = map.get(player); gguide.setPage(pageno, guideField.getText()); gguide.setDate(new SimpleDateFormat("HH:mm dd-MM").format(Calendar.getInstance().getTime())); if (guideInvisible.isVisible()) { gguide.setName(guideInvisible.getText()); guideName.setText(guideInvisible.getText()).setWidth(-1); guideInvisible.setVisible(false); guideName.setVisible(true); GuideManager.addGuide(gguide); } Bukkit.broadcastMessage(ChatColor.GOLD + "~Dockter" + ChatColor.YELLOW + " updated the guide " + ChatColor.GOLD + guide.getName() + ChatColor.YELLOW + " on page "+pageno+"!"); gguide.save(); refreshItems(); guide.prepareForLoad(); map.put(player, guide); pagelabel.setText(Integer.toString(pageno)); guideField.setText(guide.getPage(pageno)); } void onDeleteClick() { if (box.getItems().size() == 1) { return; } GuideManager.removeLoadedGuide(guideName.getText()); refreshItems(); setGuide(GuideManager.getLoadedGuides().get(box.getItems().get(0))); } void onCloseClick() { Screen screen = ((SpoutPlayer) player).getMainScreen(); screen.removeWidget(this); //player.getMainScreen().closePopup(); player.closeActiveWindow(); } void onSelect(int i, String text) { setGuide(GuideManager.getLoadedGuides().get(text)); } private void refreshItems() { List<String> items = new ArrayList<String>(); for (String gguide : GuideManager.getLoadedGuides().keySet()) { if (player.hasPermission("infoguide.view." + gguide) || player.hasPermission("infoguide.view")) { items.add(gguide); } } Collections.sort(items, String.CASE_INSENSITIVE_ORDER); box.setItems(items); box.setDirty(true); } }
true
true
public GUIGuide(SpoutPlayer player) { super(); this.player = player; GenericLabel label = new GenericLabel(); label.setText(Main.getInstance().getConfig().getString("PromptTitle")); label.setAnchor(WidgetAnchor.CENTER_CENTER); label.shiftXPos(-35).shiftYPos(-122); label.setPriority(RenderPriority.Highest); label.setWidth(-1).setHeight(-1); guideName = new GenericLabel("TheGuideNameHere"); guideName.setWidth(-1).setHeight(-1); guideName.setAnchor(WidgetAnchor.CENTER_CENTER); guideName.shiftXPos(-200).shiftYPos(-105); guideInvisible = new GenericTextField(); guideInvisible.setWidth(150).setHeight(18); guideInvisible.setAnchor(WidgetAnchor.CENTER_CENTER); guideInvisible.shiftXPos(-200).shiftYPos(-110); guideInvisible.setMaximumCharacters(30); guideInvisible.setMaximumLines(1); guideInvisible.setVisible(false); guideDate = new GenericLabel("Updated: " + new SimpleDateFormat("HH:mm dd-MM").format(Calendar.getInstance().getTime())); guideDate.setWidth(-1).setHeight(-1); guideDate.setAnchor(WidgetAnchor.CENTER_CENTER); guideDate.shiftXPos(-200).shiftYPos(90); box = new MyCombo(this); box.setText("Guides"); box.setAnchor(WidgetAnchor.CENTER_CENTER); box.setWidth(GenericLabel.getStringWidth("12345678901234567890123459")); box.setHeight(18); box.shiftXPos(25).shiftYPos(-110); box.setAuto(true); box.setPriority(RenderPriority.Low); refreshItems(); GenericTexture border = new GenericTexture("http://www.almuramc.com/images/sguide.png"); border.setAnchor(WidgetAnchor.CENTER_CENTER); border.setPriority(RenderPriority.High); border.setWidth(626).setHeight(240); border.shiftXPos(-220).shiftYPos(-128); guideField = new GenericTextField(); guideField.setText("first guide goes here"); // The default text guideField.setAnchor(WidgetAnchor.CENTER_CENTER); guideField.setBorderColor(new Color(1.0F, 1.0F, 1.0F, 1.0F)); // White border guideField.setMaximumCharacters(1000); guideField.setMaximumLines(13); guideField.setHeight(160).setWidth(377); guideField.shiftXPos(-195).shiftYPos(-83); guideField.setMargin(0); close = new CloseButton(this); close.setAuto(true); close.setAnchor(WidgetAnchor.CENTER_CENTER); close.setHeight(18).setWidth(40); close.shiftXPos(142).shiftYPos(87); pu = new PageUpButton(this); pu.setAuto(true).setText("<<<"); pu.setAnchor(WidgetAnchor.CENTER_CENTER); pu.setHeight(18).setWidth(40); pu.shiftXPos(17).shiftYPos(87); pagelabel = new GenericLabel(); pagelabel.setText(Integer.toString(pageno)); pagelabel.setAnchor(WidgetAnchor.CENTER_CENTER); pagelabel.shiftXPos(66).shiftYPos(92); pagelabel.setPriority(RenderPriority.Normal); pagelabel.setWidth(5).setHeight(18); pd = new PageDownButton(this); pd.setAuto(true).setText(">>>"); pd.setAnchor(WidgetAnchor.CENTER_CENTER); pd.setHeight(18).setWidth(40); pd.shiftXPos(82).shiftYPos(87); checkBox = new BypassCheckBox(player, this); checkBox.setText("Bypass"); checkBox.setAnchor(WidgetAnchor.CENTER_CENTER); checkBox.setHeight(20).setWidth(19); checkBox.shiftXPos(-52).shiftYPos(87); checkBox.setAuto(true); this.setTransparent(true); attachWidgets(Main.getInstance(), border, label); this.setTransparent(true); attachWidget(Main.getInstance(), label); attachWidget(Main.getInstance(), border); attachWidget(Main.getInstance(), guideField); attachWidget(Main.getInstance(), close); attachWidget(Main.getInstance(), pu); attachWidget(Main.getInstance(), pagelabel); attachWidget(Main.getInstance(), pd); attachWidget(Main.getInstance(), guideName); attachWidget(Main.getInstance(), guideInvisible); attachWidget(Main.getInstance(), guideDate); attachWidget(Main.getInstance(), box); if (Main.getInstance().canBypass(player.getName()) || player.hasPermission("infoguide.bypass") || player.hasPermission("infoguide.admin")) { attachWidget(Main.getInstance(), checkBox); } if (player.hasPermission("infoguide.edit") || player.hasPermission("infoguide.admin")) { saveb = new SaveButton(this); saveb.setAnchor(WidgetAnchor.CENTER_CENTER); saveb.setAuto(true).setHeight(18).setWidth(40).shiftXPos(-145).shiftYPos(87); attachWidget(Main.getInstance(), saveb); } else { saveb = null; } if (player.hasPermission("infoguide.create") || player.hasPermission("infoguide.edit") || player.hasPermission("infoguide.admin")) { guideDate.setVisible(false); newb = new NewButton(this); newb.setAuto(true); newb.setAnchor(WidgetAnchor.CENTER_CENTER); newb.setAuto(true).setHeight(18).setWidth(40).shiftXPos(-190).shiftYPos(87); attachWidget(Main.getInstance(), newb); } else { newb = null; guideDate.setVisible(true); } if (player.hasPermission("infoguide.delete") || player.hasPermission("infoguide.admin")) { deleteb = new DeleteButton(this); deleteb.setAnchor(WidgetAnchor.CENTER_CENTER); deleteb.setAuto(true).setHeight(18).setWidth(40).shiftXPos(-100).shiftYPos(87); attachWidget(Main.getInstance(), deleteb); } else { deleteb = null; } if (player.hasPermission("infoguide.moderatorguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("ModeratorGuide"))); return; } else if (player.hasPermission("infoguide.supermemberguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("SuperMemberGuide"))); return; } else if (player.hasPermission("infoguide.memberguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("MemberGuide"))); return; } else if (player.hasPermission("infoguide.guestguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("GuestGuide"))); return; } else { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("DefaultGuide"))); } }
public GUIGuide(SpoutPlayer player) { super(); this.player = player; GenericLabel label = new GenericLabel(); label.setText(Main.getInstance().getConfig().getString("PromptTitle")); label.setAnchor(WidgetAnchor.CENTER_CENTER); label.shiftXPos(-35).shiftYPos(-122); label.setPriority(RenderPriority.Highest); label.setWidth(-1).setHeight(-1); guideName = new GenericLabel("TheGuideNameHere"); guideName.setWidth(-1).setHeight(-1); guideName.setAnchor(WidgetAnchor.CENTER_CENTER); guideName.shiftXPos(-200).shiftYPos(-105); guideInvisible = new GenericTextField(); guideInvisible.setWidth(150).setHeight(18); guideInvisible.setAnchor(WidgetAnchor.CENTER_CENTER); guideInvisible.shiftXPos(-200).shiftYPos(-110); guideInvisible.setMaximumCharacters(30); guideInvisible.setMaximumLines(1); guideInvisible.setVisible(false); guideDate = new GenericLabel("Updated: " + new SimpleDateFormat("HH:mm dd-MM").format(Calendar.getInstance().getTime())); guideDate.setWidth(-1).setHeight(-1); guideDate.setAnchor(WidgetAnchor.CENTER_CENTER); guideDate.shiftXPos(-200).shiftYPos(90); box = new MyCombo(this); box.setText("Guides - Click Here"); box.setAnchor(WidgetAnchor.CENTER_CENTER); box.setWidth(GenericLabel.getStringWidth("12345678901234567890123459")); box.setHeight(18); box.shiftXPos(25).shiftYPos(-110); box.setAuto(true); box.setPriority(RenderPriority.Low); refreshItems(); GenericTexture border = new GenericTexture("http://www.almuramc.com/images/sguide.png"); border.setAnchor(WidgetAnchor.CENTER_CENTER); border.setPriority(RenderPriority.High); border.setWidth(626).setHeight(240); border.shiftXPos(-220).shiftYPos(-128); guideField = new GenericTextField(); guideField.setText("first guide goes here"); // The default text guideField.setAnchor(WidgetAnchor.CENTER_CENTER); guideField.setBorderColor(new Color(1.0F, 1.0F, 1.0F, 1.0F)); // White border guideField.setMaximumCharacters(1000); guideField.setMaximumLines(13); guideField.setHeight(160).setWidth(377); guideField.shiftXPos(-195).shiftYPos(-83); guideField.setMargin(0); close = new CloseButton(this); close.setAuto(true); close.setAnchor(WidgetAnchor.CENTER_CENTER); close.setHeight(18).setWidth(40); close.shiftXPos(142).shiftYPos(87); pu = new PageUpButton(this); pu.setAuto(true).setText("<<<"); pu.setAnchor(WidgetAnchor.CENTER_CENTER); pu.setHeight(18).setWidth(40); pu.shiftXPos(17).shiftYPos(87); pagelabel = new GenericLabel(); pagelabel.setText(Integer.toString(pageno)); pagelabel.setAnchor(WidgetAnchor.CENTER_CENTER); pagelabel.shiftXPos(66).shiftYPos(92); pagelabel.setPriority(RenderPriority.Normal); pagelabel.setWidth(5).setHeight(18); pd = new PageDownButton(this); pd.setAuto(true).setText(">>>"); pd.setAnchor(WidgetAnchor.CENTER_CENTER); pd.setHeight(18).setWidth(40); pd.shiftXPos(82).shiftYPos(87); checkBox = new BypassCheckBox(player, this); checkBox.setText("Bypass"); checkBox.setAnchor(WidgetAnchor.CENTER_CENTER); checkBox.setHeight(20).setWidth(19); checkBox.shiftXPos(-52).shiftYPos(87); checkBox.setAuto(true); this.setTransparent(true); attachWidgets(Main.getInstance(), border, label); this.setTransparent(true); attachWidget(Main.getInstance(), label); attachWidget(Main.getInstance(), border); attachWidget(Main.getInstance(), guideField); attachWidget(Main.getInstance(), close); attachWidget(Main.getInstance(), pu); attachWidget(Main.getInstance(), pagelabel); attachWidget(Main.getInstance(), pd); attachWidget(Main.getInstance(), guideName); attachWidget(Main.getInstance(), guideInvisible); attachWidget(Main.getInstance(), guideDate); attachWidget(Main.getInstance(), box); if (Main.getInstance().canBypass(player.getName()) || player.hasPermission("infoguide.bypass") || player.hasPermission("infoguide.admin")) { attachWidget(Main.getInstance(), checkBox); } if (player.hasPermission("infoguide.edit") || player.hasPermission("infoguide.admin")) { saveb = new SaveButton(this); saveb.setAnchor(WidgetAnchor.CENTER_CENTER); saveb.setAuto(true).setHeight(18).setWidth(40).shiftXPos(-145).shiftYPos(87); attachWidget(Main.getInstance(), saveb); } else { saveb = null; } if (player.hasPermission("infoguide.create") || player.hasPermission("infoguide.edit") || player.hasPermission("infoguide.admin")) { guideDate.setVisible(false); newb = new NewButton(this); newb.setAuto(true); newb.setAnchor(WidgetAnchor.CENTER_CENTER); newb.setAuto(true).setHeight(18).setWidth(40).shiftXPos(-190).shiftYPos(87); attachWidget(Main.getInstance(), newb); } else { newb = null; guideDate.setVisible(true); } if (player.hasPermission("infoguide.delete") || player.hasPermission("infoguide.admin")) { deleteb = new DeleteButton(this); deleteb.setAnchor(WidgetAnchor.CENTER_CENTER); deleteb.setAuto(true).setHeight(18).setWidth(40).shiftXPos(-100).shiftYPos(87); attachWidget(Main.getInstance(), deleteb); } else { deleteb = null; } if (player.hasPermission("infoguide.moderatorguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("ModeratorGuide"))); return; } else if (player.hasPermission("infoguide.supermemberguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("SuperMemberGuide"))); return; } else if (player.hasPermission("infoguide.memberguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("MemberGuide"))); return; } else if (player.hasPermission("infoguide.guestguide")) { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("GuestGuide"))); return; } else { setGuide(GuideManager.getLoadedGuides().get(Main.getInstance().getConfig().getString("DefaultGuide"))); } }
diff --git a/plugins/com.aptana.editor.erb/src/com/aptana/editor/erb/html/outline/RHTMLOutlineLabelProvider.java b/plugins/com.aptana.editor.erb/src/com/aptana/editor/erb/html/outline/RHTMLOutlineLabelProvider.java index 47bec58..73b0d48 100644 --- a/plugins/com.aptana.editor.erb/src/com/aptana/editor/erb/html/outline/RHTMLOutlineLabelProvider.java +++ b/plugins/com.aptana.editor.erb/src/com/aptana/editor/erb/html/outline/RHTMLOutlineLabelProvider.java @@ -1,97 +1,98 @@ /** * Aptana Studio * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions). * Please see the license.html included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package com.aptana.editor.erb.html.outline; import java.util.StringTokenizer; import org.eclipse.jface.text.IDocument; import org.eclipse.swt.graphics.Image; import com.aptana.core.util.StringUtil; import com.aptana.editor.common.outline.CommonOutlineItem; import com.aptana.editor.erb.ERBEditorPlugin; import com.aptana.editor.erb.html.parsing.ERBScript; import com.aptana.editor.html.outline.HTMLOutlineLabelProvider; import com.aptana.editor.ruby.outline.RubyOutlineLabelProvider; import com.aptana.parsing.ast.IParseNode; import com.aptana.ruby.core.IRubyConstants; import com.aptana.ruby.core.IRubyScript; public class RHTMLOutlineLabelProvider extends HTMLOutlineLabelProvider { private static final Image ERB_ICON = ERBEditorPlugin.getImage("icons/embedded_code_fragment.png"); //$NON-NLS-1$ private static final int TRIM_TO_LENGTH = 20; private IDocument fDocument; public RHTMLOutlineLabelProvider(IDocument document) { fDocument = document; addSubLanguage(IRubyConstants.CONTENT_TYPE_RUBY, new RubyOutlineLabelProvider()); } @Override public Image getImage(Object element) { if (element instanceof CommonOutlineItem) { IParseNode node = ((CommonOutlineItem) element).getReferenceNode(); if (node instanceof ERBScript) { return ERB_ICON; } } return super.getImage(element); } @Override public String getText(Object element) { if (element instanceof CommonOutlineItem) { IParseNode node = ((CommonOutlineItem) element).getReferenceNode(); if (node instanceof ERBScript) { return getDisplayText((ERBScript) node); } } return super.getText(element); } private String getDisplayText(ERBScript script) { StringBuilder text = new StringBuilder(); text.append(script.getStartTag()); String source = fDocument.get(); // locates the ruby source IRubyScript ruby = script.getScript(); - source = source.substring(ruby.getStartingOffset(), Math.min(ruby.getEndingOffset() + 1, source.length())); + source = source.substring(Math.max(ruby.getStartingOffset(), 0), + Math.min(ruby.getEndingOffset() + 1, source.length())); // gets the first line of the ruby source StringTokenizer st = new StringTokenizer(source, "\n\r\f"); //$NON-NLS-1$ // $codepro.audit.disable platformSpecificLineSeparator if (st.hasMoreTokens()) { source = st.nextToken(); } else { source = StringUtil.EMPTY; } if (source.length() <= TRIM_TO_LENGTH) { text.append(source); } else { text.append(source.substring(0, TRIM_TO_LENGTH - 1)).append("... "); //$NON-NLS-1$ } text.append(script.getEndTag()); return text.toString(); } }
true
true
private String getDisplayText(ERBScript script) { StringBuilder text = new StringBuilder(); text.append(script.getStartTag()); String source = fDocument.get(); // locates the ruby source IRubyScript ruby = script.getScript(); source = source.substring(ruby.getStartingOffset(), Math.min(ruby.getEndingOffset() + 1, source.length())); // gets the first line of the ruby source StringTokenizer st = new StringTokenizer(source, "\n\r\f"); //$NON-NLS-1$ // $codepro.audit.disable platformSpecificLineSeparator if (st.hasMoreTokens()) { source = st.nextToken(); } else { source = StringUtil.EMPTY; } if (source.length() <= TRIM_TO_LENGTH) { text.append(source); } else { text.append(source.substring(0, TRIM_TO_LENGTH - 1)).append("... "); //$NON-NLS-1$ } text.append(script.getEndTag()); return text.toString(); }
private String getDisplayText(ERBScript script) { StringBuilder text = new StringBuilder(); text.append(script.getStartTag()); String source = fDocument.get(); // locates the ruby source IRubyScript ruby = script.getScript(); source = source.substring(Math.max(ruby.getStartingOffset(), 0), Math.min(ruby.getEndingOffset() + 1, source.length())); // gets the first line of the ruby source StringTokenizer st = new StringTokenizer(source, "\n\r\f"); //$NON-NLS-1$ // $codepro.audit.disable platformSpecificLineSeparator if (st.hasMoreTokens()) { source = st.nextToken(); } else { source = StringUtil.EMPTY; } if (source.length() <= TRIM_TO_LENGTH) { text.append(source); } else { text.append(source.substring(0, TRIM_TO_LENGTH - 1)).append("... "); //$NON-NLS-1$ } text.append(script.getEndTag()); return text.toString(); }
diff --git a/nuxeo-core-event/src/main/java/org/nuxeo/ecm/core/event/impl/ReconnectedEventBundleImpl.java b/nuxeo-core-event/src/main/java/org/nuxeo/ecm/core/event/impl/ReconnectedEventBundleImpl.java index a6905b99d..dcd0c22eb 100644 --- a/nuxeo-core-event/src/main/java/org/nuxeo/ecm/core/event/impl/ReconnectedEventBundleImpl.java +++ b/nuxeo-core-event/src/main/java/org/nuxeo/ecm/core/event/impl/ReconnectedEventBundleImpl.java @@ -1,232 +1,232 @@ /* * (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Nuxeo - initial API and implementation * * $Id$ */ package org.nuxeo.ecm.core.event.impl; import java.io.Serializable; import java.rmi.dgc.VMID; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreInstance; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.core.api.repository.Repository; import org.nuxeo.ecm.core.api.repository.RepositoryManager; import org.nuxeo.ecm.core.event.Event; import org.nuxeo.ecm.core.event.EventBundle; import org.nuxeo.ecm.core.event.EventContext; import org.nuxeo.ecm.core.event.ReconnectedEventBundle; import org.nuxeo.runtime.api.Framework; /** * Default implementation for an {@link EventBundle} that need to be reconnected * to a usable Session * * @author tiry */ public class ReconnectedEventBundleImpl implements ReconnectedEventBundle { private static final long serialVersionUID = 1L; protected EventBundle sourceEventBundle; protected List<Event> reconnectedEvents; protected LoginContext loginCtx; protected CoreSession reconnectedCoreSession; private static final Log log = LogFactory.getLog(ReconnectedEventBundleImpl.class); public ReconnectedEventBundleImpl() { } public ReconnectedEventBundleImpl(EventBundle sourceEventBundle) { this.sourceEventBundle = sourceEventBundle; } protected CoreSession getReconnectedCoreSession(String repoName) { if (reconnectedCoreSession == null) { try { loginCtx = Framework.login(); } catch (LoginException e) { log.error("Can not connect", e); return null; } try { RepositoryManager mgr = Framework .getService(RepositoryManager.class); Repository repo; if (repoName != null) { repo = mgr.getRepository(repoName); } else { repo = mgr.getDefaultRepository(); repoName = repo.getName(); } reconnectedCoreSession = repo.open(); } catch (Exception e) { log.error("Error while openning core session on repo " + repoName, e); return null; } } else { // Sanity Check if (!reconnectedCoreSession.getRepositoryName().equals(repoName)) { if (repoName != null) { throw new IllegalStateException( "Can no reconnected a Bundle tied to several Core instances !"); } } } return reconnectedCoreSession; } protected List<Event> getReconnectedEvents() { if (reconnectedEvents == null) { reconnectedEvents = new ArrayList<Event>(); for (Event event : sourceEventBundle) { EventContext ctx = event.getContext(); CoreSession session = ctx.getRepositoryName() == null ? null : getReconnectedCoreSession(ctx.getRepositoryName()); List<Object> newArgs = new ArrayList<Object>(); for (Object arg : ctx.getArguments()) { Object newArg = arg; if (arg instanceof DocumentModel && session != null) { DocumentModel oldDoc = (DocumentModel) arg; DocumentRef ref = oldDoc.getRef(); if (ref != null) { try { if (session.exists(oldDoc.getRef())) { newArg = session.getDocument(oldDoc.getRef()); } else { // probably deleted doc - newArg = oldDoc; + newArg = null; } } catch (ClientException e) { log.error("Can not refetch Doc with ref " + ref.toString(), e); } } } // XXX treat here other cases !!!! newArgs.add(newArg); } EventContext newCtx = null; if (ctx instanceof DocumentEventContext) { newCtx = new DocumentEventContext(session, ctx .getPrincipal(), (DocumentModel) newArgs.get(0), (DocumentRef) newArgs.get(1)); } else { newCtx = new EventContextImpl(session, ctx.getPrincipal()); ((EventContextImpl) newCtx).setArgs(newArgs.toArray()); } Map<String, Serializable> newProps = new HashMap<String, Serializable>(); for (Entry<String, Serializable> prop : ctx.getProperties() .entrySet()) { Serializable propValue = prop.getValue(); if (propValue instanceof DocumentModel && session != null) { DocumentModel oldDoc = (DocumentModel) propValue; try { propValue = session.getDocument(oldDoc.getRef()); } catch (ClientException e) { log.error("Can not refetch Doc with ref " + oldDoc.getRef().toString(), e); } } // XXX treat here other cases !!!! newProps.put(prop.getKey(), propValue); } newCtx.setProperties(newProps); Event newEvt = new EventImpl(event.getName(), newCtx, event .getFlags(), event.getTime()); reconnectedEvents.add(newEvt); } } return reconnectedEvents; } public String getName() { return sourceEventBundle.getName(); } public VMID getSourceVMID() { return sourceEventBundle.getSourceVMID(); } public boolean hasRemoteSource() { return sourceEventBundle.hasRemoteSource(); } public boolean isEmpty() { return sourceEventBundle.isEmpty(); } public Event peek() { return getReconnectedEvents().get(0); } public void push(Event event) { throw new UnsupportedOperationException(); } public int size() { return sourceEventBundle.size(); } public Iterator<Event> iterator() { return getReconnectedEvents().iterator(); } public void disconnect() { if (reconnectedCoreSession != null) { CoreInstance.getInstance().close(reconnectedCoreSession); } if (loginCtx != null) { try { loginCtx.logout(); } catch (LoginException e) { log.error("Error while logging out", e); } } } public boolean comesFromJMS() { return false; } public boolean containsEventName(String eventName) { return sourceEventBundle.containsEventName(eventName); } }
true
true
protected List<Event> getReconnectedEvents() { if (reconnectedEvents == null) { reconnectedEvents = new ArrayList<Event>(); for (Event event : sourceEventBundle) { EventContext ctx = event.getContext(); CoreSession session = ctx.getRepositoryName() == null ? null : getReconnectedCoreSession(ctx.getRepositoryName()); List<Object> newArgs = new ArrayList<Object>(); for (Object arg : ctx.getArguments()) { Object newArg = arg; if (arg instanceof DocumentModel && session != null) { DocumentModel oldDoc = (DocumentModel) arg; DocumentRef ref = oldDoc.getRef(); if (ref != null) { try { if (session.exists(oldDoc.getRef())) { newArg = session.getDocument(oldDoc.getRef()); } else { // probably deleted doc newArg = oldDoc; } } catch (ClientException e) { log.error("Can not refetch Doc with ref " + ref.toString(), e); } } } // XXX treat here other cases !!!! newArgs.add(newArg); } EventContext newCtx = null; if (ctx instanceof DocumentEventContext) { newCtx = new DocumentEventContext(session, ctx .getPrincipal(), (DocumentModel) newArgs.get(0), (DocumentRef) newArgs.get(1)); } else { newCtx = new EventContextImpl(session, ctx.getPrincipal()); ((EventContextImpl) newCtx).setArgs(newArgs.toArray()); } Map<String, Serializable> newProps = new HashMap<String, Serializable>(); for (Entry<String, Serializable> prop : ctx.getProperties() .entrySet()) { Serializable propValue = prop.getValue(); if (propValue instanceof DocumentModel && session != null) { DocumentModel oldDoc = (DocumentModel) propValue; try { propValue = session.getDocument(oldDoc.getRef()); } catch (ClientException e) { log.error("Can not refetch Doc with ref " + oldDoc.getRef().toString(), e); } } // XXX treat here other cases !!!! newProps.put(prop.getKey(), propValue); } newCtx.setProperties(newProps); Event newEvt = new EventImpl(event.getName(), newCtx, event .getFlags(), event.getTime()); reconnectedEvents.add(newEvt); } } return reconnectedEvents; }
protected List<Event> getReconnectedEvents() { if (reconnectedEvents == null) { reconnectedEvents = new ArrayList<Event>(); for (Event event : sourceEventBundle) { EventContext ctx = event.getContext(); CoreSession session = ctx.getRepositoryName() == null ? null : getReconnectedCoreSession(ctx.getRepositoryName()); List<Object> newArgs = new ArrayList<Object>(); for (Object arg : ctx.getArguments()) { Object newArg = arg; if (arg instanceof DocumentModel && session != null) { DocumentModel oldDoc = (DocumentModel) arg; DocumentRef ref = oldDoc.getRef(); if (ref != null) { try { if (session.exists(oldDoc.getRef())) { newArg = session.getDocument(oldDoc.getRef()); } else { // probably deleted doc newArg = null; } } catch (ClientException e) { log.error("Can not refetch Doc with ref " + ref.toString(), e); } } } // XXX treat here other cases !!!! newArgs.add(newArg); } EventContext newCtx = null; if (ctx instanceof DocumentEventContext) { newCtx = new DocumentEventContext(session, ctx .getPrincipal(), (DocumentModel) newArgs.get(0), (DocumentRef) newArgs.get(1)); } else { newCtx = new EventContextImpl(session, ctx.getPrincipal()); ((EventContextImpl) newCtx).setArgs(newArgs.toArray()); } Map<String, Serializable> newProps = new HashMap<String, Serializable>(); for (Entry<String, Serializable> prop : ctx.getProperties() .entrySet()) { Serializable propValue = prop.getValue(); if (propValue instanceof DocumentModel && session != null) { DocumentModel oldDoc = (DocumentModel) propValue; try { propValue = session.getDocument(oldDoc.getRef()); } catch (ClientException e) { log.error("Can not refetch Doc with ref " + oldDoc.getRef().toString(), e); } } // XXX treat here other cases !!!! newProps.put(prop.getKey(), propValue); } newCtx.setProperties(newProps); Event newEvt = new EventImpl(event.getName(), newCtx, event .getFlags(), event.getTime()); reconnectedEvents.add(newEvt); } } return reconnectedEvents; }
diff --git a/src/kundera-cassandra/src/test/java/com/impetus/kundera/client/crud/inheritence/InheritenceDomainTest.java b/src/kundera-cassandra/src/test/java/com/impetus/kundera/client/crud/inheritence/InheritenceDomainTest.java index 7b3159c87..039823a12 100644 --- a/src/kundera-cassandra/src/test/java/com/impetus/kundera/client/crud/inheritence/InheritenceDomainTest.java +++ b/src/kundera-cassandra/src/test/java/com/impetus/kundera/client/crud/inheritence/InheritenceDomainTest.java @@ -1,263 +1,263 @@ /** * Copyright 2013 Impetus Infotech. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.impetus.kundera.client.crud.inheritence; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import junit.framework.Assert; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.impetus.client.cassandra.common.CassandraConstants; import com.impetus.client.cassandra.thrift.ThriftClient; import com.impetus.client.persistence.CassandraCli; import com.impetus.kundera.client.Client; import com.impetus.kundera.metadata.model.KunderaMetadata; /** * Junit for abstract entity class's operation. * * @author vivek.mishra * */ public class InheritenceDomainTest { protected static String _PU = "twissandraTest"; /** The emf. */ private static EntityManagerFactory emfThrift; /** The em. */ private static EntityManager emThrift; @BeforeClass public static void setUpBeforeClass() throws Exception { KunderaMetadata.INSTANCE.setApplicationMetadata(null); CassandraCli.cassandraSetUp(); CassandraCli.createKeySpace("KunderaExamples"); emfThrift = Persistence.createEntityManagerFactory(_PU); emThrift = emfThrift.createEntityManager(); } /** * Test abstract entity relations via thrift. */ @Test public void testRelationViaThrift() { assertRelation(emThrift); } /** * Test abstract entity operations via thrift. */ @Test public void testAbstractEntityViaThrift() { assertAbstractEntity(emThrift); } /** * Test abstract entity relations via thrift. */ @Test public void testRelationViaCQL() { Map<String, Client> clientMap = (Map<String, Client>) emThrift.getDelegate(); ThriftClient tc = (ThriftClient) clientMap.get(_PU); tc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0); assertRelation(emThrift); tc.setCqlVersion(CassandraConstants.CQL_VERSION_2_0); // reset CQL // version to 2.0 } /** * Test abstract entity operations via thrift. */ @Test public void testAbstractEntityViaCQL() { Map<String, Client> clientMap = (Map<String, Client>) emThrift.getDelegate(); ThriftClient tc = (ThriftClient) clientMap.get(_PU); tc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0); assertAbstractEntity(emThrift); tc.setCqlVersion(CassandraConstants.CQL_VERSION_2_0); // reset CQL // version to 2.0 } // TODO:: enable once // https://github.com/impetus-opensource/Kundera/issues/456 is fixed! // @Test public void testRelationViaPelops() { EntityManagerFactory emfPelops = Persistence.createEntityManagerFactory("cass_pu"); EntityManager emPelops = emfPelops.createEntityManager(); assertRelation(emPelops); emPelops.clear(); emPelops.close(); emfPelops.close(); } // @Test public void testAbstractEntityViaPelops() { EntityManagerFactory emfPelops = Persistence.createEntityManagerFactory("cass_pu"); EntityManager emPelops = emfPelops.createEntityManager(); assertAbstractEntity(emPelops); emPelops.clear(); emPelops.close(); emfPelops.close(); } /** * Tear down. * * @throws Exception * the exception */ @After public void tearDown() throws Exception { CassandraCli.truncateColumnFamily("KunderaExamples", "user_account", "social_profile"); } @AfterClass public static void tearDownAfterClass() { if (emThrift != null) { emThrift.close(); emThrift = null; } if (emfThrift != null) { emfThrift.close(); emfThrift = null; } } private void assertRelation(EntityManager em) { List<SocialProfile> profiles = new ArrayList<SocialProfile>(); FacebookProfile fbprofile = new FacebookProfile(); fbprofile.setId(103l); fbprofile.setFacebookId("fb1"); fbprofile.setFacebookUser("facebook"); fbprofile.setuserType("dumbo"); profiles.add(fbprofile); TwitterProfile twprofile1 = new TwitterProfile(); twprofile1.setTwitterId("2"); twprofile1.setTwitterName("test2"); twprofile1.setId(102l); profiles.add(twprofile1); twprofile1.setuserType("dumbo"); UserAccount uacc = new UserAccount(); uacc.setId(101l); uacc.setDispName("Test"); uacc.setSocialProfiles(profiles); twprofile1.setuserAccount(uacc); fbprofile.setuserAccount(uacc); em.getTransaction().begin(); em.persist(uacc); em.getTransaction().commit(); // TODO: Stack over flow error. // Uncomment this to test // https://github.com/impetus-opensource/Kundera/issues/460 uacc.setDispName("UpdatedTest"); em.persist(fbprofile); em.persist(twprofile1); em.clear(); String uaQuery = "Select ua from UserAccount ua"; Query q = em.createQuery(uaQuery); List<UserAccount> results = q.getResultList(); Assert.assertEquals(1, results.size()); - Assert.assertEquals("Test", results.get(0).getDispName()); + Assert.assertEquals("UpdatedTest", results.get(0).getDispName()); Assert.assertEquals(2, results.get(0).getSocialProfiles().size()); Assert.assertFalse(results.get(0).getSocialProfiles().get(0).getId().equals(results.get(0).getId())); em.clear(); } private void assertAbstractEntity(EntityManager em) { FacebookProfile fbprofile = new FacebookProfile(); fbprofile.setId(Long.MIN_VALUE); fbprofile.setFacebookId("fb1"); fbprofile.setFacebookUser("facebook"); fbprofile.setuserType("dumbo"); em.persist(fbprofile); TwitterProfile twprofile = new TwitterProfile(); twprofile.setTwitterId("2"); twprofile.setTwitterName("test2"); twprofile.setId(Long.MAX_VALUE); twprofile.setuserType("dumbo"); em.persist(twprofile); SocialProfile facebookProfile = em.find(SocialProfile.class, Long.MIN_VALUE); Assert.assertNotNull(facebookProfile); Assert.assertTrue(facebookProfile.getClass().isAssignableFrom(FacebookProfile.class)); SocialProfile twitterProfile = em.find(SocialProfile.class, Long.MAX_VALUE); Assert.assertNotNull(twitterProfile); Assert.assertTrue(twitterProfile.getClass().isAssignableFrom(TwitterProfile.class)); String queryStr = "Select s from SocialProfile s"; Query query = em.createQuery(queryStr); List<SocialProfile> socialProfiles = query.getResultList(); Assert.assertFalse(socialProfiles.isEmpty()); Assert.assertEquals(2, socialProfiles.size()); Assert.assertFalse(socialProfiles.get(0).getClass().getSimpleName() .equals(socialProfiles.get(1).getClass().getSimpleName())); } }
true
true
private void assertRelation(EntityManager em) { List<SocialProfile> profiles = new ArrayList<SocialProfile>(); FacebookProfile fbprofile = new FacebookProfile(); fbprofile.setId(103l); fbprofile.setFacebookId("fb1"); fbprofile.setFacebookUser("facebook"); fbprofile.setuserType("dumbo"); profiles.add(fbprofile); TwitterProfile twprofile1 = new TwitterProfile(); twprofile1.setTwitterId("2"); twprofile1.setTwitterName("test2"); twprofile1.setId(102l); profiles.add(twprofile1); twprofile1.setuserType("dumbo"); UserAccount uacc = new UserAccount(); uacc.setId(101l); uacc.setDispName("Test"); uacc.setSocialProfiles(profiles); twprofile1.setuserAccount(uacc); fbprofile.setuserAccount(uacc); em.getTransaction().begin(); em.persist(uacc); em.getTransaction().commit(); // TODO: Stack over flow error. // Uncomment this to test // https://github.com/impetus-opensource/Kundera/issues/460 uacc.setDispName("UpdatedTest"); em.persist(fbprofile); em.persist(twprofile1); em.clear(); String uaQuery = "Select ua from UserAccount ua"; Query q = em.createQuery(uaQuery); List<UserAccount> results = q.getResultList(); Assert.assertEquals(1, results.size()); Assert.assertEquals("Test", results.get(0).getDispName()); Assert.assertEquals(2, results.get(0).getSocialProfiles().size()); Assert.assertFalse(results.get(0).getSocialProfiles().get(0).getId().equals(results.get(0).getId())); em.clear(); }
private void assertRelation(EntityManager em) { List<SocialProfile> profiles = new ArrayList<SocialProfile>(); FacebookProfile fbprofile = new FacebookProfile(); fbprofile.setId(103l); fbprofile.setFacebookId("fb1"); fbprofile.setFacebookUser("facebook"); fbprofile.setuserType("dumbo"); profiles.add(fbprofile); TwitterProfile twprofile1 = new TwitterProfile(); twprofile1.setTwitterId("2"); twprofile1.setTwitterName("test2"); twprofile1.setId(102l); profiles.add(twprofile1); twprofile1.setuserType("dumbo"); UserAccount uacc = new UserAccount(); uacc.setId(101l); uacc.setDispName("Test"); uacc.setSocialProfiles(profiles); twprofile1.setuserAccount(uacc); fbprofile.setuserAccount(uacc); em.getTransaction().begin(); em.persist(uacc); em.getTransaction().commit(); // TODO: Stack over flow error. // Uncomment this to test // https://github.com/impetus-opensource/Kundera/issues/460 uacc.setDispName("UpdatedTest"); em.persist(fbprofile); em.persist(twprofile1); em.clear(); String uaQuery = "Select ua from UserAccount ua"; Query q = em.createQuery(uaQuery); List<UserAccount> results = q.getResultList(); Assert.assertEquals(1, results.size()); Assert.assertEquals("UpdatedTest", results.get(0).getDispName()); Assert.assertEquals(2, results.get(0).getSocialProfiles().size()); Assert.assertFalse(results.get(0).getSocialProfiles().get(0).getId().equals(results.get(0).getId())); em.clear(); }
diff --git a/src/com/modcrafting/diablodrops/items/Socket.java b/src/com/modcrafting/diablodrops/items/Socket.java index 3187064..2dffa42 100644 --- a/src/com/modcrafting/diablodrops/items/Socket.java +++ b/src/com/modcrafting/diablodrops/items/Socket.java @@ -1,69 +1,70 @@ package com.modcrafting.diablodrops.items; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.material.MaterialData; import com.modcrafting.diablodrops.DiabloDrops; public class Socket extends ItemStack { public enum SkullType { SKELETON(0), WITHER(1), ZOMBIE(2), PLAYER(3), CREEPER(4); public int type; private SkullType(final int i) { type = i; } public byte getData() { return (byte) type; } } public Socket(final Material mat) { super(mat); ChatColor color = null; switch (DiabloDrops.getInstance().gen.nextInt(3)) { case 1: color = ChatColor.RED; break; case 2: color = ChatColor.BLUE; break; default: color = ChatColor.GREEN; } ItemMeta meta = this.getItemMeta(); meta.setDisplayName(color + "Socket Enhancement"); List<String> list = new ArrayList<String>(); list.add(ChatColor.GOLD + "Put in the bottom of a furnace"); list.add(ChatColor.GOLD + "with another item in the top"); list.add(ChatColor.GOLD + "to add socket enhancements."); if (mat.equals(Material.SKULL_ITEM)) { SkullMeta sk = (SkullMeta) meta; SkullType type = SkullType.values()[DiabloDrops.getInstance().gen .nextInt(SkullType.values().length)]; if (type.equals(SkullType.PLAYER)){ sk.setOwner(Bukkit.getServer().getOfflinePlayers()[DiabloDrops .getInstance().gen.nextInt(Bukkit.getServer() .getOfflinePlayers().length)].getName()); } MaterialData md = this.getData(); md.setData(type.getData()); this.setData(md); } + meta.setLore(list); this.setItemMeta(meta); } }
true
true
public Socket(final Material mat) { super(mat); ChatColor color = null; switch (DiabloDrops.getInstance().gen.nextInt(3)) { case 1: color = ChatColor.RED; break; case 2: color = ChatColor.BLUE; break; default: color = ChatColor.GREEN; } ItemMeta meta = this.getItemMeta(); meta.setDisplayName(color + "Socket Enhancement"); List<String> list = new ArrayList<String>(); list.add(ChatColor.GOLD + "Put in the bottom of a furnace"); list.add(ChatColor.GOLD + "with another item in the top"); list.add(ChatColor.GOLD + "to add socket enhancements."); if (mat.equals(Material.SKULL_ITEM)) { SkullMeta sk = (SkullMeta) meta; SkullType type = SkullType.values()[DiabloDrops.getInstance().gen .nextInt(SkullType.values().length)]; if (type.equals(SkullType.PLAYER)){ sk.setOwner(Bukkit.getServer().getOfflinePlayers()[DiabloDrops .getInstance().gen.nextInt(Bukkit.getServer() .getOfflinePlayers().length)].getName()); } MaterialData md = this.getData(); md.setData(type.getData()); this.setData(md); } this.setItemMeta(meta); }
public Socket(final Material mat) { super(mat); ChatColor color = null; switch (DiabloDrops.getInstance().gen.nextInt(3)) { case 1: color = ChatColor.RED; break; case 2: color = ChatColor.BLUE; break; default: color = ChatColor.GREEN; } ItemMeta meta = this.getItemMeta(); meta.setDisplayName(color + "Socket Enhancement"); List<String> list = new ArrayList<String>(); list.add(ChatColor.GOLD + "Put in the bottom of a furnace"); list.add(ChatColor.GOLD + "with another item in the top"); list.add(ChatColor.GOLD + "to add socket enhancements."); if (mat.equals(Material.SKULL_ITEM)) { SkullMeta sk = (SkullMeta) meta; SkullType type = SkullType.values()[DiabloDrops.getInstance().gen .nextInt(SkullType.values().length)]; if (type.equals(SkullType.PLAYER)){ sk.setOwner(Bukkit.getServer().getOfflinePlayers()[DiabloDrops .getInstance().gen.nextInt(Bukkit.getServer() .getOfflinePlayers().length)].getName()); } MaterialData md = this.getData(); md.setData(type.getData()); this.setData(md); } meta.setLore(list); this.setItemMeta(meta); }
diff --git a/commons/src/main/java/net/oauth/client/OAuthResponseMessage.java b/commons/src/main/java/net/oauth/client/OAuthResponseMessage.java index 71e7473..5e0c8f4 100644 --- a/commons/src/main/java/net/oauth/client/OAuthResponseMessage.java +++ b/commons/src/main/java/net/oauth/client/OAuthResponseMessage.java @@ -1,116 +1,117 @@ /* * Copyright 2008 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oauth.client; import java.io.IOException; import java.io.InputStream; import java.util.Map; import net.oauth.OAuth; import net.oauth.OAuthMessage; import net.oauth.OAuthProblemException; import net.oauth.http.HttpResponseMessage; /** * An HTTP response, encapsulated as an OAuthMessage. * * @author John Kristian */ public class OAuthResponseMessage extends OAuthMessage { OAuthResponseMessage(HttpResponseMessage http) throws IOException { super(http.method, http.url.toExternalForm(), null); this.http = http; getHeaders().addAll(http.headers); for (Map.Entry<String, String> header : http.headers) { if ("WWW-Authenticate".equalsIgnoreCase(header.getKey())) { for (OAuth.Parameter parameter : decodeAuthorization(header.getValue())) { if (!"realm".equalsIgnoreCase(parameter.getKey())) { addParameter(parameter); } } } } } private final HttpResponseMessage http; public HttpResponseMessage getHttpResponse() { return http; } @Override public InputStream getBodyAsStream() throws IOException { return http.getBody(); } @Override public String getBodyEncoding() { return http.getContentCharset(); } @Override public void requireParameters(String... names) throws OAuthProblemException, IOException { try { super.requireParameters(names); } catch (OAuthProblemException problem) { problem.getParameters().putAll(getDump()); throw problem; } } /** * Encapsulate this message as an exception. Read and close the body of this * message. */ public OAuthProblemException toOAuthProblemException() throws IOException { OAuthProblemException problem = new OAuthProblemException(); try { getParameters(); // decode the response body } catch (IOException ignored) { + } catch (IllegalArgumentException ignored) { } problem.getParameters().putAll(getDump()); try { InputStream b = getBodyAsStream(); if (b != null) { b.close(); // release resources } } catch (IOException ignored) { } return problem; } @Override protected void completeParameters() throws IOException { super.completeParameters(); String body = readBodyAsString(); if (body != null) { addParameters(OAuth.decodeForm(body.trim())); } } @Override protected void dump(Map<String, Object> into) throws IOException { super.dump(into); http.dump(into); } }
true
true
public OAuthProblemException toOAuthProblemException() throws IOException { OAuthProblemException problem = new OAuthProblemException(); try { getParameters(); // decode the response body } catch (IOException ignored) { } problem.getParameters().putAll(getDump()); try { InputStream b = getBodyAsStream(); if (b != null) { b.close(); // release resources } } catch (IOException ignored) { } return problem; }
public OAuthProblemException toOAuthProblemException() throws IOException { OAuthProblemException problem = new OAuthProblemException(); try { getParameters(); // decode the response body } catch (IOException ignored) { } catch (IllegalArgumentException ignored) { } problem.getParameters().putAll(getDump()); try { InputStream b = getBodyAsStream(); if (b != null) { b.close(); // release resources } } catch (IOException ignored) { } return problem; }
diff --git a/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUpdateThrottling.java b/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUpdateThrottling.java index 7362a83..8ecbb4b 100644 --- a/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUpdateThrottling.java +++ b/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUpdateThrottling.java @@ -1,91 +1,91 @@ /* * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.switchyard.as7.extension.admin; import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION_NAME; import static org.switchyard.as7.extension.SwitchYardModelConstants.ENABLED; import static org.switchyard.as7.extension.SwitchYardModelConstants.MAX_REQUESTS; import static org.switchyard.as7.extension.SwitchYardModelConstants.SERVICE_NAME; import static org.switchyard.as7.extension.SwitchYardModelConstants.THROTTLING; import javax.xml.namespace.QName; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceController; import org.switchyard.admin.Application; import org.switchyard.admin.Service; import org.switchyard.admin.SwitchYard; import org.switchyard.admin.Throttling; import org.switchyard.as7.extension.services.SwitchYardAdminService; /** * SwitchYardSubsystemStartGateway * * Operation for starting a gateway. */ public final class SwitchYardSubsystemUpdateThrottling implements OperationStepHandler { /** * The global instance for this operation. */ public static final SwitchYardSubsystemUpdateThrottling INSTANCE = new SwitchYardSubsystemUpdateThrottling(); private SwitchYardSubsystemUpdateThrottling() { // forbidden inheritance } /* * (non-Javadoc) * * @see * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller * .OperationContext, org.jboss.dmr.ModelNode) */ @Override public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { context.addStep(new OperationStepHandler() { @Override public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { final ServiceController<?> controller = context.getServiceRegistry(false).getRequiredService( SwitchYardAdminService.SERVICE_NAME); SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); final Application application = switchYard.getApplication(QName.valueOf(operation.get(APPLICATION_NAME) .asString())); final QName serviceQName = QName.valueOf(operation.get(SERVICE_NAME).asString()); final Service service = application.getService(serviceQName); try { final Throttling throttling = service.getThrottling(); final ModelNode throttlingNode = operation.get(THROTTLING); if (throttlingNode != null) { final ModelNode enabled = throttlingNode.get(ENABLED); final ModelNode maxRequests = throttlingNode.get(MAX_REQUESTS); - throttling.update(enabled == null ? null : enabled.asBoolean(), maxRequests == null ? null - : maxRequests.asInt()); + throttling.update(enabled == null || !enabled.isDefined() ? null : enabled.asBoolean(), + maxRequests == null || !maxRequests.isDefined() ? null : maxRequests.asInt()); } context.stepCompleted(); } catch (Throwable e) { throw new OperationFailedException(new ModelNode().set("Error updating throttling: " + e.getMessage())); } } }, OperationContext.Stage.RUNTIME); context.stepCompleted(); } }
true
true
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { context.addStep(new OperationStepHandler() { @Override public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { final ServiceController<?> controller = context.getServiceRegistry(false).getRequiredService( SwitchYardAdminService.SERVICE_NAME); SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); final Application application = switchYard.getApplication(QName.valueOf(operation.get(APPLICATION_NAME) .asString())); final QName serviceQName = QName.valueOf(operation.get(SERVICE_NAME).asString()); final Service service = application.getService(serviceQName); try { final Throttling throttling = service.getThrottling(); final ModelNode throttlingNode = operation.get(THROTTLING); if (throttlingNode != null) { final ModelNode enabled = throttlingNode.get(ENABLED); final ModelNode maxRequests = throttlingNode.get(MAX_REQUESTS); throttling.update(enabled == null ? null : enabled.asBoolean(), maxRequests == null ? null : maxRequests.asInt()); } context.stepCompleted(); } catch (Throwable e) { throw new OperationFailedException(new ModelNode().set("Error updating throttling: " + e.getMessage())); } } }, OperationContext.Stage.RUNTIME); context.stepCompleted(); }
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { context.addStep(new OperationStepHandler() { @Override public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { final ServiceController<?> controller = context.getServiceRegistry(false).getRequiredService( SwitchYardAdminService.SERVICE_NAME); SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); final Application application = switchYard.getApplication(QName.valueOf(operation.get(APPLICATION_NAME) .asString())); final QName serviceQName = QName.valueOf(operation.get(SERVICE_NAME).asString()); final Service service = application.getService(serviceQName); try { final Throttling throttling = service.getThrottling(); final ModelNode throttlingNode = operation.get(THROTTLING); if (throttlingNode != null) { final ModelNode enabled = throttlingNode.get(ENABLED); final ModelNode maxRequests = throttlingNode.get(MAX_REQUESTS); throttling.update(enabled == null || !enabled.isDefined() ? null : enabled.asBoolean(), maxRequests == null || !maxRequests.isDefined() ? null : maxRequests.asInt()); } context.stepCompleted(); } catch (Throwable e) { throw new OperationFailedException(new ModelNode().set("Error updating throttling: " + e.getMessage())); } } }, OperationContext.Stage.RUNTIME); context.stepCompleted(); }
diff --git a/src/main/java/com/ripariandata/timberwolf/exchange/SyncFolderItemIterator.java b/src/main/java/com/ripariandata/timberwolf/exchange/SyncFolderItemIterator.java index f126833..32d221f 100644 --- a/src/main/java/com/ripariandata/timberwolf/exchange/SyncFolderItemIterator.java +++ b/src/main/java/com/ripariandata/timberwolf/exchange/SyncFolderItemIterator.java @@ -1,92 +1,92 @@ /** * Copyright 2012 Riparian Data * http://www.ripariandata.com * [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ripariandata.timberwolf.exchange; import com.ripariandata.timberwolf.MailboxItem; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Runs a GetItemIterator over many ids, retrieved more efficiently with findItems. * <p/> * This class pages the calls to findItems. */ public class SyncFolderItemIterator extends BaseChainIterator<MailboxItem> { private static final Logger LOG = LoggerFactory.getLogger(SyncFolderItemIterator.class); private ExchangeService service; private Configuration config; private FolderContext folder; private boolean retrievedLastItem; private String syncState; public SyncFolderItemIterator(final ExchangeService exchangeService, final Configuration configuration, final FolderContext folderContext) { service = exchangeService; config = configuration; folder = folderContext; } @Override protected Iterator<MailboxItem> createIterator() { try { if (syncState == null) { // if this is the first run, just get the stored sync state syncState = folder.getSyncStateToken(); } else { // We have successfully retrieved all the items for the given sync state, // so we can now store that sync state in the folder context. folder.setSyncStateToken(syncState); } if (retrievedLastItem) { return null; } SyncFolderItemsHelper.SyncFolderItemsResult result = SyncFolderItemsHelper.syncFolderItems(service, config, folder); syncState = result.getSyncState(); - LOG.debug("Got {} email ids, which was {}the last them.", result.getIds().size(), + LOG.debug("Got {} email ids, which were {}the last of them.", result.getIds().size(), result.includesLastItem() ? "" : "not "); retrievedLastItem = result.includesLastItem(); if (result.getIds().size() > 0) { return new GetItemIterator(service, result.getIds(), config, folder); } else { return null; } } catch (ServiceCallException e) { throw ExchangeRuntimeException.log(LOG, new ExchangeRuntimeException("Failed to sync folder items.", e)); } catch (HttpErrorException e) { throw ExchangeRuntimeException.log(LOG, new ExchangeRuntimeException("Failed to sync folder items.", e)); } } }
true
true
protected Iterator<MailboxItem> createIterator() { try { if (syncState == null) { // if this is the first run, just get the stored sync state syncState = folder.getSyncStateToken(); } else { // We have successfully retrieved all the items for the given sync state, // so we can now store that sync state in the folder context. folder.setSyncStateToken(syncState); } if (retrievedLastItem) { return null; } SyncFolderItemsHelper.SyncFolderItemsResult result = SyncFolderItemsHelper.syncFolderItems(service, config, folder); syncState = result.getSyncState(); LOG.debug("Got {} email ids, which was {}the last them.", result.getIds().size(), result.includesLastItem() ? "" : "not "); retrievedLastItem = result.includesLastItem(); if (result.getIds().size() > 0) { return new GetItemIterator(service, result.getIds(), config, folder); } else { return null; } } catch (ServiceCallException e) { throw ExchangeRuntimeException.log(LOG, new ExchangeRuntimeException("Failed to sync folder items.", e)); } catch (HttpErrorException e) { throw ExchangeRuntimeException.log(LOG, new ExchangeRuntimeException("Failed to sync folder items.", e)); } }
protected Iterator<MailboxItem> createIterator() { try { if (syncState == null) { // if this is the first run, just get the stored sync state syncState = folder.getSyncStateToken(); } else { // We have successfully retrieved all the items for the given sync state, // so we can now store that sync state in the folder context. folder.setSyncStateToken(syncState); } if (retrievedLastItem) { return null; } SyncFolderItemsHelper.SyncFolderItemsResult result = SyncFolderItemsHelper.syncFolderItems(service, config, folder); syncState = result.getSyncState(); LOG.debug("Got {} email ids, which were {}the last of them.", result.getIds().size(), result.includesLastItem() ? "" : "not "); retrievedLastItem = result.includesLastItem(); if (result.getIds().size() > 0) { return new GetItemIterator(service, result.getIds(), config, folder); } else { return null; } } catch (ServiceCallException e) { throw ExchangeRuntimeException.log(LOG, new ExchangeRuntimeException("Failed to sync folder items.", e)); } catch (HttpErrorException e) { throw ExchangeRuntimeException.log(LOG, new ExchangeRuntimeException("Failed to sync folder items.", e)); } }
diff --git a/android-app/RPInfo/src/org/rpi/rpinfo/DetailedView/DetailedViewActivity.java b/android-app/RPInfo/src/org/rpi/rpinfo/DetailedView/DetailedViewActivity.java index cf43f44..2d72135 100644 --- a/android-app/RPInfo/src/org/rpi/rpinfo/DetailedView/DetailedViewActivity.java +++ b/android-app/RPInfo/src/org/rpi/rpinfo/DetailedView/DetailedViewActivity.java @@ -1,89 +1,90 @@ package org.rpi.rpinfo.DetailedView; import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; import org.rpi.rpinfo.R; import org.rpi.rpinfo.QueryView.PersonModel; import org.rpi.rpinfo.R.id; import org.rpi.rpinfo.R.layout; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.Html; import android.text.Spanned; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class DetailedViewActivity extends Activity { private static final String TAG = "DetailedDataDisplayerActivity"; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detailed_data_view); Bundle b = getIntent().getExtras(); if( b == null ){ finish(); } //Extract the selected person from the intent PersonModel selectedPerson = (PersonModel)b.getSerializable("selectedPerson"); if( selectedPerson == null ){ finish(); } ArrayList<DetailedResultModel> models = DetailedResultModel.generateModels(selectedPerson.getAllElements()); /* //Extract the data from the selected person and prepare to put it into a nice list view Map<String, String> raw_data = selectedPerson.getAllElements(); //Spanned is like a string but it can contain formatting data and such ArrayList<Spanned> parsed_data = new ArrayList<Spanned>(); for( Entry<String, String> entry : raw_data.entrySet() ){ if( !entry.getKey().equals("name") ){ //Make the name of the field bold parsed_data.add( Html.fromHtml("<b>" + formatField( entry.getKey() ) + "</b>: " + formatValue( entry.getKey(), entry.getValue() ) ) ); } } */ //Put the person's name in TextView name = (TextView)this.findViewById(R.id.person_name); name.setText(selectedPerson.getElement("name", "N/A")); //Set up the list view ListView lv = (ListView)this.findViewById(R.id.data_list); lv.setAdapter(new DetailedListArrayAdapter(this, R.layout.detailed_view_list_item, models)); //lv.setAdapter(new ArrayAdapter<DetailedResultModel>(this, R.layout.detailed_view_list_item, models)); //If a list element is pressed lv.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DetailedResultModel model = (DetailedResultModel)parent.getAdapter().getItem(position); String key = model.getRawKey(); if( key.equals("phone") ){ Log.i(TAG, "Calling" + model.getValue()); Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("tel:" + model.getValue())); startActivity(intent); } else if( key.equals("email") ) { Log.i(TAG, "Sending email to " + model.getValue()); Intent intent = new Intent(android.content.Intent.ACTION_SEND); + intent.setType("message/rfc822"); intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{model.getValue()}); startActivity(Intent.createChooser(intent, "Send email...")); } } }); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detailed_data_view); Bundle b = getIntent().getExtras(); if( b == null ){ finish(); } //Extract the selected person from the intent PersonModel selectedPerson = (PersonModel)b.getSerializable("selectedPerson"); if( selectedPerson == null ){ finish(); } ArrayList<DetailedResultModel> models = DetailedResultModel.generateModels(selectedPerson.getAllElements()); /* //Extract the data from the selected person and prepare to put it into a nice list view Map<String, String> raw_data = selectedPerson.getAllElements(); //Spanned is like a string but it can contain formatting data and such ArrayList<Spanned> parsed_data = new ArrayList<Spanned>(); for( Entry<String, String> entry : raw_data.entrySet() ){ if( !entry.getKey().equals("name") ){ //Make the name of the field bold parsed_data.add( Html.fromHtml("<b>" + formatField( entry.getKey() ) + "</b>: " + formatValue( entry.getKey(), entry.getValue() ) ) ); } } */ //Put the person's name in TextView name = (TextView)this.findViewById(R.id.person_name); name.setText(selectedPerson.getElement("name", "N/A")); //Set up the list view ListView lv = (ListView)this.findViewById(R.id.data_list); lv.setAdapter(new DetailedListArrayAdapter(this, R.layout.detailed_view_list_item, models)); //lv.setAdapter(new ArrayAdapter<DetailedResultModel>(this, R.layout.detailed_view_list_item, models)); //If a list element is pressed lv.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DetailedResultModel model = (DetailedResultModel)parent.getAdapter().getItem(position); String key = model.getRawKey(); if( key.equals("phone") ){ Log.i(TAG, "Calling" + model.getValue()); Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("tel:" + model.getValue())); startActivity(intent); } else if( key.equals("email") ) { Log.i(TAG, "Sending email to " + model.getValue()); Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{model.getValue()}); startActivity(Intent.createChooser(intent, "Send email...")); } } }); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detailed_data_view); Bundle b = getIntent().getExtras(); if( b == null ){ finish(); } //Extract the selected person from the intent PersonModel selectedPerson = (PersonModel)b.getSerializable("selectedPerson"); if( selectedPerson == null ){ finish(); } ArrayList<DetailedResultModel> models = DetailedResultModel.generateModels(selectedPerson.getAllElements()); /* //Extract the data from the selected person and prepare to put it into a nice list view Map<String, String> raw_data = selectedPerson.getAllElements(); //Spanned is like a string but it can contain formatting data and such ArrayList<Spanned> parsed_data = new ArrayList<Spanned>(); for( Entry<String, String> entry : raw_data.entrySet() ){ if( !entry.getKey().equals("name") ){ //Make the name of the field bold parsed_data.add( Html.fromHtml("<b>" + formatField( entry.getKey() ) + "</b>: " + formatValue( entry.getKey(), entry.getValue() ) ) ); } } */ //Put the person's name in TextView name = (TextView)this.findViewById(R.id.person_name); name.setText(selectedPerson.getElement("name", "N/A")); //Set up the list view ListView lv = (ListView)this.findViewById(R.id.data_list); lv.setAdapter(new DetailedListArrayAdapter(this, R.layout.detailed_view_list_item, models)); //lv.setAdapter(new ArrayAdapter<DetailedResultModel>(this, R.layout.detailed_view_list_item, models)); //If a list element is pressed lv.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DetailedResultModel model = (DetailedResultModel)parent.getAdapter().getItem(position); String key = model.getRawKey(); if( key.equals("phone") ){ Log.i(TAG, "Calling" + model.getValue()); Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("tel:" + model.getValue())); startActivity(intent); } else if( key.equals("email") ) { Log.i(TAG, "Sending email to " + model.getValue()); Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{model.getValue()}); startActivity(Intent.createChooser(intent, "Send email...")); } } }); }
diff --git a/cube-client-core/src/main/java/ch/admin/vbs/cube/core/vm/ctrtasks/Start.java b/cube-client-core/src/main/java/ch/admin/vbs/cube/core/vm/ctrtasks/Start.java index 03925f6..8028263 100644 --- a/cube-client-core/src/main/java/ch/admin/vbs/cube/core/vm/ctrtasks/Start.java +++ b/cube-client-core/src/main/java/ch/admin/vbs/cube/core/vm/ctrtasks/Start.java @@ -1,201 +1,202 @@ /** * Copyright (C) 2011 / cube-team <https://cube.forge.osor.eu> * * Licensed under the Apache License, Version 2.0 (the "License"). * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.admin.vbs.cube.core.vm.ctrtasks; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.admin.vbs.cube.common.Chronos; import ch.admin.vbs.cube.common.container.Container; import ch.admin.vbs.cube.common.container.IContainerFactory; import ch.admin.vbs.cube.common.keyring.EncryptionKey; import ch.admin.vbs.cube.common.keyring.IKeyring; import ch.admin.vbs.cube.core.I18nBundleProvider; import ch.admin.vbs.cube.core.ISession.IOption; import ch.admin.vbs.cube.core.network.vpn.VpnManager; import ch.admin.vbs.cube.core.network.vpn.VpnManager.VpnListener; import ch.admin.vbs.cube.core.vm.IVmProduct.VmProductState; import ch.admin.vbs.cube.core.vm.Vm; import ch.admin.vbs.cube.core.vm.VmController; import ch.admin.vbs.cube.core.vm.VmException; import ch.admin.vbs.cube.core.vm.VmModel; import ch.admin.vbs.cube.core.vm.VmState; import ch.admin.vbs.cube.core.vm.VmVpnState; import ch.admin.vbs.cube.core.vm.vbox.VBoxProduct; public class Start extends AbstractCtrlTask { /** Logger */ private static final Logger LOG = LoggerFactory.getLogger(Start.class); private static final long START_TIMEOUT = 40000; // ms private static final long UNKNOWN_STATE_TIMEOUT = 4000; // ms public Start(VmController vmController, IKeyring keyring, Vm vm, IContainerFactory containerFactory, VpnManager vpnManager, VBoxProduct product, Container transfer, VmModel vmModel, IOption option) { super(vmController, keyring, vm, containerFactory, vpnManager, product, transfer, vmModel, option); } @Override public void run() { EncryptionKey vmKey = null; EncryptionKey rtKey = null; try { Chronos c = new Chronos(); vmModel.fireVmStateUpdatedEvent(vm); c.zap("fireVmStateUpdateEvent()"); // set temporary status ctrl.setTempStatus(vm, VmState.STARTING); // vm.setProgressMessage(I18nBundleProvider.getBundle().getString("vm.starting")); ctrl.refreshVmState(vm); c.zap("refresh vm state"); // vmKey = keyring.getKey(vm.getVmContainer().getId()); c.zap("got vm's key"); rtKey = keyring.getKey(vm.getRuntimeContainer().getId()); c.zap("got runtime's key"); containerFactory.mountContainer(vm.getVmContainer(), vmKey); c.zap("mounted vm container"); containerFactory.mountContainer(vm.getRuntimeContainer(), rtKey); c.zap("mounted runtime container"); rtKey.shred(); // shred key asap c.zap("shred runtime key"); vmKey.shred(); // shred key asap c.zap("shred vm key"); // prepare transfer folders File sessionTransferFolder = new File(transfer.getMountpoint(), vm.getId() + "_transfer"); vm.setTempFolder(new File(sessionTransferFolder, "temporary")); vm.setImportFolder(new File(sessionTransferFolder, "import")); vm.setExportFolder(new File(sessionTransferFolder, "export")); vm.getTempFolder().mkdirs(); vm.getImportFolder().mkdirs(); vm.getExportFolder().mkdirs(); c.zap("configure vm object"); // product.registerVm(vm); // register VM c.zap("register vm"); vpnManager.openVpn(vm, keyring, new VpnListener() { @Override public void opened() { try { // could not connect when starting or restoring. wait while (product.getProductState(vm) == VmProductState.STARTING) { Thread.sleep(500); } // connect cable to trigger host's network manager product.connectNic(vm, true); // } catch (Exception e) { LOG.error("VM's VPN was opened but we failed to connect VM's NIC", e); vm.setVpnState(VmVpnState.NOT_CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } vm.setVpnState(VmVpnState.CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } @Override public void closed() { try { product.connectNic(vm, false); } catch (VmException e) { LOG.error("Failed to disconnect NIC",e); } vm.setVpnState(VmVpnState.NOT_CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } @Override public void connecting() { try { product.connectNic(vm, false); + vm.setVpnState(VmVpnState.CONNECTING); } catch (VmException e) { - LOG.error("Failed to disconnect NIC",e); + LOG.error("Failed to connect NIC",e); + vm.setVpnState(VmVpnState.NOT_CONNECTED); } - vm.setVpnState(VmVpnState.CONNECTING); vmModel.fireVmStateUpdatedEvent(vm); } @Override public void failed() { try { product.connectNic(vm, false); } catch (VmException e) { LOG.error("VM's VPN failed and we failed to disconnect NIC", e); } vm.setVpnState(VmVpnState.NOT_CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } }); // open vpn c.zap("VPN opened (in another thred)"); product.startVm(vm); // start VM c.zap("vm started"); /* * wait that the VM reach the state RUNNING. If it fails within the * timeout, remove the tempStatus flag and let VmContorller handle * it. */ boolean isUnknown = false; long isUnknownSince = 0; long timeout = System.currentTimeMillis() + START_TIMEOUT; while (System.currentTimeMillis() < timeout) { VmProductState ps = product.getProductState(vm); if (ps == VmProductState.RUNNING || ps == VmProductState.ERROR) { c.zap("Reached state ["+ps+"]"); break; } else if (ps == VmProductState.UNKNOWN) { if (isUnknown) { // was already unknown. check timeout if (isUnknownSince + UNKNOWN_STATE_TIMEOUT < System.currentTimeMillis()) { /* * VM was too long in UNKNOWN state (VirtualBox vm * is 'saved' or 'stopped' which is normal between * the 'register' and 'start' commands or between * 'save/poweroff' and 'unregister' commands) but * which should last only few seconds. Do not wait * until START_TIMEOUT is reached and break asap. */ LOG.debug("VM was in UNKNOWN state for to many seconds. It is abnormal."); break; } } else { // just entered unknown state isUnknown = true; isUnknownSince = System.currentTimeMillis(); LOG.debug("Reached an unknown state (will break if VM stay in this state for too long)."); } } else { isUnknown = false; } LOG.debug("Wait VM to be RUNNING.."); Thread.sleep(500); } c.zap("VM reached state ["+product.getProductState(vm)+"]"); LOG.debug("Wait VM reached state [{}]", product.getProductState(vm)); } catch (Exception e) { LOG.error("Failed to start VM", e); } finally { // shred keys if (rtKey != null) rtKey.shred(); // just in case.. if (vmKey != null) vmKey.shred(); // just in case.. ctrl.clearTempStatus(vm); ctrl.refreshVmState(vm); } } }
false
true
public void run() { EncryptionKey vmKey = null; EncryptionKey rtKey = null; try { Chronos c = new Chronos(); vmModel.fireVmStateUpdatedEvent(vm); c.zap("fireVmStateUpdateEvent()"); // set temporary status ctrl.setTempStatus(vm, VmState.STARTING); // vm.setProgressMessage(I18nBundleProvider.getBundle().getString("vm.starting")); ctrl.refreshVmState(vm); c.zap("refresh vm state"); // vmKey = keyring.getKey(vm.getVmContainer().getId()); c.zap("got vm's key"); rtKey = keyring.getKey(vm.getRuntimeContainer().getId()); c.zap("got runtime's key"); containerFactory.mountContainer(vm.getVmContainer(), vmKey); c.zap("mounted vm container"); containerFactory.mountContainer(vm.getRuntimeContainer(), rtKey); c.zap("mounted runtime container"); rtKey.shred(); // shred key asap c.zap("shred runtime key"); vmKey.shred(); // shred key asap c.zap("shred vm key"); // prepare transfer folders File sessionTransferFolder = new File(transfer.getMountpoint(), vm.getId() + "_transfer"); vm.setTempFolder(new File(sessionTransferFolder, "temporary")); vm.setImportFolder(new File(sessionTransferFolder, "import")); vm.setExportFolder(new File(sessionTransferFolder, "export")); vm.getTempFolder().mkdirs(); vm.getImportFolder().mkdirs(); vm.getExportFolder().mkdirs(); c.zap("configure vm object"); // product.registerVm(vm); // register VM c.zap("register vm"); vpnManager.openVpn(vm, keyring, new VpnListener() { @Override public void opened() { try { // could not connect when starting or restoring. wait while (product.getProductState(vm) == VmProductState.STARTING) { Thread.sleep(500); } // connect cable to trigger host's network manager product.connectNic(vm, true); // } catch (Exception e) { LOG.error("VM's VPN was opened but we failed to connect VM's NIC", e); vm.setVpnState(VmVpnState.NOT_CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } vm.setVpnState(VmVpnState.CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } @Override public void closed() { try { product.connectNic(vm, false); } catch (VmException e) { LOG.error("Failed to disconnect NIC",e); } vm.setVpnState(VmVpnState.NOT_CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } @Override public void connecting() { try { product.connectNic(vm, false); } catch (VmException e) { LOG.error("Failed to disconnect NIC",e); } vm.setVpnState(VmVpnState.CONNECTING); vmModel.fireVmStateUpdatedEvent(vm); } @Override public void failed() { try { product.connectNic(vm, false); } catch (VmException e) { LOG.error("VM's VPN failed and we failed to disconnect NIC", e); } vm.setVpnState(VmVpnState.NOT_CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } }); // open vpn c.zap("VPN opened (in another thred)"); product.startVm(vm); // start VM c.zap("vm started"); /* * wait that the VM reach the state RUNNING. If it fails within the * timeout, remove the tempStatus flag and let VmContorller handle * it. */ boolean isUnknown = false; long isUnknownSince = 0; long timeout = System.currentTimeMillis() + START_TIMEOUT; while (System.currentTimeMillis() < timeout) { VmProductState ps = product.getProductState(vm); if (ps == VmProductState.RUNNING || ps == VmProductState.ERROR) { c.zap("Reached state ["+ps+"]"); break; } else if (ps == VmProductState.UNKNOWN) { if (isUnknown) { // was already unknown. check timeout if (isUnknownSince + UNKNOWN_STATE_TIMEOUT < System.currentTimeMillis()) { /* * VM was too long in UNKNOWN state (VirtualBox vm * is 'saved' or 'stopped' which is normal between * the 'register' and 'start' commands or between * 'save/poweroff' and 'unregister' commands) but * which should last only few seconds. Do not wait * until START_TIMEOUT is reached and break asap. */ LOG.debug("VM was in UNKNOWN state for to many seconds. It is abnormal."); break; } } else { // just entered unknown state isUnknown = true; isUnknownSince = System.currentTimeMillis(); LOG.debug("Reached an unknown state (will break if VM stay in this state for too long)."); } } else { isUnknown = false; } LOG.debug("Wait VM to be RUNNING.."); Thread.sleep(500); } c.zap("VM reached state ["+product.getProductState(vm)+"]"); LOG.debug("Wait VM reached state [{}]", product.getProductState(vm)); } catch (Exception e) { LOG.error("Failed to start VM", e); } finally { // shred keys if (rtKey != null) rtKey.shred(); // just in case.. if (vmKey != null) vmKey.shred(); // just in case.. ctrl.clearTempStatus(vm); ctrl.refreshVmState(vm); } }
public void run() { EncryptionKey vmKey = null; EncryptionKey rtKey = null; try { Chronos c = new Chronos(); vmModel.fireVmStateUpdatedEvent(vm); c.zap("fireVmStateUpdateEvent()"); // set temporary status ctrl.setTempStatus(vm, VmState.STARTING); // vm.setProgressMessage(I18nBundleProvider.getBundle().getString("vm.starting")); ctrl.refreshVmState(vm); c.zap("refresh vm state"); // vmKey = keyring.getKey(vm.getVmContainer().getId()); c.zap("got vm's key"); rtKey = keyring.getKey(vm.getRuntimeContainer().getId()); c.zap("got runtime's key"); containerFactory.mountContainer(vm.getVmContainer(), vmKey); c.zap("mounted vm container"); containerFactory.mountContainer(vm.getRuntimeContainer(), rtKey); c.zap("mounted runtime container"); rtKey.shred(); // shred key asap c.zap("shred runtime key"); vmKey.shred(); // shred key asap c.zap("shred vm key"); // prepare transfer folders File sessionTransferFolder = new File(transfer.getMountpoint(), vm.getId() + "_transfer"); vm.setTempFolder(new File(sessionTransferFolder, "temporary")); vm.setImportFolder(new File(sessionTransferFolder, "import")); vm.setExportFolder(new File(sessionTransferFolder, "export")); vm.getTempFolder().mkdirs(); vm.getImportFolder().mkdirs(); vm.getExportFolder().mkdirs(); c.zap("configure vm object"); // product.registerVm(vm); // register VM c.zap("register vm"); vpnManager.openVpn(vm, keyring, new VpnListener() { @Override public void opened() { try { // could not connect when starting or restoring. wait while (product.getProductState(vm) == VmProductState.STARTING) { Thread.sleep(500); } // connect cable to trigger host's network manager product.connectNic(vm, true); // } catch (Exception e) { LOG.error("VM's VPN was opened but we failed to connect VM's NIC", e); vm.setVpnState(VmVpnState.NOT_CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } vm.setVpnState(VmVpnState.CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } @Override public void closed() { try { product.connectNic(vm, false); } catch (VmException e) { LOG.error("Failed to disconnect NIC",e); } vm.setVpnState(VmVpnState.NOT_CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } @Override public void connecting() { try { product.connectNic(vm, false); vm.setVpnState(VmVpnState.CONNECTING); } catch (VmException e) { LOG.error("Failed to connect NIC",e); vm.setVpnState(VmVpnState.NOT_CONNECTED); } vmModel.fireVmStateUpdatedEvent(vm); } @Override public void failed() { try { product.connectNic(vm, false); } catch (VmException e) { LOG.error("VM's VPN failed and we failed to disconnect NIC", e); } vm.setVpnState(VmVpnState.NOT_CONNECTED); vmModel.fireVmStateUpdatedEvent(vm); } }); // open vpn c.zap("VPN opened (in another thred)"); product.startVm(vm); // start VM c.zap("vm started"); /* * wait that the VM reach the state RUNNING. If it fails within the * timeout, remove the tempStatus flag and let VmContorller handle * it. */ boolean isUnknown = false; long isUnknownSince = 0; long timeout = System.currentTimeMillis() + START_TIMEOUT; while (System.currentTimeMillis() < timeout) { VmProductState ps = product.getProductState(vm); if (ps == VmProductState.RUNNING || ps == VmProductState.ERROR) { c.zap("Reached state ["+ps+"]"); break; } else if (ps == VmProductState.UNKNOWN) { if (isUnknown) { // was already unknown. check timeout if (isUnknownSince + UNKNOWN_STATE_TIMEOUT < System.currentTimeMillis()) { /* * VM was too long in UNKNOWN state (VirtualBox vm * is 'saved' or 'stopped' which is normal between * the 'register' and 'start' commands or between * 'save/poweroff' and 'unregister' commands) but * which should last only few seconds. Do not wait * until START_TIMEOUT is reached and break asap. */ LOG.debug("VM was in UNKNOWN state for to many seconds. It is abnormal."); break; } } else { // just entered unknown state isUnknown = true; isUnknownSince = System.currentTimeMillis(); LOG.debug("Reached an unknown state (will break if VM stay in this state for too long)."); } } else { isUnknown = false; } LOG.debug("Wait VM to be RUNNING.."); Thread.sleep(500); } c.zap("VM reached state ["+product.getProductState(vm)+"]"); LOG.debug("Wait VM reached state [{}]", product.getProductState(vm)); } catch (Exception e) { LOG.error("Failed to start VM", e); } finally { // shred keys if (rtKey != null) rtKey.shred(); // just in case.. if (vmKey != null) vmKey.shred(); // just in case.. ctrl.clearTempStatus(vm); ctrl.refreshVmState(vm); } }
diff --git a/src/com/android/gallery3d/app/AbstractGalleryActivity.java b/src/com/android/gallery3d/app/AbstractGalleryActivity.java index f674c0b..144485d 100644 --- a/src/com/android/gallery3d/app/AbstractGalleryActivity.java +++ b/src/com/android/gallery3d/app/AbstractGalleryActivity.java @@ -1,269 +1,269 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.app; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.os.Bundle; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import com.android.gallery3d.R; import com.android.gallery3d.data.DataManager; import com.android.gallery3d.data.MediaItem; import com.android.gallery3d.ui.GLRoot; import com.android.gallery3d.ui.GLRootView; import com.android.gallery3d.util.ThreadPool; public class AbstractGalleryActivity extends Activity implements GalleryActivity { @SuppressWarnings("unused") private static final String TAG = "AbstractGalleryActivity"; private GLRootView mGLRootView; private StateManager mStateManager; private GalleryActionBar mActionBar; private OrientationManager mOrientationManager; private TransitionStore mTransitionStore = new TransitionStore(); private boolean mDisableToggleStatusBar; private AlertDialog mAlertDialog = null; private BroadcastReceiver mMountReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (getExternalCacheDir() != null) onStorageReady(); } }; private IntentFilter mMountFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mOrientationManager = new OrientationManager(this); toggleStatusBarByOrientation(); getWindow().setBackgroundDrawable(null); } @Override protected void onSaveInstanceState(Bundle outState) { mGLRootView.lockRenderThread(); try { super.onSaveInstanceState(outState); getStateManager().saveState(outState); } finally { mGLRootView.unlockRenderThread(); } } @Override public void onConfigurationChanged(Configuration config) { super.onConfigurationChanged(config); mStateManager.onConfigurationChange(config); invalidateOptionsMenu(); toggleStatusBarByOrientation(); } public Context getAndroidContext() { return this; } public DataManager getDataManager() { return ((GalleryApp) getApplication()).getDataManager(); } public ThreadPool getThreadPool() { return ((GalleryApp) getApplication()).getThreadPool(); } public synchronized StateManager getStateManager() { if (mStateManager == null) { mStateManager = new StateManager(this); } return mStateManager; } public GLRoot getGLRoot() { return mGLRootView; } public OrientationManager getOrientationManager() { return mOrientationManager; } @Override public void setContentView(int resId) { super.setContentView(resId); mGLRootView = (GLRootView) findViewById(R.id.gl_root_view); } protected void onStorageReady() { if (mAlertDialog != null) { mAlertDialog.dismiss(); mAlertDialog = null; unregisterReceiver(mMountReceiver); } } @Override protected void onStart() { super.onStart(); if (getExternalCacheDir() == null) { OnCancelListener onCancel = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }; OnClickListener onClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }; mAlertDialog = new AlertDialog.Builder(this) - .setIcon(android.R.drawable.ic_dialog_alert) + .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("No Storage") .setMessage("No external storage available.") .setNegativeButton(android.R.string.cancel, onClick) .setOnCancelListener(onCancel) .show(); registerReceiver(mMountReceiver, mMountFilter); } } @Override protected void onStop() { super.onStop(); if (mAlertDialog != null) { unregisterReceiver(mMountReceiver); mAlertDialog.dismiss(); mAlertDialog = null; } } @Override protected void onResume() { super.onResume(); mGLRootView.lockRenderThread(); try { getStateManager().resume(); getDataManager().resume(); } finally { mGLRootView.unlockRenderThread(); } mGLRootView.onResume(); mOrientationManager.resume(); } @Override protected void onPause() { super.onPause(); mOrientationManager.pause(); mGLRootView.onPause(); mGLRootView.lockRenderThread(); try { getStateManager().pause(); getDataManager().pause(); } finally { mGLRootView.unlockRenderThread(); } MediaItem.getMicroThumbPool().clear(); MediaItem.getThumbPool().clear(); MediaItem.getBytesBufferPool().clear(); } @Override protected void onDestroy() { super.onDestroy(); mGLRootView.lockRenderThread(); try { getStateManager().destroy(); } finally { mGLRootView.unlockRenderThread(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { mGLRootView.lockRenderThread(); try { getStateManager().notifyActivityResult( requestCode, resultCode, data); } finally { mGLRootView.unlockRenderThread(); } } @Override public void onBackPressed() { // send the back event to the top sub-state GLRoot root = getGLRoot(); root.lockRenderThread(); try { getStateManager().onBackPressed(); } finally { root.unlockRenderThread(); } } @Override public GalleryActionBar getGalleryActionBar() { if (mActionBar == null) { mActionBar = new GalleryActionBar(this); } return mActionBar; } @Override public boolean onOptionsItemSelected(MenuItem item) { GLRoot root = getGLRoot(); root.lockRenderThread(); try { return getStateManager().itemSelected(item); } finally { root.unlockRenderThread(); } } protected void disableToggleStatusBar() { mDisableToggleStatusBar = true; } // Shows status bar in portrait view, hide in landscape view private void toggleStatusBarByOrientation() { if (mDisableToggleStatusBar) return; Window win = getWindow(); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } } @Override public TransitionStore getTransitionStore() { return mTransitionStore; } }
true
true
protected void onStart() { super.onStart(); if (getExternalCacheDir() == null) { OnCancelListener onCancel = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }; OnClickListener onClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }; mAlertDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("No Storage") .setMessage("No external storage available.") .setNegativeButton(android.R.string.cancel, onClick) .setOnCancelListener(onCancel) .show(); registerReceiver(mMountReceiver, mMountFilter); } }
protected void onStart() { super.onStart(); if (getExternalCacheDir() == null) { OnCancelListener onCancel = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }; OnClickListener onClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }; mAlertDialog = new AlertDialog.Builder(this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("No Storage") .setMessage("No external storage available.") .setNegativeButton(android.R.string.cancel, onClick) .setOnCancelListener(onCancel) .show(); registerReceiver(mMountReceiver, mMountFilter); } }
diff --git a/flexodesktop/model/flexoutils/src/test/java/org/openflexo/antar/binding/TestBinding.java b/flexodesktop/model/flexoutils/src/test/java/org/openflexo/antar/binding/TestBinding.java index 6a4fce307..d2844c666 100644 --- a/flexodesktop/model/flexoutils/src/test/java/org/openflexo/antar/binding/TestBinding.java +++ b/flexodesktop/model/flexoutils/src/test/java/org/openflexo/antar/binding/TestBinding.java @@ -1,303 +1,303 @@ package org.openflexo.antar.binding; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.openflexo.antar.binding.AbstractBinding.BindingEvaluationContext; import org.openflexo.antar.binding.BindingDefinition.BindingDefinitionType; import org.openflexo.antar.expr.NullReferenceException; import org.openflexo.antar.expr.TypeMismatchException; import com.google.common.reflect.TypeToken; public class TestBinding extends TestCase { private static final DefaultBindingFactory BINDING_FACTORY = new DefaultBindingFactory(); private static final TestBindingContext BINDING_CONTEXT = new TestBindingContext(); private static final TestBindingModel BINDING_MODEL = new TestBindingModel(); public static class TestBindingContext implements Bindable, BindingEvaluationContext { public static String aString = "this is a test"; public static boolean aBoolean = false; public static int anInt = 7; public static List<String> aList = new ArrayList<String>(); static { aList.add("this"); aList.add("is"); aList.add("a"); aList.add("test"); } @Override public BindingFactory getBindingFactory() { return BINDING_FACTORY; } @Override public BindingModel getBindingModel() { return BINDING_MODEL; } @Override public Object getValue(BindingVariable variable) { System.out.println("Value for " + variable + " ?"); if (variable.getVariableName().equals("aString")) { return aString; } else if (variable.getVariableName().equals("aBoolean")) { return aBoolean; } else if (variable.getVariableName().equals("anInt")) { return anInt; } else if (variable.getVariableName().equals("aList")) { return aList; } return null; } } // String aString; // Boolean aBoolean; // List<String> aList; public static class TestBindingModel extends BindingModel { public TestBindingModel() { super(); addToBindingVariables(new BindingVariableImpl(BINDING_CONTEXT, "aString", String.class)); addToBindingVariables(new BindingVariableImpl(BINDING_CONTEXT, "aBoolean", Boolean.TYPE)); addToBindingVariables(new BindingVariableImpl(BINDING_CONTEXT, "anInt", Integer.TYPE)); addToBindingVariables(new BindingVariableImpl(BINDING_CONTEXT, "aList", new TypeToken<List<String>>() { }.getType())); } } /*public static class TestObject implements Bindable, BindingEvaluationContext { private Object object; private BindingDefinition bindingDefinition; private BindingModel bindingModel; private BindingEvaluator(Object object) { this.object = object; bindingDefinition = new BindingDefinition("object", object.getClass(), BindingDefinitionType.GET, true); bindingModel = new BindingModel(); bindingModel.addToBindingVariables(new BindingVariableImpl(this, "object", object.getClass())); BINDING_FACTORY.setBindable(this); } private static String normalizeBindingPath(String bindingPath) { DefaultExpressionParser parser = new DefaultExpressionParser(); Expression expression = null; try { expression = ExpressionParser.parse(bindingPath); expression = expression.transform(new ExpressionTransformer() { @Override public Expression performTransformation(Expression e) throws TransformException { if (e instanceof BindingValueAsExpression) { BindingValueAsExpression bv = (BindingValueAsExpression) e; if (bv.getBindingPath().size() > 0) { AbstractBindingPathElement firstPathElement = bv.getBindingPath().get(0); if (!(firstPathElement instanceof NormalBindingPathElement) || !((NormalBindingPathElement) firstPathElement).property.equals("object")) { bv.getBindingPath().add(0, new NormalBindingPathElement("object")); } } return bv; } return e; } }); return expression.toString(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformException e) { // TODO Auto-generated catch block e.printStackTrace(); } return expression.toString(); } @Override public BindingModel getBindingModel() { return bindingModel; } @Override public BindingFactory getBindingFactory() { return BINDING_FACTORY; } @Override public Object getValue(BindingVariable variable) { return object; } } @Override protected void setUp() throws Exception { super.setUp(); } public void test1() { String thisIsATest = "Hello world, this is a test"; genericTest("toString", thisIsATest, thisIsATest); } public void test2() { String thisIsATest = "Hello world, this is a test"; genericTest("toString()", thisIsATest, thisIsATest); } public void test3() { String thisIsATest = "Hello world, this is a test"; genericTest("substring(2,8)", thisIsATest, "llo wo"); } public void test4() { String thisIsATest = "Hello world, this is a test"; genericTest("substring(2,5*2-2)", thisIsATest, "llo wo"); } public void test5() { String thisIsATest = "Hello world, this is a test"; genericTest("toString()+toString()", thisIsATest, "Hello world, this is a testHello world, this is a test"); } public void test6() { String thisIsATest = "Hello world, this is a test"; genericTest("toString()+' hash='+object.hashCode()", thisIsATest, thisIsATest + " hash=" + thisIsATest.hashCode()); } public void test7() { String thisIsATest = "Hello world, this is a test"; genericTest("substring(0,5)+' '+substring(23,27).toUpperCase()", thisIsATest, "Hello TEST"); } public void test8() { genericTest("object*2-7", 10, 13); } public void test9() { String thisIsATest = "Hello world, this is a test"; genericTest("substring(3,length()-2)+' hash='+hashCode()", thisIsATest, "lo world, this is a te hash=" + thisIsATest.hashCode()); }*/ public static void genericTest(String bindingPath, Type expectedType, Object expectedResult) { System.out.println("Evaluate " + bindingPath); - AbstractBinding binding = BINDING_FACTORY.convertFromString(bindingPath); + AbstractBinding binding = BINDING_FACTORY.convertFromString(bindingPath, BINDING_CONTEXT); binding.setBindingDefinition(new BindingDefinition("test", expectedType, BindingDefinitionType.GET, true)); System.out.println("Parsed " + binding + " as " + binding.getClass()); if (!binding.isBindingValid()) { fail(binding.invalidBindingReason()); } Object evaluation = null; try { evaluation = binding.getBindingValue(BINDING_CONTEXT); } catch (TypeMismatchException e) { e.printStackTrace(); fail(); } catch (NullReferenceException e) { e.printStackTrace(); fail(); } System.out.println("Evaluated as " + evaluation); System.out.println("expectedResult = " + expectedResult + " of " + expectedResult.getClass()); System.out.println("evaluation = " + evaluation + " of " + evaluation.getClass()); assertEquals(expectedResult, TypeUtils.castTo(evaluation, expectedType)); /*Object evaluatedResult = null; try { evaluatedResult = BindingEvaluator.evaluateBinding(bindingPath, object); } catch (InvalidKeyValuePropertyException e) { fail(); } catch (TypeMismatchException e) { fail(); } catch (NullReferenceException e) { fail(); } System.out.println("Evaluated as " + evaluatedResult); if (expectedResult instanceof Number) { if (evaluatedResult instanceof Number) { assertEquals(((Number) expectedResult).doubleValue(), ((Number) evaluatedResult).doubleValue()); } else { fail("Evaluated value is not a number (expected: " + expectedResult + ") but " + evaluatedResult); } } else { assertEquals(expectedResult, evaluatedResult); }*/ } public void test1() { genericTest("aString", String.class, "this is a test"); } public void test2() { genericTest("aString.substring(5,7)", String.class, "is"); } public void test3() { genericTest("aString.substring(anInt+3,anInt+7)", String.class, "test"); } public void test4() { genericTest("aString.length", Integer.class, 14); } public void test5() { genericTest("aString.length+aList.size()", Integer.class, 18); } public void test6() { genericTest("aString.length > aList.size()", Boolean.class, true); } public void test7() { genericTest("aString.length > aList.size()", Boolean.TYPE, true); } public void test8() { genericTest("aString == null", Boolean.TYPE, false); } public void test9() { genericTest("aString == ''", Boolean.TYPE, false); } public void test10() { TestBindingContext.aString = ""; genericTest("aString == ''", Boolean.TYPE, true); } public void test11() { TestBindingContext.aString = "foo"; genericTest("aString+((aString != 'foo' ? ('=' + aString) : ''))", String.class, "foo"); TestBindingContext.aString = "foo2"; genericTest("aString+((aString != 'foo' ? ('=' + aString) : ''))", String.class, "foo2=foo2"); } public void test12() { TestBindingContext.aString = ""; genericTest("anInt > 2 ? 'anInt > 2' : 'anInt<=2' ", String.class, "anInt > 2"); } public void test13() { genericTest("aString != null", Boolean.TYPE, true); } }
true
true
public static void genericTest(String bindingPath, Type expectedType, Object expectedResult) { System.out.println("Evaluate " + bindingPath); AbstractBinding binding = BINDING_FACTORY.convertFromString(bindingPath); binding.setBindingDefinition(new BindingDefinition("test", expectedType, BindingDefinitionType.GET, true)); System.out.println("Parsed " + binding + " as " + binding.getClass()); if (!binding.isBindingValid()) { fail(binding.invalidBindingReason()); } Object evaluation = null; try { evaluation = binding.getBindingValue(BINDING_CONTEXT); } catch (TypeMismatchException e) { e.printStackTrace(); fail(); } catch (NullReferenceException e) { e.printStackTrace(); fail(); } System.out.println("Evaluated as " + evaluation); System.out.println("expectedResult = " + expectedResult + " of " + expectedResult.getClass()); System.out.println("evaluation = " + evaluation + " of " + evaluation.getClass()); assertEquals(expectedResult, TypeUtils.castTo(evaluation, expectedType)); /*Object evaluatedResult = null; try { evaluatedResult = BindingEvaluator.evaluateBinding(bindingPath, object); } catch (InvalidKeyValuePropertyException e) { fail(); } catch (TypeMismatchException e) { fail(); } catch (NullReferenceException e) { fail(); } System.out.println("Evaluated as " + evaluatedResult); if (expectedResult instanceof Number) { if (evaluatedResult instanceof Number) { assertEquals(((Number) expectedResult).doubleValue(), ((Number) evaluatedResult).doubleValue()); } else { fail("Evaluated value is not a number (expected: " + expectedResult + ") but " + evaluatedResult); } } else { assertEquals(expectedResult, evaluatedResult); }*/ }
public static void genericTest(String bindingPath, Type expectedType, Object expectedResult) { System.out.println("Evaluate " + bindingPath); AbstractBinding binding = BINDING_FACTORY.convertFromString(bindingPath, BINDING_CONTEXT); binding.setBindingDefinition(new BindingDefinition("test", expectedType, BindingDefinitionType.GET, true)); System.out.println("Parsed " + binding + " as " + binding.getClass()); if (!binding.isBindingValid()) { fail(binding.invalidBindingReason()); } Object evaluation = null; try { evaluation = binding.getBindingValue(BINDING_CONTEXT); } catch (TypeMismatchException e) { e.printStackTrace(); fail(); } catch (NullReferenceException e) { e.printStackTrace(); fail(); } System.out.println("Evaluated as " + evaluation); System.out.println("expectedResult = " + expectedResult + " of " + expectedResult.getClass()); System.out.println("evaluation = " + evaluation + " of " + evaluation.getClass()); assertEquals(expectedResult, TypeUtils.castTo(evaluation, expectedType)); /*Object evaluatedResult = null; try { evaluatedResult = BindingEvaluator.evaluateBinding(bindingPath, object); } catch (InvalidKeyValuePropertyException e) { fail(); } catch (TypeMismatchException e) { fail(); } catch (NullReferenceException e) { fail(); } System.out.println("Evaluated as " + evaluatedResult); if (expectedResult instanceof Number) { if (evaluatedResult instanceof Number) { assertEquals(((Number) expectedResult).doubleValue(), ((Number) evaluatedResult).doubleValue()); } else { fail("Evaluated value is not a number (expected: " + expectedResult + ") but " + evaluatedResult); } } else { assertEquals(expectedResult, evaluatedResult); }*/ }
diff --git a/jetty-http/src/main/java/org/eclipse/jetty/http/AbstractGenerator.java b/jetty-http/src/main/java/org/eclipse/jetty/http/AbstractGenerator.java index 15d680df0..7d42a27d7 100644 --- a/jetty-http/src/main/java/org/eclipse/jetty/http/AbstractGenerator.java +++ b/jetty-http/src/main/java/org/eclipse/jetty/http/AbstractGenerator.java @@ -1,498 +1,498 @@ // ======================================================================== // Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.http; import java.io.IOException; import org.eclipse.jetty.io.Buffer; import org.eclipse.jetty.io.Buffers; import org.eclipse.jetty.io.ByteArrayBuffer; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.io.EofException; import org.eclipse.jetty.io.View; import org.eclipse.jetty.util.log.Log; /* ------------------------------------------------------------ */ /** * Abstract Generator. Builds HTTP Messages. * * Currently this class uses a system parameter "jetty.direct.writers" to control * two optional writer to byte conversions. buffer.writers=true will probably be * faster, but will consume more memory. This option is just for testing and tuning. * * * */ public abstract class AbstractGenerator implements Generator { // states public final static int STATE_HEADER = 0; public final static int STATE_CONTENT = 2; public final static int STATE_FLUSHING = 3; public final static int STATE_END = 4; public static final byte[] NO_BYTES = {}; // data protected final Buffers _buffers; // source of buffers protected final EndPoint _endp; protected int _state = STATE_HEADER; protected int _status = 0; protected int _version = HttpVersions.HTTP_1_1_ORDINAL; protected Buffer _reason; protected Buffer _method; protected String _uri; protected long _contentWritten = 0; protected long _contentLength = HttpTokens.UNKNOWN_CONTENT; protected boolean _last = false; protected boolean _head = false; protected boolean _noContent = false; protected Boolean _persistent = null; protected Buffer _header; // Buffer for HTTP header (and maybe small _content) protected Buffer _buffer; // Buffer for copy of passed _content protected Buffer _content; // Buffer passed to addContent protected Buffer _date; private boolean _sendServerVersion; /* ------------------------------------------------------------------------------- */ /** * Constructor. * * @param buffers buffer pool * @param headerBufferSize Size of the buffer to allocate for HTTP header * @param contentBufferSize Size of the buffer to allocate for HTTP content */ public AbstractGenerator(Buffers buffers, EndPoint io) { this._buffers = buffers; this._endp = io; } /* ------------------------------------------------------------------------------- */ public abstract boolean isRequest(); /* ------------------------------------------------------------------------------- */ public abstract boolean isResponse(); /* ------------------------------------------------------------------------------- */ public boolean isOpen() { return _endp.isOpen(); } /* ------------------------------------------------------------------------------- */ public void reset(boolean returnBuffers) { _state = STATE_HEADER; _status = 0; _version = HttpVersions.HTTP_1_1_ORDINAL; _reason = null; _last = false; _head = false; _noContent=false; - _persistent = true; + _persistent = null; _contentWritten = 0; _contentLength = HttpTokens.UNKNOWN_CONTENT; _date = null; // always return the buffer if (_buffer!=null) _buffers.returnBuffer(_buffer); _buffer=null; if (returnBuffers) { if (_header!=null) _buffers.returnBuffer(_header); _header=null; } else if (_header != null) _header.clear(); _content = null; _method=null; } /* ------------------------------------------------------------------------------- */ public void resetBuffer() { if(_state>=STATE_FLUSHING) throw new IllegalStateException("Flushed"); _last = false; _persistent=null; _contentWritten = 0; _contentLength = HttpTokens.UNKNOWN_CONTENT; _content=null; if (_buffer!=null) _buffer.clear(); } /* ------------------------------------------------------------ */ /** * @return Returns the contentBufferSize. */ public int getContentBufferSize() { if (_buffer==null) _buffer=_buffers.getBuffer(); return _buffer.capacity(); } /* ------------------------------------------------------------ */ /** * @param contentBufferSize The contentBufferSize to set. */ public void increaseContentBufferSize(int contentBufferSize) { if (_buffer==null) _buffer=_buffers.getBuffer(); if (contentBufferSize > _buffer.capacity()) { Buffer nb = _buffers.getBuffer(contentBufferSize); nb.put(_buffer); _buffers.returnBuffer(_buffer); _buffer = nb; } } /* ------------------------------------------------------------ */ public Buffer getUncheckedBuffer() { return _buffer; } /* ------------------------------------------------------------ */ public boolean getSendServerVersion () { return _sendServerVersion; } /* ------------------------------------------------------------ */ public void setSendServerVersion (boolean sendServerVersion) { _sendServerVersion = sendServerVersion; } /* ------------------------------------------------------------ */ public int getState() { return _state; } /* ------------------------------------------------------------ */ public boolean isState(int state) { return _state == state; } /* ------------------------------------------------------------ */ public boolean isComplete() { return _state == STATE_END; } /* ------------------------------------------------------------ */ public boolean isIdle() { return _state == STATE_HEADER && _method==null && _status==0; } /* ------------------------------------------------------------ */ public boolean isCommitted() { return _state != STATE_HEADER; } /* ------------------------------------------------------------ */ /** * @return Returns the head. */ public boolean isHead() { return _head; } /* ------------------------------------------------------------ */ public void setContentLength(long value) { if (value<0) _contentLength=HttpTokens.UNKNOWN_CONTENT; else _contentLength=value; } /* ------------------------------------------------------------ */ /** * @param head The head to set. */ public void setHead(boolean head) { _head = head; } /* ------------------------------------------------------------ */ /** * @return <code>false</code> if the connection should be closed after a request has been read, * <code>true</code> if it should be used for additional requests. */ public boolean isPersistent() { return _persistent!=null ?_persistent.booleanValue() :(isRequest()?true:_version>HttpVersions.HTTP_1_0_ORDINAL); } /* ------------------------------------------------------------ */ public void setPersistent(boolean persistent) { _persistent=persistent; } /* ------------------------------------------------------------ */ /** * @param version The version of the client the response is being sent to (NB. Not the version * in the response, which is the version of the server). */ public void setVersion(int version) { if (_state != STATE_HEADER) throw new IllegalStateException("STATE!=START "+_state); _version = version; if (_version==HttpVersions.HTTP_0_9_ORDINAL && _method!=null) _noContent=true; } /* ------------------------------------------------------------ */ public int getVersion() { return _version; } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.http.Generator#setDate(org.eclipse.jetty.io.Buffer) */ public void setDate(Buffer timeStampBuffer) { _date=timeStampBuffer; } /* ------------------------------------------------------------ */ /** */ public void setRequest(String method, String uri) { if (method==null || HttpMethods.GET.equals(method) ) _method=HttpMethods.GET_BUFFER; else _method=HttpMethods.CACHE.lookup(method); _uri=uri; if (_version==HttpVersions.HTTP_0_9_ORDINAL) _noContent=true; } /* ------------------------------------------------------------ */ /** * @param status The status code to send. * @param reason the status message to send. */ public void setResponse(int status, String reason) { if (_state != STATE_HEADER) throw new IllegalStateException("STATE!=START"); _method=null; _status = status; if (reason!=null) { int len=reason.length(); // TODO don't hard code if (len>1024) len=1024; _reason=new ByteArrayBuffer(len); for (int i=0;i<len;i++) { char ch = reason.charAt(i); if (ch!='\r'&&ch!='\n') _reason.put((byte)ch); else _reason.put((byte)' '); } } } /* ------------------------------------------------------------ */ /** Prepare buffer for unchecked writes. * Prepare the generator buffer to receive unchecked writes * @return the available space in the buffer. * @throws IOException */ public abstract int prepareUncheckedAddContent() throws IOException; /* ------------------------------------------------------------ */ void uncheckedAddContent(int b) { _buffer.put((byte)b); } /* ------------------------------------------------------------ */ public void completeUncheckedAddContent() { if (_noContent) { if(_buffer!=null) _buffer.clear(); } else { _contentWritten+=_buffer.length(); if (_head) _buffer.clear(); } } /* ------------------------------------------------------------ */ public boolean isBufferFull() { if (_buffer != null && _buffer.space()==0) { if (_buffer.length()==0 && !_buffer.isImmutable()) _buffer.compact(); return _buffer.space()==0; } return _content!=null && _content.length()>0; } /* ------------------------------------------------------------ */ public boolean isContentWritten() { return _contentLength>=0 && _contentWritten>=_contentLength; } /* ------------------------------------------------------------ */ public abstract void completeHeader(HttpFields fields, boolean allContentAdded) throws IOException; /* ------------------------------------------------------------ */ /** * Complete the message. * * @throws IOException */ public void complete() throws IOException { if (_state == STATE_HEADER) { throw new IllegalStateException("State==HEADER"); } if (_contentLength >= 0 && _contentLength != _contentWritten && !_head) { if (Log.isDebugEnabled()) Log.debug("ContentLength written=="+_contentWritten+" != contentLength=="+_contentLength); _persistent = false; } } /* ------------------------------------------------------------ */ public abstract long flushBuffer() throws IOException; /* ------------------------------------------------------------ */ public void flush(long maxIdleTime) throws IOException { // block until everything is flushed Buffer content = _content; Buffer buffer = _buffer; if (content!=null && content.length()>0 || buffer!=null && buffer.length()>0 || isBufferFull()) { flushBuffer(); while ((content!=null && content.length()>0 ||buffer!=null && buffer.length()>0) && _endp.isOpen()) blockForOutput(maxIdleTime); } } /* ------------------------------------------------------------ */ /** * Utility method to send an error response. If the builder is not committed, this call is * equivalent to a setResponse, addcontent and complete call. * * @param code * @param reason * @param content * @param close * @throws IOException */ public void sendError(int code, String reason, String content, boolean close) throws IOException { if (!isCommitted()) { setResponse(code, reason); if (close) _persistent=false; completeHeader(null, false); if (content != null) addContent(new View(new ByteArrayBuffer(content)), Generator.LAST); complete(); } } /* ------------------------------------------------------------ */ /** * @return Returns the contentWritten. */ public long getContentWritten() { return _contentWritten; } /* ------------------------------------------------------------ */ public void blockForOutput(long maxIdleTime) throws IOException { if (_endp.isBlocking()) { try { flushBuffer(); } catch(IOException e) { _endp.close(); throw e; } } else { if (!_endp.blockWritable(maxIdleTime)) { _endp.close(); throw new EofException("timeout"); } flushBuffer(); } } }
true
true
public void reset(boolean returnBuffers) { _state = STATE_HEADER; _status = 0; _version = HttpVersions.HTTP_1_1_ORDINAL; _reason = null; _last = false; _head = false; _noContent=false; _persistent = true; _contentWritten = 0; _contentLength = HttpTokens.UNKNOWN_CONTENT; _date = null; // always return the buffer if (_buffer!=null) _buffers.returnBuffer(_buffer); _buffer=null; if (returnBuffers) { if (_header!=null) _buffers.returnBuffer(_header); _header=null; } else if (_header != null) _header.clear(); _content = null; _method=null; }
public void reset(boolean returnBuffers) { _state = STATE_HEADER; _status = 0; _version = HttpVersions.HTTP_1_1_ORDINAL; _reason = null; _last = false; _head = false; _noContent=false; _persistent = null; _contentWritten = 0; _contentLength = HttpTokens.UNKNOWN_CONTENT; _date = null; // always return the buffer if (_buffer!=null) _buffers.returnBuffer(_buffer); _buffer=null; if (returnBuffers) { if (_header!=null) _buffers.returnBuffer(_header); _header=null; } else if (_header != null) _header.clear(); _content = null; _method=null; }
diff --git a/enabler/src/com/openxc/enabler/preferences/NetworkSourcePreferenceManager.java b/enabler/src/com/openxc/enabler/preferences/NetworkSourcePreferenceManager.java index 79b2cfa3..f71b8498 100644 --- a/enabler/src/com/openxc/enabler/preferences/NetworkSourcePreferenceManager.java +++ b/enabler/src/com/openxc/enabler/preferences/NetworkSourcePreferenceManager.java @@ -1,101 +1,98 @@ package com.openxc.enabler.preferences; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import android.widget.Toast; import com.openxc.enabler.R; import com.openxc.sources.DataSourceException; import com.openxc.sources.network.NetworkVehicleDataSource; public class NetworkSourcePreferenceManager extends VehiclePreferenceManager { private NetworkVehicleDataSource mNetworkSource; private final static String TAG = "NetworkSourcePreferenceManager"; public NetworkSourcePreferenceManager(Context context) { super(context); } protected PreferenceListener createPreferenceListener( SharedPreferences preferences) { return new NetworkSourcePreferenceListener(preferences); } /** * Enable or disable receiving vehicle data from a Network device * * @param enabled * true if network should be enabled */ private void setNetworkSourceStatus(boolean enabled) { Log.i(TAG, "Setting network data source to " + enabled); if(enabled) { String address = getPreferenceString(R.string.network_host_key); if(!NetworkVehicleDataSource.validateAddress(address)) { String error = "Network host address (" + address + ") not valid -- not starting network data source"; Log.w(TAG, error); Toast.makeText(getContext(), error, Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getPreferences().edit(); editor.putBoolean(getString(R.string.uploading_checkbox_key), false); editor.commit(); - } else if(address != null) { + } else { if(mNetworkSource == null || !mNetworkSource.getAddress().equals(address)) { stopNetwork(); try { mNetworkSource = new NetworkVehicleDataSource(address, getContext()); } catch (DataSourceException e) { Log.w(TAG, "Unable to add network source", e); return; } getVehicleManager().addSource(mNetworkSource); } else { Log.d(TAG, "Network connection to address " + address + " already running"); } - } else { - Log.d(TAG, "No network host address set yet (" + address + - "), not starting source"); } } else { stopNetwork(); } } public void close() { super.close(); stopNetwork(); } private void stopNetwork() { getVehicleManager().removeSource(mNetworkSource); mNetworkSource = null; } private class NetworkSourcePreferenceListener extends PreferenceListener { public NetworkSourcePreferenceListener(SharedPreferences preferences) { super(preferences); } public void readStoredPreferences() { onSharedPreferenceChanged(mPreferences, getString(R.string.network_checkbox_key)); } public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { if(key.equals(getString(R.string.network_checkbox_key)) || key.equals(getString(R.string.network_host_key))) { setNetworkSourceStatus(preferences.getBoolean(getString( R.string.network_checkbox_key), false)); } } } }
false
true
private void setNetworkSourceStatus(boolean enabled) { Log.i(TAG, "Setting network data source to " + enabled); if(enabled) { String address = getPreferenceString(R.string.network_host_key); if(!NetworkVehicleDataSource.validateAddress(address)) { String error = "Network host address (" + address + ") not valid -- not starting network data source"; Log.w(TAG, error); Toast.makeText(getContext(), error, Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getPreferences().edit(); editor.putBoolean(getString(R.string.uploading_checkbox_key), false); editor.commit(); } else if(address != null) { if(mNetworkSource == null || !mNetworkSource.getAddress().equals(address)) { stopNetwork(); try { mNetworkSource = new NetworkVehicleDataSource(address, getContext()); } catch (DataSourceException e) { Log.w(TAG, "Unable to add network source", e); return; } getVehicleManager().addSource(mNetworkSource); } else { Log.d(TAG, "Network connection to address " + address + " already running"); } } else { Log.d(TAG, "No network host address set yet (" + address + "), not starting source"); } } else { stopNetwork(); } }
private void setNetworkSourceStatus(boolean enabled) { Log.i(TAG, "Setting network data source to " + enabled); if(enabled) { String address = getPreferenceString(R.string.network_host_key); if(!NetworkVehicleDataSource.validateAddress(address)) { String error = "Network host address (" + address + ") not valid -- not starting network data source"; Log.w(TAG, error); Toast.makeText(getContext(), error, Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getPreferences().edit(); editor.putBoolean(getString(R.string.uploading_checkbox_key), false); editor.commit(); } else { if(mNetworkSource == null || !mNetworkSource.getAddress().equals(address)) { stopNetwork(); try { mNetworkSource = new NetworkVehicleDataSource(address, getContext()); } catch (DataSourceException e) { Log.w(TAG, "Unable to add network source", e); return; } getVehicleManager().addSource(mNetworkSource); } else { Log.d(TAG, "Network connection to address " + address + " already running"); } } } else { stopNetwork(); } }
diff --git a/src/main/java/org/sandag/abm/accessibilities/SkimsAppender.java b/src/main/java/org/sandag/abm/accessibilities/SkimsAppender.java index 266aa84f..187e3a38 100644 --- a/src/main/java/org/sandag/abm/accessibilities/SkimsAppender.java +++ b/src/main/java/org/sandag/abm/accessibilities/SkimsAppender.java @@ -1,788 +1,788 @@ package org.sandag.abm.accessibilities; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.ResourceBundle; import org.apache.log4j.Logger; import org.sandag.abm.ctramp.MatrixDataServer; import org.sandag.abm.ctramp.MatrixDataServerRmi; import org.sandag.abm.ctramp.McLogsumsCalculator; import org.sandag.abm.ctramp.Util; import org.sandag.abm.modechoice.MgraDataManager; import org.sandag.abm.modechoice.Modes; import org.sandag.abm.modechoice.TapDataManager; import org.sandag.abm.modechoice.TazDataManager; import com.pb.common.calculator.MatrixDataManager; import com.pb.common.calculator.MatrixDataServerIf; import com.pb.common.datafile.OLD_CSVFileReader; import com.pb.common.datafile.TableDataSet; import com.pb.common.util.ResourceUtil; public final class SkimsAppender { protected transient Logger logger = Logger.getLogger(SkimsAppender.class); private static final String OBS_DATA_RECORDS_FILE_KEY = "onBoard.survey.file"; private static final String HIS_DATA_RECORDS_FILE_KEY = "homeInterview.survey.file"; private static final int OBS_UNIQUE_ID = 1; private static final int OBS_ORIG_MGRA = 78; private static final int OBS_DEST_MGRA = 79; // used for trip file: private static final int OBS_OUT_TOUR_PERIOD = 133; private static final int OBS_IN_TOUR_PERIOD = 134; // used for tour file: // private static final int OBS_DEPART_PERIOD = 132; // private static final int OBS_ARRIVE_PERIOD = 133; /* * for home based tour mode choice estimation files private static final int * HIS_ORIG_MGRA = 72; private static final int HIS_DEST_MGRA = 75; private * static final int HIS_DEPART_PERIOD = 185; private static final int * HIS_ARRIVE_PERIOD = 186; */ /* * for work based tour mode choice estimation files */ private static final int HIS_ORIG_MGRA = 76; private static final int HIS_DEST_MGRA = 84; private static final int HIS_DEPART_PERIOD = 159; private static final int HIS_ARRIVE_PERIOD = 160; // survey periods are: 0=not used, 1=03:00-05:59, 2=06:00-08:59, // 3=09:00-11:59, // 4=12:00-15:29, 5=15:30-18:59, 6=19:00-02:59 // skim periods are: 0=0(N/A), 1=3(OP), 2=1(AM), 3=3(OP), 4=3(OP), 5=2(PM), // 6=3(OP) // define a conversion array to convert period values in the survey file to // skim // period indices used in this propgram: 1=am peak, 2=pm peak, // 3=off-peak. private static final String[] SKIM_PERIOD_LABELS = {"am", "pm", "op"}; private static final int[] SURVEY_PERIOD_TO_SKIM_PERIOD = {0, 3, 1, 3, 3, 2, 3}; private MatrixDataServerIf ms; private BestTransitPathCalculator bestPathUEC; private SkimsAppender() { } private void runSkimsAppender(ResourceBundle rb) { HashMap<String, String> rbMap = ResourceUtil.changeResourceBundleIntoHashMap(rb); // instantiate these objects right away TazDataManager tazs = TazDataManager.getInstance(rbMap); MgraDataManager mgraManager = MgraDataManager.getInstance(rbMap); TapDataManager tapManager = TapDataManager.getInstance(rbMap); AutoAndNonMotorizedSkimsCalculator anm = null; WalkTransitWalkSkimsCalculator wtw = null; WalkTransitDriveSkimsCalculator wtd = null; DriveTransitWalkSkimsCalculator dtw = null; Logger autoLogger = Logger.getLogger("auto"); Logger wtwLogger = Logger.getLogger("wtw"); Logger wtdLogger = Logger.getLogger("wtd"); Logger dtwLogger = Logger.getLogger("dtw"); String outputFileNameObs = Util.getStringValueFromPropertyMap(rbMap, "obs.skims.output.file"); String outputFileNameHis = Util.getStringValueFromPropertyMap(rbMap, "his.skims.output.file"); FileWriter writer; PrintWriter outStreamObs = null; PrintWriter outStreamHis = null; PrintWriter[] outStreamObsTod = new PrintWriter[SKIM_PERIOD_LABELS.length]; PrintWriter[] outStreamHisTod = new PrintWriter[SKIM_PERIOD_LABELS.length]; - if (outputFileNameObs != "" || outputFileNameHis != "") + if (!outputFileNameObs.isEmpty() || !outputFileNameHis.isEmpty()) { anm = new AutoAndNonMotorizedSkimsCalculator(rbMap); McLogsumsCalculator logsumHelper = new McLogsumsCalculator(); bestPathUEC = logsumHelper.getBestTransitPathCalculator(); wtw = new WalkTransitWalkSkimsCalculator(); wtw.setup(rbMap, wtwLogger, bestPathUEC); wtd = new WalkTransitDriveSkimsCalculator(); wtd.setup(rbMap, wtdLogger, bestPathUEC); dtw = new DriveTransitWalkSkimsCalculator(); dtw.setup(rbMap, dtwLogger, bestPathUEC); String heading = "Seq,Id"; heading += ",obOrigMgra,obDestMgra,obPeriod"; heading += getAutoSkimsHeaderRecord("auto", anm.getAutoSkimNames()); heading += getNonMotorizedSkimsHeaderRecord("nm", anm.getNmSkimNames()); heading += getTransitSkimsHeaderRecord("wtw", wtw.getLocalSkimNames(), wtw.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("wtd", wtd.getLocalSkimNames(), wtd.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("dtw", dtw.getLocalSkimNames(), dtw.getPremiumSkimNames()); heading += ",ObsSeq,Id,ibOrigMgra,ibDestMgra,ibPeriod"; heading += getAutoSkimsHeaderRecord("auto", anm.getAutoSkimNames()); heading += getNonMotorizedSkimsHeaderRecord("nm", anm.getNmSkimNames()); heading += getTransitSkimsHeaderRecord("wtw", wtw.getLocalSkimNames(), wtw.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("wtd", wtd.getLocalSkimNames(), wtd.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("dtw", dtw.getLocalSkimNames(), dtw.getPremiumSkimNames()); - if (outputFileNameObs != "") + if (!outputFileNameObs.isEmpty()) { try { // create an output stream for the mode choice estimation // file // with // observed TOD writer = new FileWriter(new File(outputFileNameObs)); outStreamObs = new PrintWriter(new BufferedWriter(writer)); // create an array of similar files, 1 for each TOD period, // for // TOD // choice estimation for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { int dotIndex = outputFileNameObs.lastIndexOf('.'); String newName = outputFileNameObs.substring(0, dotIndex) + "_" + SKIM_PERIOD_LABELS[i] + outputFileNameObs.substring(dotIndex); writer = new FileWriter(new File(newName)); outStreamObsTod[i] = new PrintWriter(new BufferedWriter(writer)); } } catch (IOException e) { logger.fatal(String.format("Exception occurred opening output skims file: %s.", outputFileNameObs)); throw new RuntimeException(e); } outStreamObs.println("obs" + heading); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].println("obs" + heading); } - if (outputFileNameHis != "") + if (!outputFileNameHis.isEmpty()) { try { writer = new FileWriter(new File(outputFileNameHis)); outStreamHis = new PrintWriter(new BufferedWriter(writer)); // create an array of similar files, 1 for each TOD period, // for // TOD // choice estimation for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { int dotIndex = outputFileNameHis.lastIndexOf('.'); String newName = outputFileNameHis.substring(0, dotIndex) + "_" + SKIM_PERIOD_LABELS[i] + outputFileNameHis.substring(dotIndex); writer = new FileWriter(new File(newName)); outStreamHisTod[i] = new PrintWriter(new BufferedWriter(writer)); } } catch (IOException e) { logger.fatal(String.format("Exception occurred opening output skims file: %s.", outputFileNameHis)); throw new RuntimeException(e); } outStreamHis.println("his" + heading); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].println("his" + heading); } } Logger[] loggers = new Logger[4]; loggers[0] = autoLogger; loggers[1] = autoLogger; loggers[2] = wtdLogger; loggers[3] = dtwLogger; int[] odt = new int[5]; - if (outputFileNameObs != "") + if (!outputFileNameObs.isEmpty()) { TableDataSet obsTds = getOnBoardSurveyTableDataSet(rbMap); int[][] obsOdts = getOnBoardSurveyOrigDestTimes(obsTds); // write skims data for on-board survey records int seq = 1; for (int[] obsOdt : obsOdts) { // write outbound direction odt[0] = obsOdt[0]; // orig odt[1] = obsOdt[1]; // dest odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[obsOdt[2]]; // depart skim // period odt[3] = obsOdt[3]; odt[4] = obsOdt[4]; if (odt[0] == 0 || odt[1] == 0) { outStreamObs.println(String.format("%d,%d,%d,%d,%d", seq, odt[4], odt[0], odt[1], odt[2])); seq++; continue; } // index // for debugging a specific mgra pair // odt[0] = 25646; // odt[1] = 4319; // odt[2] = 1; boolean debugFlag = false; if (odt[0] == 25646 && odt[1] == 4319) debugFlag = true; writeSkimsToFile(seq, outStreamObs, debugFlag, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamObsTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } // write inbound direction odt[0] = obsOdt[1]; // dest odt[1] = obsOdt[0]; // orig odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[obsOdt[3]]; // arrival // skim // period // index outStreamObs.print(","); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].print(","); writeSkimsToFile(seq, outStreamObs, debugFlag, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamObsTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } if (outStreamObs != null) { outStreamObs.println(""); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].println(""); } if (seq % 1000 == 0) logger.info("wrote OBS record: " + seq); seq++; } if (outStreamObs != null) { outStreamObs.close(); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].close(); } } - if (outputFileNameHis != "") + if (!outputFileNameHis.isEmpty()) { TableDataSet hisTds = getHomeInterviewSurveyTableDataSet(rbMap); int[][] hisOdts = getHomeInterviewSurveyOrigDestTimes(hisTds); // write skims data for home interview survey records int seq = 1; for (int[] hisOdt : hisOdts) { // write outbound direction odt[0] = hisOdt[0]; // orig odt[1] = hisOdt[1]; // dest odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[hisOdt[2]]; // depart skim // period // index writeSkimsToFile(seq, outStreamHis, false, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamHisTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } // write inbound direction odt[0] = hisOdt[1]; // dest odt[1] = hisOdt[0]; // orig odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[hisOdt[3]]; // arrival // skim // period // index outStreamHis.print(","); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].print(","); writeSkimsToFile(seq, outStreamHis, false, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamHisTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } if (outStreamHis != null) { outStreamHis.println(""); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].println(""); } if (seq % 1000 == 0) logger.info("wrote HIS record: " + seq); seq++; } if (outStreamHis != null) { outStreamHis.close(); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].close(); } } } private void writeSkimsToFile(int sequence, PrintWriter outStream, boolean loggingEnabled, int[] odt, AutoAndNonMotorizedSkimsCalculator anm, WalkTransitWalkSkimsCalculator wtw, WalkTransitDriveSkimsCalculator wtd, DriveTransitWalkSkimsCalculator dtw, Logger[] loggers) { Logger autoLogger = loggers[0]; Logger wtwLogger = loggers[1]; Logger wtdLogger = loggers[2]; Logger dtwLogger = loggers[3]; int[][] bestTapPairs = null; double[][] returnedSkims = null; if (outStream != null) outStream.print(String.format("%d,%d,%d,%d,%d", sequence, odt[4], odt[0], odt[1], odt[2])); double[] skims = anm.getAutoSkims(odt[0], odt[1], odt[2], loggingEnabled, autoLogger); if (loggingEnabled) anm.logReturnedSkims(odt[0], odt[1], odt[2], skims, "auto", autoLogger); if (outStream != null) { String autoRecord = getAutoSkimsRecord(skims); outStream.print(autoRecord); } skims = anm.getNonMotorizedSkims(odt[0], odt[1], odt[2], loggingEnabled, autoLogger); if (loggingEnabled) anm.logReturnedSkims(odt[0], odt[1], odt[2], skims, "non-motorized", autoLogger); if (outStream != null) { String nmRecord = getAutoSkimsRecord(skims); outStream.print(nmRecord); } bestTapPairs = wtw.getBestTapPairs(odt[0], odt[1], odt[2], loggingEnabled, wtwLogger); returnedSkims = new double[bestTapPairs.length][]; for (int i = 0; i < bestTapPairs.length; i++) { if (bestTapPairs[i] == null) returnedSkims[i] = wtw.getNullTransitSkims(i); else { returnedSkims[i] = wtw.getWalkTransitWalkSkims(i, bestPathUEC.getBestAccessTime(i), bestPathUEC.getBestEgressTime(i), bestTapPairs[i][0], bestTapPairs[i][1], odt[2], loggingEnabled); } } if (loggingEnabled) wtw.logReturnedSkims(odt, bestTapPairs, returnedSkims); if (outStream != null) { String wtwRecord = getTransitSkimsRecord(odt, returnedSkims); outStream.print(wtwRecord); } bestTapPairs = wtd.getBestTapPairs(odt[0], odt[1], odt[2], loggingEnabled, wtdLogger); returnedSkims = new double[bestTapPairs.length][]; for (int i = 0; i < bestTapPairs.length; i++) { if (bestTapPairs[i] == null) returnedSkims[i] = wtd.getNullTransitSkims(i); else { returnedSkims[i] = wtd.getWalkTransitDriveSkims(i, bestPathUEC.getBestAccessTime(i), bestPathUEC.getBestEgressTime(i), bestTapPairs[i][0], bestTapPairs[i][1], odt[2], loggingEnabled); } } if (loggingEnabled) wtd.logReturnedSkims(odt, bestTapPairs, returnedSkims); if (outStream != null) { String wtdRecord = getTransitSkimsRecord(odt, returnedSkims); outStream.print(wtdRecord); } bestTapPairs = dtw.getBestTapPairs(odt[0], odt[1], odt[2], loggingEnabled, dtwLogger); returnedSkims = new double[bestTapPairs.length][]; for (int i = 0; i < bestTapPairs.length; i++) { if (bestTapPairs[i] == null) returnedSkims[i] = dtw.getNullTransitSkims(i); else { returnedSkims[i] = dtw.getDriveTransitWalkSkims(i, bestPathUEC.getBestAccessTime(i), bestPathUEC.getBestEgressTime(i), bestTapPairs[i][0], bestTapPairs[i][1], odt[2], loggingEnabled); } } if (loggingEnabled) dtw.logReturnedSkims(odt, bestTapPairs, returnedSkims); if (outStream != null) { String dtwRecord = getTransitSkimsRecord(odt, returnedSkims); outStream.print(dtwRecord); } } /** * Start the matrix server * * @param rb * is a ResourceBundle for the properties file for this * application */ private void startMatrixServer(ResourceBundle rb) { logger.info(""); logger.info(""); String serverAddress = rb.getString("RunModel.MatrixServerAddress"); int serverPort = new Integer(rb.getString("RunModel.MatrixServerPort")); logger.info("connecting to matrix server " + serverAddress + ":" + serverPort); try { MatrixDataManager mdm = MatrixDataManager.getInstance(); ms = new MatrixDataServerRmi(serverAddress, serverPort, MatrixDataServer.MATRIX_DATA_SERVER_NAME); ms.testRemote(Thread.currentThread().getName()); mdm.setMatrixDataServerObject(ms); } catch (Exception e) { logger.error( String.format("exception caught running ctramp model components -- exiting."), e); throw new RuntimeException(); } } /** * create a String which can be written to an output file with all the skim * values for the orig/dest/period. * * @param odt * is an int[] with the first element the origin mgra and the * second element the dest mgra and third element the departure * period index * @param skims * is a double[][] of skim values with the first dimesion the * ride mode indices and second dimention the skim categories */ private String getTransitSkimsRecord(int[] odt, double[][] skims) { int nrows = skims.length; int ncols = 0; for (int i = 0; i < nrows; i++) if (skims[i].length > ncols) ncols = skims[i].length; String tableRecord = ""; for (int i = 0; i < skims.length; i++) { for (int j = 0; j < skims[i].length; j++) tableRecord += String.format(",%.5f", skims[i][j]); } return tableRecord; } /** * create a String which can be written to an output file with all the skim * values for the orig/dest/period. * * @param odt * is an int[] with the first element the origin mgra and the * second element the dest mgra and third element the departure * period index * @param skims * is a double[] of skim values */ private String getAutoSkimsRecord(double[] skims) { String tableRecord = ""; for (int i = 0; i < skims.length; i++) { tableRecord += String.format(",%.5f", skims[i]); } return tableRecord; } /** * create a String for the output file header record which can be written to * an output file with all the skim value namess for the orig/dest/period. * * @param odt * is an int[] with the first element the origin mgra and the * second element the dest mgra and third element the departure * period index */ private String getTransitSkimsHeaderRecord(String transitServiveLabel, String[] localNames, String[] premiumNames) { Modes.TransitMode[] mode = Modes.TransitMode.values(); String heading = ""; for (int i = 0; i < mode.length; i++) { if (mode[i].isPremiumMode(mode[i])) { for (int j = 0; j < premiumNames.length; j++) heading += String.format(",%s_%s_%s", transitServiveLabel, mode[i], premiumNames[j]); } else { for (int j = 0; j < localNames.length; j++) heading += String.format(",%s_%s_%s", transitServiveLabel, mode[i], localNames[j]); } } return heading; } /** * create a String for the output file header record which can be written to * an output file with all the skim value namess for the orig/dest/period. * * @param odt * is an int[] with the first element the origin mgra and the * second element the dest mgra and third element the departure * period index */ private String getAutoSkimsHeaderRecord(String label, String[] names) { String heading = ""; for (int i = 0; i < names.length; i++) heading += String.format(",%s_%s", label, names[i]); return heading; } /** * create a String for the output file header record which can be written to * an output file with all the skim value namess for the orig/dest/period. * * @param odt * is an int[] with the first element the origin mgra and the * second element the dest mgra and third element the departure * period index */ private String getNonMotorizedSkimsHeaderRecord(String label, String[] names) { String heading = ""; for (int i = 0; i < names.length; i++) heading += String.format(",%s_%s", label, names[i]); return heading; } private TableDataSet getOnBoardSurveyTableDataSet(HashMap<String, String> rbMap) { String obsFileName = Util.getStringValueFromPropertyMap(rbMap, OBS_DATA_RECORDS_FILE_KEY); if (obsFileName == null) { logger.error("Error getting the filename from the properties file for the Sandag on-board survey data records file."); logger.error("Properties file target: " + OBS_DATA_RECORDS_FILE_KEY + " not found."); logger.error("Please specify a filename value for the " + OBS_DATA_RECORDS_FILE_KEY + " property."); throw new RuntimeException(); } try { TableDataSet inTds = null; OLD_CSVFileReader reader = new OLD_CSVFileReader(); reader.setDelimSet("," + reader.getDelimSet()); inTds = reader.readFile(new File(obsFileName)); return inTds; } catch (Exception e) { logger.fatal(String .format("Exception occurred reading Sandag on-board survey data records file: %s into TableDataSet object.", obsFileName)); throw new RuntimeException(e); } } private TableDataSet getHomeInterviewSurveyTableDataSet(HashMap<String, String> rbMap) { String hisFileName = Util.getStringValueFromPropertyMap(rbMap, HIS_DATA_RECORDS_FILE_KEY); if (hisFileName == null) { logger.error("Error getting the filename from the properties file for the Sandag home interview survey data records file."); logger.error("Properties file target: " + HIS_DATA_RECORDS_FILE_KEY + " not found."); logger.error("Please specify a filename value for the " + HIS_DATA_RECORDS_FILE_KEY + " property."); throw new RuntimeException(); } try { TableDataSet inTds = null; OLD_CSVFileReader reader = new OLD_CSVFileReader(); reader.setDelimSet("," + reader.getDelimSet()); inTds = reader.readFile(new File(hisFileName)); return inTds; } catch (Exception e) { logger.fatal(String .format("Exception occurred reading Sandag home interview survey data records file: %s into TableDataSet object.", hisFileName)); throw new RuntimeException(e); } } private int[][] getOnBoardSurveyOrigDestTimes(TableDataSet obsTds) { // odts are an array with elements: origin mgra, destination mgra, // departure // period(1-6), and arrival period(1-6). int[][] odts = new int[obsTds.getRowCount()][5]; int[] origs = obsTds.getColumnAsInt(OBS_ORIG_MGRA); int[] dests = obsTds.getColumnAsInt(OBS_DEST_MGRA); int[] departs = obsTds.getColumnAsInt(OBS_OUT_TOUR_PERIOD); int[] arrives = obsTds.getColumnAsInt(OBS_IN_TOUR_PERIOD); int[] ids = obsTds.getColumnAsInt(OBS_UNIQUE_ID); for (int r = 1; r <= obsTds.getRowCount(); r++) { odts[r - 1][0] = origs[r - 1]; odts[r - 1][1] = dests[r - 1]; odts[r - 1][2] = departs[r - 1]; odts[r - 1][3] = arrives[r - 1]; odts[r - 1][4] = ids[r - 1]; } return odts; } private int[][] getHomeInterviewSurveyOrigDestTimes(TableDataSet hisTds) { // odts are an array with elements: origin mgra, destination mgra, // departure // period(1-6), and arrival period(1-6). int[][] odts = new int[hisTds.getRowCount()][4]; int[] origs = hisTds.getColumnAsInt(HIS_ORIG_MGRA); int[] dests = hisTds.getColumnAsInt(HIS_DEST_MGRA); int[] departs = hisTds.getColumnAsInt(HIS_DEPART_PERIOD); int[] arrives = hisTds.getColumnAsInt(HIS_ARRIVE_PERIOD); for (int r = 1; r <= hisTds.getRowCount(); r++) { odts[r - 1][0] = origs[r - 1]; odts[r - 1][1] = dests[r - 1]; odts[r - 1][2] = departs[r - 1]; odts[r - 1][3] = arrives[r - 1]; } return odts; } public static void main(String[] args) { ResourceBundle rb; if (args.length == 0) { System.out .println(String .format("no properties file base name (without .properties extension) was specified as an argument.")); return; } else { rb = ResourceBundle.getBundle(args[0]); } SkimsAppender appender = new SkimsAppender(); appender.startMatrixServer(rb); appender.runSkimsAppender(rb); } }
false
true
private void runSkimsAppender(ResourceBundle rb) { HashMap<String, String> rbMap = ResourceUtil.changeResourceBundleIntoHashMap(rb); // instantiate these objects right away TazDataManager tazs = TazDataManager.getInstance(rbMap); MgraDataManager mgraManager = MgraDataManager.getInstance(rbMap); TapDataManager tapManager = TapDataManager.getInstance(rbMap); AutoAndNonMotorizedSkimsCalculator anm = null; WalkTransitWalkSkimsCalculator wtw = null; WalkTransitDriveSkimsCalculator wtd = null; DriveTransitWalkSkimsCalculator dtw = null; Logger autoLogger = Logger.getLogger("auto"); Logger wtwLogger = Logger.getLogger("wtw"); Logger wtdLogger = Logger.getLogger("wtd"); Logger dtwLogger = Logger.getLogger("dtw"); String outputFileNameObs = Util.getStringValueFromPropertyMap(rbMap, "obs.skims.output.file"); String outputFileNameHis = Util.getStringValueFromPropertyMap(rbMap, "his.skims.output.file"); FileWriter writer; PrintWriter outStreamObs = null; PrintWriter outStreamHis = null; PrintWriter[] outStreamObsTod = new PrintWriter[SKIM_PERIOD_LABELS.length]; PrintWriter[] outStreamHisTod = new PrintWriter[SKIM_PERIOD_LABELS.length]; if (outputFileNameObs != "" || outputFileNameHis != "") { anm = new AutoAndNonMotorizedSkimsCalculator(rbMap); McLogsumsCalculator logsumHelper = new McLogsumsCalculator(); bestPathUEC = logsumHelper.getBestTransitPathCalculator(); wtw = new WalkTransitWalkSkimsCalculator(); wtw.setup(rbMap, wtwLogger, bestPathUEC); wtd = new WalkTransitDriveSkimsCalculator(); wtd.setup(rbMap, wtdLogger, bestPathUEC); dtw = new DriveTransitWalkSkimsCalculator(); dtw.setup(rbMap, dtwLogger, bestPathUEC); String heading = "Seq,Id"; heading += ",obOrigMgra,obDestMgra,obPeriod"; heading += getAutoSkimsHeaderRecord("auto", anm.getAutoSkimNames()); heading += getNonMotorizedSkimsHeaderRecord("nm", anm.getNmSkimNames()); heading += getTransitSkimsHeaderRecord("wtw", wtw.getLocalSkimNames(), wtw.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("wtd", wtd.getLocalSkimNames(), wtd.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("dtw", dtw.getLocalSkimNames(), dtw.getPremiumSkimNames()); heading += ",ObsSeq,Id,ibOrigMgra,ibDestMgra,ibPeriod"; heading += getAutoSkimsHeaderRecord("auto", anm.getAutoSkimNames()); heading += getNonMotorizedSkimsHeaderRecord("nm", anm.getNmSkimNames()); heading += getTransitSkimsHeaderRecord("wtw", wtw.getLocalSkimNames(), wtw.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("wtd", wtd.getLocalSkimNames(), wtd.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("dtw", dtw.getLocalSkimNames(), dtw.getPremiumSkimNames()); if (outputFileNameObs != "") { try { // create an output stream for the mode choice estimation // file // with // observed TOD writer = new FileWriter(new File(outputFileNameObs)); outStreamObs = new PrintWriter(new BufferedWriter(writer)); // create an array of similar files, 1 for each TOD period, // for // TOD // choice estimation for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { int dotIndex = outputFileNameObs.lastIndexOf('.'); String newName = outputFileNameObs.substring(0, dotIndex) + "_" + SKIM_PERIOD_LABELS[i] + outputFileNameObs.substring(dotIndex); writer = new FileWriter(new File(newName)); outStreamObsTod[i] = new PrintWriter(new BufferedWriter(writer)); } } catch (IOException e) { logger.fatal(String.format("Exception occurred opening output skims file: %s.", outputFileNameObs)); throw new RuntimeException(e); } outStreamObs.println("obs" + heading); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].println("obs" + heading); } if (outputFileNameHis != "") { try { writer = new FileWriter(new File(outputFileNameHis)); outStreamHis = new PrintWriter(new BufferedWriter(writer)); // create an array of similar files, 1 for each TOD period, // for // TOD // choice estimation for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { int dotIndex = outputFileNameHis.lastIndexOf('.'); String newName = outputFileNameHis.substring(0, dotIndex) + "_" + SKIM_PERIOD_LABELS[i] + outputFileNameHis.substring(dotIndex); writer = new FileWriter(new File(newName)); outStreamHisTod[i] = new PrintWriter(new BufferedWriter(writer)); } } catch (IOException e) { logger.fatal(String.format("Exception occurred opening output skims file: %s.", outputFileNameHis)); throw new RuntimeException(e); } outStreamHis.println("his" + heading); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].println("his" + heading); } } Logger[] loggers = new Logger[4]; loggers[0] = autoLogger; loggers[1] = autoLogger; loggers[2] = wtdLogger; loggers[3] = dtwLogger; int[] odt = new int[5]; if (outputFileNameObs != "") { TableDataSet obsTds = getOnBoardSurveyTableDataSet(rbMap); int[][] obsOdts = getOnBoardSurveyOrigDestTimes(obsTds); // write skims data for on-board survey records int seq = 1; for (int[] obsOdt : obsOdts) { // write outbound direction odt[0] = obsOdt[0]; // orig odt[1] = obsOdt[1]; // dest odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[obsOdt[2]]; // depart skim // period odt[3] = obsOdt[3]; odt[4] = obsOdt[4]; if (odt[0] == 0 || odt[1] == 0) { outStreamObs.println(String.format("%d,%d,%d,%d,%d", seq, odt[4], odt[0], odt[1], odt[2])); seq++; continue; } // index // for debugging a specific mgra pair // odt[0] = 25646; // odt[1] = 4319; // odt[2] = 1; boolean debugFlag = false; if (odt[0] == 25646 && odt[1] == 4319) debugFlag = true; writeSkimsToFile(seq, outStreamObs, debugFlag, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamObsTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } // write inbound direction odt[0] = obsOdt[1]; // dest odt[1] = obsOdt[0]; // orig odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[obsOdt[3]]; // arrival // skim // period // index outStreamObs.print(","); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].print(","); writeSkimsToFile(seq, outStreamObs, debugFlag, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamObsTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } if (outStreamObs != null) { outStreamObs.println(""); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].println(""); } if (seq % 1000 == 0) logger.info("wrote OBS record: " + seq); seq++; } if (outStreamObs != null) { outStreamObs.close(); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].close(); } } if (outputFileNameHis != "") { TableDataSet hisTds = getHomeInterviewSurveyTableDataSet(rbMap); int[][] hisOdts = getHomeInterviewSurveyOrigDestTimes(hisTds); // write skims data for home interview survey records int seq = 1; for (int[] hisOdt : hisOdts) { // write outbound direction odt[0] = hisOdt[0]; // orig odt[1] = hisOdt[1]; // dest odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[hisOdt[2]]; // depart skim // period // index writeSkimsToFile(seq, outStreamHis, false, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamHisTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } // write inbound direction odt[0] = hisOdt[1]; // dest odt[1] = hisOdt[0]; // orig odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[hisOdt[3]]; // arrival // skim // period // index outStreamHis.print(","); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].print(","); writeSkimsToFile(seq, outStreamHis, false, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamHisTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } if (outStreamHis != null) { outStreamHis.println(""); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].println(""); } if (seq % 1000 == 0) logger.info("wrote HIS record: " + seq); seq++; } if (outStreamHis != null) { outStreamHis.close(); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].close(); } } }
private void runSkimsAppender(ResourceBundle rb) { HashMap<String, String> rbMap = ResourceUtil.changeResourceBundleIntoHashMap(rb); // instantiate these objects right away TazDataManager tazs = TazDataManager.getInstance(rbMap); MgraDataManager mgraManager = MgraDataManager.getInstance(rbMap); TapDataManager tapManager = TapDataManager.getInstance(rbMap); AutoAndNonMotorizedSkimsCalculator anm = null; WalkTransitWalkSkimsCalculator wtw = null; WalkTransitDriveSkimsCalculator wtd = null; DriveTransitWalkSkimsCalculator dtw = null; Logger autoLogger = Logger.getLogger("auto"); Logger wtwLogger = Logger.getLogger("wtw"); Logger wtdLogger = Logger.getLogger("wtd"); Logger dtwLogger = Logger.getLogger("dtw"); String outputFileNameObs = Util.getStringValueFromPropertyMap(rbMap, "obs.skims.output.file"); String outputFileNameHis = Util.getStringValueFromPropertyMap(rbMap, "his.skims.output.file"); FileWriter writer; PrintWriter outStreamObs = null; PrintWriter outStreamHis = null; PrintWriter[] outStreamObsTod = new PrintWriter[SKIM_PERIOD_LABELS.length]; PrintWriter[] outStreamHisTod = new PrintWriter[SKIM_PERIOD_LABELS.length]; if (!outputFileNameObs.isEmpty() || !outputFileNameHis.isEmpty()) { anm = new AutoAndNonMotorizedSkimsCalculator(rbMap); McLogsumsCalculator logsumHelper = new McLogsumsCalculator(); bestPathUEC = logsumHelper.getBestTransitPathCalculator(); wtw = new WalkTransitWalkSkimsCalculator(); wtw.setup(rbMap, wtwLogger, bestPathUEC); wtd = new WalkTransitDriveSkimsCalculator(); wtd.setup(rbMap, wtdLogger, bestPathUEC); dtw = new DriveTransitWalkSkimsCalculator(); dtw.setup(rbMap, dtwLogger, bestPathUEC); String heading = "Seq,Id"; heading += ",obOrigMgra,obDestMgra,obPeriod"; heading += getAutoSkimsHeaderRecord("auto", anm.getAutoSkimNames()); heading += getNonMotorizedSkimsHeaderRecord("nm", anm.getNmSkimNames()); heading += getTransitSkimsHeaderRecord("wtw", wtw.getLocalSkimNames(), wtw.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("wtd", wtd.getLocalSkimNames(), wtd.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("dtw", dtw.getLocalSkimNames(), dtw.getPremiumSkimNames()); heading += ",ObsSeq,Id,ibOrigMgra,ibDestMgra,ibPeriod"; heading += getAutoSkimsHeaderRecord("auto", anm.getAutoSkimNames()); heading += getNonMotorizedSkimsHeaderRecord("nm", anm.getNmSkimNames()); heading += getTransitSkimsHeaderRecord("wtw", wtw.getLocalSkimNames(), wtw.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("wtd", wtd.getLocalSkimNames(), wtd.getPremiumSkimNames()); heading += getTransitSkimsHeaderRecord("dtw", dtw.getLocalSkimNames(), dtw.getPremiumSkimNames()); if (!outputFileNameObs.isEmpty()) { try { // create an output stream for the mode choice estimation // file // with // observed TOD writer = new FileWriter(new File(outputFileNameObs)); outStreamObs = new PrintWriter(new BufferedWriter(writer)); // create an array of similar files, 1 for each TOD period, // for // TOD // choice estimation for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { int dotIndex = outputFileNameObs.lastIndexOf('.'); String newName = outputFileNameObs.substring(0, dotIndex) + "_" + SKIM_PERIOD_LABELS[i] + outputFileNameObs.substring(dotIndex); writer = new FileWriter(new File(newName)); outStreamObsTod[i] = new PrintWriter(new BufferedWriter(writer)); } } catch (IOException e) { logger.fatal(String.format("Exception occurred opening output skims file: %s.", outputFileNameObs)); throw new RuntimeException(e); } outStreamObs.println("obs" + heading); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].println("obs" + heading); } if (!outputFileNameHis.isEmpty()) { try { writer = new FileWriter(new File(outputFileNameHis)); outStreamHis = new PrintWriter(new BufferedWriter(writer)); // create an array of similar files, 1 for each TOD period, // for // TOD // choice estimation for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { int dotIndex = outputFileNameHis.lastIndexOf('.'); String newName = outputFileNameHis.substring(0, dotIndex) + "_" + SKIM_PERIOD_LABELS[i] + outputFileNameHis.substring(dotIndex); writer = new FileWriter(new File(newName)); outStreamHisTod[i] = new PrintWriter(new BufferedWriter(writer)); } } catch (IOException e) { logger.fatal(String.format("Exception occurred opening output skims file: %s.", outputFileNameHis)); throw new RuntimeException(e); } outStreamHis.println("his" + heading); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].println("his" + heading); } } Logger[] loggers = new Logger[4]; loggers[0] = autoLogger; loggers[1] = autoLogger; loggers[2] = wtdLogger; loggers[3] = dtwLogger; int[] odt = new int[5]; if (!outputFileNameObs.isEmpty()) { TableDataSet obsTds = getOnBoardSurveyTableDataSet(rbMap); int[][] obsOdts = getOnBoardSurveyOrigDestTimes(obsTds); // write skims data for on-board survey records int seq = 1; for (int[] obsOdt : obsOdts) { // write outbound direction odt[0] = obsOdt[0]; // orig odt[1] = obsOdt[1]; // dest odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[obsOdt[2]]; // depart skim // period odt[3] = obsOdt[3]; odt[4] = obsOdt[4]; if (odt[0] == 0 || odt[1] == 0) { outStreamObs.println(String.format("%d,%d,%d,%d,%d", seq, odt[4], odt[0], odt[1], odt[2])); seq++; continue; } // index // for debugging a specific mgra pair // odt[0] = 25646; // odt[1] = 4319; // odt[2] = 1; boolean debugFlag = false; if (odt[0] == 25646 && odt[1] == 4319) debugFlag = true; writeSkimsToFile(seq, outStreamObs, debugFlag, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamObsTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } // write inbound direction odt[0] = obsOdt[1]; // dest odt[1] = obsOdt[0]; // orig odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[obsOdt[3]]; // arrival // skim // period // index outStreamObs.print(","); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].print(","); writeSkimsToFile(seq, outStreamObs, debugFlag, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamObsTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } if (outStreamObs != null) { outStreamObs.println(""); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].println(""); } if (seq % 1000 == 0) logger.info("wrote OBS record: " + seq); seq++; } if (outStreamObs != null) { outStreamObs.close(); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamObsTod[i].close(); } } if (!outputFileNameHis.isEmpty()) { TableDataSet hisTds = getHomeInterviewSurveyTableDataSet(rbMap); int[][] hisOdts = getHomeInterviewSurveyOrigDestTimes(hisTds); // write skims data for home interview survey records int seq = 1; for (int[] hisOdt : hisOdts) { // write outbound direction odt[0] = hisOdt[0]; // orig odt[1] = hisOdt[1]; // dest odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[hisOdt[2]]; // depart skim // period // index writeSkimsToFile(seq, outStreamHis, false, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamHisTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } // write inbound direction odt[0] = hisOdt[1]; // dest odt[1] = hisOdt[0]; // orig odt[2] = SURVEY_PERIOD_TO_SKIM_PERIOD[hisOdt[3]]; // arrival // skim // period // index outStreamHis.print(","); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].print(","); writeSkimsToFile(seq, outStreamHis, false, odt, anm, wtw, wtd, dtw, loggers); // set odt[2] to be each skim priod index (1,2,3) and write a // separate // output file for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) { odt[2] = i + 1; writeSkimsToFile(seq, outStreamHisTod[i], false, odt, anm, wtw, wtd, dtw, loggers); } if (outStreamHis != null) { outStreamHis.println(""); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].println(""); } if (seq % 1000 == 0) logger.info("wrote HIS record: " + seq); seq++; } if (outStreamHis != null) { outStreamHis.close(); for (int i = 0; i < SKIM_PERIOD_LABELS.length; i++) outStreamHisTod[i].close(); } } }
diff --git a/src/test/java/org/apache/commons/logging/security/MockSecurityManager.java b/src/test/java/org/apache/commons/logging/security/MockSecurityManager.java index d9620f5..462c26e 100644 --- a/src/test/java/org/apache/commons/logging/security/MockSecurityManager.java +++ b/src/test/java/org/apache/commons/logging/security/MockSecurityManager.java @@ -1,142 +1,142 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.logging.security; import java.io.FilePermission; import java.security.Permission; import java.security.Permissions; /** * Custom implementation of a security manager, so we can control the * security environment for tests in this package. */ public class MockSecurityManager extends SecurityManager { private final Permissions permissions = new Permissions(); private static final Permission setSecurityManagerPerm = new RuntimePermission("setSecurityManager"); private int untrustedCodeCount = 0; public MockSecurityManager() { permissions.add(setSecurityManagerPerm); } /** * Define the set of permissions to be granted to classes in the o.a.c.l package, * but NOT to unit-test classes in o.a.c.l.security package. */ public void addPermission(Permission p) { permissions.add(p); } /** * This returns the number of times that a check of a permission failed * due to stack-walking tracing up into untrusted code. Any non-zero * value indicates a bug in JCL, ie a situation where code was not * correctly wrapped in an AccessController block. The result of such a * bug is that signing JCL is not sufficient to allow JCL to perform * the operation; the caller would need to be signed too. */ public int getUntrustedCodeCount() { return untrustedCodeCount; } public void checkPermission(Permission p) throws SecurityException { if (setSecurityManagerPerm.implies(p)) { // ok, allow this; we don't want to block any calls to setSecurityManager // otherwise this custom security manager cannot be reset to the original. // System.out.println("setSecurityManager: granted"); return; } // Allow read-only access to files, as this is needed to load classes! // Ideally, we would limit this to just .class and .jar files. if (p instanceof FilePermission) { FilePermission fp = (FilePermission) p; if (fp.getActions().equals("read")) { // System.out.println("Permit read of files"); return; } } System.out.println("\n\ntesting permission:" + p.getClass() + ":"+ p); Exception e = new Exception(); e.fillInStackTrace(); StackTraceElement[] stack = e.getStackTrace(); // scan the call stack from most recent to oldest. // start at 1 to skip the entry in the stack for this method for(int i=1; i<stack.length; ++i) { String cname = stack[i].getClassName(); System.out.println("" + i + ":" + stack[i].getClassName() + - "." + stack[i].getMethodName() + stack[i].getLineNumber()); + "." + stack[i].getMethodName() + ":" + stack[i].getLineNumber()); if (cname.equals("java.util.logging.Handler") && stack[i].getMethodName().equals("setLevel")) { // LOGGING CODE CAUSES ACCESSCONTROLEXCEPTION // http://www-01.ibm.com/support/docview.wss?uid=swg1IZ51152 return; } if (cname.equals("java.security.AccessController")) { // Presumably method name equals "doPrivileged" // // The previous iteration of this loop verified that the // PrivilegedAction.run method associated with this // doPrivileged method call had the right permissions, // so we just return here. Effectively, the method invoking // doPrivileged asserted that it checked the input params // and found them safe, and that code is trusted, so we // don't need to check the trust level of code higher in // the call stack. System.out.println("Access controller found: returning"); return; } else if (cname.startsWith("java.") || cname.startsWith("javax.") || cname.startsWith("junit.") || cname.startsWith("org.apache.tools.ant.") || cname.startsWith("sun.")) { // Code in these packages is trusted if the caller is trusted. // // TODO: maybe check class is loaded via system loader or similar rather // than checking name? Trusted domains may be different in alternative // jvms.. } else if (cname.startsWith("org.apache.commons.logging.security")) { // this is the unit test code; treat this like an untrusted client // app that is using JCL ++untrustedCodeCount; System.out.println("Untrusted code [testcase] found"); throw new SecurityException("Untrusted code [testcase] found"); } else if (cname.startsWith("org.apache.commons.logging.")) { if (permissions.implies(p)) { // Code here is trusted if the caller is trusted System.out.println("Permission in allowed set for JCL class"); } else { System.out.println("Permission refused:" + p.getClass() + ":" + p); throw new SecurityException("Permission refused:" + p.getClass() + ":" + p); } } else { // we found some code that is not trusted to perform this operation. System.out.println("Unexpected code: permission refused:" + p.getClass() + ":" + p); throw new SecurityException("Unexpected code: permission refused:" + p.getClass() + ":" + p); } } } }
true
true
public void checkPermission(Permission p) throws SecurityException { if (setSecurityManagerPerm.implies(p)) { // ok, allow this; we don't want to block any calls to setSecurityManager // otherwise this custom security manager cannot be reset to the original. // System.out.println("setSecurityManager: granted"); return; } // Allow read-only access to files, as this is needed to load classes! // Ideally, we would limit this to just .class and .jar files. if (p instanceof FilePermission) { FilePermission fp = (FilePermission) p; if (fp.getActions().equals("read")) { // System.out.println("Permit read of files"); return; } } System.out.println("\n\ntesting permission:" + p.getClass() + ":"+ p); Exception e = new Exception(); e.fillInStackTrace(); StackTraceElement[] stack = e.getStackTrace(); // scan the call stack from most recent to oldest. // start at 1 to skip the entry in the stack for this method for(int i=1; i<stack.length; ++i) { String cname = stack[i].getClassName(); System.out.println("" + i + ":" + stack[i].getClassName() + "." + stack[i].getMethodName() + stack[i].getLineNumber()); if (cname.equals("java.util.logging.Handler") && stack[i].getMethodName().equals("setLevel")) { // LOGGING CODE CAUSES ACCESSCONTROLEXCEPTION // http://www-01.ibm.com/support/docview.wss?uid=swg1IZ51152 return; } if (cname.equals("java.security.AccessController")) { // Presumably method name equals "doPrivileged" // // The previous iteration of this loop verified that the // PrivilegedAction.run method associated with this // doPrivileged method call had the right permissions, // so we just return here. Effectively, the method invoking // doPrivileged asserted that it checked the input params // and found them safe, and that code is trusted, so we // don't need to check the trust level of code higher in // the call stack. System.out.println("Access controller found: returning"); return; } else if (cname.startsWith("java.") || cname.startsWith("javax.") || cname.startsWith("junit.") || cname.startsWith("org.apache.tools.ant.") || cname.startsWith("sun.")) { // Code in these packages is trusted if the caller is trusted. // // TODO: maybe check class is loaded via system loader or similar rather // than checking name? Trusted domains may be different in alternative // jvms.. } else if (cname.startsWith("org.apache.commons.logging.security")) { // this is the unit test code; treat this like an untrusted client // app that is using JCL ++untrustedCodeCount; System.out.println("Untrusted code [testcase] found"); throw new SecurityException("Untrusted code [testcase] found"); } else if (cname.startsWith("org.apache.commons.logging.")) { if (permissions.implies(p)) { // Code here is trusted if the caller is trusted System.out.println("Permission in allowed set for JCL class"); } else { System.out.println("Permission refused:" + p.getClass() + ":" + p); throw new SecurityException("Permission refused:" + p.getClass() + ":" + p); } } else { // we found some code that is not trusted to perform this operation. System.out.println("Unexpected code: permission refused:" + p.getClass() + ":" + p); throw new SecurityException("Unexpected code: permission refused:" + p.getClass() + ":" + p); } } }
public void checkPermission(Permission p) throws SecurityException { if (setSecurityManagerPerm.implies(p)) { // ok, allow this; we don't want to block any calls to setSecurityManager // otherwise this custom security manager cannot be reset to the original. // System.out.println("setSecurityManager: granted"); return; } // Allow read-only access to files, as this is needed to load classes! // Ideally, we would limit this to just .class and .jar files. if (p instanceof FilePermission) { FilePermission fp = (FilePermission) p; if (fp.getActions().equals("read")) { // System.out.println("Permit read of files"); return; } } System.out.println("\n\ntesting permission:" + p.getClass() + ":"+ p); Exception e = new Exception(); e.fillInStackTrace(); StackTraceElement[] stack = e.getStackTrace(); // scan the call stack from most recent to oldest. // start at 1 to skip the entry in the stack for this method for(int i=1; i<stack.length; ++i) { String cname = stack[i].getClassName(); System.out.println("" + i + ":" + stack[i].getClassName() + "." + stack[i].getMethodName() + ":" + stack[i].getLineNumber()); if (cname.equals("java.util.logging.Handler") && stack[i].getMethodName().equals("setLevel")) { // LOGGING CODE CAUSES ACCESSCONTROLEXCEPTION // http://www-01.ibm.com/support/docview.wss?uid=swg1IZ51152 return; } if (cname.equals("java.security.AccessController")) { // Presumably method name equals "doPrivileged" // // The previous iteration of this loop verified that the // PrivilegedAction.run method associated with this // doPrivileged method call had the right permissions, // so we just return here. Effectively, the method invoking // doPrivileged asserted that it checked the input params // and found them safe, and that code is trusted, so we // don't need to check the trust level of code higher in // the call stack. System.out.println("Access controller found: returning"); return; } else if (cname.startsWith("java.") || cname.startsWith("javax.") || cname.startsWith("junit.") || cname.startsWith("org.apache.tools.ant.") || cname.startsWith("sun.")) { // Code in these packages is trusted if the caller is trusted. // // TODO: maybe check class is loaded via system loader or similar rather // than checking name? Trusted domains may be different in alternative // jvms.. } else if (cname.startsWith("org.apache.commons.logging.security")) { // this is the unit test code; treat this like an untrusted client // app that is using JCL ++untrustedCodeCount; System.out.println("Untrusted code [testcase] found"); throw new SecurityException("Untrusted code [testcase] found"); } else if (cname.startsWith("org.apache.commons.logging.")) { if (permissions.implies(p)) { // Code here is trusted if the caller is trusted System.out.println("Permission in allowed set for JCL class"); } else { System.out.println("Permission refused:" + p.getClass() + ":" + p); throw new SecurityException("Permission refused:" + p.getClass() + ":" + p); } } else { // we found some code that is not trusted to perform this operation. System.out.println("Unexpected code: permission refused:" + p.getClass() + ":" + p); throw new SecurityException("Unexpected code: permission refused:" + p.getClass() + ":" + p); } } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/planner/DateSelectionDialog.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/planner/DateSelectionDialog.java index 813f8a05e..425e08a4b 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/planner/DateSelectionDialog.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/planner/DateSelectionDialog.java @@ -1,104 +1,104 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.tasks.ui.planner; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.mylar.internal.tasks.ui.views.DatePickerPanel; import org.eclipse.mylar.internal.tasks.ui.views.DatePickerPanel.DateSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.forms.widgets.FormToolkit; /** * @author Ken Sueda * @author Mik Kersten * @author Rob Elves */ public class DateSelectionDialog extends Dialog { private Date reminderDate = null; private String title = "Date Selection"; private Calendar initialCalendar = GregorianCalendar.getInstance(); private FormToolkit toolkit; public DateSelectionDialog(Shell parentShell, String title) { this(parentShell, GregorianCalendar.getInstance(), title); } public DateSelectionDialog(Shell parentShell, Calendar initialDate, String title) { super(parentShell); toolkit = new FormToolkit(parentShell.getDisplay());; if(title != null) { this.title = title; } if(initialDate != null) { this.initialCalendar.setTime(initialDate.getTime()); } reminderDate = initialCalendar.getTime(); } @Override protected Control createDialogArea(Composite parent) { getShell().setText(title); DatePickerPanel datePanel = new DatePickerPanel(parent, SWT.NULL, initialCalendar); datePanel.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!event.getSelection().isEmpty()) { DateSelection dateSelection = (DateSelection) event.getSelection(); reminderDate = dateSelection.getDate().getTime(); } } }); - //datePanel.setBackground(toolkit.getColors().getBackground()); + datePanel.setBackground(toolkit.getColors().getBackground()); return datePanel; } @Override public boolean close() { toolkit.dispose(); return super.close(); } @Override protected void createButtonsForButtonBar(Composite parent) { parent.setBackground(toolkit.getColors().getBackground()); createButton(parent, IDialogConstants.CLIENT_ID + 1, "Clear", false); super.createButtonsForButtonBar(parent); } @Override protected void buttonPressed(int buttonId) { super.buttonPressed(buttonId); if(buttonId == IDialogConstants.CLIENT_ID + 1) { reminderDate = null; okPressed(); } } public Date getDate() { return reminderDate; } }
true
true
protected Control createDialogArea(Composite parent) { getShell().setText(title); DatePickerPanel datePanel = new DatePickerPanel(parent, SWT.NULL, initialCalendar); datePanel.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!event.getSelection().isEmpty()) { DateSelection dateSelection = (DateSelection) event.getSelection(); reminderDate = dateSelection.getDate().getTime(); } } }); //datePanel.setBackground(toolkit.getColors().getBackground()); return datePanel; }
protected Control createDialogArea(Composite parent) { getShell().setText(title); DatePickerPanel datePanel = new DatePickerPanel(parent, SWT.NULL, initialCalendar); datePanel.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!event.getSelection().isEmpty()) { DateSelection dateSelection = (DateSelection) event.getSelection(); reminderDate = dateSelection.getDate().getTime(); } } }); datePanel.setBackground(toolkit.getColors().getBackground()); return datePanel; }
diff --git a/src/com/android/providers/contacts/ContactsProvider2.java b/src/com/android/providers/contacts/ContactsProvider2.java index 331c1a3f..a56021e4 100644 --- a/src/com/android/providers/contacts/ContactsProvider2.java +++ b/src/com/android/providers/contacts/ContactsProvider2.java @@ -1,7988 +1,7993 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.providers.contacts; import com.android.common.content.SyncStateContentProviderHelper; import com.android.providers.contacts.ContactAggregator.AggregationSuggestionParameter; import com.android.providers.contacts.ContactLookupKey.LookupKeySegment; import com.android.providers.contacts.ContactsDatabaseHelper.AggregatedPresenceColumns; import com.android.providers.contacts.ContactsDatabaseHelper.AggregationExceptionColumns; import com.android.providers.contacts.ContactsDatabaseHelper.Clauses; import com.android.providers.contacts.ContactsDatabaseHelper.ContactsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.ContactsStatusUpdatesColumns; import com.android.providers.contacts.ContactsDatabaseHelper.DataColumns; import com.android.providers.contacts.ContactsDatabaseHelper.DataUsageStatColumns; import com.android.providers.contacts.ContactsDatabaseHelper.GroupsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.Joins; import com.android.providers.contacts.ContactsDatabaseHelper.MimetypesColumns; import com.android.providers.contacts.ContactsDatabaseHelper.NameLookupColumns; import com.android.providers.contacts.ContactsDatabaseHelper.NameLookupType; import com.android.providers.contacts.ContactsDatabaseHelper.PhoneColumns; import com.android.providers.contacts.ContactsDatabaseHelper.PhoneLookupColumns; import com.android.providers.contacts.ContactsDatabaseHelper.PhotoFilesColumns; import com.android.providers.contacts.ContactsDatabaseHelper.PresenceColumns; import com.android.providers.contacts.ContactsDatabaseHelper.RawContactsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.SearchIndexColumns; import com.android.providers.contacts.ContactsDatabaseHelper.SettingsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.StatusUpdatesColumns; import com.android.providers.contacts.ContactsDatabaseHelper.StreamItemPhotosColumns; import com.android.providers.contacts.ContactsDatabaseHelper.StreamItemsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.Tables; import com.android.providers.contacts.ContactsDatabaseHelper.Views; import com.android.providers.contacts.SearchIndexManager.FtsQueryBuilder; import com.android.providers.contacts.util.DbQueryUtils; import com.android.vcard.VCardComposer; import com.android.vcard.VCardConfig; import com.google.android.collect.Lists; import com.google.android.collect.Maps; import com.google.android.collect.Sets; import com.google.common.annotations.VisibleForTesting; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.OnAccountsUpdateListener; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.SearchManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.IContentService; import android.content.Intent; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.content.SyncAdapterType; import android.content.UriMatcher; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ProviderInfo; import android.content.res.AssetFileDescriptor; import android.content.res.Resources; import android.content.res.Resources.NotFoundException; import android.database.AbstractCursor; import android.database.CrossProcessCursor; import android.database.Cursor; import android.database.CursorWindow; import android.database.CursorWrapper; import android.database.DatabaseUtils; import android.database.MatrixCursor; import android.database.MatrixCursor.RowBuilder; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteQueryBuilder; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.net.Uri.Builder; import android.os.AsyncTask; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.os.ParcelFileDescriptor; import android.os.ParcelFileDescriptor.AutoCloseInputStream; import android.os.Process; import android.os.RemoteException; import android.os.StrictMode; import android.os.SystemClock; import android.os.SystemProperties; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.provider.ContactsContract; import android.provider.ContactsContract.AggregationExceptions; import android.provider.ContactsContract.Authorization; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Im; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.provider.ContactsContract.CommonDataKinds.SipAddress; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.ContactCounts; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Contacts.AggregationSuggestions; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.DataUsageFeedback; import android.provider.ContactsContract.Directory; import android.provider.ContactsContract.DisplayPhoto; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.PhotoFiles; import android.provider.ContactsContract.Profile; import android.provider.ContactsContract.ProviderStatus; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.RawContactsEntity; import android.provider.ContactsContract.SearchSnippetColumns; import android.provider.ContactsContract.Settings; import android.provider.ContactsContract.StatusUpdates; import android.provider.ContactsContract.StreamItemPhotos; import android.provider.ContactsContract.StreamItems; import android.provider.OpenableColumns; import android.provider.SyncStateContract; import android.telephony.PhoneNumberUtils; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.security.SecureRandom; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; /** * Contacts content provider. The contract between this provider and applications * is defined in {@link ContactsContract}. */ public class ContactsProvider2 extends AbstractContactsProvider implements OnAccountsUpdateListener { private static final String TAG = "ContactsProvider"; private static final boolean VERBOSE_LOGGING = Log.isLoggable(TAG, Log.VERBOSE); private static final int BACKGROUND_TASK_INITIALIZE = 0; private static final int BACKGROUND_TASK_OPEN_WRITE_ACCESS = 1; private static final int BACKGROUND_TASK_IMPORT_LEGACY_CONTACTS = 2; private static final int BACKGROUND_TASK_UPDATE_ACCOUNTS = 3; private static final int BACKGROUND_TASK_UPDATE_LOCALE = 4; private static final int BACKGROUND_TASK_UPGRADE_AGGREGATION_ALGORITHM = 5; private static final int BACKGROUND_TASK_UPDATE_SEARCH_INDEX = 6; private static final int BACKGROUND_TASK_UPDATE_PROVIDER_STATUS = 7; private static final int BACKGROUND_TASK_UPDATE_DIRECTORIES = 8; private static final int BACKGROUND_TASK_CHANGE_LOCALE = 9; private static final int BACKGROUND_TASK_CLEANUP_PHOTOS = 10; /** Default for the maximum number of returned aggregation suggestions. */ private static final int DEFAULT_MAX_SUGGESTIONS = 5; /** Limit for the maximum number of social stream items to store under a raw contact. */ private static final int MAX_STREAM_ITEMS_PER_RAW_CONTACT = 5; /** Rate limit (in ms) for photo cleanup. Do it at most once per day. */ private static final int PHOTO_CLEANUP_RATE_LIMIT = 24 * 60 * 60 * 1000; /** * Default expiration duration for pre-authorized URIs. May be overridden from a secure * setting. */ private static final int DEFAULT_PREAUTHORIZED_URI_EXPIRATION = 5 * 60 * 1000; /** * Random URI parameter that will be appended to preauthorized URIs for uniqueness. */ private static final String PREAUTHORIZED_URI_TOKEN = "perm_token"; /** * Property key for the legacy contact import version. The need for a version * as opposed to a boolean flag is that if we discover bugs in the contact import process, * we can trigger re-import by incrementing the import version. */ private static final String PROPERTY_CONTACTS_IMPORTED = "contacts_imported_v1"; private static final int PROPERTY_CONTACTS_IMPORT_VERSION = 1; private static final String PREF_LOCALE = "locale"; private static final String PROPERTY_AGGREGATION_ALGORITHM = "aggregation_v2"; private static final int PROPERTY_AGGREGATION_ALGORITHM_VERSION = 2; private static final String AGGREGATE_CONTACTS = "sync.contacts.aggregate"; private static final ProfileAwareUriMatcher sUriMatcher = new ProfileAwareUriMatcher(UriMatcher.NO_MATCH); /** * Used to insert a column into strequent results, which enables SQL to sort the list using * the total times contacted. See also {@link #sStrequentFrequentProjectionMap}. */ private static final String TIMES_USED_SORT_COLUMN = "times_used_sort"; private static final String STREQUENT_ORDER_BY = Contacts.STARRED + " DESC, " + TIMES_USED_SORT_COLUMN + " DESC, " + Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; private static final String STREQUENT_LIMIT = "(SELECT COUNT(1) FROM " + Tables.CONTACTS + " WHERE " + Contacts.STARRED + "=1) + 25"; private static final String FREQUENT_ORDER_BY = DataUsageStatColumns.TIMES_USED + " DESC," + Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; /* package */ static final String UPDATE_TIMES_CONTACTED_CONTACTS_TABLE = "UPDATE " + Tables.CONTACTS + " SET " + Contacts.TIMES_CONTACTED + "=" + " CASE WHEN " + Contacts.TIMES_CONTACTED + " IS NULL THEN 1 ELSE " + " (" + Contacts.TIMES_CONTACTED + " + 1) END WHERE " + Contacts._ID + "=?"; /* package */ static final String UPDATE_TIMES_CONTACTED_RAWCONTACTS_TABLE = "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.TIMES_CONTACTED + "=" + " CASE WHEN " + RawContacts.TIMES_CONTACTED + " IS NULL THEN 1 ELSE " + " (" + RawContacts.TIMES_CONTACTED + " + 1) END WHERE " + RawContacts.CONTACT_ID + "=?"; /* package */ static final String PHONEBOOK_COLLATOR_NAME = "PHONEBOOK"; // Regex for splitting query strings - we split on any group of non-alphanumeric characters, // excluding the @ symbol. /* package */ static final String QUERY_TOKENIZER_REGEX = "[^\\w@]+"; private static final int CONTACTS = 1000; private static final int CONTACTS_ID = 1001; private static final int CONTACTS_LOOKUP = 1002; private static final int CONTACTS_LOOKUP_ID = 1003; private static final int CONTACTS_ID_DATA = 1004; private static final int CONTACTS_FILTER = 1005; private static final int CONTACTS_STREQUENT = 1006; private static final int CONTACTS_STREQUENT_FILTER = 1007; private static final int CONTACTS_GROUP = 1008; private static final int CONTACTS_ID_PHOTO = 1009; private static final int CONTACTS_LOOKUP_PHOTO = 1010; private static final int CONTACTS_LOOKUP_ID_PHOTO = 1011; private static final int CONTACTS_ID_DISPLAY_PHOTO = 1012; private static final int CONTACTS_LOOKUP_DISPLAY_PHOTO = 1013; private static final int CONTACTS_LOOKUP_ID_DISPLAY_PHOTO = 1014; private static final int CONTACTS_AS_VCARD = 1015; private static final int CONTACTS_AS_MULTI_VCARD = 1016; private static final int CONTACTS_LOOKUP_DATA = 1017; private static final int CONTACTS_LOOKUP_ID_DATA = 1018; private static final int CONTACTS_ID_ENTITIES = 1019; private static final int CONTACTS_LOOKUP_ENTITIES = 1020; private static final int CONTACTS_LOOKUP_ID_ENTITIES = 1021; private static final int CONTACTS_ID_STREAM_ITEMS = 1022; private static final int CONTACTS_LOOKUP_STREAM_ITEMS = 1023; private static final int CONTACTS_LOOKUP_ID_STREAM_ITEMS = 1024; private static final int CONTACTS_FREQUENT = 1025; private static final int RAW_CONTACTS = 2002; private static final int RAW_CONTACTS_ID = 2003; private static final int RAW_CONTACTS_DATA = 2004; private static final int RAW_CONTACT_ENTITY_ID = 2005; private static final int RAW_CONTACTS_ID_DISPLAY_PHOTO = 2006; private static final int RAW_CONTACTS_ID_STREAM_ITEMS = 2007; private static final int RAW_CONTACTS_ID_STREAM_ITEMS_ID = 2008; private static final int DATA = 3000; private static final int DATA_ID = 3001; private static final int PHONES = 3002; private static final int PHONES_ID = 3003; private static final int PHONES_FILTER = 3004; private static final int EMAILS = 3005; private static final int EMAILS_ID = 3006; private static final int EMAILS_LOOKUP = 3007; private static final int EMAILS_FILTER = 3008; private static final int POSTALS = 3009; private static final int POSTALS_ID = 3010; private static final int PHONE_LOOKUP = 4000; private static final int AGGREGATION_EXCEPTIONS = 6000; private static final int AGGREGATION_EXCEPTION_ID = 6001; private static final int STATUS_UPDATES = 7000; private static final int STATUS_UPDATES_ID = 7001; private static final int AGGREGATION_SUGGESTIONS = 8000; private static final int SETTINGS = 9000; private static final int GROUPS = 10000; private static final int GROUPS_ID = 10001; private static final int GROUPS_SUMMARY = 10003; private static final int SYNCSTATE = 11000; private static final int SYNCSTATE_ID = 11001; private static final int PROFILE_SYNCSTATE = 11002; private static final int PROFILE_SYNCSTATE_ID = 11003; private static final int SEARCH_SUGGESTIONS = 12001; private static final int SEARCH_SHORTCUT = 12002; private static final int RAW_CONTACT_ENTITIES = 15001; private static final int PROVIDER_STATUS = 16001; private static final int DIRECTORIES = 17001; private static final int DIRECTORIES_ID = 17002; private static final int COMPLETE_NAME = 18000; private static final int PROFILE = 19000; private static final int PROFILE_ENTITIES = 19001; private static final int PROFILE_DATA = 19002; private static final int PROFILE_DATA_ID = 19003; private static final int PROFILE_AS_VCARD = 19004; private static final int PROFILE_RAW_CONTACTS = 19005; private static final int PROFILE_RAW_CONTACTS_ID = 19006; private static final int PROFILE_RAW_CONTACTS_ID_DATA = 19007; private static final int PROFILE_RAW_CONTACTS_ID_ENTITIES = 19008; private static final int PROFILE_STATUS_UPDATES = 19009; private static final int PROFILE_RAW_CONTACT_ENTITIES = 19010; private static final int PROFILE_PHOTO = 19011; private static final int PROFILE_DISPLAY_PHOTO = 19012; private static final int DATA_USAGE_FEEDBACK_ID = 20001; private static final int STREAM_ITEMS = 21000; private static final int STREAM_ITEMS_PHOTOS = 21001; private static final int STREAM_ITEMS_ID = 21002; private static final int STREAM_ITEMS_ID_PHOTOS = 21003; private static final int STREAM_ITEMS_ID_PHOTOS_ID = 21004; private static final int STREAM_ITEMS_LIMIT = 21005; private static final int DISPLAY_PHOTO = 22000; private static final int PHOTO_DIMENSIONS = 22001; // Inserts into URIs in this map will direct to the profile database if the parent record's // value (looked up from the ContentValues object with the key specified by the value in this // map) is in the profile ID-space (see {@link ProfileDatabaseHelper#PROFILE_ID_SPACE}). private static final Map<Integer, String> INSERT_URI_ID_VALUE_MAP = Maps.newHashMap(); static { INSERT_URI_ID_VALUE_MAP.put(DATA, Data.RAW_CONTACT_ID); INSERT_URI_ID_VALUE_MAP.put(RAW_CONTACTS_DATA, Data.RAW_CONTACT_ID); INSERT_URI_ID_VALUE_MAP.put(STATUS_UPDATES, StatusUpdates.DATA_ID); INSERT_URI_ID_VALUE_MAP.put(STREAM_ITEMS, StreamItems.RAW_CONTACT_ID); INSERT_URI_ID_VALUE_MAP.put(RAW_CONTACTS_ID_STREAM_ITEMS, StreamItems.RAW_CONTACT_ID); INSERT_URI_ID_VALUE_MAP.put(STREAM_ITEMS_PHOTOS, StreamItemPhotos.STREAM_ITEM_ID); INSERT_URI_ID_VALUE_MAP.put(STREAM_ITEMS_ID_PHOTOS, StreamItemPhotos.STREAM_ITEM_ID); } // Any interactions that involve these URIs will also require the calling package to have either // android.permission.READ_SOCIAL_STREAM permission or android.permission.WRITE_SOCIAL_STREAM // permission, depending on the type of operation being performed. private static final List<Integer> SOCIAL_STREAM_URIS = Lists.newArrayList( CONTACTS_ID_STREAM_ITEMS, CONTACTS_LOOKUP_STREAM_ITEMS, CONTACTS_LOOKUP_ID_STREAM_ITEMS, RAW_CONTACTS_ID_STREAM_ITEMS, RAW_CONTACTS_ID_STREAM_ITEMS_ID, STREAM_ITEMS, STREAM_ITEMS_PHOTOS, STREAM_ITEMS_ID, STREAM_ITEMS_ID_PHOTOS, STREAM_ITEMS_ID_PHOTOS_ID ); private static final String SELECTION_FAVORITES_GROUPS_BY_RAW_CONTACT_ID = RawContactsColumns.CONCRETE_ID + "=? AND " + GroupsColumns.CONCRETE_ACCOUNT_NAME + "=" + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AND " + GroupsColumns.CONCRETE_ACCOUNT_TYPE + "=" + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AND (" + GroupsColumns.CONCRETE_DATA_SET + "=" + RawContactsColumns.CONCRETE_DATA_SET + " OR " + GroupsColumns.CONCRETE_DATA_SET + " IS NULL AND " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL)" + " AND " + Groups.FAVORITES + " != 0"; private static final String SELECTION_AUTO_ADD_GROUPS_BY_RAW_CONTACT_ID = RawContactsColumns.CONCRETE_ID + "=? AND " + GroupsColumns.CONCRETE_ACCOUNT_NAME + "=" + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AND " + GroupsColumns.CONCRETE_ACCOUNT_TYPE + "=" + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AND (" + GroupsColumns.CONCRETE_DATA_SET + "=" + RawContactsColumns.CONCRETE_DATA_SET + " OR " + GroupsColumns.CONCRETE_DATA_SET + " IS NULL AND " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL)" + " AND " + Groups.AUTO_ADD + " != 0"; private static final String[] PROJECTION_GROUP_ID = new String[]{Tables.GROUPS + "." + Groups._ID}; private static final String SELECTION_GROUPMEMBERSHIP_DATA = DataColumns.MIMETYPE_ID + "=? " + "AND " + GroupMembership.GROUP_ROW_ID + "=? " + "AND " + GroupMembership.RAW_CONTACT_ID + "=?"; private static final String SELECTION_STARRED_FROM_RAW_CONTACTS = "SELECT " + RawContacts.STARRED + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=?"; private interface DataContactsQuery { public static final String TABLE = "data " + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) " + "JOIN contacts ON (raw_contacts.contact_id = contacts._id)"; public static final String[] PROJECTION = new String[] { RawContactsColumns.CONCRETE_ID, RawContactsColumns.CONCRETE_ACCOUNT_TYPE, RawContactsColumns.CONCRETE_ACCOUNT_NAME, RawContactsColumns.CONCRETE_DATA_SET, DataColumns.CONCRETE_ID, ContactsColumns.CONCRETE_ID }; public static final int RAW_CONTACT_ID = 0; public static final int ACCOUNT_TYPE = 1; public static final int ACCOUNT_NAME = 2; public static final int DATA_SET = 3; public static final int DATA_ID = 4; public static final int CONTACT_ID = 5; } interface RawContactsQuery { String TABLE = Tables.RAW_CONTACTS; String[] COLUMNS = new String[] { RawContacts.DELETED, RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_NAME, RawContacts.DATA_SET, }; int DELETED = 0; int ACCOUNT_TYPE = 1; int ACCOUNT_NAME = 2; int DATA_SET = 3; } public static final String DEFAULT_ACCOUNT_TYPE = "com.google"; /** Sql where statement for filtering on groups. */ private static final String CONTACTS_IN_GROUP_SELECT = Contacts._ID + " IN " + "(SELECT " + RawContacts.CONTACT_ID + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContactsColumns.CONCRETE_ID + " IN " + "(SELECT " + DataColumns.CONCRETE_RAW_CONTACT_ID + " FROM " + Tables.DATA_JOIN_MIMETYPES + " WHERE " + DataColumns.MIMETYPE_ID + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=" + "(SELECT " + Tables.GROUPS + "." + Groups._ID + " FROM " + Tables.GROUPS + " WHERE " + Groups.TITLE + "=?)))"; /** Sql for updating DIRTY flag on multiple raw contacts */ private static final String UPDATE_RAW_CONTACT_SET_DIRTY_SQL = "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.DIRTY + "=1" + " WHERE " + RawContacts._ID + " IN ("; /** Sql for updating VERSION on multiple raw contacts */ private static final String UPDATE_RAW_CONTACT_SET_VERSION_SQL = "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.VERSION + " = " + RawContacts.VERSION + " + 1" + " WHERE " + RawContacts._ID + " IN ("; // Current contacts - those contacted within the last 3 days (in seconds) private static final long EMAIL_FILTER_CURRENT = 3 * 24 * 60 * 60; // Recent contacts - those contacted within the last 30 days (in seconds) private static final long EMAIL_FILTER_RECENT = 30 * 24 * 60 * 60; private static final String TIME_SINCE_LAST_USED = "(strftime('%s', 'now') - " + DataUsageStatColumns.LAST_TIME_USED + "/1000)"; /* * Sorting order for email address suggestions: first starred, then the rest. * second in_visible_group, then the rest. * Within the four (starred/unstarred, in_visible_group/not-in_visible_group) groups * - three buckets: very recently contacted, then fairly * recently contacted, then the rest. Within each of the bucket - descending count * of times contacted (both for data row and for contact row). If all else fails, alphabetical. * (Super)primary email address is returned before other addresses for the same contact. */ private static final String EMAIL_FILTER_SORT_ORDER = Contacts.STARRED + " DESC, " + Contacts.IN_VISIBLE_GROUP + " DESC, " + "(CASE WHEN " + TIME_SINCE_LAST_USED + " < " + EMAIL_FILTER_CURRENT + " THEN 0 " + " WHEN " + TIME_SINCE_LAST_USED + " < " + EMAIL_FILTER_RECENT + " THEN 1 " + " ELSE 2 END), " + DataUsageStatColumns.TIMES_USED + " DESC, " + Contacts.DISPLAY_NAME + ", " + Data.CONTACT_ID + ", " + Data.IS_SUPER_PRIMARY + " DESC, " + Data.IS_PRIMARY + " DESC"; /** Currently same as {@link #EMAIL_FILTER_SORT_ORDER} */ private static final String PHONE_FILTER_SORT_ORDER = EMAIL_FILTER_SORT_ORDER; /** Name lookup types used for contact filtering */ private static final String CONTACT_LOOKUP_NAME_TYPES = NameLookupType.NAME_COLLATION_KEY + "," + NameLookupType.EMAIL_BASED_NICKNAME + "," + NameLookupType.NICKNAME; /** * If any of these columns are used in a Data projection, there is no point in * using the DISTINCT keyword, which can negatively affect performance. */ private static final String[] DISTINCT_DATA_PROHIBITING_COLUMNS = { Data._ID, Data.RAW_CONTACT_ID, Data.NAME_RAW_CONTACT_ID, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DATA_SET, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.DIRTY, RawContacts.NAME_VERIFIED, RawContacts.SOURCE_ID, RawContacts.VERSION, }; private static final ProjectionMap sContactsColumns = ProjectionMap.builder() .add(Contacts.CUSTOM_RINGTONE) .add(Contacts.DISPLAY_NAME) .add(Contacts.DISPLAY_NAME_ALTERNATIVE) .add(Contacts.DISPLAY_NAME_SOURCE) .add(Contacts.IN_VISIBLE_GROUP) .add(Contacts.LAST_TIME_CONTACTED) .add(Contacts.LOOKUP_KEY) .add(Contacts.PHONETIC_NAME) .add(Contacts.PHONETIC_NAME_STYLE) .add(Contacts.PHOTO_ID) .add(Contacts.PHOTO_FILE_ID) .add(Contacts.PHOTO_URI) .add(Contacts.PHOTO_THUMBNAIL_URI) .add(Contacts.SEND_TO_VOICEMAIL) .add(Contacts.SORT_KEY_ALTERNATIVE) .add(Contacts.SORT_KEY_PRIMARY) .add(Contacts.STARRED) .add(Contacts.TIMES_CONTACTED) .add(Contacts.HAS_PHONE_NUMBER) .build(); private static final ProjectionMap sContactsPresenceColumns = ProjectionMap.builder() .add(Contacts.CONTACT_PRESENCE, Tables.AGGREGATED_PRESENCE + "." + StatusUpdates.PRESENCE) .add(Contacts.CONTACT_CHAT_CAPABILITY, Tables.AGGREGATED_PRESENCE + "." + StatusUpdates.CHAT_CAPABILITY) .add(Contacts.CONTACT_STATUS, ContactsStatusUpdatesColumns.CONCRETE_STATUS) .add(Contacts.CONTACT_STATUS_TIMESTAMP, ContactsStatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP) .add(Contacts.CONTACT_STATUS_RES_PACKAGE, ContactsStatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE) .add(Contacts.CONTACT_STATUS_LABEL, ContactsStatusUpdatesColumns.CONCRETE_STATUS_LABEL) .add(Contacts.CONTACT_STATUS_ICON, ContactsStatusUpdatesColumns.CONCRETE_STATUS_ICON) .build(); private static final ProjectionMap sSnippetColumns = ProjectionMap.builder() .add(SearchSnippetColumns.SNIPPET) .build(); private static final ProjectionMap sRawContactColumns = ProjectionMap.builder() .add(RawContacts.ACCOUNT_NAME) .add(RawContacts.ACCOUNT_TYPE) .add(RawContacts.DATA_SET) .add(RawContacts.ACCOUNT_TYPE_AND_DATA_SET) .add(RawContacts.DIRTY) .add(RawContacts.NAME_VERIFIED) .add(RawContacts.SOURCE_ID) .add(RawContacts.VERSION) .build(); private static final ProjectionMap sRawContactSyncColumns = ProjectionMap.builder() .add(RawContacts.SYNC1) .add(RawContacts.SYNC2) .add(RawContacts.SYNC3) .add(RawContacts.SYNC4) .build(); private static final ProjectionMap sDataColumns = ProjectionMap.builder() .add(Data.DATA1) .add(Data.DATA2) .add(Data.DATA3) .add(Data.DATA4) .add(Data.DATA5) .add(Data.DATA6) .add(Data.DATA7) .add(Data.DATA8) .add(Data.DATA9) .add(Data.DATA10) .add(Data.DATA11) .add(Data.DATA12) .add(Data.DATA13) .add(Data.DATA14) .add(Data.DATA15) .add(Data.DATA_VERSION) .add(Data.IS_PRIMARY) .add(Data.IS_SUPER_PRIMARY) .add(Data.MIMETYPE) .add(Data.RES_PACKAGE) .add(Data.SYNC1) .add(Data.SYNC2) .add(Data.SYNC3) .add(Data.SYNC4) .add(GroupMembership.GROUP_SOURCE_ID) .build(); private static final ProjectionMap sContactPresenceColumns = ProjectionMap.builder() .add(Contacts.CONTACT_PRESENCE, Tables.AGGREGATED_PRESENCE + '.' + StatusUpdates.PRESENCE) .add(Contacts.CONTACT_CHAT_CAPABILITY, Tables.AGGREGATED_PRESENCE + '.' + StatusUpdates.CHAT_CAPABILITY) .add(Contacts.CONTACT_STATUS, ContactsStatusUpdatesColumns.CONCRETE_STATUS) .add(Contacts.CONTACT_STATUS_TIMESTAMP, ContactsStatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP) .add(Contacts.CONTACT_STATUS_RES_PACKAGE, ContactsStatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE) .add(Contacts.CONTACT_STATUS_LABEL, ContactsStatusUpdatesColumns.CONCRETE_STATUS_LABEL) .add(Contacts.CONTACT_STATUS_ICON, ContactsStatusUpdatesColumns.CONCRETE_STATUS_ICON) .build(); private static final ProjectionMap sDataPresenceColumns = ProjectionMap.builder() .add(Data.PRESENCE, Tables.PRESENCE + "." + StatusUpdates.PRESENCE) .add(Data.CHAT_CAPABILITY, Tables.PRESENCE + "." + StatusUpdates.CHAT_CAPABILITY) .add(Data.STATUS, StatusUpdatesColumns.CONCRETE_STATUS) .add(Data.STATUS_TIMESTAMP, StatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP) .add(Data.STATUS_RES_PACKAGE, StatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE) .add(Data.STATUS_LABEL, StatusUpdatesColumns.CONCRETE_STATUS_LABEL) .add(Data.STATUS_ICON, StatusUpdatesColumns.CONCRETE_STATUS_ICON) .build(); /** Contains just BaseColumns._COUNT */ private static final ProjectionMap sCountProjectionMap = ProjectionMap.builder() .add(BaseColumns._COUNT, "COUNT(*)") .build(); /** Contains just the contacts columns */ private static final ProjectionMap sContactsProjectionMap = ProjectionMap.builder() .add(Contacts._ID) .add(Contacts.HAS_PHONE_NUMBER) .add(Contacts.NAME_RAW_CONTACT_ID) .add(Contacts.IS_USER_PROFILE) .addAll(sContactsColumns) .addAll(sContactsPresenceColumns) .build(); /** Contains just the contacts columns */ private static final ProjectionMap sContactsProjectionWithSnippetMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .addAll(sSnippetColumns) .build(); /** Used for pushing starred contacts to the top of a times contacted list **/ private static final ProjectionMap sStrequentStarredProjectionMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .add(TIMES_USED_SORT_COLUMN, String.valueOf(Long.MAX_VALUE)) .build(); private static final ProjectionMap sStrequentFrequentProjectionMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .add(TIMES_USED_SORT_COLUMN, "SUM(" + DataUsageStatColumns.CONCRETE_TIMES_USED + ")") .build(); /** * Used for Strequent Uri with {@link ContactsContract#STREQUENT_PHONE_ONLY}, which allows * users to obtain part of Data columns. Right now Starred part just returns NULL for * those data columns (frequent part should return real ones in data table). **/ private static final ProjectionMap sStrequentPhoneOnlyStarredProjectionMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .add(TIMES_USED_SORT_COLUMN, String.valueOf(Long.MAX_VALUE)) .add(Phone.NUMBER, "NULL") .add(Phone.TYPE, "NULL") .add(Phone.LABEL, "NULL") .build(); /** * Used for Strequent Uri with {@link ContactsContract#STREQUENT_PHONE_ONLY}, which allows * users to obtain part of Data columns. We hard-code {@link Contacts#IS_USER_PROFILE} to NULL, * because sContactsProjectionMap specifies a field that doesn't exist in the view behind the * query that uses this projection map. **/ private static final ProjectionMap sStrequentPhoneOnlyFrequentProjectionMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .add(TIMES_USED_SORT_COLUMN, DataUsageStatColumns.CONCRETE_TIMES_USED) .add(Phone.NUMBER) .add(Phone.TYPE) .add(Phone.LABEL) .add(Contacts.IS_USER_PROFILE, "NULL") .build(); /** Contains just the contacts vCard columns */ private static final ProjectionMap sContactsVCardProjectionMap = ProjectionMap.builder() .add(Contacts._ID) .add(OpenableColumns.DISPLAY_NAME, Contacts.DISPLAY_NAME + " || '.vcf'") .add(OpenableColumns.SIZE, "NULL") .build(); /** Contains just the raw contacts columns */ private static final ProjectionMap sRawContactsProjectionMap = ProjectionMap.builder() .add(RawContacts._ID) .add(RawContacts.CONTACT_ID) .add(RawContacts.DELETED) .add(RawContacts.DISPLAY_NAME_PRIMARY) .add(RawContacts.DISPLAY_NAME_ALTERNATIVE) .add(RawContacts.DISPLAY_NAME_SOURCE) .add(RawContacts.PHONETIC_NAME) .add(RawContacts.PHONETIC_NAME_STYLE) .add(RawContacts.SORT_KEY_PRIMARY) .add(RawContacts.SORT_KEY_ALTERNATIVE) .add(RawContacts.TIMES_CONTACTED) .add(RawContacts.LAST_TIME_CONTACTED) .add(RawContacts.CUSTOM_RINGTONE) .add(RawContacts.SEND_TO_VOICEMAIL) .add(RawContacts.STARRED) .add(RawContacts.AGGREGATION_MODE) .add(RawContacts.RAW_CONTACT_IS_USER_PROFILE) .addAll(sRawContactColumns) .addAll(sRawContactSyncColumns) .build(); /** Contains the columns from the raw entity view*/ private static final ProjectionMap sRawEntityProjectionMap = ProjectionMap.builder() .add(RawContacts._ID) .add(RawContacts.CONTACT_ID) .add(RawContacts.Entity.DATA_ID) .add(RawContacts.DELETED) .add(RawContacts.STARRED) .add(RawContacts.RAW_CONTACT_IS_USER_PROFILE) .addAll(sRawContactColumns) .addAll(sRawContactSyncColumns) .addAll(sDataColumns) .build(); /** Contains the columns from the contact entity view*/ private static final ProjectionMap sEntityProjectionMap = ProjectionMap.builder() .add(Contacts.Entity._ID) .add(Contacts.Entity.CONTACT_ID) .add(Contacts.Entity.RAW_CONTACT_ID) .add(Contacts.Entity.DATA_ID) .add(Contacts.Entity.NAME_RAW_CONTACT_ID) .add(Contacts.Entity.DELETED) .add(Contacts.IS_USER_PROFILE) .addAll(sContactsColumns) .addAll(sContactPresenceColumns) .addAll(sRawContactColumns) .addAll(sRawContactSyncColumns) .addAll(sDataColumns) .addAll(sDataPresenceColumns) .build(); /** Contains columns in PhoneLookup which are not contained in the data view. */ private static final ProjectionMap sSipLookupColumns = ProjectionMap.builder() .add(PhoneLookup.NUMBER, SipAddress.SIP_ADDRESS) .add(PhoneLookup.TYPE, "0") .add(PhoneLookup.LABEL, "NULL") .add(PhoneLookup.NORMALIZED_NUMBER, "NULL") .build(); /** Contains columns from the data view */ private static final ProjectionMap sDataProjectionMap = ProjectionMap.builder() .add(Data._ID) .add(Data.RAW_CONTACT_ID) .add(Data.CONTACT_ID) .add(Data.NAME_RAW_CONTACT_ID) .add(RawContacts.RAW_CONTACT_IS_USER_PROFILE) .addAll(sDataColumns) .addAll(sDataPresenceColumns) .addAll(sRawContactColumns) .addAll(sContactsColumns) .addAll(sContactPresenceColumns) .build(); /** Contains columns from the data view used for SIP address lookup. */ private static final ProjectionMap sDataSipLookupProjectionMap = ProjectionMap.builder() .addAll(sDataProjectionMap) .addAll(sSipLookupColumns) .build(); /** Contains columns from the data view */ private static final ProjectionMap sDistinctDataProjectionMap = ProjectionMap.builder() .add(Data._ID, "MIN(" + Data._ID + ")") .add(RawContacts.CONTACT_ID) .add(RawContacts.RAW_CONTACT_IS_USER_PROFILE) .addAll(sDataColumns) .addAll(sDataPresenceColumns) .addAll(sContactsColumns) .addAll(sContactPresenceColumns) .build(); /** Contains columns from the data view used for SIP address lookup. */ private static final ProjectionMap sDistinctDataSipLookupProjectionMap = ProjectionMap.builder() .addAll(sDistinctDataProjectionMap) .addAll(sSipLookupColumns) .build(); /** Contains the data and contacts columns, for joined tables */ private static final ProjectionMap sPhoneLookupProjectionMap = ProjectionMap.builder() .add(PhoneLookup._ID, "contacts_view." + Contacts._ID) .add(PhoneLookup.LOOKUP_KEY, "contacts_view." + Contacts.LOOKUP_KEY) .add(PhoneLookup.DISPLAY_NAME, "contacts_view." + Contacts.DISPLAY_NAME) .add(PhoneLookup.LAST_TIME_CONTACTED, "contacts_view." + Contacts.LAST_TIME_CONTACTED) .add(PhoneLookup.TIMES_CONTACTED, "contacts_view." + Contacts.TIMES_CONTACTED) .add(PhoneLookup.STARRED, "contacts_view." + Contacts.STARRED) .add(PhoneLookup.IN_VISIBLE_GROUP, "contacts_view." + Contacts.IN_VISIBLE_GROUP) .add(PhoneLookup.PHOTO_ID, "contacts_view." + Contacts.PHOTO_ID) .add(PhoneLookup.PHOTO_URI, "contacts_view." + Contacts.PHOTO_URI) .add(PhoneLookup.PHOTO_THUMBNAIL_URI, "contacts_view." + Contacts.PHOTO_THUMBNAIL_URI) .add(PhoneLookup.CUSTOM_RINGTONE, "contacts_view." + Contacts.CUSTOM_RINGTONE) .add(PhoneLookup.HAS_PHONE_NUMBER, "contacts_view." + Contacts.HAS_PHONE_NUMBER) .add(PhoneLookup.SEND_TO_VOICEMAIL, "contacts_view." + Contacts.SEND_TO_VOICEMAIL) .add(PhoneLookup.NUMBER, Phone.NUMBER) .add(PhoneLookup.TYPE, Phone.TYPE) .add(PhoneLookup.LABEL, Phone.LABEL) .add(PhoneLookup.NORMALIZED_NUMBER, Phone.NORMALIZED_NUMBER) .build(); /** Contains the just the {@link Groups} columns */ private static final ProjectionMap sGroupsProjectionMap = ProjectionMap.builder() .add(Groups._ID) .add(Groups.ACCOUNT_NAME) .add(Groups.ACCOUNT_TYPE) .add(Groups.DATA_SET) .add(Groups.ACCOUNT_TYPE_AND_DATA_SET) .add(Groups.SOURCE_ID) .add(Groups.DIRTY) .add(Groups.VERSION) .add(Groups.RES_PACKAGE) .add(Groups.TITLE) .add(Groups.TITLE_RES) .add(Groups.GROUP_VISIBLE) .add(Groups.SYSTEM_ID) .add(Groups.DELETED) .add(Groups.NOTES) .add(Groups.SHOULD_SYNC) .add(Groups.FAVORITES) .add(Groups.AUTO_ADD) .add(Groups.GROUP_IS_READ_ONLY) .add(Groups.SYNC1) .add(Groups.SYNC2) .add(Groups.SYNC3) .add(Groups.SYNC4) .build(); /** * Contains {@link Groups} columns along with summary details. * * Note {@link Groups#SUMMARY_COUNT} doesn't exist in groups/view_groups. * When we detect this column being requested, we join {@link Joins#GROUP_MEMBER_COUNT} to * generate it. */ private static final ProjectionMap sGroupsSummaryProjectionMap = ProjectionMap.builder() .addAll(sGroupsProjectionMap) .add(Groups.SUMMARY_COUNT, "ifnull(group_member_count, 0)") .add(Groups.SUMMARY_WITH_PHONES, "(SELECT COUNT(" + ContactsColumns.CONCRETE_ID + ") FROM " + Tables.CONTACTS_JOIN_RAW_CONTACTS_DATA_FILTERED_BY_GROUPMEMBERSHIP + " WHERE " + Contacts.HAS_PHONE_NUMBER + ")") .build(); // This is only exposed as hidden API for the contacts app, so we can be very specific in // the filtering private static final ProjectionMap sGroupsSummaryProjectionMapWithGroupCountPerAccount = ProjectionMap.builder() .addAll(sGroupsSummaryProjectionMap) .add(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, "(SELECT COUNT(*) FROM " + Views.GROUPS + " WHERE " + "(" + Groups.ACCOUNT_NAME + "=" + GroupsColumns.CONCRETE_ACCOUNT_NAME + " AND " + Groups.ACCOUNT_TYPE + "=" + GroupsColumns.CONCRETE_ACCOUNT_TYPE + " AND " + Groups.DELETED + "=0 AND " + Groups.FAVORITES + "=0 AND " + Groups.AUTO_ADD + "=0" + ")" + " GROUP BY " + Groups.ACCOUNT_NAME + ", " + Groups.ACCOUNT_TYPE + ")") .build(); /** Contains the agg_exceptions columns */ private static final ProjectionMap sAggregationExceptionsProjectionMap = ProjectionMap.builder() .add(AggregationExceptionColumns._ID, Tables.AGGREGATION_EXCEPTIONS + "._id") .add(AggregationExceptions.TYPE) .add(AggregationExceptions.RAW_CONTACT_ID1) .add(AggregationExceptions.RAW_CONTACT_ID2) .build(); /** Contains the agg_exceptions columns */ private static final ProjectionMap sSettingsProjectionMap = ProjectionMap.builder() .add(Settings.ACCOUNT_NAME) .add(Settings.ACCOUNT_TYPE) .add(Settings.DATA_SET) .add(Settings.UNGROUPED_VISIBLE) .add(Settings.SHOULD_SYNC) .add(Settings.ANY_UNSYNCED, "(CASE WHEN MIN(" + Settings.SHOULD_SYNC + ",(SELECT " + "(CASE WHEN MIN(" + Groups.SHOULD_SYNC + ") IS NULL" + " THEN 1" + " ELSE MIN(" + Groups.SHOULD_SYNC + ")" + " END)" + " FROM " + Tables.GROUPS + " WHERE " + GroupsColumns.CONCRETE_ACCOUNT_NAME + "=" + SettingsColumns.CONCRETE_ACCOUNT_NAME + " AND " + GroupsColumns.CONCRETE_ACCOUNT_TYPE + "=" + SettingsColumns.CONCRETE_ACCOUNT_TYPE + " AND ((" + GroupsColumns.CONCRETE_DATA_SET + " IS NULL AND " + SettingsColumns.CONCRETE_DATA_SET + " IS NULL) OR (" + GroupsColumns.CONCRETE_DATA_SET + "=" + SettingsColumns.CONCRETE_DATA_SET + "))))=0" + " THEN 1" + " ELSE 0" + " END)") .add(Settings.UNGROUPED_COUNT, "(SELECT COUNT(*)" + " FROM (SELECT 1" + " FROM " + Tables.SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS + " GROUP BY " + Clauses.GROUP_BY_ACCOUNT_CONTACT_ID + " HAVING " + Clauses.HAVING_NO_GROUPS + "))") .add(Settings.UNGROUPED_WITH_PHONES, "(SELECT COUNT(*)" + " FROM (SELECT 1" + " FROM " + Tables.SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS + " WHERE " + Contacts.HAS_PHONE_NUMBER + " GROUP BY " + Clauses.GROUP_BY_ACCOUNT_CONTACT_ID + " HAVING " + Clauses.HAVING_NO_GROUPS + "))") .build(); /** Contains StatusUpdates columns */ private static final ProjectionMap sStatusUpdatesProjectionMap = ProjectionMap.builder() .add(PresenceColumns.RAW_CONTACT_ID) .add(StatusUpdates.DATA_ID, DataColumns.CONCRETE_ID) .add(StatusUpdates.IM_ACCOUNT) .add(StatusUpdates.IM_HANDLE) .add(StatusUpdates.PROTOCOL) // We cannot allow a null in the custom protocol field, because SQLite3 does not // properly enforce uniqueness of null values .add(StatusUpdates.CUSTOM_PROTOCOL, "(CASE WHEN " + StatusUpdates.CUSTOM_PROTOCOL + "=''" + " THEN NULL" + " ELSE " + StatusUpdates.CUSTOM_PROTOCOL + " END)") .add(StatusUpdates.PRESENCE) .add(StatusUpdates.CHAT_CAPABILITY) .add(StatusUpdates.STATUS) .add(StatusUpdates.STATUS_TIMESTAMP) .add(StatusUpdates.STATUS_RES_PACKAGE) .add(StatusUpdates.STATUS_ICON) .add(StatusUpdates.STATUS_LABEL) .build(); /** Contains StreamItems columns */ private static final ProjectionMap sStreamItemsProjectionMap = ProjectionMap.builder() .add(StreamItems._ID) .add(StreamItems.CONTACT_ID) .add(StreamItems.CONTACT_LOOKUP_KEY) .add(StreamItems.ACCOUNT_NAME) .add(StreamItems.ACCOUNT_TYPE) .add(StreamItems.DATA_SET) .add(StreamItems.RAW_CONTACT_ID) .add(StreamItems.RAW_CONTACT_SOURCE_ID) .add(StreamItems.RES_PACKAGE) .add(StreamItems.RES_ICON) .add(StreamItems.RES_LABEL) .add(StreamItems.TEXT) .add(StreamItems.TIMESTAMP) .add(StreamItems.COMMENTS) .add(StreamItems.SYNC1) .add(StreamItems.SYNC2) .add(StreamItems.SYNC3) .add(StreamItems.SYNC4) .build(); private static final ProjectionMap sStreamItemPhotosProjectionMap = ProjectionMap.builder() .add(StreamItemPhotos._ID, StreamItemPhotosColumns.CONCRETE_ID) .add(StreamItems.RAW_CONTACT_ID) .add(StreamItems.RAW_CONTACT_SOURCE_ID, RawContactsColumns.CONCRETE_SOURCE_ID) .add(StreamItemPhotos.STREAM_ITEM_ID) .add(StreamItemPhotos.SORT_INDEX) .add(StreamItemPhotos.PHOTO_FILE_ID) .add(StreamItemPhotos.PHOTO_URI, "'" + DisplayPhoto.CONTENT_URI + "'||'/'||" + StreamItemPhotos.PHOTO_FILE_ID) .add(PhotoFiles.HEIGHT) .add(PhotoFiles.WIDTH) .add(PhotoFiles.FILESIZE) .add(StreamItemPhotos.SYNC1) .add(StreamItemPhotos.SYNC2) .add(StreamItemPhotos.SYNC3) .add(StreamItemPhotos.SYNC4) .build(); /** Contains {@link Directory} columns */ private static final ProjectionMap sDirectoryProjectionMap = ProjectionMap.builder() .add(Directory._ID) .add(Directory.PACKAGE_NAME) .add(Directory.TYPE_RESOURCE_ID) .add(Directory.DISPLAY_NAME) .add(Directory.DIRECTORY_AUTHORITY) .add(Directory.ACCOUNT_TYPE) .add(Directory.ACCOUNT_NAME) .add(Directory.EXPORT_SUPPORT) .add(Directory.SHORTCUT_SUPPORT) .add(Directory.PHOTO_SUPPORT) .build(); // where clause to update the status_updates table private static final String WHERE_CLAUSE_FOR_STATUS_UPDATES_TABLE = StatusUpdatesColumns.DATA_ID + " IN (SELECT Distinct " + StatusUpdates.DATA_ID + " FROM " + Tables.STATUS_UPDATES + " LEFT OUTER JOIN " + Tables.PRESENCE + " ON " + StatusUpdatesColumns.DATA_ID + " = " + StatusUpdates.DATA_ID + " WHERE "; private static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * Notification ID for failure to import contacts. */ private static final int LEGACY_IMPORT_FAILED_NOTIFICATION = 1; private static final String DEFAULT_SNIPPET_ARG_START_MATCH = "["; private static final String DEFAULT_SNIPPET_ARG_END_MATCH = "]"; private static final String DEFAULT_SNIPPET_ARG_ELLIPSIS = "..."; private static final int DEFAULT_SNIPPET_ARG_MAX_TOKENS = -10; private boolean sIsPhoneInitialized; private boolean sIsPhone; private StringBuilder mSb = new StringBuilder(); private String[] mSelectionArgs1 = new String[1]; private String[] mSelectionArgs2 = new String[2]; private ArrayList<String> mSelectionArgs = Lists.newArrayList(); private Account mAccount; /** * Stores mapping from type Strings exposed via {@link DataUsageFeedback} to * type integers in {@link DataUsageStatColumns}. */ private static final Map<String, Integer> sDataUsageTypeMap; static { // Contacts URI matching table final UriMatcher matcher = sUriMatcher; matcher.addURI(ContactsContract.AUTHORITY, "contacts", CONTACTS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#", CONTACTS_ID); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/data", CONTACTS_ID_DATA); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/entities", CONTACTS_ID_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/suggestions", AGGREGATION_SUGGESTIONS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/suggestions/*", AGGREGATION_SUGGESTIONS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/photo", CONTACTS_ID_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/display_photo", CONTACTS_ID_DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/stream_items", CONTACTS_ID_STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/filter", CONTACTS_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "contacts/filter/*", CONTACTS_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*", CONTACTS_LOOKUP); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/data", CONTACTS_LOOKUP_DATA); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/photo", CONTACTS_LOOKUP_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#", CONTACTS_LOOKUP_ID); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/data", CONTACTS_LOOKUP_ID_DATA); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/photo", CONTACTS_LOOKUP_ID_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/display_photo", CONTACTS_LOOKUP_DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/display_photo", CONTACTS_LOOKUP_ID_DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/entities", CONTACTS_LOOKUP_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/entities", CONTACTS_LOOKUP_ID_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/stream_items", CONTACTS_LOOKUP_STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/stream_items", CONTACTS_LOOKUP_ID_STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/as_vcard/*", CONTACTS_AS_VCARD); matcher.addURI(ContactsContract.AUTHORITY, "contacts/as_multi_vcard/*", CONTACTS_AS_MULTI_VCARD); matcher.addURI(ContactsContract.AUTHORITY, "contacts/strequent/", CONTACTS_STREQUENT); matcher.addURI(ContactsContract.AUTHORITY, "contacts/strequent/filter/*", CONTACTS_STREQUENT_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "contacts/group/*", CONTACTS_GROUP); matcher.addURI(ContactsContract.AUTHORITY, "contacts/frequent", CONTACTS_FREQUENT); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts", RAW_CONTACTS); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#", RAW_CONTACTS_ID); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/data", RAW_CONTACTS_DATA); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/display_photo", RAW_CONTACTS_ID_DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/entity", RAW_CONTACT_ENTITY_ID); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/stream_items", RAW_CONTACTS_ID_STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/stream_items/#", RAW_CONTACTS_ID_STREAM_ITEMS_ID); matcher.addURI(ContactsContract.AUTHORITY, "raw_contact_entities", RAW_CONTACT_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "data", DATA); matcher.addURI(ContactsContract.AUTHORITY, "data/#", DATA_ID); matcher.addURI(ContactsContract.AUTHORITY, "data/phones", PHONES); matcher.addURI(ContactsContract.AUTHORITY, "data/phones/#", PHONES_ID); matcher.addURI(ContactsContract.AUTHORITY, "data/phones/filter", PHONES_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "data/phones/filter/*", PHONES_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "data/emails", EMAILS); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/#", EMAILS_ID); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/lookup", EMAILS_LOOKUP); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/lookup/*", EMAILS_LOOKUP); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/filter", EMAILS_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/filter/*", EMAILS_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "data/postals", POSTALS); matcher.addURI(ContactsContract.AUTHORITY, "data/postals/#", POSTALS_ID); /** "*" is in CSV form with data ids ("123,456,789") */ matcher.addURI(ContactsContract.AUTHORITY, "data/usagefeedback/*", DATA_USAGE_FEEDBACK_ID); matcher.addURI(ContactsContract.AUTHORITY, "groups", GROUPS); matcher.addURI(ContactsContract.AUTHORITY, "groups/#", GROUPS_ID); matcher.addURI(ContactsContract.AUTHORITY, "groups_summary", GROUPS_SUMMARY); matcher.addURI(ContactsContract.AUTHORITY, SyncStateContentProviderHelper.PATH, SYNCSTATE); matcher.addURI(ContactsContract.AUTHORITY, SyncStateContentProviderHelper.PATH + "/#", SYNCSTATE_ID); matcher.addURI(ContactsContract.AUTHORITY, "profile/" + SyncStateContentProviderHelper.PATH, PROFILE_SYNCSTATE); matcher.addURI(ContactsContract.AUTHORITY, "profile/" + SyncStateContentProviderHelper.PATH + "/#", PROFILE_SYNCSTATE_ID); matcher.addURI(ContactsContract.AUTHORITY, "phone_lookup/*", PHONE_LOOKUP); matcher.addURI(ContactsContract.AUTHORITY, "aggregation_exceptions", AGGREGATION_EXCEPTIONS); matcher.addURI(ContactsContract.AUTHORITY, "aggregation_exceptions/*", AGGREGATION_EXCEPTION_ID); matcher.addURI(ContactsContract.AUTHORITY, "settings", SETTINGS); matcher.addURI(ContactsContract.AUTHORITY, "status_updates", STATUS_UPDATES); matcher.addURI(ContactsContract.AUTHORITY, "status_updates/#", STATUS_UPDATES_ID); matcher.addURI(ContactsContract.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGESTIONS); matcher.addURI(ContactsContract.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGESTIONS); matcher.addURI(ContactsContract.AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", SEARCH_SHORTCUT); matcher.addURI(ContactsContract.AUTHORITY, "provider_status", PROVIDER_STATUS); matcher.addURI(ContactsContract.AUTHORITY, "directories", DIRECTORIES); matcher.addURI(ContactsContract.AUTHORITY, "directories/#", DIRECTORIES_ID); matcher.addURI(ContactsContract.AUTHORITY, "complete_name", COMPLETE_NAME); matcher.addURI(ContactsContract.AUTHORITY, "profile", PROFILE); matcher.addURI(ContactsContract.AUTHORITY, "profile/entities", PROFILE_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "profile/data", PROFILE_DATA); matcher.addURI(ContactsContract.AUTHORITY, "profile/data/#", PROFILE_DATA_ID); matcher.addURI(ContactsContract.AUTHORITY, "profile/photo", PROFILE_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "profile/display_photo", PROFILE_DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "profile/as_vcard", PROFILE_AS_VCARD); matcher.addURI(ContactsContract.AUTHORITY, "profile/raw_contacts", PROFILE_RAW_CONTACTS); matcher.addURI(ContactsContract.AUTHORITY, "profile/raw_contacts/#", PROFILE_RAW_CONTACTS_ID); matcher.addURI(ContactsContract.AUTHORITY, "profile/raw_contacts/#/data", PROFILE_RAW_CONTACTS_ID_DATA); matcher.addURI(ContactsContract.AUTHORITY, "profile/raw_contacts/#/entity", PROFILE_RAW_CONTACTS_ID_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "profile/status_updates", PROFILE_STATUS_UPDATES); matcher.addURI(ContactsContract.AUTHORITY, "profile/raw_contact_entities", PROFILE_RAW_CONTACT_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "stream_items", STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "stream_items/photo", STREAM_ITEMS_PHOTOS); matcher.addURI(ContactsContract.AUTHORITY, "stream_items/#", STREAM_ITEMS_ID); matcher.addURI(ContactsContract.AUTHORITY, "stream_items/#/photo", STREAM_ITEMS_ID_PHOTOS); matcher.addURI(ContactsContract.AUTHORITY, "stream_items/#/photo/#", STREAM_ITEMS_ID_PHOTOS_ID); matcher.addURI(ContactsContract.AUTHORITY, "stream_items_limit", STREAM_ITEMS_LIMIT); matcher.addURI(ContactsContract.AUTHORITY, "display_photo/#", DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "photo_dimensions", PHOTO_DIMENSIONS); HashMap<String, Integer> tmpTypeMap = new HashMap<String, Integer>(); tmpTypeMap.put(DataUsageFeedback.USAGE_TYPE_CALL, DataUsageStatColumns.USAGE_TYPE_INT_CALL); tmpTypeMap.put(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT); tmpTypeMap.put(DataUsageFeedback.USAGE_TYPE_SHORT_TEXT, DataUsageStatColumns.USAGE_TYPE_INT_SHORT_TEXT); sDataUsageTypeMap = Collections.unmodifiableMap(tmpTypeMap); } private static class DirectoryInfo { String authority; String accountName; String accountType; } /** * Cached information about contact directories. */ private HashMap<String, DirectoryInfo> mDirectoryCache = new HashMap<String, DirectoryInfo>(); private boolean mDirectoryCacheValid = false; /** * An entry in group id cache. It maps the combination of (account type, account name, data set, * and source id) to group row id. */ public static class GroupIdCacheEntry { String accountType; String accountName; String dataSet; String sourceId; long groupId; } // We don't need a soft cache for groups - the assumption is that there will only // be a small number of contact groups. The cache is keyed off source id. The value // is a list of groups with this group id. private HashMap<String, ArrayList<GroupIdCacheEntry>> mGroupIdCache = Maps.newHashMap(); /** * Maximum dimension (height or width) of display photos. Larger images will be scaled * to fit. */ private int mMaxDisplayPhotoDim; /** * Maximum dimension (height or width) of photo thumbnails. */ private int mMaxThumbnailPhotoDim; /** * Sub-provider for handling profile requests against the profile database. */ private ProfileProvider mProfileProvider; private NameSplitter mNameSplitter; private NameLookupBuilder mNameLookupBuilder; private PostalSplitter mPostalSplitter; private ContactDirectoryManager mContactDirectoryManager; // The database tag to use for representing the contacts DB in contacts transactions. /* package */ static final String CONTACTS_DB_TAG = "contacts"; // The database tag to use for representing the profile DB in contacts transactions. /* package */ static final String PROFILE_DB_TAG = "profile"; /** * The active (thread-local) database. This will be switched between a contacts-specific * database and a profile-specific database, depending on what the current operation is * targeted to. */ private final ThreadLocal<SQLiteDatabase> mActiveDb = new ThreadLocal<SQLiteDatabase>(); /** * The thread-local holder of the active transaction. Shared between this and the profile * provider, to keep transactions on both databases synchronized. */ private final ThreadLocal<ContactsTransaction> mTransactionHolder = new ThreadLocal<ContactsTransaction>(); // This variable keeps track of whether the current operation is intended for the profile DB. private final ThreadLocal<Boolean> mInProfileMode = new ThreadLocal<Boolean>(); // Separate data row handler instances for contact data and profile data. private HashMap<String, DataRowHandler> mDataRowHandlers; private HashMap<String, DataRowHandler> mProfileDataRowHandlers; // Depending on whether the action being performed is for the profile, we will use one of two // database helper instances. private final ThreadLocal<ContactsDatabaseHelper> mDbHelper = new ThreadLocal<ContactsDatabaseHelper>(); private ContactsDatabaseHelper mContactsHelper; private ProfileDatabaseHelper mProfileHelper; // Depending on whether the action being performed is for the profile or not, we will use one of // two aggregator instances. private final ThreadLocal<ContactAggregator> mAggregator = new ThreadLocal<ContactAggregator>(); private ContactAggregator mContactAggregator; private ContactAggregator mProfileAggregator; // Depending on whether the action being performed is for the profile or not, we will use one of // two photo store instances (with their files stored in separate subdirectories). private final ThreadLocal<PhotoStore> mPhotoStore = new ThreadLocal<PhotoStore>(); private PhotoStore mContactsPhotoStore; private PhotoStore mProfilePhotoStore; // The active transaction context will switch depending on the operation being performed. // Both transaction contexts will be cleared out when a batch transaction is started, and // each will be processed separately when a batch transaction completes. private TransactionContext mContactTransactionContext = new TransactionContext(false); private TransactionContext mProfileTransactionContext = new TransactionContext(true); private final ThreadLocal<TransactionContext> mTransactionContext = new ThreadLocal<TransactionContext>(); // Duration in milliseconds that pre-authorized URIs will remain valid. private long mPreAuthorizedUriDuration; // Map of single-use pre-authorized URIs to expiration times. private Map<Uri, Long> mPreAuthorizedUris = Maps.newHashMap(); // Random number generator. private SecureRandom mRandom = new SecureRandom(); private LegacyApiSupport mLegacyApiSupport; private GlobalSearchSupport mGlobalSearchSupport; private CommonNicknameCache mCommonNicknameCache; private SearchIndexManager mSearchIndexManager; private ContentValues mValues = new ContentValues(); private HashMap<String, Boolean> mAccountWritability = Maps.newHashMap(); private int mProviderStatus = ProviderStatus.STATUS_NORMAL; private boolean mProviderStatusUpdateNeeded; private long mEstimatedStorageRequirement = 0; private volatile CountDownLatch mReadAccessLatch; private volatile CountDownLatch mWriteAccessLatch; private boolean mAccountUpdateListenerRegistered; private boolean mOkToOpenAccess = true; private boolean mVisibleTouched = false; private boolean mSyncToNetwork; private Locale mCurrentLocale; private int mContactsAccountCount; private HandlerThread mBackgroundThread; private Handler mBackgroundHandler; private long mLastPhotoCleanup = 0; @Override public boolean onCreate() { if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) { Log.d(Constants.PERFORMANCE_TAG, "ContactsProvider2.onCreate start"); } super.onCreate(); try { return initialize(); } catch (RuntimeException e) { Log.e(TAG, "Cannot start provider", e); return false; } finally { if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) { Log.d(Constants.PERFORMANCE_TAG, "ContactsProvider2.onCreate finish"); } } } private boolean initialize() { StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build()); Resources resources = getContext().getResources(); mMaxDisplayPhotoDim = resources.getInteger( R.integer.config_max_display_photo_dim); mMaxThumbnailPhotoDim = resources.getInteger( R.integer.config_max_thumbnail_photo_dim); mContactsHelper = getDatabaseHelper(getContext()); mDbHelper.set(mContactsHelper); // Set up the DB helper for keeping transactions serialized. setDbHelperToSerializeOn(mContactsHelper, CONTACTS_DB_TAG); mContactDirectoryManager = new ContactDirectoryManager(this); mGlobalSearchSupport = new GlobalSearchSupport(this); // The provider is closed for business until fully initialized mReadAccessLatch = new CountDownLatch(1); mWriteAccessLatch = new CountDownLatch(1); mBackgroundThread = new HandlerThread("ContactsProviderWorker", Process.THREAD_PRIORITY_BACKGROUND); mBackgroundThread.start(); mBackgroundHandler = new Handler(mBackgroundThread.getLooper()) { @Override public void handleMessage(Message msg) { performBackgroundTask(msg.what, msg.obj); } }; // Set up the sub-provider for handling profiles. mProfileProvider = getProfileProvider(); mProfileProvider.setDbHelperToSerializeOn(mContactsHelper, CONTACTS_DB_TAG); ProviderInfo profileInfo = new ProviderInfo(); profileInfo.readPermission = "android.permission.READ_PROFILE"; profileInfo.writePermission = "android.permission.WRITE_PROFILE"; mProfileProvider.attachInfo(getContext(), profileInfo); mProfileHelper = mProfileProvider.getDatabaseHelper(getContext()); // Initialize the pre-authorized URI duration. mPreAuthorizedUriDuration = android.provider.Settings.Secure.getLong( getContext().getContentResolver(), android.provider.Settings.Secure.CONTACTS_PREAUTH_URI_EXPIRATION, DEFAULT_PREAUTHORIZED_URI_EXPIRATION); scheduleBackgroundTask(BACKGROUND_TASK_INITIALIZE); scheduleBackgroundTask(BACKGROUND_TASK_IMPORT_LEGACY_CONTACTS); scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_ACCOUNTS); scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_LOCALE); scheduleBackgroundTask(BACKGROUND_TASK_UPGRADE_AGGREGATION_ALGORITHM); scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_SEARCH_INDEX); scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_PROVIDER_STATUS); scheduleBackgroundTask(BACKGROUND_TASK_OPEN_WRITE_ACCESS); scheduleBackgroundTask(BACKGROUND_TASK_CLEANUP_PHOTOS); return true; } /** * (Re)allocates all locale-sensitive structures. */ private void initForDefaultLocale() { Context context = getContext(); mLegacyApiSupport = new LegacyApiSupport(context, mContactsHelper, this, mGlobalSearchSupport); mCurrentLocale = getLocale(); mNameSplitter = mContactsHelper.createNameSplitter(); mNameLookupBuilder = new StructuredNameLookupBuilder(mNameSplitter); mPostalSplitter = new PostalSplitter(mCurrentLocale); mCommonNicknameCache = new CommonNicknameCache(mContactsHelper.getReadableDatabase()); ContactLocaleUtils.getIntance().setLocale(mCurrentLocale); mContactAggregator = new ContactAggregator(this, mContactsHelper, createPhotoPriorityResolver(context), mNameSplitter, mCommonNicknameCache); mContactAggregator.setEnabled(SystemProperties.getBoolean(AGGREGATE_CONTACTS, true)); mProfileAggregator = new ProfileAggregator(this, mProfileHelper, createPhotoPriorityResolver(context), mNameSplitter, mCommonNicknameCache); mProfileAggregator.setEnabled(SystemProperties.getBoolean(AGGREGATE_CONTACTS, true)); mSearchIndexManager = new SearchIndexManager(this); mContactsPhotoStore = new PhotoStore(getContext().getFilesDir(), mContactsHelper); mProfilePhotoStore = new PhotoStore(new File(getContext().getFilesDir(), "profile"), mProfileHelper); mDataRowHandlers = new HashMap<String, DataRowHandler>(); initDataRowHandlers(mDataRowHandlers, mContactsHelper, mContactAggregator, mContactsPhotoStore); mProfileDataRowHandlers = new HashMap<String, DataRowHandler>(); initDataRowHandlers(mProfileDataRowHandlers, mProfileHelper, mProfileAggregator, mProfilePhotoStore); // Set initial thread-local state variables for the Contacts DB. switchToContactMode(); } private void initDataRowHandlers(Map<String, DataRowHandler> handlerMap, ContactsDatabaseHelper dbHelper, ContactAggregator contactAggregator, PhotoStore photoStore) { Context context = getContext(); handlerMap.put(Email.CONTENT_ITEM_TYPE, new DataRowHandlerForEmail(context, dbHelper, contactAggregator)); handlerMap.put(Im.CONTENT_ITEM_TYPE, new DataRowHandlerForIm(context, dbHelper, contactAggregator)); handlerMap.put(Organization.CONTENT_ITEM_TYPE, new DataRowHandlerForOrganization(context, dbHelper, contactAggregator)); handlerMap.put(Phone.CONTENT_ITEM_TYPE, new DataRowHandlerForPhoneNumber(context, dbHelper, contactAggregator)); handlerMap.put(Nickname.CONTENT_ITEM_TYPE, new DataRowHandlerForNickname(context, dbHelper, contactAggregator)); handlerMap.put(StructuredName.CONTENT_ITEM_TYPE, new DataRowHandlerForStructuredName(context, dbHelper, contactAggregator, mNameSplitter, mNameLookupBuilder)); handlerMap.put(StructuredPostal.CONTENT_ITEM_TYPE, new DataRowHandlerForStructuredPostal(context, dbHelper, contactAggregator, mPostalSplitter)); handlerMap.put(GroupMembership.CONTENT_ITEM_TYPE, new DataRowHandlerForGroupMembership(context, dbHelper, contactAggregator, mGroupIdCache)); handlerMap.put(Photo.CONTENT_ITEM_TYPE, new DataRowHandlerForPhoto(context, dbHelper, contactAggregator, photoStore)); handlerMap.put(Note.CONTENT_ITEM_TYPE, new DataRowHandlerForNote(context, dbHelper, contactAggregator)); } /** * Visible for testing. */ /* package */ PhotoPriorityResolver createPhotoPriorityResolver(Context context) { return new PhotoPriorityResolver(context); } protected void scheduleBackgroundTask(int task) { mBackgroundHandler.sendEmptyMessage(task); } protected void scheduleBackgroundTask(int task, Object arg) { mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(task, arg)); } protected void performBackgroundTask(int task, Object arg) { switch (task) { case BACKGROUND_TASK_INITIALIZE: { initForDefaultLocale(); mReadAccessLatch.countDown(); mReadAccessLatch = null; break; } case BACKGROUND_TASK_OPEN_WRITE_ACCESS: { if (mOkToOpenAccess) { mWriteAccessLatch.countDown(); mWriteAccessLatch = null; } break; } case BACKGROUND_TASK_IMPORT_LEGACY_CONTACTS: { if (isLegacyContactImportNeeded()) { importLegacyContactsInBackground(); } break; } case BACKGROUND_TASK_UPDATE_ACCOUNTS: { Context context = getContext(); if (!mAccountUpdateListenerRegistered) { AccountManager.get(context).addOnAccountsUpdatedListener(this, null, false); mAccountUpdateListenerRegistered = true; } // Update the accounts for both the contacts and profile DBs. Account[] accounts = AccountManager.get(context).getAccounts(); switchToContactMode(); boolean accountsChanged = updateAccountsInBackground(accounts); switchToProfileMode(); accountsChanged |= updateAccountsInBackground(accounts); updateContactsAccountCount(accounts); updateDirectoriesInBackground(accountsChanged); break; } case BACKGROUND_TASK_UPDATE_LOCALE: { updateLocaleInBackground(); break; } case BACKGROUND_TASK_CHANGE_LOCALE: { changeLocaleInBackground(); break; } case BACKGROUND_TASK_UPGRADE_AGGREGATION_ALGORITHM: { if (isAggregationUpgradeNeeded()) { upgradeAggregationAlgorithmInBackground(); } break; } case BACKGROUND_TASK_UPDATE_SEARCH_INDEX: { updateSearchIndexInBackground(); break; } case BACKGROUND_TASK_UPDATE_PROVIDER_STATUS: { updateProviderStatus(); break; } case BACKGROUND_TASK_UPDATE_DIRECTORIES: { if (arg != null) { mContactDirectoryManager.onPackageChanged((String) arg); } break; } case BACKGROUND_TASK_CLEANUP_PHOTOS: { // Check rate limit. long now = System.currentTimeMillis(); if (now - mLastPhotoCleanup > PHOTO_CLEANUP_RATE_LIMIT) { mLastPhotoCleanup = now; // Clean up photo stores for both contacts and profiles. switchToContactMode(); cleanupPhotoStore(); switchToProfileMode(); cleanupPhotoStore(); break; } } } } public void onLocaleChanged() { if (mProviderStatus != ProviderStatus.STATUS_NORMAL && mProviderStatus != ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS) { return; } scheduleBackgroundTask(BACKGROUND_TASK_CHANGE_LOCALE); } /** * Verifies that the contacts database is properly configured for the current locale. * If not, changes the database locale to the current locale using an asynchronous task. * This needs to be done asynchronously because the process involves rebuilding * large data structures (name lookup, sort keys), which can take minutes on * a large set of contacts. */ protected void updateLocaleInBackground() { // The process is already running - postpone the change if (mProviderStatus == ProviderStatus.STATUS_CHANGING_LOCALE) { return; } final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); final String providerLocale = prefs.getString(PREF_LOCALE, null); final Locale currentLocale = mCurrentLocale; if (currentLocale.toString().equals(providerLocale)) { return; } int providerStatus = mProviderStatus; setProviderStatus(ProviderStatus.STATUS_CHANGING_LOCALE); mContactsHelper.setLocale(this, currentLocale); mProfileHelper.setLocale(this, currentLocale); prefs.edit().putString(PREF_LOCALE, currentLocale.toString()).apply(); setProviderStatus(providerStatus); } /** * Reinitializes the provider for a new locale. */ private void changeLocaleInBackground() { // Re-initializing the provider without stopping it. // Locking the database will prevent inserts/updates/deletes from // running at the same time, but queries may still be running // on other threads. Those queries may return inconsistent results. SQLiteDatabase db = mContactsHelper.getWritableDatabase(); SQLiteDatabase profileDb = mProfileHelper.getWritableDatabase(); db.beginTransaction(); profileDb.beginTransaction(); try { initForDefaultLocale(); db.setTransactionSuccessful(); profileDb.setTransactionSuccessful(); } finally { db.endTransaction(); profileDb.endTransaction(); } updateLocaleInBackground(); } protected void updateSearchIndexInBackground() { mSearchIndexManager.updateIndex(); } protected void updateDirectoriesInBackground(boolean rescan) { mContactDirectoryManager.scanAllPackages(rescan); } private void updateProviderStatus() { if (mProviderStatus != ProviderStatus.STATUS_NORMAL && mProviderStatus != ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS) { return; } // No accounts/no contacts status is true if there are no account and // there are no contacts or one profile contact if (mContactsAccountCount == 0) { long contactsNum = DatabaseUtils.queryNumEntries(mContactsHelper.getReadableDatabase(), Tables.CONTACTS, null); long profileNum = DatabaseUtils.queryNumEntries(mProfileHelper.getReadableDatabase(), Tables.CONTACTS, null); // TODO: Different status if there is a profile but no contacts? if (contactsNum == 0 && profileNum <= 1) { setProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } else { setProviderStatus(ProviderStatus.STATUS_NORMAL); } } else { setProviderStatus(ProviderStatus.STATUS_NORMAL); } } /* Visible for testing */ protected void cleanupPhotoStore() { SQLiteDatabase db = mDbHelper.get().getWritableDatabase(); mActiveDb.set(db); // Assemble the set of photo store file IDs that are in use, and send those to the photo // store. Any photos that aren't in that set will be deleted, and any photos that no // longer exist in the photo store will be returned for us to clear out in the DB. long photoMimeTypeId = mDbHelper.get().getMimeTypeId(Photo.CONTENT_ITEM_TYPE); Cursor c = db.query(Views.DATA, new String[]{Data._ID, Photo.PHOTO_FILE_ID}, DataColumns.MIMETYPE_ID + "=" + photoMimeTypeId + " AND " + Photo.PHOTO_FILE_ID + " IS NOT NULL", null, null, null, null); Set<Long> usedPhotoFileIds = Sets.newHashSet(); Map<Long, Long> photoFileIdToDataId = Maps.newHashMap(); try { while (c.moveToNext()) { long dataId = c.getLong(0); long photoFileId = c.getLong(1); usedPhotoFileIds.add(photoFileId); photoFileIdToDataId.put(photoFileId, dataId); } } finally { c.close(); } // Also query for all social stream item photos. c = db.query(Tables.STREAM_ITEM_PHOTOS + " JOIN " + Tables.STREAM_ITEMS + " ON " + StreamItemPhotos.STREAM_ITEM_ID + "=" + StreamItemsColumns.CONCRETE_ID + " JOIN " + Tables.RAW_CONTACTS + " ON " + StreamItems.RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID, new String[]{ StreamItemPhotosColumns.CONCRETE_ID, StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID, StreamItemPhotos.PHOTO_FILE_ID, RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_NAME }, null, null, null, null, null); Map<Long, Long> photoFileIdToStreamItemPhotoId = Maps.newHashMap(); Map<Long, Long> streamItemPhotoIdToStreamItemId = Maps.newHashMap(); Map<Long, Account> streamItemPhotoIdToAccount = Maps.newHashMap(); try { while (c.moveToNext()) { long streamItemPhotoId = c.getLong(0); long streamItemId = c.getLong(1); long photoFileId = c.getLong(2); String accountType = c.getString(3); String accountName = c.getString(4); usedPhotoFileIds.add(photoFileId); photoFileIdToStreamItemPhotoId.put(photoFileId, streamItemPhotoId); streamItemPhotoIdToStreamItemId.put(streamItemPhotoId, streamItemId); Account account = new Account(accountName, accountType); streamItemPhotoIdToAccount.put(photoFileId, account); } } finally { c.close(); } // Run the photo store cleanup. Set<Long> missingPhotoIds = mPhotoStore.get().cleanup(usedPhotoFileIds); // If any of the keys we're using no longer exist, clean them up. We need to do these // using internal APIs or direct DB access to avoid permission errors. if (!missingPhotoIds.isEmpty()) { try { db.beginTransactionWithListener(this); for (long missingPhotoId : missingPhotoIds) { if (photoFileIdToDataId.containsKey(missingPhotoId)) { long dataId = photoFileIdToDataId.get(missingPhotoId); ContentValues updateValues = new ContentValues(); updateValues.putNull(Photo.PHOTO_FILE_ID); updateData(ContentUris.withAppendedId(Data.CONTENT_URI, dataId), updateValues, null, null, false); } if (photoFileIdToStreamItemPhotoId.containsKey(missingPhotoId)) { // For missing photos that were in stream item photos, just delete the // stream item photo. long streamItemPhotoId = photoFileIdToStreamItemPhotoId.get(missingPhotoId); db.delete(Tables.STREAM_ITEM_PHOTOS, StreamItemPhotos._ID + "=?", new String[]{String.valueOf(streamItemPhotoId)}); } } db.setTransactionSuccessful(); } catch (Exception e) { // Cleanup failure is not a fatal problem. We'll try again later. Log.e(TAG, "Failed to clean up outdated photo references", e); } finally { db.endTransaction(); } } } @Override protected ContactsDatabaseHelper getDatabaseHelper(final Context context) { return ContactsDatabaseHelper.getInstance(context); } @Override protected ThreadLocal<ContactsTransaction> getTransactionHolder() { return mTransactionHolder; } public ProfileProvider getProfileProvider() { return new ProfileProvider(this); } @VisibleForTesting /* package */ PhotoStore getPhotoStore() { return mContactsPhotoStore; } @VisibleForTesting /* package */ PhotoStore getProfilePhotoStore() { return mProfilePhotoStore; } /* package */ int getMaxDisplayPhotoDim() { return mMaxDisplayPhotoDim; } /* package */ int getMaxThumbnailPhotoDim() { return mMaxThumbnailPhotoDim; } /* package */ NameSplitter getNameSplitter() { return mNameSplitter; } /* package */ NameLookupBuilder getNameLookupBuilder() { return mNameLookupBuilder; } /* Visible for testing */ public ContactDirectoryManager getContactDirectoryManagerForTest() { return mContactDirectoryManager; } /* Visible for testing */ protected Locale getLocale() { return Locale.getDefault(); } private boolean inProfileMode() { Boolean profileMode = mInProfileMode.get(); return profileMode != null && profileMode; } protected boolean isLegacyContactImportNeeded() { int version = Integer.parseInt( mContactsHelper.getProperty(PROPERTY_CONTACTS_IMPORTED, "0")); return version < PROPERTY_CONTACTS_IMPORT_VERSION; } protected LegacyContactImporter getLegacyContactImporter() { return new LegacyContactImporter(getContext(), this); } /** * Imports legacy contacts as a background task. */ private void importLegacyContactsInBackground() { Log.v(TAG, "Importing legacy contacts"); setProviderStatus(ProviderStatus.STATUS_UPGRADING); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); mContactsHelper.setLocale(this, mCurrentLocale); prefs.edit().putString(PREF_LOCALE, mCurrentLocale.toString()).commit(); LegacyContactImporter importer = getLegacyContactImporter(); if (importLegacyContacts(importer)) { onLegacyContactImportSuccess(); } else { onLegacyContactImportFailure(); } } /** * Unlocks the provider and declares that the import process is complete. */ private void onLegacyContactImportSuccess() { NotificationManager nm = (NotificationManager)getContext().getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(LEGACY_IMPORT_FAILED_NOTIFICATION); // Store a property in the database indicating that the conversion process succeeded mContactsHelper.setProperty(PROPERTY_CONTACTS_IMPORTED, String.valueOf(PROPERTY_CONTACTS_IMPORT_VERSION)); setProviderStatus(ProviderStatus.STATUS_NORMAL); Log.v(TAG, "Completed import of legacy contacts"); } /** * Announces the provider status and keeps the provider locked. */ private void onLegacyContactImportFailure() { Context context = getContext(); NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); // Show a notification Notification n = new Notification(android.R.drawable.stat_notify_error, context.getString(R.string.upgrade_out_of_memory_notification_ticker), System.currentTimeMillis()); n.setLatestEventInfo(context, context.getString(R.string.upgrade_out_of_memory_notification_title), context.getString(R.string.upgrade_out_of_memory_notification_text), PendingIntent.getActivity(context, 0, new Intent(Intents.UI.LIST_DEFAULT), 0)); n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; nm.notify(LEGACY_IMPORT_FAILED_NOTIFICATION, n); setProviderStatus(ProviderStatus.STATUS_UPGRADE_OUT_OF_MEMORY); Log.v(TAG, "Failed to import legacy contacts"); // Do not let any database changes until this issue is resolved. mOkToOpenAccess = false; } /* Visible for testing */ /* package */ boolean importLegacyContacts(LegacyContactImporter importer) { boolean aggregatorEnabled = mContactAggregator.isEnabled(); mContactAggregator.setEnabled(false); try { if (importer.importContacts()) { // TODO aggregate all newly added raw contacts mContactAggregator.setEnabled(aggregatorEnabled); return true; } } catch (Throwable e) { Log.e(TAG, "Legacy contact import failed", e); } mEstimatedStorageRequirement = importer.getEstimatedStorageRequirement(); return false; } /** * Wipes all data from the contacts database. */ /* package */ void wipeData() { mContactsHelper.wipeData(); mProfileHelper.wipeData(); mContactsPhotoStore.clear(); mProfilePhotoStore.clear(); mProviderStatus = ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS; } /** * During intialization, this content provider will * block all attempts to change contacts data. In particular, it will hold * up all contact syncs. As soon as the import process is complete, all * processes waiting to write to the provider are unblocked and can proceed * to compete for the database transaction monitor. */ private void waitForAccess(CountDownLatch latch) { if (latch == null) { return; } while (true) { try { latch.await(); return; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } /** * Determines whether the given URI should be directed to the profile * database rather than the contacts database. This is true under either * of three conditions: * 1. The URI itself is specifically for the profile. * 2. The URI contains ID references that are in the profile ID-space. * 3. The URI contains lookup key references that match the special profile lookup key. * @param uri The URI to examine. * @return Whether to direct the DB operation to the profile database. */ private boolean mapsToProfileDb(Uri uri) { return sUriMatcher.mapsToProfile(uri); } /** * Determines whether the given URI with the given values being inserted * should be directed to the profile database rather than the contacts * database. This is true if the URI already maps to the profile DB from * a call to {@link #mapsToProfileDb} or if the URI matches a URI that * specifies parent IDs via the ContentValues, and the given ContentValues * contains an ID in the profile ID-space. * @param uri The URI to examine. * @param values The values being inserted. * @return Whether to direct the DB insert to the profile database. */ private boolean mapsToProfileDbWithInsertedValues(Uri uri, ContentValues values) { if (mapsToProfileDb(uri)) { return true; } int match = sUriMatcher.match(uri); if (INSERT_URI_ID_VALUE_MAP.containsKey(match)) { String idField = INSERT_URI_ID_VALUE_MAP.get(match); if (values.containsKey(idField)) { long id = values.getAsLong(idField); if (ContactsContract.isProfileId(id)) { return true; } } } return false; } /** * Switches the provider's thread-local context variables to prepare for performing * a profile operation. */ protected void switchToProfileMode() { mDbHelper.set(mProfileHelper); mTransactionContext.set(mProfileTransactionContext); mAggregator.set(mProfileAggregator); mPhotoStore.set(mProfilePhotoStore); mInProfileMode.set(true); } /** * Switches the provider's thread-local context variables to prepare for performing * a contacts operation. */ protected void switchToContactMode() { mDbHelper.set(mContactsHelper); mTransactionContext.set(mContactTransactionContext); mAggregator.set(mContactAggregator); mPhotoStore.set(mContactsPhotoStore); mInProfileMode.set(false); // Clear out the active database; modification operations will set this to the contacts DB. mActiveDb.set(null); } @Override public Uri insert(Uri uri, ContentValues values) { waitForAccess(mWriteAccessLatch); // Enforce stream items access check if applicable. enforceSocialStreamWritePermission(uri); if (mapsToProfileDbWithInsertedValues(uri, values)) { switchToProfileMode(); return mProfileProvider.insert(uri, values); } else { switchToContactMode(); return super.insert(uri, values); } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (mWriteAccessLatch != null) { // We are stuck trying to upgrade contacts db. The only update request // allowed in this case is an update of provider status, which will trigger // an attempt to upgrade contacts again. int match = sUriMatcher.match(uri); if (match == PROVIDER_STATUS) { Integer newStatus = values.getAsInteger(ProviderStatus.STATUS); if (newStatus != null && newStatus == ProviderStatus.STATUS_UPGRADING) { scheduleBackgroundTask(BACKGROUND_TASK_IMPORT_LEGACY_CONTACTS); return 1; } else { return 0; } } } waitForAccess(mWriteAccessLatch); // Enforce stream items access check if applicable. enforceSocialStreamWritePermission(uri); if (mapsToProfileDb(uri)) { switchToProfileMode(); return mProfileProvider.update(uri, values, selection, selectionArgs); } else { switchToContactMode(); return super.update(uri, values, selection, selectionArgs); } } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { waitForAccess(mWriteAccessLatch); // Enforce stream items access check if applicable. enforceSocialStreamWritePermission(uri); if (mapsToProfileDb(uri)) { switchToProfileMode(); return mProfileProvider.delete(uri, selection, selectionArgs); } else { switchToContactMode(); return super.delete(uri, selection, selectionArgs); } } /** * Replaces the current (thread-local) database to use for the operation with the given one. * @param db The database to use. */ /* package */ void substituteDb(SQLiteDatabase db) { mActiveDb.set(db); } @Override public Bundle call(String method, String arg, Bundle extras) { waitForAccess(mReadAccessLatch); if (method.equals(Authorization.AUTHORIZATION_METHOD)) { Uri uri = (Uri) extras.getParcelable(Authorization.KEY_URI_TO_AUTHORIZE); // Check permissions on the caller. The URI can only be pre-authorized if the caller // already has the necessary permissions. enforceSocialStreamReadPermission(uri); if (mapsToProfileDb(uri)) { mProfileProvider.enforceReadPermission(uri); } // If there hasn't been a security violation yet, we're clear to pre-authorize the URI. Uri authUri = preAuthorizeUri(uri); Bundle response = new Bundle(); response.putParcelable(Authorization.KEY_AUTHORIZED_URI, authUri); return response; } return null; } /** * Pre-authorizes the given URI, adding an expiring permission token to it and placing that * in our map of pre-authorized URIs. * @param uri The URI to pre-authorize. * @return A pre-authorized URI that will not require special permissions to use. */ private Uri preAuthorizeUri(Uri uri) { String token = String.valueOf(mRandom.nextLong()); Uri authUri = uri.buildUpon() .appendQueryParameter(PREAUTHORIZED_URI_TOKEN, token) .build(); long expiration = SystemClock.elapsedRealtime() + mPreAuthorizedUriDuration; mPreAuthorizedUris.put(authUri, expiration); return authUri; } /** * Checks whether the given URI has an unexpired permission token that would grant access to * query the content. If it does, the regular permission check should be skipped. * @param uri The URI being accessed. * @return Whether the URI is a pre-authorized URI that is still valid. */ public boolean isValidPreAuthorizedUri(Uri uri) { // Only proceed if the URI has a permission token parameter. if (uri.getQueryParameter(PREAUTHORIZED_URI_TOKEN) != null) { // First expire any pre-authorization URIs that are no longer valid. long now = SystemClock.elapsedRealtime(); Set<Uri> expiredUris = Sets.newHashSet(); for (Uri preAuthUri : mPreAuthorizedUris.keySet()) { if (mPreAuthorizedUris.get(preAuthUri) < now) { expiredUris.add(preAuthUri); } } for (Uri expiredUri : expiredUris) { mPreAuthorizedUris.remove(expiredUri); } // Now check to see if the pre-authorized URI map contains the URI. if (mPreAuthorizedUris.containsKey(uri)) { // Unexpired token - skip the permission check. return true; } } return false; } @Override protected boolean yield(ContactsTransaction transaction) { // If there's a profile transaction in progress, and we're yielding, we need to // end it. Unlike the Contacts DB yield (which re-starts a transaction at its // conclusion), we can just go back into a state in which we have no active // profile transaction, and let it be re-created as needed. We can't hold onto // the transaction without risking a deadlock. SQLiteDatabase profileDb = transaction.removeDbForTag(PROFILE_DB_TAG); if (profileDb != null) { profileDb.setTransactionSuccessful(); profileDb.endTransaction(); } // Now proceed with the Contacts DB yield. SQLiteDatabase contactsDb = transaction.getDbForTag(CONTACTS_DB_TAG); return contactsDb != null && contactsDb.yieldIfContendedSafely(SLEEP_AFTER_YIELD_DELAY); } @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { waitForAccess(mWriteAccessLatch); return super.applyBatch(operations); } @Override public int bulkInsert(Uri uri, ContentValues[] values) { waitForAccess(mWriteAccessLatch); return super.bulkInsert(uri, values); } @Override public void onBegin() { if (VERBOSE_LOGGING) { Log.v(TAG, "onBeginTransaction"); } if (inProfileMode()) { mProfileAggregator.clearPendingAggregations(); mProfileTransactionContext.clear(); } else { mContactAggregator.clearPendingAggregations(); mContactTransactionContext.clear(); } } @Override public void onCommit() { if (VERBOSE_LOGGING) { Log.v(TAG, "beforeTransactionCommit"); } flushTransactionalChanges(); mAggregator.get().aggregateInTransaction(mTransactionContext.get(), mActiveDb.get()); if (mVisibleTouched) { mVisibleTouched = false; mDbHelper.get().updateAllVisible(); } updateSearchIndexInTransaction(); if (mProviderStatusUpdateNeeded) { updateProviderStatus(); mProviderStatusUpdateNeeded = false; } } @Override public void onRollback() { // Not used. } private void updateSearchIndexInTransaction() { Set<Long> staleContacts = mTransactionContext.get().getStaleSearchIndexContactIds(); Set<Long> staleRawContacts = mTransactionContext.get().getStaleSearchIndexRawContactIds(); if (!staleContacts.isEmpty() || !staleRawContacts.isEmpty()) { mSearchIndexManager.updateIndexForRawContacts(staleContacts, staleRawContacts); mTransactionContext.get().clearSearchIndexUpdates(); } } private void flushTransactionalChanges() { if (VERBOSE_LOGGING) { Log.v(TAG, "flushTransactionChanges"); } for (long rawContactId : mTransactionContext.get().getInsertedRawContactIds()) { mDbHelper.get().updateRawContactDisplayName(mActiveDb.get(), rawContactId); mAggregator.get().onRawContactInsert(mTransactionContext.get(), mActiveDb.get(), rawContactId); } Set<Long> dirtyRawContacts = mTransactionContext.get().getDirtyRawContactIds(); if (!dirtyRawContacts.isEmpty()) { mSb.setLength(0); mSb.append(UPDATE_RAW_CONTACT_SET_DIRTY_SQL); appendIds(mSb, dirtyRawContacts); mSb.append(")"); mActiveDb.get().execSQL(mSb.toString()); } Set<Long> updatedRawContacts = mTransactionContext.get().getUpdatedRawContactIds(); if (!updatedRawContacts.isEmpty()) { mSb.setLength(0); mSb.append(UPDATE_RAW_CONTACT_SET_VERSION_SQL); appendIds(mSb, updatedRawContacts); mSb.append(")"); mActiveDb.get().execSQL(mSb.toString()); } // Update sync states. for (Map.Entry<Long, Object> entry : mTransactionContext.get().getUpdatedSyncStates()) { long id = entry.getKey(); if (mDbHelper.get().getSyncState().update(mActiveDb.get(), id, entry.getValue()) <= 0) { throw new IllegalStateException( "unable to update sync state, does it still exist?"); } } mTransactionContext.get().clear(); } /** * Appends comma separated ids. * @param ids Should not be empty */ private void appendIds(StringBuilder sb, Set<Long> ids) { for (long id : ids) { sb.append(id).append(','); } sb.setLength(sb.length() - 1); // Yank the last comma } @Override protected void notifyChange() { notifyChange(mSyncToNetwork); mSyncToNetwork = false; } protected void notifyChange(boolean syncToNetwork) { getContext().getContentResolver().notifyChange(ContactsContract.AUTHORITY_URI, null, syncToNetwork); } protected void setProviderStatus(int status) { if (mProviderStatus != status) { mProviderStatus = status; getContext().getContentResolver().notifyChange(ProviderStatus.CONTENT_URI, null, false); } } public DataRowHandler getDataRowHandler(final String mimeType) { if (inProfileMode()) { return getDataRowHandlerForProfile(mimeType); } DataRowHandler handler = mDataRowHandlers.get(mimeType); if (handler == null) { handler = new DataRowHandlerForCustomMimetype( getContext(), mContactsHelper, mContactAggregator, mimeType); mDataRowHandlers.put(mimeType, handler); } return handler; } public DataRowHandler getDataRowHandlerForProfile(final String mimeType) { DataRowHandler handler = mProfileDataRowHandlers.get(mimeType); if (handler == null) { handler = new DataRowHandlerForCustomMimetype( getContext(), mProfileHelper, mProfileAggregator, mimeType); mProfileDataRowHandlers.put(mimeType, handler); } return handler; } @Override protected Uri insertInTransaction(Uri uri, ContentValues values) { if (VERBOSE_LOGGING) { Log.v(TAG, "insertInTransaction: " + uri + " " + values); } // Default active DB to the contacts DB if none has been set. if (mActiveDb.get() == null) { mActiveDb.set(mContactsHelper.getWritableDatabase()); } final boolean callerIsSyncAdapter = readBooleanQueryParameter(uri, ContactsContract.CALLER_IS_SYNCADAPTER, false); final int match = sUriMatcher.match(uri); long id = 0; switch (match) { case SYNCSTATE: case PROFILE_SYNCSTATE: id = mDbHelper.get().getSyncState().insert(mActiveDb.get(), values); break; case CONTACTS: { insertContact(values); break; } case PROFILE: { throw new UnsupportedOperationException( "The profile contact is created automatically"); } case RAW_CONTACTS: case PROFILE_RAW_CONTACTS: { id = insertRawContact(uri, values, callerIsSyncAdapter); mSyncToNetwork |= !callerIsSyncAdapter; break; } case RAW_CONTACTS_DATA: case PROFILE_RAW_CONTACTS_ID_DATA: { int segment = match == RAW_CONTACTS_DATA ? 1 : 2; values.put(Data.RAW_CONTACT_ID, uri.getPathSegments().get(segment)); id = insertData(values, callerIsSyncAdapter); mSyncToNetwork |= !callerIsSyncAdapter; break; } case RAW_CONTACTS_ID_STREAM_ITEMS: { values.put(StreamItems.RAW_CONTACT_ID, uri.getPathSegments().get(1)); id = insertStreamItem(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } case DATA: case PROFILE_DATA: { id = insertData(values, callerIsSyncAdapter); mSyncToNetwork |= !callerIsSyncAdapter; break; } case GROUPS: { id = insertGroup(uri, values, callerIsSyncAdapter); mSyncToNetwork |= !callerIsSyncAdapter; break; } case SETTINGS: { id = insertSettings(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } case STATUS_UPDATES: case PROFILE_STATUS_UPDATES: { id = insertStatusUpdate(values); break; } case STREAM_ITEMS: { id = insertStreamItem(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } case STREAM_ITEMS_PHOTOS: { id = insertStreamItemPhoto(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } case STREAM_ITEMS_ID_PHOTOS: { values.put(StreamItemPhotos.STREAM_ITEM_ID, uri.getPathSegments().get(1)); id = insertStreamItemPhoto(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } default: mSyncToNetwork = true; return mLegacyApiSupport.insert(uri, values); } if (id < 0) { return null; } return ContentUris.withAppendedId(uri, id); } /** * If account is non-null then store it in the values. If the account is * already specified in the values then it must be consistent with the * account, if it is non-null. * * @param uri Current {@link Uri} being operated on. * @param values {@link ContentValues} to read and possibly update. * @throws IllegalArgumentException when only one of * {@link RawContacts#ACCOUNT_NAME} or * {@link RawContacts#ACCOUNT_TYPE} is specified, leaving the * other undefined. * @throws IllegalArgumentException when {@link RawContacts#ACCOUNT_NAME} * and {@link RawContacts#ACCOUNT_TYPE} are inconsistent between * the given {@link Uri} and {@link ContentValues}. */ private Account resolveAccount(Uri uri, ContentValues values) throws IllegalArgumentException { String accountName = getQueryParameter(uri, RawContacts.ACCOUNT_NAME); String accountType = getQueryParameter(uri, RawContacts.ACCOUNT_TYPE); final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType); String valueAccountName = values.getAsString(RawContacts.ACCOUNT_NAME); String valueAccountType = values.getAsString(RawContacts.ACCOUNT_TYPE); final boolean partialValues = TextUtils.isEmpty(valueAccountName) ^ TextUtils.isEmpty(valueAccountType); if (partialUri || partialValues) { // Throw when either account is incomplete throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE", uri)); } // Accounts are valid by only checking one parameter, since we've // already ruled out partial accounts. final boolean validUri = !TextUtils.isEmpty(accountName); final boolean validValues = !TextUtils.isEmpty(valueAccountName); if (validValues && validUri) { // Check that accounts match when both present final boolean accountMatch = TextUtils.equals(accountName, valueAccountName) && TextUtils.equals(accountType, valueAccountType); if (!accountMatch) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "When both specified, ACCOUNT_NAME and ACCOUNT_TYPE must match", uri)); } } else if (validUri) { // Fill values from Uri when not present values.put(RawContacts.ACCOUNT_NAME, accountName); values.put(RawContacts.ACCOUNT_TYPE, accountType); } else if (validValues) { accountName = valueAccountName; accountType = valueAccountType; } else { return null; } // Use cached Account object when matches, otherwise create if (mAccount == null || !mAccount.name.equals(accountName) || !mAccount.type.equals(accountType)) { mAccount = new Account(accountName, accountType); } return mAccount; } /** * Resolves the account and builds an {@link AccountWithDataSet} based on the data set specified * in the URI or values (if any). * @param uri Current {@link Uri} being operated on. * @param values {@link ContentValues} to read and possibly update. */ private AccountWithDataSet resolveAccountWithDataSet(Uri uri, ContentValues values) { final Account account = resolveAccount(uri, values); AccountWithDataSet accountWithDataSet = null; if (account != null) { String dataSet = getQueryParameter(uri, RawContacts.DATA_SET); if (dataSet == null) { dataSet = values.getAsString(RawContacts.DATA_SET); } else { values.put(RawContacts.DATA_SET, dataSet); } accountWithDataSet = new AccountWithDataSet(account.name, account.type, dataSet); } return accountWithDataSet; } /** * Inserts an item in the contacts table * * @param values the values for the new row * @return the row ID of the newly created row */ private long insertContact(ContentValues values) { throw new UnsupportedOperationException("Aggregate contacts are created automatically"); } /** * Inserts an item in the raw contacts table * * @param uri the values for the new row * @param values the account this contact should be associated with. may be null. * @param callerIsSyncAdapter * @return the row ID of the newly created row */ private long insertRawContact(Uri uri, ContentValues values, boolean callerIsSyncAdapter) { mValues.clear(); mValues.putAll(values); mValues.putNull(RawContacts.CONTACT_ID); AccountWithDataSet accountWithDataSet = resolveAccountWithDataSet(uri, mValues); if (values.containsKey(RawContacts.DELETED) && values.getAsInteger(RawContacts.DELETED) != 0) { mValues.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED); } long rawContactId = mActiveDb.get().insert(Tables.RAW_CONTACTS, RawContacts.CONTACT_ID, mValues); int aggregationMode = RawContacts.AGGREGATION_MODE_DEFAULT; if (mValues.containsKey(RawContacts.AGGREGATION_MODE)) { aggregationMode = mValues.getAsInteger(RawContacts.AGGREGATION_MODE); } mAggregator.get().markNewForAggregation(rawContactId, aggregationMode); // Trigger creation of a Contact based on this RawContact at the end of transaction mTransactionContext.get().rawContactInserted(rawContactId, accountWithDataSet); if (!callerIsSyncAdapter) { addAutoAddMembership(rawContactId); final Long starred = values.getAsLong(RawContacts.STARRED); if (starred != null && starred != 0) { updateFavoritesMembership(rawContactId, starred != 0); } } mProviderStatusUpdateNeeded = true; return rawContactId; } private void addAutoAddMembership(long rawContactId) { final Long groupId = findGroupByRawContactId(SELECTION_AUTO_ADD_GROUPS_BY_RAW_CONTACT_ID, rawContactId); if (groupId != null) { insertDataGroupMembership(rawContactId, groupId); } } private Long findGroupByRawContactId(String selection, long rawContactId) { Cursor c = mActiveDb.get().query(Tables.GROUPS + "," + Tables.RAW_CONTACTS, PROJECTION_GROUP_ID, selection, new String[]{Long.toString(rawContactId)}, null /* groupBy */, null /* having */, null /* orderBy */); try { while (c.moveToNext()) { return c.getLong(0); } return null; } finally { c.close(); } } private void updateFavoritesMembership(long rawContactId, boolean isStarred) { final Long groupId = findGroupByRawContactId(SELECTION_FAVORITES_GROUPS_BY_RAW_CONTACT_ID, rawContactId); if (groupId != null) { if (isStarred) { insertDataGroupMembership(rawContactId, groupId); } else { deleteDataGroupMembership(rawContactId, groupId); } } } private void insertDataGroupMembership(long rawContactId, long groupId) { ContentValues groupMembershipValues = new ContentValues(); groupMembershipValues.put(GroupMembership.GROUP_ROW_ID, groupId); groupMembershipValues.put(GroupMembership.RAW_CONTACT_ID, rawContactId); groupMembershipValues.put(DataColumns.MIMETYPE_ID, mDbHelper.get().getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); mActiveDb.get().insert(Tables.DATA, null, groupMembershipValues); } private void deleteDataGroupMembership(long rawContactId, long groupId) { final String[] selectionArgs = { Long.toString(mDbHelper.get().getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)), Long.toString(groupId), Long.toString(rawContactId)}; mActiveDb.get().delete(Tables.DATA, SELECTION_GROUPMEMBERSHIP_DATA, selectionArgs); } /** * Inserts an item in the data table * * @param values the values for the new row * @return the row ID of the newly created row */ private long insertData(ContentValues values, boolean callerIsSyncAdapter) { long id = 0; mValues.clear(); mValues.putAll(values); long rawContactId = mValues.getAsLong(Data.RAW_CONTACT_ID); // Replace package with internal mapping final String packageName = mValues.getAsString(Data.RES_PACKAGE); if (packageName != null) { mValues.put(DataColumns.PACKAGE_ID, mDbHelper.get().getPackageId(packageName)); } mValues.remove(Data.RES_PACKAGE); // Replace mimetype with internal mapping final String mimeType = mValues.getAsString(Data.MIMETYPE); if (TextUtils.isEmpty(mimeType)) { throw new IllegalArgumentException(Data.MIMETYPE + " is required"); } mValues.put(DataColumns.MIMETYPE_ID, mDbHelper.get().getMimeTypeId(mimeType)); mValues.remove(Data.MIMETYPE); DataRowHandler rowHandler = getDataRowHandler(mimeType); id = rowHandler.insert(mActiveDb.get(), mTransactionContext.get(), rawContactId, mValues); if (!callerIsSyncAdapter) { mTransactionContext.get().markRawContactDirty(rawContactId); } mTransactionContext.get().rawContactUpdated(rawContactId); return id; } /** * Inserts an item in the stream_items table. The account is checked against the * account in the raw contact for which the stream item is being inserted. If the * new stream item results in more stream items under this raw contact than the limit, * the oldest one will be deleted (note that if the stream item inserted was the * oldest, it will be immediately deleted, and this will return 0). * * @param uri the insertion URI * @param values the values for the new row * @return the stream item _ID of the newly created row, or 0 if it was not created */ private long insertStreamItem(Uri uri, ContentValues values) { long id = 0; mValues.clear(); mValues.putAll(values); long rawContactId = mValues.getAsLong(StreamItems.RAW_CONTACT_ID); // Ensure that the raw contact exists and belongs to the caller's account. Account account = resolveAccount(uri, mValues); enforceModifyingAccount(account, rawContactId); // Don't attempt to insert accounts params - they don't exist in the stream items table. mValues.remove(RawContacts.ACCOUNT_NAME); mValues.remove(RawContacts.ACCOUNT_TYPE); // Insert the new stream item. id = mActiveDb.get().insert(Tables.STREAM_ITEMS, null, mValues); if (id == -1) { // Insertion failed. return 0; } // Check to see if we're over the limit for stream items under this raw contact. // It's possible that the inserted stream item is older than the the existing // ones, in which case it may be deleted immediately (resetting the ID to 0). id = cleanUpOldStreamItems(rawContactId, id); return id; } /** * Inserts an item in the stream_item_photos table. The account is checked against * the account in the raw contact that owns the stream item being modified. * * @param uri the insertion URI * @param values the values for the new row * @return the stream item photo _ID of the newly created row, or 0 if there was an issue * with processing the photo or creating the row */ private long insertStreamItemPhoto(Uri uri, ContentValues values) { long id = 0; mValues.clear(); mValues.putAll(values); long streamItemId = mValues.getAsLong(StreamItemPhotos.STREAM_ITEM_ID); if (streamItemId != 0) { long rawContactId = lookupRawContactIdForStreamId(streamItemId); // Ensure that the raw contact exists and belongs to the caller's account. Account account = resolveAccount(uri, mValues); enforceModifyingAccount(account, rawContactId); // Don't attempt to insert accounts params - they don't exist in the stream item // photos table. mValues.remove(RawContacts.ACCOUNT_NAME); mValues.remove(RawContacts.ACCOUNT_TYPE); // Process the photo and store it. if (processStreamItemPhoto(mValues, false)) { // Insert the stream item photo. id = mActiveDb.get().insert(Tables.STREAM_ITEM_PHOTOS, null, mValues); } } return id; } /** * Processes the photo contained in the {@link ContactsContract.StreamItemPhotos#PHOTO} * field of the given values, attempting to store it in the photo store. If successful, * the resulting photo file ID will be added to the values for insert/update in the table. * <p> * If updating, it is valid for the picture to be empty or unspecified (the function will * still return true). If inserting, a valid picture must be specified. * @param values The content values provided by the caller. * @param forUpdate Whether this photo is being processed for update (vs. insert). * @return Whether the insert or update should proceed. */ private boolean processStreamItemPhoto(ContentValues values, boolean forUpdate) { if (!values.containsKey(StreamItemPhotos.PHOTO)) { return forUpdate; } byte[] photoBytes = values.getAsByteArray(StreamItemPhotos.PHOTO); if (photoBytes == null) { return forUpdate; } // Process the photo and store it. try { long photoFileId = mPhotoStore.get().insert(new PhotoProcessor(photoBytes, mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim, true), true); if (photoFileId != 0) { values.put(StreamItemPhotos.PHOTO_FILE_ID, photoFileId); values.remove(StreamItemPhotos.PHOTO); return true; } else { // Couldn't store the photo, return 0. Log.e(TAG, "Could not process stream item photo for insert"); return false; } } catch (IOException ioe) { Log.e(TAG, "Could not process stream item photo for insert", ioe); return false; } } /** * Looks up the raw contact ID that owns the specified stream item. * @param streamItemId The ID of the stream item. * @return The associated raw contact ID, or -1 if no such stream item exists. */ private long lookupRawContactIdForStreamId(long streamItemId) { long rawContactId = -1; Cursor c = mActiveDb.get().query(Tables.STREAM_ITEMS, new String[]{StreamItems.RAW_CONTACT_ID}, StreamItems._ID + "=?", new String[]{String.valueOf(streamItemId)}, null, null, null); try { if (c.moveToFirst()) { rawContactId = c.getLong(0); } } finally { c.close(); } return rawContactId; } /** * If the given URI is reading stream items or stream photos, this will run a permission check * for the android.permission.READ_SOCIAL_STREAM permission - otherwise it will do nothing. * @param uri The URI to check. */ private void enforceSocialStreamReadPermission(Uri uri) { if (SOCIAL_STREAM_URIS.contains(sUriMatcher.match(uri)) && !isValidPreAuthorizedUri(uri)) { getContext().enforceCallingOrSelfPermission( "android.permission.READ_SOCIAL_STREAM", null); } } /** * If the given URI is modifying stream items or stream photos, this will run a permission check * for the android.permission.WRITE_SOCIAL_STREAM permission - otherwise it will do nothing. * @param uri The URI to check. */ private void enforceSocialStreamWritePermission(Uri uri) { if (SOCIAL_STREAM_URIS.contains(sUriMatcher.match(uri))) { getContext().enforceCallingOrSelfPermission( "android.permission.WRITE_SOCIAL_STREAM", null); } } /** * Checks whether the given raw contact ID is owned by the given account. * If the resolved account is null, this will return true iff the raw contact * is also associated with the "null" account. * * If the resolved account does not match, this will throw a security exception. * @param account The resolved account (may be null). * @param rawContactId The raw contact ID to check for. */ private void enforceModifyingAccount(Account account, long rawContactId) { String accountSelection = RawContactsColumns.CONCRETE_ID + "=? AND " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + "=? AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + "=?"; String noAccountSelection = RawContactsColumns.CONCRETE_ID + "=? AND " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL"; Cursor c; if (account != null) { c = mActiveDb.get().query(Tables.RAW_CONTACTS, new String[]{RawContactsColumns.CONCRETE_ID}, accountSelection, new String[]{String.valueOf(rawContactId), mAccount.name, mAccount.type}, null, null, null); } else { c = mActiveDb.get().query(Tables.RAW_CONTACTS, new String[]{RawContactsColumns.CONCRETE_ID}, noAccountSelection, new String[]{String.valueOf(rawContactId)}, null, null, null); } try { if(c.getCount() == 0) { throw new SecurityException("Caller account does not match raw contact ID " + rawContactId); } } finally { c.close(); } } /** * Checks whether the given selection of stream items matches up with the given * account. If any of the raw contacts fail the account check, this will throw a * security exception. * @param account The resolved account (may be null). * @param selection The selection. * @param selectionArgs The selection arguments. * @return The list of stream item IDs that would be included in this selection. */ private List<Long> enforceModifyingAccountForStreamItems(Account account, String selection, String[] selectionArgs) { List<Long> streamItemIds = Lists.newArrayList(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItems(qb); Cursor c = qb.query(mActiveDb.get(), new String[]{StreamItems._ID, StreamItems.RAW_CONTACT_ID}, selection, selectionArgs, null, null, null); try { while (c.moveToNext()) { streamItemIds.add(c.getLong(0)); // Throw a security exception if the account doesn't match the raw contact's. enforceModifyingAccount(account, c.getLong(1)); } } finally { c.close(); } return streamItemIds; } /** * Checks whether the given selection of stream item photos matches up with the given * account. If any of the raw contacts fail the account check, this will throw a * security exception. * @param account The resolved account (may be null). * @param selection The selection. * @param selectionArgs The selection arguments. * @return The list of stream item photo IDs that would be included in this selection. */ private List<Long> enforceModifyingAccountForStreamItemPhotos(Account account, String selection, String[] selectionArgs) { List<Long> streamItemPhotoIds = Lists.newArrayList(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItemPhotos(qb); Cursor c = qb.query(mActiveDb.get(), new String[]{StreamItemPhotos._ID, StreamItems.RAW_CONTACT_ID}, selection, selectionArgs, null, null, null); try { while (c.moveToNext()) { streamItemPhotoIds.add(c.getLong(0)); // Throw a security exception if the account doesn't match the raw contact's. enforceModifyingAccount(account, c.getLong(1)); } } finally { c.close(); } return streamItemPhotoIds; } /** * Queries the database for stream items under the given raw contact. If there are * more entries than {@link ContactsProvider2#MAX_STREAM_ITEMS_PER_RAW_CONTACT}, * the oldest entries (as determined by timestamp) will be deleted. * @param rawContactId The raw contact ID to examine for stream items. * @param insertedStreamItemId The ID of the stream item that was just inserted, * prompting this cleanup. Callers may pass 0 if no insertion prompted the * cleanup. * @return The ID of the inserted stream item if it still exists after cleanup; * 0 otherwise. */ private long cleanUpOldStreamItems(long rawContactId, long insertedStreamItemId) { long postCleanupInsertedStreamId = insertedStreamItemId; Cursor c = mActiveDb.get().query(Tables.STREAM_ITEMS, new String[]{StreamItems._ID}, StreamItems.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(rawContactId)}, null, null, StreamItems.TIMESTAMP + " DESC, " + StreamItems._ID + " DESC"); try { int streamItemCount = c.getCount(); if (streamItemCount <= MAX_STREAM_ITEMS_PER_RAW_CONTACT) { // Still under the limit - nothing to clean up! return insertedStreamItemId; } else { c.moveToLast(); while (c.getPosition() >= MAX_STREAM_ITEMS_PER_RAW_CONTACT) { long streamItemId = c.getLong(0); if (insertedStreamItemId == streamItemId) { // The stream item just inserted is being deleted. postCleanupInsertedStreamId = 0; } deleteStreamItem(c.getLong(0)); c.moveToPrevious(); } } } finally { c.close(); } return postCleanupInsertedStreamId; } /** * Delete data row by row so that fixing of primaries etc work correctly. */ private int deleteData(String selection, String[] selectionArgs, boolean callerIsSyncAdapter) { int count = 0; // Note that the query will return data according to the access restrictions, // so we don't need to worry about deleting data we don't have permission to read. Uri dataUri = inProfileMode() ? Uri.withAppendedPath(Profile.CONTENT_URI, RawContacts.Data.CONTENT_DIRECTORY) : Data.CONTENT_URI; Cursor c = query(dataUri, DataRowHandler.DataDeleteQuery.COLUMNS, selection, selectionArgs, null); try { while(c.moveToNext()) { long rawContactId = c.getLong(DataRowHandler.DataDeleteQuery.RAW_CONTACT_ID); String mimeType = c.getString(DataRowHandler.DataDeleteQuery.MIMETYPE); DataRowHandler rowHandler = getDataRowHandler(mimeType); count += rowHandler.delete(mActiveDb.get(), mTransactionContext.get(), c); if (!callerIsSyncAdapter) { mTransactionContext.get().markRawContactDirty(rawContactId); } } } finally { c.close(); } return count; } /** * Delete a data row provided that it is one of the allowed mime types. */ public int deleteData(long dataId, String[] allowedMimeTypes) { // Note that the query will return data according to the access restrictions, // so we don't need to worry about deleting data we don't have permission to read. mSelectionArgs1[0] = String.valueOf(dataId); Cursor c = query(Data.CONTENT_URI, DataRowHandler.DataDeleteQuery.COLUMNS, Data._ID + "=?", mSelectionArgs1, null); try { if (!c.moveToFirst()) { return 0; } String mimeType = c.getString(DataRowHandler.DataDeleteQuery.MIMETYPE); boolean valid = false; for (int i = 0; i < allowedMimeTypes.length; i++) { if (TextUtils.equals(mimeType, allowedMimeTypes[i])) { valid = true; break; } } if (!valid) { throw new IllegalArgumentException("Data type mismatch: expected " + Lists.newArrayList(allowedMimeTypes)); } DataRowHandler rowHandler = getDataRowHandler(mimeType); return rowHandler.delete(mActiveDb.get(), mTransactionContext.get(), c); } finally { c.close(); } } /** * Inserts an item in the groups table */ private long insertGroup(Uri uri, ContentValues values, boolean callerIsSyncAdapter) { mValues.clear(); mValues.putAll(values); final AccountWithDataSet accountWithDataSet = resolveAccountWithDataSet(uri, mValues); // Replace package with internal mapping final String packageName = mValues.getAsString(Groups.RES_PACKAGE); if (packageName != null) { mValues.put(GroupsColumns.PACKAGE_ID, mDbHelper.get().getPackageId(packageName)); } mValues.remove(Groups.RES_PACKAGE); final boolean isFavoritesGroup = mValues.getAsLong(Groups.FAVORITES) != null ? mValues.getAsLong(Groups.FAVORITES) != 0 : false; if (!callerIsSyncAdapter) { mValues.put(Groups.DIRTY, 1); } long result = mActiveDb.get().insert(Tables.GROUPS, Groups.TITLE, mValues); if (!callerIsSyncAdapter && isFavoritesGroup) { // add all starred raw contacts to this group String selection; String[] selectionArgs; if (accountWithDataSet == null) { selection = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL AND " + RawContacts.DATA_SET + " IS NULL"; selectionArgs = null; } else if (accountWithDataSet.getDataSet() == null) { selection = RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=? AND " + RawContacts.DATA_SET + " IS NULL"; selectionArgs = new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType() }; } else { selection = RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=? AND " + RawContacts.DATA_SET + "=?"; selectionArgs = new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType(), accountWithDataSet.getDataSet() }; } Cursor c = mActiveDb.get().query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID, RawContacts.STARRED}, selection, selectionArgs, null, null, null); try { while (c.moveToNext()) { if (c.getLong(1) != 0) { final long rawContactId = c.getLong(0); insertDataGroupMembership(rawContactId, result); mTransactionContext.get().markRawContactDirty(rawContactId); } } } finally { c.close(); } } if (mValues.containsKey(Groups.GROUP_VISIBLE)) { mVisibleTouched = true; } return result; } private long insertSettings(Uri uri, ContentValues values) { // Before inserting, ensure that no settings record already exists for the // values being inserted (this used to be enforced by a primary key, but that no // longer works with the nullable data_set field added). String accountName = values.getAsString(Settings.ACCOUNT_NAME); String accountType = values.getAsString(Settings.ACCOUNT_TYPE); String dataSet = values.getAsString(Settings.DATA_SET); Uri.Builder settingsUri = Settings.CONTENT_URI.buildUpon(); if (accountName != null) { settingsUri.appendQueryParameter(Settings.ACCOUNT_NAME, accountName); } if (accountType != null) { settingsUri.appendQueryParameter(Settings.ACCOUNT_TYPE, accountType); } if (dataSet != null) { settingsUri.appendQueryParameter(Settings.DATA_SET, dataSet); } Cursor c = queryLocal(settingsUri.build(), null, null, null, null, 0); try { if (c.getCount() > 0) { // If a record was found, replace it with the new values. String selection = null; String[] selectionArgs = null; if (accountName != null && accountType != null) { selection = Settings.ACCOUNT_NAME + "=? AND " + Settings.ACCOUNT_TYPE + "=?"; if (dataSet == null) { selection += " AND " + Settings.DATA_SET + " IS NULL"; selectionArgs = new String[] {accountName, accountType}; } else { selection += " AND " + Settings.DATA_SET + "=?"; selectionArgs = new String[] {accountName, accountType, dataSet}; } } return updateSettings(uri, values, selection, selectionArgs); } } finally { c.close(); } // If we didn't find a duplicate, we're fine to insert. final long id = mActiveDb.get().insert(Tables.SETTINGS, null, values); if (values.containsKey(Settings.UNGROUPED_VISIBLE)) { mVisibleTouched = true; } return id; } /** * Inserts a status update. */ public long insertStatusUpdate(ContentValues values) { final String handle = values.getAsString(StatusUpdates.IM_HANDLE); final Integer protocol = values.getAsInteger(StatusUpdates.PROTOCOL); String customProtocol = null; if (protocol != null && protocol == Im.PROTOCOL_CUSTOM) { customProtocol = values.getAsString(StatusUpdates.CUSTOM_PROTOCOL); if (TextUtils.isEmpty(customProtocol)) { throw new IllegalArgumentException( "CUSTOM_PROTOCOL is required when PROTOCOL=PROTOCOL_CUSTOM"); } } long rawContactId = -1; long contactId = -1; Long dataId = values.getAsLong(StatusUpdates.DATA_ID); String accountType = null; String accountName = null; mSb.setLength(0); mSelectionArgs.clear(); if (dataId != null) { // Lookup the contact info for the given data row. mSb.append(Tables.DATA + "." + Data._ID + "=?"); mSelectionArgs.add(String.valueOf(dataId)); } else { // Lookup the data row to attach this presence update to if (TextUtils.isEmpty(handle) || protocol == null) { throw new IllegalArgumentException("PROTOCOL and IM_HANDLE are required"); } // TODO: generalize to allow other providers to match against email boolean matchEmail = Im.PROTOCOL_GOOGLE_TALK == protocol; String mimeTypeIdIm = String.valueOf(mDbHelper.get().getMimeTypeIdForIm()); if (matchEmail) { String mimeTypeIdEmail = String.valueOf(mDbHelper.get().getMimeTypeIdForEmail()); // The following hack forces SQLite to use the (mimetype_id,data1) index, otherwise // the "OR" conjunction confuses it and it switches to a full scan of // the raw_contacts table. // This code relies on the fact that Im.DATA and Email.DATA are in fact the same // column - Data.DATA1 mSb.append(DataColumns.MIMETYPE_ID + " IN (?,?)" + " AND " + Data.DATA1 + "=?" + " AND ((" + DataColumns.MIMETYPE_ID + "=? AND " + Im.PROTOCOL + "=?"); mSelectionArgs.add(mimeTypeIdEmail); mSelectionArgs.add(mimeTypeIdIm); mSelectionArgs.add(handle); mSelectionArgs.add(mimeTypeIdIm); mSelectionArgs.add(String.valueOf(protocol)); if (customProtocol != null) { mSb.append(" AND " + Im.CUSTOM_PROTOCOL + "=?"); mSelectionArgs.add(customProtocol); } mSb.append(") OR (" + DataColumns.MIMETYPE_ID + "=?))"); mSelectionArgs.add(mimeTypeIdEmail); } else { mSb.append(DataColumns.MIMETYPE_ID + "=?" + " AND " + Im.PROTOCOL + "=?" + " AND " + Im.DATA + "=?"); mSelectionArgs.add(mimeTypeIdIm); mSelectionArgs.add(String.valueOf(protocol)); mSelectionArgs.add(handle); if (customProtocol != null) { mSb.append(" AND " + Im.CUSTOM_PROTOCOL + "=?"); mSelectionArgs.add(customProtocol); } } if (values.containsKey(StatusUpdates.DATA_ID)) { mSb.append(" AND " + DataColumns.CONCRETE_ID + "=?"); mSelectionArgs.add(values.getAsString(StatusUpdates.DATA_ID)); } } Cursor cursor = null; try { cursor = mActiveDb.get().query(DataContactsQuery.TABLE, DataContactsQuery.PROJECTION, mSb.toString(), mSelectionArgs.toArray(EMPTY_STRING_ARRAY), null, null, Clauses.CONTACT_VISIBLE + " DESC, " + Data.RAW_CONTACT_ID); if (cursor.moveToFirst()) { dataId = cursor.getLong(DataContactsQuery.DATA_ID); rawContactId = cursor.getLong(DataContactsQuery.RAW_CONTACT_ID); accountType = cursor.getString(DataContactsQuery.ACCOUNT_TYPE); accountName = cursor.getString(DataContactsQuery.ACCOUNT_NAME); contactId = cursor.getLong(DataContactsQuery.CONTACT_ID); } else { // No contact found, return a null URI return -1; } } finally { if (cursor != null) { cursor.close(); } } if (values.containsKey(StatusUpdates.PRESENCE)) { if (customProtocol == null) { // We cannot allow a null in the custom protocol field, because SQLite3 does not // properly enforce uniqueness of null values customProtocol = ""; } mValues.clear(); mValues.put(StatusUpdates.DATA_ID, dataId); mValues.put(PresenceColumns.RAW_CONTACT_ID, rawContactId); mValues.put(PresenceColumns.CONTACT_ID, contactId); mValues.put(StatusUpdates.PROTOCOL, protocol); mValues.put(StatusUpdates.CUSTOM_PROTOCOL, customProtocol); mValues.put(StatusUpdates.IM_HANDLE, handle); if (values.containsKey(StatusUpdates.IM_ACCOUNT)) { mValues.put(StatusUpdates.IM_ACCOUNT, values.getAsString(StatusUpdates.IM_ACCOUNT)); } mValues.put(StatusUpdates.PRESENCE, values.getAsString(StatusUpdates.PRESENCE)); mValues.put(StatusUpdates.CHAT_CAPABILITY, values.getAsString(StatusUpdates.CHAT_CAPABILITY)); // Insert the presence update mActiveDb.get().replace(Tables.PRESENCE, null, mValues); } if (values.containsKey(StatusUpdates.STATUS)) { String status = values.getAsString(StatusUpdates.STATUS); String resPackage = values.getAsString(StatusUpdates.STATUS_RES_PACKAGE); Resources resources = getContext().getResources(); if (!TextUtils.isEmpty(resPackage)) { PackageManager pm = getContext().getPackageManager(); try { resources = pm.getResourcesForApplication(resPackage); } catch (NameNotFoundException e) { Log.w(TAG, "Contact status update resource package not found: " + resPackage); } } Integer labelResourceId = values.getAsInteger(StatusUpdates.STATUS_LABEL); if ((labelResourceId == null || labelResourceId == 0) && protocol != null) { labelResourceId = Im.getProtocolLabelResource(protocol); } String labelResource = getResourceName(resources, "string", labelResourceId); Integer iconResourceId = values.getAsInteger(StatusUpdates.STATUS_ICON); // TODO compute the default icon based on the protocol String iconResource = getResourceName(resources, "drawable", iconResourceId); if (TextUtils.isEmpty(status)) { mDbHelper.get().deleteStatusUpdate(dataId); } else { Long timestamp = values.getAsLong(StatusUpdates.STATUS_TIMESTAMP); if (timestamp != null) { mDbHelper.get().replaceStatusUpdate(dataId, timestamp, status, resPackage, iconResourceId, labelResourceId); } else { mDbHelper.get().insertStatusUpdate(dataId, status, resPackage, iconResourceId, labelResourceId); } // For forward compatibility with the new stream item API, insert this status update // there as well. If we already have a stream item from this source, update that // one instead of inserting a new one (since the semantics of the old status update // API is to only have a single record). if (rawContactId != -1 && !TextUtils.isEmpty(status)) { ContentValues streamItemValues = new ContentValues(); streamItemValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); // Status updates are text only but stream items are HTML. streamItemValues.put(StreamItems.TEXT, statusUpdateToHtml(status)); streamItemValues.put(StreamItems.COMMENTS, ""); streamItemValues.put(StreamItems.RES_PACKAGE, resPackage); streamItemValues.put(StreamItems.RES_ICON, iconResource); streamItemValues.put(StreamItems.RES_LABEL, labelResource); streamItemValues.put(StreamItems.TIMESTAMP, timestamp == null ? System.currentTimeMillis() : timestamp); // Note: The following is basically a workaround for the fact that status // updates didn't do any sort of account enforcement, while social stream item // updates do. We can't expect callers of the old API to start passing account // information along, so we just populate the account params appropriately for // the raw contact. Data set is not relevant here, as we only check account // name and type. if (accountName != null && accountType != null) { streamItemValues.put(RawContacts.ACCOUNT_NAME, accountName); streamItemValues.put(RawContacts.ACCOUNT_TYPE, accountType); } // Check for an existing stream item from this source, and insert or update. Uri streamUri = StreamItems.CONTENT_URI; Cursor c = queryLocal(streamUri, new String[]{StreamItems._ID}, StreamItems.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(rawContactId)}, null, -1 /* directory ID */); try { if (c.getCount() > 0) { c.moveToFirst(); updateInTransaction(ContentUris.withAppendedId(streamUri, c.getLong(0)), streamItemValues, null, null); } else { insertInTransaction(streamUri, streamItemValues); } } finally { c.close(); } } } } if (contactId != -1) { mAggregator.get().updateLastStatusUpdateId(contactId); } return dataId; } /** Converts a status update to HTML. */ private String statusUpdateToHtml(String status) { return TextUtils.htmlEncode(status); } private String getResourceName(Resources resources, String expectedType, Integer resourceId) { try { if (resourceId == null || resourceId == 0) return null; // Resource has an invalid type (e.g. a string as icon)? ignore final String resourceEntryName = resources.getResourceEntryName(resourceId); final String resourceTypeName = resources.getResourceTypeName(resourceId); if (!expectedType.equals(resourceTypeName)) { Log.w(TAG, "Resource " + resourceId + " (" + resourceEntryName + ") is of type " + resourceTypeName + " but " + expectedType + " is required."); return null; } return resourceEntryName; } catch (NotFoundException e) { return null; } } @Override protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs) { if (VERBOSE_LOGGING) { Log.v(TAG, "deleteInTransaction: " + uri); } // Default active DB to the contacts DB if none has been set. if (mActiveDb.get() == null) { mActiveDb.set(mContactsHelper.getWritableDatabase()); } flushTransactionalChanges(); final boolean callerIsSyncAdapter = readBooleanQueryParameter(uri, ContactsContract.CALLER_IS_SYNCADAPTER, false); final int match = sUriMatcher.match(uri); switch (match) { case SYNCSTATE: case PROFILE_SYNCSTATE: return mDbHelper.get().getSyncState().delete(mActiveDb.get(), selection, selectionArgs); case SYNCSTATE_ID: { String selectionWithId = (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ") + (selection == null ? "" : " AND (" + selection + ")"); return mDbHelper.get().getSyncState().delete(mActiveDb.get(), selectionWithId, selectionArgs); } case PROFILE_SYNCSTATE_ID: { String selectionWithId = (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ") + (selection == null ? "" : " AND (" + selection + ")"); return mProfileHelper.getSyncState().delete(mActiveDb.get(), selectionWithId, selectionArgs); } case CONTACTS: { // TODO return 0; } case CONTACTS_ID: { long contactId = ContentUris.parseId(uri); return deleteContact(contactId, callerIsSyncAdapter); } case CONTACTS_LOOKUP: { final List<String> pathSegments = uri.getPathSegments(); final int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } final String lookupKey = pathSegments.get(2); final long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); return deleteContact(contactId, callerIsSyncAdapter); } case CONTACTS_LOOKUP_ID: { // lookup contact by id and lookup key to see if they still match the actual record final List<String> pathSegments = uri.getPathSegments(); final String lookupKey = pathSegments.get(2); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, null); long contactId = ContentUris.parseId(uri); String[] args; if (selectionArgs == null) { args = new String[2]; } else { args = new String[selectionArgs.length + 2]; System.arraycopy(selectionArgs, 0, args, 2, selectionArgs.length); } args[0] = String.valueOf(contactId); args[1] = Uri.encode(lookupKey); lookupQb.appendWhere(Contacts._ID + "=? AND " + Contacts.LOOKUP_KEY + "=?"); Cursor c = query(mActiveDb.get(), lookupQb, null, selection, args, null, null, null); try { if (c.getCount() == 1) { // contact was unmodified so go ahead and delete it return deleteContact(contactId, callerIsSyncAdapter); } else { // row was changed (e.g. the merging might have changed), we got multiple // rows or the supplied selection filtered the record out return 0; } } finally { c.close(); } } case RAW_CONTACTS: case PROFILE_RAW_CONTACTS: { int numDeletes = 0; Cursor c = mActiveDb.get().query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID, RawContacts.CONTACT_ID}, appendAccountToSelection(uri, selection), selectionArgs, null, null, null); try { while (c.moveToNext()) { final long rawContactId = c.getLong(0); long contactId = c.getLong(1); numDeletes += deleteRawContact(rawContactId, contactId, callerIsSyncAdapter); } } finally { c.close(); } return numDeletes; } case RAW_CONTACTS_ID: case PROFILE_RAW_CONTACTS_ID: { final long rawContactId = ContentUris.parseId(uri); return deleteRawContact(rawContactId, mDbHelper.get().getContactId(rawContactId), callerIsSyncAdapter); } case DATA: case PROFILE_DATA: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteData(appendAccountToSelection(uri, selection), selectionArgs, callerIsSyncAdapter); } case DATA_ID: case PHONES_ID: case EMAILS_ID: case POSTALS_ID: case PROFILE_DATA_ID: { long dataId = ContentUris.parseId(uri); mSyncToNetwork |= !callerIsSyncAdapter; mSelectionArgs1[0] = String.valueOf(dataId); return deleteData(Data._ID + "=?", mSelectionArgs1, callerIsSyncAdapter); } case GROUPS_ID: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteGroup(uri, ContentUris.parseId(uri), callerIsSyncAdapter); } case GROUPS: { int numDeletes = 0; Cursor c = mActiveDb.get().query(Tables.GROUPS, new String[]{Groups._ID}, appendAccountToSelection(uri, selection), selectionArgs, null, null, null); try { while (c.moveToNext()) { numDeletes += deleteGroup(uri, c.getLong(0), callerIsSyncAdapter); } } finally { c.close(); } if (numDeletes > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } return numDeletes; } case SETTINGS: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteSettings(uri, appendAccountToSelection(uri, selection), selectionArgs); } case STATUS_UPDATES: case PROFILE_STATUS_UPDATES: { return deleteStatusUpdates(selection, selectionArgs); } case STREAM_ITEMS: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteStreamItems(uri, new ContentValues(), selection, selectionArgs); } case STREAM_ITEMS_ID: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteStreamItems(uri, new ContentValues(), StreamItems._ID + "=?", new String[]{uri.getLastPathSegment()}); } case RAW_CONTACTS_ID_STREAM_ITEMS_ID: { mSyncToNetwork |= !callerIsSyncAdapter; String rawContactId = uri.getPathSegments().get(1); String streamItemId = uri.getLastPathSegment(); return deleteStreamItems(uri, new ContentValues(), StreamItems.RAW_CONTACT_ID + "=? AND " + StreamItems._ID + "=?", new String[]{rawContactId, streamItemId}); } case STREAM_ITEMS_ID_PHOTOS: { mSyncToNetwork |= !callerIsSyncAdapter; String streamItemId = uri.getPathSegments().get(1); String selectionWithId = (StreamItemPhotos.STREAM_ITEM_ID + "=" + streamItemId + " ") + (selection == null ? "" : " AND (" + selection + ")"); return deleteStreamItemPhotos(uri, new ContentValues(), selectionWithId, selectionArgs); } case STREAM_ITEMS_ID_PHOTOS_ID: { mSyncToNetwork |= !callerIsSyncAdapter; String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); return deleteStreamItemPhotos(uri, new ContentValues(), StreamItemPhotosColumns.CONCRETE_ID + "=? AND " + StreamItemPhotos.STREAM_ITEM_ID + "=?", new String[]{streamItemPhotoId, streamItemId}); } default: { mSyncToNetwork = true; return mLegacyApiSupport.delete(uri, selection, selectionArgs); } } } public int deleteGroup(Uri uri, long groupId, boolean callerIsSyncAdapter) { mGroupIdCache.clear(); final long groupMembershipMimetypeId = mDbHelper.get() .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE); mActiveDb.get().delete(Tables.DATA, DataColumns.MIMETYPE_ID + "=" + groupMembershipMimetypeId + " AND " + GroupMembership.GROUP_ROW_ID + "=" + groupId, null); try { if (callerIsSyncAdapter) { return mActiveDb.get().delete(Tables.GROUPS, Groups._ID + "=" + groupId, null); } else { mValues.clear(); mValues.put(Groups.DELETED, 1); mValues.put(Groups.DIRTY, 1); return mActiveDb.get().update(Tables.GROUPS, mValues, Groups._ID + "=" + groupId, null); } } finally { mVisibleTouched = true; } } private int deleteSettings(Uri uri, String selection, String[] selectionArgs) { final int count = mActiveDb.get().delete(Tables.SETTINGS, selection, selectionArgs); mVisibleTouched = true; return count; } private int deleteContact(long contactId, boolean callerIsSyncAdapter) { mSelectionArgs1[0] = Long.toString(contactId); Cursor c = mActiveDb.get().query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID}, RawContacts.CONTACT_ID + "=?", mSelectionArgs1, null, null, null); try { while (c.moveToNext()) { long rawContactId = c.getLong(0); markRawContactAsDeleted(rawContactId, callerIsSyncAdapter); } } finally { c.close(); } mProviderStatusUpdateNeeded = true; return mActiveDb.get().delete(Tables.CONTACTS, Contacts._ID + "=" + contactId, null); } public int deleteRawContact(long rawContactId, long contactId, boolean callerIsSyncAdapter) { mAggregator.get().invalidateAggregationExceptionCache(); mProviderStatusUpdateNeeded = true; // Find and delete stream items associated with the raw contact. Cursor c = mActiveDb.get().query(Tables.STREAM_ITEMS, new String[]{StreamItems._ID}, StreamItems.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(rawContactId)}, null, null, null); try { while (c.moveToNext()) { deleteStreamItem(c.getLong(0)); } } finally { c.close(); } if (callerIsSyncAdapter || rawContactIsLocal(rawContactId)) { mActiveDb.get().delete(Tables.PRESENCE, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null); int count = mActiveDb.get().delete(Tables.RAW_CONTACTS, RawContacts._ID + "=" + rawContactId, null); mAggregator.get().updateAggregateData(mTransactionContext.get(), contactId); return count; } else { mDbHelper.get().removeContactIfSingleton(rawContactId); return markRawContactAsDeleted(rawContactId, callerIsSyncAdapter); } } /** * Returns whether the given raw contact ID is local (i.e. has no account associated with it). */ private boolean rawContactIsLocal(long rawContactId) { Cursor c = mActiveDb.get().query(Tables.RAW_CONTACTS, new String[] { RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DATA_SET }, RawContacts._ID + "=?", new String[] {String.valueOf(rawContactId)}, null, null, null); try { return c.moveToFirst() && c.isNull(0) && c.isNull(1) && c.isNull(2); } finally { c.close(); } } private int deleteStatusUpdates(String selection, String[] selectionArgs) { // delete from both tables: presence and status_updates // TODO should account type/name be appended to the where clause? if (VERBOSE_LOGGING) { Log.v(TAG, "deleting data from status_updates for " + selection); } mActiveDb.get().delete(Tables.STATUS_UPDATES, getWhereClauseForStatusUpdatesTable(selection), selectionArgs); return mActiveDb.get().delete(Tables.PRESENCE, selection, selectionArgs); } private int deleteStreamItems(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // First query for the stream items to be deleted, and check that they belong // to the account. Account account = resolveAccount(uri, values); List<Long> streamItemIds = enforceModifyingAccountForStreamItems( account, selection, selectionArgs); // If no security exception has been thrown, we're fine to delete. for (long streamItemId : streamItemIds) { deleteStreamItem(streamItemId); } mVisibleTouched = true; return streamItemIds.size(); } private int deleteStreamItem(long streamItemId) { // Note that this does not enforce the modifying account. deleteStreamItemPhotos(streamItemId); return mActiveDb.get().delete(Tables.STREAM_ITEMS, StreamItems._ID + "=?", new String[]{String.valueOf(streamItemId)}); } private int deleteStreamItemPhotos(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // First query for the stream item photos to be deleted, and check that they // belong to the account. Account account = resolveAccount(uri, values); enforceModifyingAccountForStreamItemPhotos(account, selection, selectionArgs); // If no security exception has been thrown, we're fine to delete. return mActiveDb.get().delete(Tables.STREAM_ITEM_PHOTOS, selection, selectionArgs); } private int deleteStreamItemPhotos(long streamItemId) { // Note that this does not enforce the modifying account. return mActiveDb.get().delete(Tables.STREAM_ITEM_PHOTOS, StreamItemPhotos.STREAM_ITEM_ID + "=?", new String[]{String.valueOf(streamItemId)}); } private int markRawContactAsDeleted(long rawContactId, boolean callerIsSyncAdapter) { mSyncToNetwork = true; mValues.clear(); mValues.put(RawContacts.DELETED, 1); mValues.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED); mValues.put(RawContactsColumns.AGGREGATION_NEEDED, 1); mValues.putNull(RawContacts.CONTACT_ID); mValues.put(RawContacts.DIRTY, 1); return updateRawContact(rawContactId, mValues, callerIsSyncAdapter); } @Override protected int updateInTransaction(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (VERBOSE_LOGGING) { Log.v(TAG, "updateInTransaction: " + uri); } // Default active DB to the contacts DB if none has been set. if (mActiveDb.get() == null) { mActiveDb.set(mContactsHelper.getWritableDatabase()); } int count = 0; final int match = sUriMatcher.match(uri); if (match == SYNCSTATE_ID && selection == null) { long rowId = ContentUris.parseId(uri); Object data = values.get(ContactsContract.SyncState.DATA); mTransactionContext.get().syncStateUpdated(rowId, data); return 1; } flushTransactionalChanges(); final boolean callerIsSyncAdapter = readBooleanQueryParameter(uri, ContactsContract.CALLER_IS_SYNCADAPTER, false); switch(match) { case SYNCSTATE: case PROFILE_SYNCSTATE: return mDbHelper.get().getSyncState().update(mActiveDb.get(), values, appendAccountToSelection(uri, selection), selectionArgs); case SYNCSTATE_ID: { selection = appendAccountToSelection(uri, selection); String selectionWithId = (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ") + (selection == null ? "" : " AND (" + selection + ")"); return mDbHelper.get().getSyncState().update(mActiveDb.get(), values, selectionWithId, selectionArgs); } case PROFILE_SYNCSTATE_ID: { selection = appendAccountToSelection(uri, selection); String selectionWithId = (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ") + (selection == null ? "" : " AND (" + selection + ")"); return mProfileHelper.getSyncState().update(mActiveDb.get(), values, selectionWithId, selectionArgs); } case CONTACTS: case PROFILE: { count = updateContactOptions(values, selection, selectionArgs, callerIsSyncAdapter); break; } case CONTACTS_ID: { count = updateContactOptions(ContentUris.parseId(uri), values, callerIsSyncAdapter); break; } case CONTACTS_LOOKUP: case CONTACTS_LOOKUP_ID: { final List<String> pathSegments = uri.getPathSegments(); final int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } final String lookupKey = pathSegments.get(2); final long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); count = updateContactOptions(contactId, values, callerIsSyncAdapter); break; } case RAW_CONTACTS_DATA: case PROFILE_RAW_CONTACTS_ID_DATA: { int segment = match == RAW_CONTACTS_DATA ? 1 : 2; final String rawContactId = uri.getPathSegments().get(segment); String selectionWithId = (Data.RAW_CONTACT_ID + "=" + rawContactId + " ") + (selection == null ? "" : " AND " + selection); count = updateData(uri, values, selectionWithId, selectionArgs, callerIsSyncAdapter); break; } case DATA: case PROFILE_DATA: { count = updateData(uri, values, appendAccountToSelection(uri, selection), selectionArgs, callerIsSyncAdapter); if (count > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } break; } case DATA_ID: case PHONES_ID: case EMAILS_ID: case POSTALS_ID: { count = updateData(uri, values, selection, selectionArgs, callerIsSyncAdapter); if (count > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } break; } case RAW_CONTACTS: case PROFILE_RAW_CONTACTS: { selection = appendAccountToSelection(uri, selection); count = updateRawContacts(values, selection, selectionArgs, callerIsSyncAdapter); break; } case RAW_CONTACTS_ID: { long rawContactId = ContentUris.parseId(uri); if (selection != null) { selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); count = updateRawContacts(values, RawContacts._ID + "=?" + " AND(" + selection + ")", selectionArgs, callerIsSyncAdapter); } else { mSelectionArgs1[0] = String.valueOf(rawContactId); count = updateRawContacts(values, RawContacts._ID + "=?", mSelectionArgs1, callerIsSyncAdapter); } break; } case GROUPS: { count = updateGroups(uri, values, appendAccountToSelection(uri, selection), selectionArgs, callerIsSyncAdapter); if (count > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } break; } case GROUPS_ID: { long groupId = ContentUris.parseId(uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(groupId)); String selectionWithId = Groups._ID + "=? " + (selection == null ? "" : " AND " + selection); count = updateGroups(uri, values, selectionWithId, selectionArgs, callerIsSyncAdapter); if (count > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } break; } case AGGREGATION_EXCEPTIONS: { count = updateAggregationException(mActiveDb.get(), values); break; } case SETTINGS: { count = updateSettings(uri, values, appendAccountToSelection(uri, selection), selectionArgs); mSyncToNetwork |= !callerIsSyncAdapter; break; } case STATUS_UPDATES: case PROFILE_STATUS_UPDATES: { count = updateStatusUpdate(uri, values, selection, selectionArgs); break; } case STREAM_ITEMS: { count = updateStreamItems(uri, values, selection, selectionArgs); break; } case STREAM_ITEMS_ID: { count = updateStreamItems(uri, values, StreamItems._ID + "=?", new String[]{uri.getLastPathSegment()}); break; } case RAW_CONTACTS_ID_STREAM_ITEMS_ID: { String rawContactId = uri.getPathSegments().get(1); String streamItemId = uri.getLastPathSegment(); count = updateStreamItems(uri, values, StreamItems.RAW_CONTACT_ID + "=? AND " + StreamItems._ID + "=?", new String[]{rawContactId, streamItemId}); break; } case STREAM_ITEMS_PHOTOS: { count = updateStreamItemPhotos(uri, values, selection, selectionArgs); break; } case STREAM_ITEMS_ID_PHOTOS: { String streamItemId = uri.getPathSegments().get(1); count = updateStreamItemPhotos(uri, values, StreamItemPhotos.STREAM_ITEM_ID + "=?", new String[]{streamItemId}); break; } case STREAM_ITEMS_ID_PHOTOS_ID: { String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); count = updateStreamItemPhotos(uri, values, StreamItemPhotosColumns.CONCRETE_ID + "=? AND " + StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?", new String[]{streamItemPhotoId, streamItemId}); break; } case DIRECTORIES: { mContactDirectoryManager.scanPackagesByUid(Binder.getCallingUid()); count = 1; break; } case DATA_USAGE_FEEDBACK_ID: { if (handleDataUsageFeedback(uri)) { count = 1; } else { count = 0; } break; } default: { mSyncToNetwork = true; return mLegacyApiSupport.update(uri, values, selection, selectionArgs); } } return count; } private int updateStatusUpdate(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // update status_updates table, if status is provided // TODO should account type/name be appended to the where clause? int updateCount = 0; ContentValues settableValues = getSettableColumnsForStatusUpdatesTable(values); if (settableValues.size() > 0) { updateCount = mActiveDb.get().update(Tables.STATUS_UPDATES, settableValues, getWhereClauseForStatusUpdatesTable(selection), selectionArgs); } // now update the Presence table settableValues = getSettableColumnsForPresenceTable(values); if (settableValues.size() > 0) { updateCount = mActiveDb.get().update(Tables.PRESENCE, settableValues, selection, selectionArgs); } // TODO updateCount is not entirely a valid count of updated rows because 2 tables could // potentially get updated in this method. return updateCount; } private int updateStreamItems(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // Stream items can't be moved to a new raw contact. values.remove(StreamItems.RAW_CONTACT_ID); // Check that the stream items being updated belong to the account. Account account = resolveAccount(uri, values); enforceModifyingAccountForStreamItems(account, selection, selectionArgs); // Don't attempt to update accounts params - they don't exist in the stream items table. values.remove(RawContacts.ACCOUNT_NAME); values.remove(RawContacts.ACCOUNT_TYPE); // If there's been no exception, the update should be fine. return mActiveDb.get().update(Tables.STREAM_ITEMS, values, selection, selectionArgs); } private int updateStreamItemPhotos(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // Stream item photos can't be moved to a new stream item. values.remove(StreamItemPhotos.STREAM_ITEM_ID); // Check that the stream item photos being updated belong to the account. Account account = resolveAccount(uri, values); enforceModifyingAccountForStreamItemPhotos(account, selection, selectionArgs); // Don't attempt to update accounts params - they don't exist in the stream item // photos table. values.remove(RawContacts.ACCOUNT_NAME); values.remove(RawContacts.ACCOUNT_TYPE); // Process the photo (since we're updating, it's valid for the photo to not be present). if (processStreamItemPhoto(values, true)) { // If there's been no exception, the update should be fine. return mActiveDb.get().update(Tables.STREAM_ITEM_PHOTOS, values, selection, selectionArgs); } return 0; } /** * Build a where clause to select the rows to be updated in status_updates table. */ private String getWhereClauseForStatusUpdatesTable(String selection) { mSb.setLength(0); mSb.append(WHERE_CLAUSE_FOR_STATUS_UPDATES_TABLE); mSb.append(selection); mSb.append(")"); return mSb.toString(); } private ContentValues getSettableColumnsForStatusUpdatesTable(ContentValues values) { mValues.clear(); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS, values, StatusUpdates.STATUS); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_TIMESTAMP, values, StatusUpdates.STATUS_TIMESTAMP); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_RES_PACKAGE, values, StatusUpdates.STATUS_RES_PACKAGE); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_LABEL, values, StatusUpdates.STATUS_LABEL); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_ICON, values, StatusUpdates.STATUS_ICON); return mValues; } private ContentValues getSettableColumnsForPresenceTable(ContentValues values) { mValues.clear(); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.PRESENCE, values, StatusUpdates.PRESENCE); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.CHAT_CAPABILITY, values, StatusUpdates.CHAT_CAPABILITY); return mValues; } private int updateGroups(Uri uri, ContentValues values, String selectionWithId, String[] selectionArgs, boolean callerIsSyncAdapter) { mGroupIdCache.clear(); ContentValues updatedValues; if (!callerIsSyncAdapter && !values.containsKey(Groups.DIRTY)) { updatedValues = mValues; updatedValues.clear(); updatedValues.putAll(values); updatedValues.put(Groups.DIRTY, 1); } else { updatedValues = values; } int count = mActiveDb.get().update(Tables.GROUPS, updatedValues, selectionWithId, selectionArgs); if (updatedValues.containsKey(Groups.GROUP_VISIBLE)) { mVisibleTouched = true; } // TODO: This will not work for groups that have a data set specified, since the content // resolver will not be able to request a sync for the right source (unless it is updated // to key off account with data set). if (updatedValues.containsKey(Groups.SHOULD_SYNC) && updatedValues.getAsInteger(Groups.SHOULD_SYNC) != 0) { Cursor c = mActiveDb.get().query(Tables.GROUPS, new String[]{Groups.ACCOUNT_NAME, Groups.ACCOUNT_TYPE}, selectionWithId, selectionArgs, null, null, null); String accountName; String accountType; try { while (c.moveToNext()) { accountName = c.getString(0); accountType = c.getString(1); if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) { Account account = new Account(accountName, accountType); ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); break; } } } finally { c.close(); } } return count; } private int updateSettings(Uri uri, ContentValues values, String selection, String[] selectionArgs) { final int count = mActiveDb.get().update(Tables.SETTINGS, values, selection, selectionArgs); if (values.containsKey(Settings.UNGROUPED_VISIBLE)) { mVisibleTouched = true; } return count; } private int updateRawContacts(ContentValues values, String selection, String[] selectionArgs, boolean callerIsSyncAdapter) { if (values.containsKey(RawContacts.CONTACT_ID)) { throw new IllegalArgumentException(RawContacts.CONTACT_ID + " should not be included " + "in content values. Contact IDs are assigned automatically"); } if (!callerIsSyncAdapter) { selection = DatabaseUtils.concatenateWhere(selection, RawContacts.RAW_CONTACT_IS_READ_ONLY + "=0"); } int count = 0; Cursor cursor = mActiveDb.get().query(Views.RAW_CONTACTS, new String[] { RawContacts._ID }, selection, selectionArgs, null, null, null); try { while (cursor.moveToNext()) { long rawContactId = cursor.getLong(0); updateRawContact(rawContactId, values, callerIsSyncAdapter); count++; } } finally { cursor.close(); } return count; } private int updateRawContact(long rawContactId, ContentValues values, boolean callerIsSyncAdapter) { final String selection = RawContacts._ID + " = ?"; mSelectionArgs1[0] = Long.toString(rawContactId); final boolean requestUndoDelete = (values.containsKey(RawContacts.DELETED) && values.getAsInteger(RawContacts.DELETED) == 0); int previousDeleted = 0; String accountType = null; String accountName = null; String dataSet = null; if (requestUndoDelete) { Cursor cursor = mActiveDb.get().query(RawContactsQuery.TABLE, RawContactsQuery.COLUMNS, selection, mSelectionArgs1, null, null, null); try { if (cursor.moveToFirst()) { previousDeleted = cursor.getInt(RawContactsQuery.DELETED); accountType = cursor.getString(RawContactsQuery.ACCOUNT_TYPE); accountName = cursor.getString(RawContactsQuery.ACCOUNT_NAME); dataSet = cursor.getString(RawContactsQuery.DATA_SET); } } finally { cursor.close(); } values.put(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT); } int count = mActiveDb.get().update(Tables.RAW_CONTACTS, values, selection, mSelectionArgs1); if (count != 0) { if (values.containsKey(RawContacts.AGGREGATION_MODE)) { int aggregationMode = values.getAsInteger(RawContacts.AGGREGATION_MODE); // As per ContactsContract documentation, changing aggregation mode // to DEFAULT should not trigger aggregation if (aggregationMode != RawContacts.AGGREGATION_MODE_DEFAULT) { mAggregator.get().markForAggregation(rawContactId, aggregationMode, false); } } if (values.containsKey(RawContacts.STARRED)) { if (!callerIsSyncAdapter) { updateFavoritesMembership(rawContactId, values.getAsLong(RawContacts.STARRED) != 0); } mAggregator.get().updateStarred(rawContactId); } else { // if this raw contact is being associated with an account, then update the // favorites group membership based on whether or not this contact is starred. // If it is starred, add a group membership, if one doesn't already exist // otherwise delete any matching group memberships. if (!callerIsSyncAdapter && values.containsKey(RawContacts.ACCOUNT_NAME)) { boolean starred = 0 != DatabaseUtils.longForQuery(mActiveDb.get(), SELECTION_STARRED_FROM_RAW_CONTACTS, new String[]{Long.toString(rawContactId)}); updateFavoritesMembership(rawContactId, starred); } } // if this raw contact is being associated with an account, then add a // group membership to the group marked as AutoAdd, if any. if (!callerIsSyncAdapter && values.containsKey(RawContacts.ACCOUNT_NAME)) { addAutoAddMembership(rawContactId); } if (values.containsKey(RawContacts.SOURCE_ID)) { mAggregator.get().updateLookupKeyForRawContact(mActiveDb.get(), rawContactId); } if (values.containsKey(RawContacts.NAME_VERIFIED)) { // If setting NAME_VERIFIED for this raw contact, reset it for all // other raw contacts in the same aggregate if (values.getAsInteger(RawContacts.NAME_VERIFIED) != 0) { mDbHelper.get().resetNameVerifiedForOtherRawContacts(rawContactId); } mAggregator.get().updateDisplayNameForRawContact(mActiveDb.get(), rawContactId); } if (requestUndoDelete && previousDeleted == 1) { mTransactionContext.get().rawContactInserted(rawContactId, new AccountWithDataSet(accountName, accountType, dataSet)); } } return count; } private int updateData(Uri uri, ContentValues values, String selection, String[] selectionArgs, boolean callerIsSyncAdapter) { mValues.clear(); mValues.putAll(values); mValues.remove(Data._ID); mValues.remove(Data.RAW_CONTACT_ID); mValues.remove(Data.MIMETYPE); String packageName = values.getAsString(Data.RES_PACKAGE); if (packageName != null) { mValues.remove(Data.RES_PACKAGE); mValues.put(DataColumns.PACKAGE_ID, mDbHelper.get().getPackageId(packageName)); } if (!callerIsSyncAdapter) { selection = DatabaseUtils.concatenateWhere(selection, Data.IS_READ_ONLY + "=0"); } int count = 0; // Note that the query will return data according to the access restrictions, // so we don't need to worry about updating data we don't have permission to read. Cursor c = queryLocal(uri, DataRowHandler.DataUpdateQuery.COLUMNS, selection, selectionArgs, null, -1 /* directory ID */); try { while(c.moveToNext()) { count += updateData(mValues, c, callerIsSyncAdapter); } } finally { c.close(); } return count; } private int updateData(ContentValues values, Cursor c, boolean callerIsSyncAdapter) { if (values.size() == 0) { return 0; } final String mimeType = c.getString(DataRowHandler.DataUpdateQuery.MIMETYPE); DataRowHandler rowHandler = getDataRowHandler(mimeType); boolean updated = rowHandler.update(mActiveDb.get(), mTransactionContext.get(), values, c, callerIsSyncAdapter); if (Photo.CONTENT_ITEM_TYPE.equals(mimeType)) { scheduleBackgroundTask(BACKGROUND_TASK_CLEANUP_PHOTOS); } return updated ? 1 : 0; } private int updateContactOptions(ContentValues values, String selection, String[] selectionArgs, boolean callerIsSyncAdapter) { int count = 0; Cursor cursor = mActiveDb.get().query(Views.CONTACTS, new String[] { Contacts._ID }, selection, selectionArgs, null, null, null); try { while (cursor.moveToNext()) { long contactId = cursor.getLong(0); updateContactOptions(contactId, values, callerIsSyncAdapter); count++; } } finally { cursor.close(); } return count; } private int updateContactOptions(long contactId, ContentValues values, boolean callerIsSyncAdapter) { mValues.clear(); ContactsDatabaseHelper.copyStringValue(mValues, RawContacts.CUSTOM_RINGTONE, values, Contacts.CUSTOM_RINGTONE); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.SEND_TO_VOICEMAIL, values, Contacts.SEND_TO_VOICEMAIL); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.LAST_TIME_CONTACTED, values, Contacts.LAST_TIME_CONTACTED); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.TIMES_CONTACTED, values, Contacts.TIMES_CONTACTED); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.STARRED, values, Contacts.STARRED); // Nothing to update - just return if (mValues.size() == 0) { return 0; } if (mValues.containsKey(RawContacts.STARRED)) { // Mark dirty when changing starred to trigger sync mValues.put(RawContacts.DIRTY, 1); } mSelectionArgs1[0] = String.valueOf(contactId); mActiveDb.get().update(Tables.RAW_CONTACTS, mValues, RawContacts.CONTACT_ID + "=?" + " AND " + RawContacts.RAW_CONTACT_IS_READ_ONLY + "=0", mSelectionArgs1); if (mValues.containsKey(RawContacts.STARRED) && !callerIsSyncAdapter) { Cursor cursor = mActiveDb.get().query(Views.RAW_CONTACTS, new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + "=?", mSelectionArgs1, null, null, null); try { while (cursor.moveToNext()) { long rawContactId = cursor.getLong(0); updateFavoritesMembership(rawContactId, mValues.getAsLong(RawContacts.STARRED) != 0); } } finally { cursor.close(); } } // Copy changeable values to prevent automatically managed fields from // being explicitly updated by clients. mValues.clear(); ContactsDatabaseHelper.copyStringValue(mValues, RawContacts.CUSTOM_RINGTONE, values, Contacts.CUSTOM_RINGTONE); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.SEND_TO_VOICEMAIL, values, Contacts.SEND_TO_VOICEMAIL); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.LAST_TIME_CONTACTED, values, Contacts.LAST_TIME_CONTACTED); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.TIMES_CONTACTED, values, Contacts.TIMES_CONTACTED); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.STARRED, values, Contacts.STARRED); int rslt = mActiveDb.get().update(Tables.CONTACTS, mValues, Contacts._ID + "=?", mSelectionArgs1); if (values.containsKey(Contacts.LAST_TIME_CONTACTED) && !values.containsKey(Contacts.TIMES_CONTACTED)) { mActiveDb.get().execSQL(UPDATE_TIMES_CONTACTED_CONTACTS_TABLE, mSelectionArgs1); mActiveDb.get().execSQL(UPDATE_TIMES_CONTACTED_RAWCONTACTS_TABLE, mSelectionArgs1); } return rslt; } private int updateAggregationException(SQLiteDatabase db, ContentValues values) { int exceptionType = values.getAsInteger(AggregationExceptions.TYPE); long rcId1 = values.getAsInteger(AggregationExceptions.RAW_CONTACT_ID1); long rcId2 = values.getAsInteger(AggregationExceptions.RAW_CONTACT_ID2); long rawContactId1; long rawContactId2; if (rcId1 < rcId2) { rawContactId1 = rcId1; rawContactId2 = rcId2; } else { rawContactId2 = rcId1; rawContactId1 = rcId2; } if (exceptionType == AggregationExceptions.TYPE_AUTOMATIC) { mSelectionArgs2[0] = String.valueOf(rawContactId1); mSelectionArgs2[1] = String.valueOf(rawContactId2); db.delete(Tables.AGGREGATION_EXCEPTIONS, AggregationExceptions.RAW_CONTACT_ID1 + "=? AND " + AggregationExceptions.RAW_CONTACT_ID2 + "=?", mSelectionArgs2); } else { ContentValues exceptionValues = new ContentValues(3); exceptionValues.put(AggregationExceptions.TYPE, exceptionType); exceptionValues.put(AggregationExceptions.RAW_CONTACT_ID1, rawContactId1); exceptionValues.put(AggregationExceptions.RAW_CONTACT_ID2, rawContactId2); db.replace(Tables.AGGREGATION_EXCEPTIONS, AggregationExceptions._ID, exceptionValues); } mAggregator.get().invalidateAggregationExceptionCache(); mAggregator.get().markForAggregation(rawContactId1, RawContacts.AGGREGATION_MODE_DEFAULT, true); mAggregator.get().markForAggregation(rawContactId2, RawContacts.AGGREGATION_MODE_DEFAULT, true); mAggregator.get().aggregateContact(mTransactionContext.get(), db, rawContactId1); mAggregator.get().aggregateContact(mTransactionContext.get(), db, rawContactId2); // The return value is fake - we just confirm that we made a change, not count actual // rows changed. return 1; } public void onAccountsUpdated(Account[] accounts) { scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_ACCOUNTS); } protected boolean updateAccountsInBackground(Account[] accounts) { // TODO : Check the unit test. boolean accountsChanged = false; SQLiteDatabase db = mDbHelper.get().getWritableDatabase(); mActiveDb.set(db); db.beginTransaction(); // WARNING: This method can be run in either contacts mode or profile mode. It is // absolutely imperative that no calls be made inside the following try block that can // interact with the contacts DB. Otherwise it is quite possible for a deadlock to occur. try { Set<AccountWithDataSet> existingAccountsWithDataSets = findValidAccountsWithDataSets(Tables.ACCOUNTS); // Add a row to the ACCOUNTS table (with no data set) for each new account. for (Account account : accounts) { AccountWithDataSet accountWithDataSet = new AccountWithDataSet( account.name, account.type, null); if (!existingAccountsWithDataSets.contains(accountWithDataSet)) { accountsChanged = true; // Add an account entry with an empty data set to match the account. db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " (" + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + RawContacts.DATA_SET + ") VALUES (?, ?, ?)", new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType(), accountWithDataSet.getDataSet() }); } } // Check each of the existing sub-accounts against the account list. If the owning // account no longer exists, the sub-account and all its data should be deleted. List<AccountWithDataSet> accountsWithDataSetsToDelete = new ArrayList<AccountWithDataSet>(); List<Account> accountList = Arrays.asList(accounts); for (AccountWithDataSet accountWithDataSet : existingAccountsWithDataSets) { Account owningAccount = new Account( accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType()); if (!accountList.contains(owningAccount)) { accountsWithDataSetsToDelete.add(accountWithDataSet); } } if (!accountsWithDataSetsToDelete.isEmpty()) { accountsChanged = true; for (AccountWithDataSet accountWithDataSet : accountsWithDataSetsToDelete) { Log.d(TAG, "removing data for removed account " + accountWithDataSet); String[] accountParams = new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType() }; String[] accountWithDataSetParams = accountWithDataSet.getDataSet() == null ? accountParams : new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType(), accountWithDataSet.getDataSet() }; String groupsDataSetClause = " AND " + Groups.DATA_SET + (accountWithDataSet.getDataSet() == null ? " IS NULL" : " = ?"); String rawContactsDataSetClause = " AND " + RawContacts.DATA_SET + (accountWithDataSet.getDataSet() == null ? " IS NULL" : " = ?"); String settingsDataSetClause = " AND " + Settings.DATA_SET + (accountWithDataSet.getDataSet() == null ? " IS NULL" : " = ?"); db.execSQL( "DELETE FROM " + Tables.GROUPS + " WHERE " + Groups.ACCOUNT_NAME + " = ?" + " AND " + Groups.ACCOUNT_TYPE + " = ?" + groupsDataSetClause, accountWithDataSetParams); db.execSQL( "DELETE FROM " + Tables.PRESENCE + " WHERE " + PresenceColumns.RAW_CONTACT_ID + " IN (" + "SELECT " + RawContacts._ID + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts.ACCOUNT_NAME + " = ?" + " AND " + RawContacts.ACCOUNT_TYPE + " = ?" + rawContactsDataSetClause + ")", accountWithDataSetParams); db.execSQL( "DELETE FROM " + Tables.STREAM_ITEM_PHOTOS + " WHERE " + StreamItemPhotos.STREAM_ITEM_ID + " IN (" + "SELECT " + StreamItems._ID + " FROM " + Tables.STREAM_ITEMS + " WHERE " + StreamItems.RAW_CONTACT_ID + " IN (" + "SELECT " + RawContacts._ID + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts.ACCOUNT_NAME + " = ?" + " AND " + RawContacts.ACCOUNT_TYPE + " = ?" + rawContactsDataSetClause + "))", accountWithDataSetParams); db.execSQL( "DELETE FROM " + Tables.STREAM_ITEMS + " WHERE " + StreamItems.RAW_CONTACT_ID + " IN (" + "SELECT " + RawContacts._ID + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts.ACCOUNT_NAME + " = ?" + " AND " + RawContacts.ACCOUNT_TYPE + " = ?" + rawContactsDataSetClause + ")", accountWithDataSetParams); db.execSQL( "DELETE FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts.ACCOUNT_NAME + " = ?" + " AND " + RawContacts.ACCOUNT_TYPE + " = ?" + rawContactsDataSetClause, accountWithDataSetParams); db.execSQL( "DELETE FROM " + Tables.SETTINGS + " WHERE " + Settings.ACCOUNT_NAME + " = ?" + " AND " + Settings.ACCOUNT_TYPE + " = ?" + settingsDataSetClause, accountWithDataSetParams); db.execSQL( "DELETE FROM " + Tables.ACCOUNTS + " WHERE " + RawContacts.ACCOUNT_NAME + "=?" + " AND " + RawContacts.ACCOUNT_TYPE + "=?" + rawContactsDataSetClause, accountWithDataSetParams); db.execSQL( "DELETE FROM " + Tables.DIRECTORIES + " WHERE " + Directory.ACCOUNT_NAME + "=?" + " AND " + Directory.ACCOUNT_TYPE + "=?", accountParams); resetDirectoryCache(); } // Find all aggregated contacts that used to contain the raw contacts // we have just deleted and see if they are still referencing the deleted // names or photos. If so, fix up those contacts. HashSet<Long> orphanContactIds = Sets.newHashSet(); Cursor cursor = db.rawQuery("SELECT " + Contacts._ID + " FROM " + Tables.CONTACTS + " WHERE (" + Contacts.NAME_RAW_CONTACT_ID + " NOT NULL AND " + Contacts.NAME_RAW_CONTACT_ID + " NOT IN " + "(SELECT " + RawContacts._ID + " FROM " + Tables.RAW_CONTACTS + "))" + " OR (" + Contacts.PHOTO_ID + " NOT NULL AND " + Contacts.PHOTO_ID + " NOT IN " + "(SELECT " + Data._ID + " FROM " + Tables.DATA + "))", null); try { while (cursor.moveToNext()) { orphanContactIds.add(cursor.getLong(0)); } } finally { cursor.close(); } for (Long contactId : orphanContactIds) { mAggregator.get().updateAggregateData(mTransactionContext.get(), contactId); } mDbHelper.get().updateAllVisible(); // Don't bother updating the search index if we're in profile mode - there is no // search index for the profile DB, and updating it for the contacts DB in this case // makes no sense and risks a deadlock. if (!inProfileMode()) { updateSearchIndexInTransaction(); } } // Now that we've done the account-based additions and subtractions from the Accounts // table, check for raw contacts that have been added with a data set and add Accounts // entries for those if necessary. existingAccountsWithDataSets = findValidAccountsWithDataSets(Tables.ACCOUNTS); Set<AccountWithDataSet> rawContactAccountsWithDataSets = findValidAccountsWithDataSets(Tables.RAW_CONTACTS); rawContactAccountsWithDataSets.removeAll(existingAccountsWithDataSets); // Any remaining raw contact sub-accounts need to be added to the Accounts table. for (AccountWithDataSet accountWithDataSet : rawContactAccountsWithDataSets) { accountsChanged = true; // Add an account entry to match the raw contact. db.execSQL("INSERT INTO " + Tables.ACCOUNTS + " (" + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + RawContacts.DATA_SET + ") VALUES (?, ?, ?)", new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType(), accountWithDataSet.getDataSet() }); } if (accountsChanged) { // TODO: Should sync state take data set into consideration? mDbHelper.get().getSyncState().onAccountsChanged(db, accounts); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } mAccountWritability.clear(); if (accountsChanged) { updateContactsAccountCount(accounts); updateProviderStatus(); } return accountsChanged; } private void updateContactsAccountCount(Account[] accounts) { int count = 0; for (Account account : accounts) { if (isContactsAccount(account)) { count++; } } mContactsAccountCount = count; } protected boolean isContactsAccount(Account account) { final IContentService cs = ContentResolver.getContentService(); try { return cs.getIsSyncable(account, ContactsContract.AUTHORITY) > 0; } catch (RemoteException e) { Log.e(TAG, "Cannot obtain sync flag for account: " + account, e); return false; } } public void onPackageChanged(String packageName) { scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_DIRECTORIES, packageName); } /** * Finds all distinct account types and data sets present in the specified table. */ private Set<AccountWithDataSet> findValidAccountsWithDataSets(String table) { Set<AccountWithDataSet> accountsWithDataSets = new HashSet<AccountWithDataSet>(); Cursor c = mActiveDb.get().rawQuery( "SELECT DISTINCT " + RawContacts.ACCOUNT_NAME + "," + RawContacts.ACCOUNT_TYPE + "," + RawContacts.DATA_SET + " FROM " + table, null); try { while (c.moveToNext()) { if (!c.isNull(0) && !c.isNull(1)) { accountsWithDataSets.add( new AccountWithDataSet(c.getString(0), c.getString(1), c.getString(2))); } } } finally { c.close(); } return accountsWithDataSets; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { waitForAccess(mReadAccessLatch); // Enforce stream items access check if applicable. enforceSocialStreamReadPermission(uri); // Query the profile DB if appropriate. if (mapsToProfileDb(uri)) { switchToProfileMode(); return mProfileProvider.query(uri, projection, selection, selectionArgs, sortOrder); } // Otherwise proceed with a normal query against the contacts DB. switchToContactMode(); mActiveDb.set(mContactsHelper.getReadableDatabase()); String directory = getQueryParameter(uri, ContactsContract.DIRECTORY_PARAM_KEY); if (directory == null) { return addSnippetExtrasToCursor(uri, queryLocal(uri, projection, selection, selectionArgs, sortOrder, -1)); } else if (directory.equals("0")) { return addSnippetExtrasToCursor(uri, queryLocal(uri, projection, selection, selectionArgs, sortOrder, Directory.DEFAULT)); } else if (directory.equals("1")) { return addSnippetExtrasToCursor(uri, queryLocal(uri, projection, selection, selectionArgs, sortOrder, Directory.LOCAL_INVISIBLE)); } DirectoryInfo directoryInfo = getDirectoryAuthority(directory); if (directoryInfo == null) { Log.e(TAG, "Invalid directory ID: " + uri); return null; } Builder builder = new Uri.Builder(); builder.scheme(ContentResolver.SCHEME_CONTENT); builder.authority(directoryInfo.authority); builder.encodedPath(uri.getEncodedPath()); if (directoryInfo.accountName != null) { builder.appendQueryParameter(RawContacts.ACCOUNT_NAME, directoryInfo.accountName); } if (directoryInfo.accountType != null) { builder.appendQueryParameter(RawContacts.ACCOUNT_TYPE, directoryInfo.accountType); } String limit = getLimit(uri); if (limit != null) { builder.appendQueryParameter(ContactsContract.LIMIT_PARAM_KEY, limit); } Uri directoryUri = builder.build(); if (projection == null) { projection = getDefaultProjection(uri); } Cursor cursor = getContext().getContentResolver().query(directoryUri, projection, selection, selectionArgs, sortOrder); if (cursor == null) { return null; } CrossProcessCursor crossProcessCursor = getCrossProcessCursor(cursor); if (crossProcessCursor != null) { return addSnippetExtrasToCursor(uri, cursor); } else { return matrixCursorFromCursor(addSnippetExtrasToCursor(uri, cursor)); } } private Cursor addSnippetExtrasToCursor(Uri uri, Cursor cursor) { // If the cursor doesn't contain a snippet column, don't bother wrapping it. if (cursor.getColumnIndex(SearchSnippetColumns.SNIPPET) < 0) { return cursor; } // Parse out snippet arguments for use when snippets are retrieved from the cursor. String[] args = null; String snippetArgs = getQueryParameter(uri, SearchSnippetColumns.SNIPPET_ARGS_PARAM_KEY); if (snippetArgs != null) { args = snippetArgs.split(","); } String query = uri.getLastPathSegment(); String startMatch = args != null && args.length > 0 ? args[0] : DEFAULT_SNIPPET_ARG_START_MATCH; String endMatch = args != null && args.length > 1 ? args[1] : DEFAULT_SNIPPET_ARG_END_MATCH; String ellipsis = args != null && args.length > 2 ? args[2] : DEFAULT_SNIPPET_ARG_ELLIPSIS; int maxTokens = args != null && args.length > 3 ? Integer.parseInt(args[3]) : DEFAULT_SNIPPET_ARG_MAX_TOKENS; // Snippet data is needed for the snippeting on the client side, so store it in the cursor if (cursor instanceof AbstractCursor && deferredSnippetingRequested(uri)){ Bundle oldExtras = cursor.getExtras(); Bundle extras = new Bundle(); if (oldExtras != null) { extras.putAll(oldExtras); } extras.putString(ContactsContract.DEFERRED_SNIPPETING_QUERY, query); ((AbstractCursor) cursor).setExtras(extras); } return cursor; } private Cursor addDeferredSnippetingExtra(Cursor cursor) { if (cursor instanceof AbstractCursor){ Bundle oldExtras = cursor.getExtras(); Bundle extras = new Bundle(); if (oldExtras != null) { extras.putAll(oldExtras); } extras.putBoolean(ContactsContract.DEFERRED_SNIPPETING, true); ((AbstractCursor) cursor).setExtras(extras); } return cursor; } private CrossProcessCursor getCrossProcessCursor(Cursor cursor) { Cursor c = cursor; if (c instanceof CrossProcessCursor) { return (CrossProcessCursor) c; } else if (c instanceof CursorWindow) { return getCrossProcessCursor(((CursorWrapper) c).getWrappedCursor()); } else { return null; } } public MatrixCursor matrixCursorFromCursor(Cursor cursor) { MatrixCursor newCursor = new MatrixCursor(cursor.getColumnNames()); int numColumns = cursor.getColumnCount(); String data[] = new String[numColumns]; cursor.moveToPosition(-1); while (cursor.moveToNext()) { for (int i = 0; i < numColumns; i++) { data[i] = cursor.getString(i); } newCursor.addRow(data); } return newCursor; } private static final class DirectoryQuery { public static final String[] COLUMNS = new String[] { Directory._ID, Directory.DIRECTORY_AUTHORITY, Directory.ACCOUNT_NAME, Directory.ACCOUNT_TYPE }; public static final int DIRECTORY_ID = 0; public static final int AUTHORITY = 1; public static final int ACCOUNT_NAME = 2; public static final int ACCOUNT_TYPE = 3; } /** * Reads and caches directory information for the database. */ private DirectoryInfo getDirectoryAuthority(String directoryId) { synchronized (mDirectoryCache) { if (!mDirectoryCacheValid) { mDirectoryCache.clear(); SQLiteDatabase db = mDbHelper.get().getReadableDatabase(); Cursor cursor = db.query(Tables.DIRECTORIES, DirectoryQuery.COLUMNS, null, null, null, null, null); try { while (cursor.moveToNext()) { DirectoryInfo info = new DirectoryInfo(); String id = cursor.getString(DirectoryQuery.DIRECTORY_ID); info.authority = cursor.getString(DirectoryQuery.AUTHORITY); info.accountName = cursor.getString(DirectoryQuery.ACCOUNT_NAME); info.accountType = cursor.getString(DirectoryQuery.ACCOUNT_TYPE); mDirectoryCache.put(id, info); } } finally { cursor.close(); } mDirectoryCacheValid = true; } return mDirectoryCache.get(directoryId); } } public void resetDirectoryCache() { synchronized(mDirectoryCache) { mDirectoryCacheValid = false; } } private boolean hasColumn(String[] projection, String column) { if (projection == null) { return true; // Null projection means "all columns". } for (int i = 0; i < projection.length; i++) { if (column.equalsIgnoreCase(projection[i])) return true; } return false; } protected Cursor queryLocal(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, long directoryId) { if (VERBOSE_LOGGING) { Log.v(TAG, "query: " + uri); } // Default active DB to the contacts DB if none has been set. if (mActiveDb.get() == null) { mActiveDb.set(mContactsHelper.getReadableDatabase()); } SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String groupBy = null; String limit = getLimit(uri); boolean snippetDeferred = false; // The expression used in bundleLetterCountExtras() to get count. String addressBookIndexerCountExpression = null; final int match = sUriMatcher.match(uri); switch (match) { case SYNCSTATE: case PROFILE_SYNCSTATE: return mDbHelper.get().getSyncState().query(mActiveDb.get(), projection, selection, selectionArgs, sortOrder); case CONTACTS: { setTablesAndProjectionMapForContacts(qb, uri, projection); appendLocalDirectorySelectionIfNeeded(qb, directoryId); break; } case CONTACTS_ID: { long contactId = ContentUris.parseId(uri); setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP: case CONTACTS_LOOKUP_ID: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 4) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, projection); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey))); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP_DATA: case CONTACTS_LOOKUP_ID_DATA: case CONTACTS_LOOKUP_PHOTO: case CONTACTS_LOOKUP_ID_PHOTO: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForData(lookupQb, uri, projection, false); if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) { qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); } lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Data.CONTACT_ID, contactId, Data.LOOKUP_KEY, lookupKey); if (c != null) { return c; } // TODO see if the contact exists but has no data rows (rare) } setTablesAndProjectionMapForData(qb, uri, projection, false); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) { qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); } qb.appendWhere(" AND " + Data.CONTACT_ID + "=?"); break; } case CONTACTS_ID_STREAM_ITEMS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(StreamItems.CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_STREAM_ITEMS: case CONTACTS_LOOKUP_ID_STREAM_ITEMS: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItems(lookupQb); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, StreamItems.CONTACT_ID, contactId, StreamItems.CONTACT_LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForStreamItems(qb); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_AS_VCARD: { final String lookupKey = Uri.encode(uri.getPathSegments().get(2)); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_AS_MULTI_VCARD: { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); String currentDateString = dateFormat.format(new Date()).toString(); return mActiveDb.get().rawQuery( "SELECT" + " 'vcards_' || ? || '.vcf' AS " + OpenableColumns.DISPLAY_NAME + "," + " NULL AS " + OpenableColumns.SIZE, new String[] { currentDateString }); } case CONTACTS_FILTER: { String filterParam = ""; boolean deferredSnipRequested = deferredSnippetingRequested(uri); if (uri.getPathSegments().size() > 2) { filterParam = uri.getLastPathSegment(); } setTablesAndProjectionMapForContactsWithSnippet( qb, uri, projection, filterParam, directoryId, deferredSnipRequested); snippetDeferred = isSingleWordQuery(filterParam) && deferredSnipRequested && snippetNeeded(projection); break; } case CONTACTS_STREQUENT_FILTER: case CONTACTS_STREQUENT: { // Basically the resultant SQL should look like this: // (SQL for listing starred items) // UNION ALL // (SQL for listing frequently contacted items) // ORDER BY ... final boolean phoneOnly = readBooleanQueryParameter( uri, ContactsContract.STREQUENT_PHONE_ONLY, false); if (match == CONTACTS_STREQUENT_FILTER && uri.getPathSegments().size() > 3) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(Contacts._ID + " IN "); appendContactFilterAsNestedQuery(sb, filterParam); selection = DbQueryUtils.concatenateClauses(selection, sb.toString()); } String[] subProjection = null; if (projection != null) { subProjection = appendProjectionArg(projection, TIMES_USED_SORT_COLUMN); } // Build the first query for starred setTablesAndProjectionMapForContacts(qb, uri, projection, false); qb.setProjectionMap(phoneOnly ? sStrequentPhoneOnlyStarredProjectionMap : sStrequentStarredProjectionMap); if (phoneOnly) { qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.HAS_PHONE_NUMBER + "=1")); } qb.setStrict(true); final String starredQuery = qb.buildQuery(subProjection, Contacts.STARRED + "=1", Contacts._ID, null, null, null); // Reset the builder. qb = new SQLiteQueryBuilder(); qb.setStrict(true); // Build the second query for frequent part. final String frequentQuery; if (phoneOnly) { final StringBuilder tableBuilder = new StringBuilder(); // In phone only mode, we need to look at view_data instead of // contacts/raw_contacts to obtain actual phone numbers. One problem is that // view_data is much larger than view_contacts, so our query might become much // slower. // // To avoid the possible slow down, we start from data usage table and join // view_data to the table, assuming data usage table is quite smaller than // data rows (almost always it should be), and we don't want any phone // numbers not used by the user. This way sqlite is able to drop a number of // rows in view_data in the early stage of data lookup. tableBuilder.append(Tables.DATA_USAGE_STAT + " INNER JOIN " + Views.DATA + " " + Tables.DATA + " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "=" + DataColumns.CONCRETE_ID + " AND " + DataUsageStatColumns.CONCRETE_USAGE_TYPE + "=" + DataUsageStatColumns.USAGE_TYPE_INT_CALL + ")"); appendContactPresenceJoin(tableBuilder, projection, RawContacts.CONTACT_ID); appendContactStatusUpdateJoin(tableBuilder, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(tableBuilder.toString()); qb.setProjectionMap(sStrequentPhoneOnlyFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.STARRED + "=0 OR " + Contacts.STARRED + " IS NULL", MimetypesColumns.MIMETYPE + " IN (" + "'" + Phone.CONTENT_ITEM_TYPE + "', " + "'" + SipAddress.CONTENT_ITEM_TYPE + "')")); frequentQuery = qb.buildQuery(subProjection, null, null, null, null, null); } else { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, "(" + Contacts.STARRED + " =0 OR " + Contacts.STARRED + " IS NULL)")); frequentQuery = qb.buildQuery(subProjection, null, Contacts._ID, null, null, null); } // Put them together final String unionQuery = qb.buildUnionQuery(new String[] {starredQuery, frequentQuery}, STREQUENT_ORDER_BY, STREQUENT_LIMIT); // Here, we need to use selection / selectionArgs (supplied from users) "twice", // as we want them both for starred items and for frequently contacted items. // // e.g. if the user specify selection = "starred =?" and selectionArgs = "0", // the resultant SQL should be like: // SELECT ... WHERE starred =? AND ... // UNION ALL // SELECT ... WHERE starred =? AND ... String[] doubledSelectionArgs = null; if (selectionArgs != null) { final int length = selectionArgs.length; doubledSelectionArgs = new String[length * 2]; System.arraycopy(selectionArgs, 0, doubledSelectionArgs, 0, length); System.arraycopy(selectionArgs, 0, doubledSelectionArgs, length, length); } Cursor cursor = mActiveDb.get().rawQuery(unionQuery, doubledSelectionArgs); if (cursor != null) { cursor.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI); } return cursor; } case CONTACTS_FREQUENT: { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); groupBy = Contacts._ID; if (!TextUtils.isEmpty(sortOrder)) { sortOrder = FREQUENT_ORDER_BY + ", " + sortOrder; } else { sortOrder = FREQUENT_ORDER_BY; } break; } case CONTACTS_GROUP: { setTablesAndProjectionMapForContacts(qb, uri, projection); if (uri.getPathSegments().size() > 2) { qb.appendWhere(CONTACTS_IN_GROUP_SELECT); String groupMimeTypeId = String.valueOf( mDbHelper.get().getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); selectionArgs = insertSelectionArg(selectionArgs, groupMimeTypeId); } break; } case PROFILE: { setTablesAndProjectionMapForContacts(qb, uri, projection); break; } case PROFILE_ENTITIES: { setTablesAndProjectionMapForEntities(qb, uri, projection); break; } case PROFILE_AS_VCARD: { qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); break; } case CONTACTS_ID_DATA: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_ID_PHOTO: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); break; } case CONTACTS_ID_ENTITIES: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_ENTITIES: case CONTACTS_LOOKUP_ID_ENTITIES: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForEntities(lookupQb, uri, projection); lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts.Entity.CONTACT_ID, contactId, Contacts.Entity.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey))); qb.appendWhere(" AND " + Contacts.Entity.CONTACT_ID + "=?"); break; } case STREAM_ITEMS: { setTablesAndProjectionMapForStreamItems(qb); break; } case STREAM_ITEMS_ID: { setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(StreamItems._ID + "=?"); break; } case STREAM_ITEMS_LIMIT: { MatrixCursor cursor = new MatrixCursor(new String[]{StreamItems.MAX_ITEMS}, 1); cursor.addRow(new Object[]{MAX_STREAM_ITEMS_PER_RAW_CONTACT}); return cursor; } case STREAM_ITEMS_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); break; } case STREAM_ITEMS_ID_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?"); break; } case STREAM_ITEMS_ID_PHOTOS_ID: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); selectionArgs = insertSelectionArg(selectionArgs, streamItemPhotoId); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=? AND " + StreamItemPhotosColumns.CONCRETE_ID + "=?"); break; } case PHOTO_DIMENSIONS: { MatrixCursor cursor = new MatrixCursor( new String[]{DisplayPhoto.DISPLAY_MAX_DIM, DisplayPhoto.THUMBNAIL_MAX_DIM}, 1); cursor.addRow(new Object[]{mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim}); return cursor; } case PHONES: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + "=" + mDbHelper.get().getMimeTypeIdForPhone()); // Dedupe phone numbers per contact. groupBy = RawContacts.CONTACT_ID + ", " + Data.DATA1; // In this case, because we dedupe phone numbers, the address book indexer needs // to take it into account too. (Otherwise headers will appear in wrong positions.) // So use count(distinct pair(CONTACT_ID, PHONE NUMBER)) instead of count(*). // But because there's no such thing as pair() on sqlite, we use // CONTACT_ID || ',' || PHONE NUMBER instead. // This only slows down the query by 14% with 10,000 contacts. addressBookIndexerCountExpression = "DISTINCT " + RawContacts.CONTACT_ID + "||','||" + Data.DATA1; break; } case PHONES_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForPhone()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PHONES_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_CALL; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForPhone()); if (uri.getPathSegments().size() > 2) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(" AND ("); boolean hasCondition = false; boolean orNeeded = false; final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery( filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING); if (ftsMatchQuery.length() > 0) { sb.append(Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH '"); sb.append(ftsMatchQuery); sb.append("')"); orNeeded = true; hasCondition = true; } String number = PhoneNumberUtils.normalizeNumber(filterParam); if (!TextUtils.isEmpty(number)) { if (orNeeded) { sb.append(" OR "); } sb.append(Data._ID + " IN (SELECT DISTINCT " + PhoneLookupColumns.DATA_ID + " FROM " + Tables.PHONE_LOOKUP + " WHERE " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(number); sb.append("%')"); hasCondition = true; } if (!hasCondition) { // If it is neither a phone number nor a name, the query should return // an empty cursor. Let's ensure that. sb.append("0"); } sb.append(")"); qb.appendWhere(sb); } groupBy = "(CASE WHEN " + PhoneColumns.NORMALIZED_NUMBER + " IS NOT NULL THEN " + PhoneColumns.NORMALIZED_NUMBER + " ELSE " + Phone.NUMBER + " END), " + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + PHONE_FILTER_SORT_ORDER; } else { sortOrder = PHONE_FILTER_SORT_ORDER; } } break; } case EMAILS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForEmail()); break; } case EMAILS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForEmail() + " AND " + Data._ID + "=?"); break; } case EMAILS_LOOKUP: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForEmail()); if (uri.getPathSegments().size() > 2) { String email = uri.getLastPathSegment(); String address = mDbHelper.get().extractAddressFromEmailAddress(email); selectionArgs = insertSelectionArg(selectionArgs, address); qb.appendWhere(" AND UPPER(" + Email.DATA + ")=UPPER(?)"); } + // unless told otherwise, we'll return visible before invisible contacts + if (sortOrder == null) { + sortOrder = "(" + RawContacts.CONTACT_ID + " IN " + + Tables.DEFAULT_DIRECTORY + ") DESC"; + } break; } case EMAILS_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); String filterParam = null; if (uri.getPathSegments().size() > 3) { filterParam = uri.getLastPathSegment(); if (TextUtils.isEmpty(filterParam)) { filterParam = null; } } if (filterParam == null) { // If the filter is unspecified, return nothing qb.appendWhere(" AND 0"); } else { StringBuilder sb = new StringBuilder(); sb.append(" AND " + Data._ID + " IN ("); sb.append( "SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE " + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.get().getMimeTypeIdForEmail()); sb.append(" AND " + Data.DATA1 + " LIKE "); DatabaseUtils.appendEscapedSQLString(sb, filterParam + '%'); if (!filterParam.contains("@")) { sb.append( " UNION SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE +" + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.get().getMimeTypeIdForEmail()); sb.append(" AND " + Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH '"); final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery( filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING); sb.append(ftsMatchQuery); sb.append("')"); } sb.append(")"); qb.appendWhere(sb); } groupBy = Email.DATA + "," + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + EMAIL_FILTER_SORT_ORDER; } else { sortOrder = EMAIL_FILTER_SORT_ORDER; } } break; } case POSTALS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForStructuredPostal()); break; } case POSTALS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForStructuredPostal()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case RAW_CONTACTS: case PROFILE_RAW_CONTACTS: { setTablesAndProjectionMapForRawContacts(qb, uri); break; } case RAW_CONTACTS_ID: case PROFILE_RAW_CONTACTS_ID: { long rawContactId = ContentUris.parseId(uri); setTablesAndProjectionMapForRawContacts(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case RAW_CONTACTS_DATA: case PROFILE_RAW_CONTACTS_ID_DATA: { int segment = match == RAW_CONTACTS_DATA ? 1 : 2; long rawContactId = Long.parseLong(uri.getPathSegments().get(segment)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + Data.RAW_CONTACT_ID + "=?"); break; } case RAW_CONTACTS_ID_STREAM_ITEMS: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=?"); break; } case RAW_CONTACTS_ID_STREAM_ITEMS_ID: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); long streamItemId = Long.parseLong(uri.getPathSegments().get(3)); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(streamItemId)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=? AND " + StreamItems._ID + "=?"); break; } case PROFILE_RAW_CONTACTS_ID_ENTITIES: { long rawContactId = Long.parseLong(uri.getPathSegments().get(2)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForRawEntities(qb, uri); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case DATA: case PROFILE_DATA: { setTablesAndProjectionMapForData(qb, uri, projection, false); break; } case DATA_ID: case PROFILE_DATA_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PROFILE_PHOTO: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); break; } case PHONE_LOOKUP: { // Phone lookup cannot be combined with a selection selection = null; selectionArgs = null; if (uri.getBooleanQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, false)) { if (TextUtils.isEmpty(sortOrder)) { // Default the sort order to something reasonable so we get consistent // results when callers don't request an ordering sortOrder = Contacts.DISPLAY_NAME + " ASC"; } String sipAddress = uri.getPathSegments().size() > 1 ? Uri.decode(uri.getLastPathSegment()) : ""; setTablesAndProjectionMapForData(qb, uri, null, false, true); StringBuilder sb = new StringBuilder(); selectionArgs = mDbHelper.get().buildSipContactQuery(sb, sipAddress); selection = sb.toString(); } else { if (TextUtils.isEmpty(sortOrder)) { // Default the sort order to something reasonable so we get consistent // results when callers don't request an ordering sortOrder = " length(lookup.normalized_number) DESC"; } String number = uri.getPathSegments().size() > 1 ? uri.getLastPathSegment() : ""; String numberE164 = PhoneNumberUtils.formatNumberToE164(number, mDbHelper.get().getCurrentCountryIso()); String normalizedNumber = PhoneNumberUtils.normalizeNumber(number); mDbHelper.get().buildPhoneLookupAndContactQuery( qb, normalizedNumber, numberE164); qb.setProjectionMap(sPhoneLookupProjectionMap); } break; } case GROUPS: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); appendAccountFromParameter(qb, uri); break; } case GROUPS_ID: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(Groups._ID + "=?"); break; } case GROUPS_SUMMARY: { final boolean returnGroupCountPerAccount = readBooleanQueryParameter(uri, Groups.PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT, false); String tables = Views.GROUPS + " AS " + Tables.GROUPS; if (hasColumn(projection, Groups.SUMMARY_COUNT)) { tables = tables + Joins.GROUP_MEMBER_COUNT; } qb.setTables(tables); qb.setProjectionMap(returnGroupCountPerAccount ? sGroupsSummaryProjectionMapWithGroupCountPerAccount : sGroupsSummaryProjectionMap); appendAccountFromParameter(qb, uri); groupBy = GroupsColumns.CONCRETE_ID; break; } case AGGREGATION_EXCEPTIONS: { qb.setTables(Tables.AGGREGATION_EXCEPTIONS); qb.setProjectionMap(sAggregationExceptionsProjectionMap); break; } case AGGREGATION_SUGGESTIONS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); String filter = null; if (uri.getPathSegments().size() > 3) { filter = uri.getPathSegments().get(3); } final int maxSuggestions; if (limit != null) { maxSuggestions = Integer.parseInt(limit); } else { maxSuggestions = DEFAULT_MAX_SUGGESTIONS; } ArrayList<AggregationSuggestionParameter> parameters = null; List<String> query = uri.getQueryParameters("query"); if (query != null && !query.isEmpty()) { parameters = new ArrayList<AggregationSuggestionParameter>(query.size()); for (String parameter : query) { int offset = parameter.indexOf(':'); parameters.add(offset == -1 ? new AggregationSuggestionParameter( AggregationSuggestions.PARAMETER_MATCH_NAME, parameter) : new AggregationSuggestionParameter( parameter.substring(0, offset), parameter.substring(offset + 1))); } } setTablesAndProjectionMapForContacts(qb, uri, projection); return mAggregator.get().queryAggregationSuggestions(qb, projection, contactId, maxSuggestions, filter, parameters); } case SETTINGS: { qb.setTables(Tables.SETTINGS); qb.setProjectionMap(sSettingsProjectionMap); appendAccountFromParameter(qb, uri); // When requesting specific columns, this query requires // late-binding of the GroupMembership MIME-type. final String groupMembershipMimetypeId = Long.toString(mDbHelper.get() .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); if (projection != null && projection.length != 0 && mDbHelper.get().isInProjection(projection, Settings.UNGROUPED_COUNT)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } if (projection != null && projection.length != 0 && mDbHelper.get().isInProjection( projection, Settings.UNGROUPED_WITH_PHONES)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } break; } case STATUS_UPDATES: case PROFILE_STATUS_UPDATES: { setTableAndProjectionMapForStatusUpdates(qb, projection); break; } case STATUS_UPDATES_ID: { setTableAndProjectionMapForStatusUpdates(qb, projection); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(DataColumns.CONCRETE_ID + "=?"); break; } case SEARCH_SUGGESTIONS: { return mGlobalSearchSupport.handleSearchSuggestionsQuery( mActiveDb.get(), uri, projection, limit); } case SEARCH_SHORTCUT: { String lookupKey = uri.getLastPathSegment(); String filter = getQueryParameter( uri, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA); return mGlobalSearchSupport.handleSearchShortcutRefresh( mActiveDb.get(), projection, lookupKey, filter); } case RAW_CONTACT_ENTITIES: case PROFILE_RAW_CONTACT_ENTITIES: { setTablesAndProjectionMapForRawEntities(qb, uri); break; } case RAW_CONTACT_ENTITY_ID: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForRawEntities(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case PROVIDER_STATUS: { return queryProviderStatus(uri, projection); } case DIRECTORIES : { qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); break; } case DIRECTORIES_ID : { long id = ContentUris.parseId(uri); qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(id)); qb.appendWhere(Directory._ID + "=?"); break; } case COMPLETE_NAME: { return completeName(uri, projection); } default: return mLegacyApiSupport.query(uri, projection, selection, selectionArgs, sortOrder, limit); } qb.setStrict(true); Cursor cursor = query(mActiveDb.get(), qb, projection, selection, selectionArgs, sortOrder, groupBy, limit); if (readBooleanQueryParameter(uri, ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, false)) { cursor = bundleLetterCountExtras(cursor, mActiveDb.get(), qb, selection, selectionArgs, sortOrder, addressBookIndexerCountExpression); } if (snippetDeferred) { cursor = addDeferredSnippetingExtra(cursor); } return cursor; } private Cursor query(final SQLiteDatabase db, SQLiteQueryBuilder qb, String[] projection, String selection, String[] selectionArgs, String sortOrder, String groupBy, String limit) { if (projection != null && projection.length == 1 && BaseColumns._COUNT.equals(projection[0])) { qb.setProjectionMap(sCountProjectionMap); } final Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, sortOrder, limit); if (c != null) { c.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI); } return c; } /** * Creates a single-row cursor containing the current status of the provider. */ private Cursor queryProviderStatus(Uri uri, String[] projection) { MatrixCursor cursor = new MatrixCursor(projection); RowBuilder row = cursor.newRow(); for (int i = 0; i < projection.length; i++) { if (ProviderStatus.STATUS.equals(projection[i])) { row.add(mProviderStatus); } else if (ProviderStatus.DATA1.equals(projection[i])) { row.add(mEstimatedStorageRequirement); } } return cursor; } /** * Runs the query with the supplied contact ID and lookup ID. If the query succeeds, * it returns the resulting cursor, otherwise it returns null and the calling * method needs to resolve the lookup key and rerun the query. */ private Cursor queryWithContactIdAndLookupKey(SQLiteQueryBuilder lookupQb, SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, String groupBy, String limit, String contactIdColumn, long contactId, String lookupKeyColumn, String lookupKey) { String[] args; if (selectionArgs == null) { args = new String[2]; } else { args = new String[selectionArgs.length + 2]; System.arraycopy(selectionArgs, 0, args, 2, selectionArgs.length); } args[0] = String.valueOf(contactId); args[1] = Uri.encode(lookupKey); lookupQb.appendWhere(contactIdColumn + "=? AND " + lookupKeyColumn + "=?"); Cursor c = query(db, lookupQb, projection, selection, args, sortOrder, groupBy, limit); if (c.getCount() != 0) { return c; } c.close(); return null; } private static final class AddressBookIndexQuery { public static final String LETTER = "letter"; public static final String TITLE = "title"; public static final String COUNT = "count"; public static final String[] COLUMNS = new String[] { LETTER, TITLE, COUNT }; public static final int COLUMN_LETTER = 0; public static final int COLUMN_TITLE = 1; public static final int COLUMN_COUNT = 2; // The first letter of the sort key column is what is used for the index headings. public static final String SECTION_HEADING = "SUBSTR(%1$s,1,1)"; public static final String ORDER_BY = LETTER + " COLLATE " + PHONEBOOK_COLLATOR_NAME; } /** * Computes counts by the address book index titles and adds the resulting tally * to the returned cursor as a bundle of extras. */ private Cursor bundleLetterCountExtras(Cursor cursor, final SQLiteDatabase db, SQLiteQueryBuilder qb, String selection, String[] selectionArgs, String sortOrder, String countExpression) { if (!(cursor instanceof AbstractCursor)) { Log.w(TAG, "Unable to bundle extras. Cursor is not AbstractCursor."); return cursor; } String sortKey; // The sort order suffix could be something like "DESC". // We want to preserve it in the query even though we will change // the sort column itself. String sortOrderSuffix = ""; if (sortOrder != null) { int spaceIndex = sortOrder.indexOf(' '); if (spaceIndex != -1) { sortKey = sortOrder.substring(0, spaceIndex); sortOrderSuffix = sortOrder.substring(spaceIndex); } else { sortKey = sortOrder; } } else { sortKey = Contacts.SORT_KEY_PRIMARY; } String locale = getLocale().toString(); HashMap<String, String> projectionMap = Maps.newHashMap(); String sectionHeading = String.format(AddressBookIndexQuery.SECTION_HEADING, sortKey); projectionMap.put(AddressBookIndexQuery.LETTER, sectionHeading + " AS " + AddressBookIndexQuery.LETTER); // If "what to count" is not specified, we just count all records. if (TextUtils.isEmpty(countExpression)) { countExpression = "*"; } /** * Use the GET_PHONEBOOK_INDEX function, which is an android extension for SQLite3, * to map the first letter of the sort key to a character that is traditionally * used in phonebooks to represent that letter. For example, in Korean it will * be the first consonant in the letter; for Japanese it will be Hiragana rather * than Katakana. */ projectionMap.put(AddressBookIndexQuery.TITLE, "GET_PHONEBOOK_INDEX(" + sectionHeading + ",'" + locale + "')" + " AS " + AddressBookIndexQuery.TITLE); projectionMap.put(AddressBookIndexQuery.COUNT, "COUNT(" + countExpression + ") AS " + AddressBookIndexQuery.COUNT); qb.setProjectionMap(projectionMap); Cursor indexCursor = qb.query(db, AddressBookIndexQuery.COLUMNS, selection, selectionArgs, AddressBookIndexQuery.ORDER_BY, null /* having */, AddressBookIndexQuery.ORDER_BY + sortOrderSuffix); try { int groupCount = indexCursor.getCount(); String titles[] = new String[groupCount]; int counts[] = new int[groupCount]; int indexCount = 0; String currentTitle = null; // Since GET_PHONEBOOK_INDEX is a many-to-1 function, we may end up // with multiple entries for the same title. The following code // collapses those duplicates. for (int i = 0; i < groupCount; i++) { indexCursor.moveToNext(); String title = indexCursor.getString(AddressBookIndexQuery.COLUMN_TITLE); int count = indexCursor.getInt(AddressBookIndexQuery.COLUMN_COUNT); if (indexCount == 0 || !TextUtils.equals(title, currentTitle)) { titles[indexCount] = currentTitle = title; counts[indexCount] = count; indexCount++; } else { counts[indexCount - 1] += count; } } if (indexCount < groupCount) { String[] newTitles = new String[indexCount]; System.arraycopy(titles, 0, newTitles, 0, indexCount); titles = newTitles; int[] newCounts = new int[indexCount]; System.arraycopy(counts, 0, newCounts, 0, indexCount); counts = newCounts; } final Bundle bundle = new Bundle(); bundle.putStringArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES, titles); bundle.putIntArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS, counts); ((AbstractCursor) cursor).setExtras(bundle); return cursor; } finally { indexCursor.close(); } } /** * Returns the contact Id for the contact identified by the lookupKey. * Robust against changes in the lookup key: if the key has changed, will * look up the contact by the raw contact IDs or name encoded in the lookup * key. */ public long lookupContactIdByLookupKey(SQLiteDatabase db, String lookupKey) { ContactLookupKey key = new ContactLookupKey(); ArrayList<LookupKeySegment> segments = key.parse(lookupKey); long contactId = -1; if (lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_PROFILE)) { // We should already be in a profile database context, so just look up a single contact. contactId = lookupSingleContactId(db); } if (lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_SOURCE_ID)) { contactId = lookupContactIdBySourceIds(db, segments); if (contactId != -1) { return contactId; } } boolean hasRawContactIds = lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID); if (hasRawContactIds) { contactId = lookupContactIdByRawContactIds(db, segments); if (contactId != -1) { return contactId; } } if (hasRawContactIds || lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_DISPLAY_NAME)) { contactId = lookupContactIdByDisplayNames(db, segments); } return contactId; } private long lookupSingleContactId(SQLiteDatabase db) { Cursor c = db.query(Tables.CONTACTS, new String[] {Contacts._ID}, null, null, null, null, null, "1"); try { if (c.moveToFirst()) { return c.getLong(0); } else { return -1; } } finally { c.close(); } } private interface LookupBySourceIdQuery { String TABLE = Views.RAW_CONTACTS; String COLUMNS[] = { RawContacts.CONTACT_ID, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.ACCOUNT_NAME, RawContacts.SOURCE_ID }; int CONTACT_ID = 0; int ACCOUNT_TYPE_AND_DATA_SET = 1; int ACCOUNT_NAME = 2; int SOURCE_ID = 3; } private long lookupContactIdBySourceIds(SQLiteDatabase db, ArrayList<LookupKeySegment> segments) { StringBuilder sb = new StringBuilder(); sb.append(RawContacts.SOURCE_ID + " IN ("); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_SOURCE_ID) { DatabaseUtils.appendEscapedSQLString(sb, segment.key); sb.append(","); } } sb.setLength(sb.length() - 1); // Last comma sb.append(") AND " + RawContacts.CONTACT_ID + " NOT NULL"); Cursor c = db.query(LookupBySourceIdQuery.TABLE, LookupBySourceIdQuery.COLUMNS, sb.toString(), null, null, null, null); try { while (c.moveToNext()) { String accountTypeAndDataSet = c.getString(LookupBySourceIdQuery.ACCOUNT_TYPE_AND_DATA_SET); String accountName = c.getString(LookupBySourceIdQuery.ACCOUNT_NAME); int accountHashCode = ContactLookupKey.getAccountHashCode(accountTypeAndDataSet, accountName); String sourceId = c.getString(LookupBySourceIdQuery.SOURCE_ID); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_SOURCE_ID && accountHashCode == segment.accountHashCode && segment.key.equals(sourceId)) { segment.contactId = c.getLong(LookupBySourceIdQuery.CONTACT_ID); break; } } } } finally { c.close(); } return getMostReferencedContactId(segments); } private interface LookupByRawContactIdQuery { String TABLE = Views.RAW_CONTACTS; String COLUMNS[] = { RawContacts.CONTACT_ID, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.ACCOUNT_NAME, RawContacts._ID, }; int CONTACT_ID = 0; int ACCOUNT_TYPE_AND_DATA_SET = 1; int ACCOUNT_NAME = 2; int ID = 3; } private long lookupContactIdByRawContactIds(SQLiteDatabase db, ArrayList<LookupKeySegment> segments) { StringBuilder sb = new StringBuilder(); sb.append(RawContacts._ID + " IN ("); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID) { sb.append(segment.rawContactId); sb.append(","); } } sb.setLength(sb.length() - 1); // Last comma sb.append(") AND " + RawContacts.CONTACT_ID + " NOT NULL"); Cursor c = db.query(LookupByRawContactIdQuery.TABLE, LookupByRawContactIdQuery.COLUMNS, sb.toString(), null, null, null, null); try { while (c.moveToNext()) { String accountTypeAndDataSet = c.getString( LookupByRawContactIdQuery.ACCOUNT_TYPE_AND_DATA_SET); String accountName = c.getString(LookupByRawContactIdQuery.ACCOUNT_NAME); int accountHashCode = ContactLookupKey.getAccountHashCode(accountTypeAndDataSet, accountName); String rawContactId = c.getString(LookupByRawContactIdQuery.ID); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID && accountHashCode == segment.accountHashCode && segment.rawContactId.equals(rawContactId)) { segment.contactId = c.getLong(LookupByRawContactIdQuery.CONTACT_ID); break; } } } } finally { c.close(); } return getMostReferencedContactId(segments); } private interface LookupByDisplayNameQuery { String TABLE = Tables.NAME_LOOKUP_JOIN_RAW_CONTACTS; String COLUMNS[] = { RawContacts.CONTACT_ID, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.ACCOUNT_NAME, NameLookupColumns.NORMALIZED_NAME }; int CONTACT_ID = 0; int ACCOUNT_TYPE_AND_DATA_SET = 1; int ACCOUNT_NAME = 2; int NORMALIZED_NAME = 3; } private long lookupContactIdByDisplayNames(SQLiteDatabase db, ArrayList<LookupKeySegment> segments) { StringBuilder sb = new StringBuilder(); sb.append(NameLookupColumns.NORMALIZED_NAME + " IN ("); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_DISPLAY_NAME || segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID) { DatabaseUtils.appendEscapedSQLString(sb, segment.key); sb.append(","); } } sb.setLength(sb.length() - 1); // Last comma sb.append(") AND " + NameLookupColumns.NAME_TYPE + "=" + NameLookupType.NAME_COLLATION_KEY + " AND " + RawContacts.CONTACT_ID + " NOT NULL"); Cursor c = db.query(LookupByDisplayNameQuery.TABLE, LookupByDisplayNameQuery.COLUMNS, sb.toString(), null, null, null, null); try { while (c.moveToNext()) { String accountTypeAndDataSet = c.getString(LookupByDisplayNameQuery.ACCOUNT_TYPE_AND_DATA_SET); String accountName = c.getString(LookupByDisplayNameQuery.ACCOUNT_NAME); int accountHashCode = ContactLookupKey.getAccountHashCode(accountTypeAndDataSet, accountName); String name = c.getString(LookupByDisplayNameQuery.NORMALIZED_NAME); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if ((segment.lookupType == ContactLookupKey.LOOKUP_TYPE_DISPLAY_NAME || segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID) && accountHashCode == segment.accountHashCode && segment.key.equals(name)) { segment.contactId = c.getLong(LookupByDisplayNameQuery.CONTACT_ID); break; } } } } finally { c.close(); } return getMostReferencedContactId(segments); } private boolean lookupKeyContainsType(ArrayList<LookupKeySegment> segments, int lookupType) { for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == lookupType) { return true; } } return false; } public void updateLookupKeyForRawContact(SQLiteDatabase db, long rawContactId) { mAggregator.get().updateLookupKeyForRawContact(db, rawContactId); } /** * Returns the contact ID that is mentioned the highest number of times. */ private long getMostReferencedContactId(ArrayList<LookupKeySegment> segments) { Collections.sort(segments); long bestContactId = -1; int bestRefCount = 0; long contactId = -1; int count = 0; int segmentCount = segments.size(); for (int i = 0; i < segmentCount; i++) { LookupKeySegment segment = segments.get(i); if (segment.contactId != -1) { if (segment.contactId == contactId) { count++; } else { if (count > bestRefCount) { bestContactId = contactId; bestRefCount = count; } contactId = segment.contactId; count = 1; } } } if (count > bestRefCount) { return contactId; } else { return bestContactId; } } private void setTablesAndProjectionMapForContacts(SQLiteQueryBuilder qb, Uri uri, String[] projection) { setTablesAndProjectionMapForContacts(qb, uri, projection, false); } /** * @param includeDataUsageStat true when the table should include DataUsageStat table. * Note that this uses INNER JOIN instead of LEFT OUTER JOIN, so some of data in Contacts * may be dropped. */ private void setTablesAndProjectionMapForContacts(SQLiteQueryBuilder qb, Uri uri, String[] projection, boolean includeDataUsageStat) { StringBuilder sb = new StringBuilder(); sb.append(Views.CONTACTS); // Just for frequently contacted contacts in Strequent Uri handling. if (includeDataUsageStat) { sb.append(" INNER JOIN " + Views.DATA_USAGE_STAT + " AS " + Tables.DATA_USAGE_STAT + " ON (" + DbQueryUtils.concatenateClauses( DataUsageStatColumns.CONCRETE_TIMES_USED + " > 0", RawContacts.CONTACT_ID + "=" + Views.CONTACTS + "." + Contacts._ID) + ")"); } appendContactPresenceJoin(sb, projection, Contacts._ID); appendContactStatusUpdateJoin(sb, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(sb.toString()); qb.setProjectionMap(sContactsProjectionMap); } /** * Finds name lookup records matching the supplied filter, picks one arbitrary match per * contact and joins that with other contacts tables. */ private void setTablesAndProjectionMapForContactsWithSnippet(SQLiteQueryBuilder qb, Uri uri, String[] projection, String filter, long directoryId, boolean deferredSnippeting) { StringBuilder sb = new StringBuilder(); sb.append(Views.CONTACTS); if (filter != null) { filter = filter.trim(); } if (TextUtils.isEmpty(filter) || (directoryId != -1 && directoryId != Directory.DEFAULT)) { sb.append(" JOIN (SELECT NULL AS " + SearchSnippetColumns.SNIPPET + " WHERE 0)"); } else { appendSearchIndexJoin(sb, uri, projection, filter, deferredSnippeting); } appendContactPresenceJoin(sb, projection, Contacts._ID); appendContactStatusUpdateJoin(sb, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(sb.toString()); qb.setProjectionMap(sContactsProjectionWithSnippetMap); } private void appendSearchIndexJoin( StringBuilder sb, Uri uri, String[] projection, String filter, boolean deferredSnippeting) { if (snippetNeeded(projection)) { String[] args = null; String snippetArgs = getQueryParameter(uri, SearchSnippetColumns.SNIPPET_ARGS_PARAM_KEY); if (snippetArgs != null) { args = snippetArgs.split(","); } String startMatch = args != null && args.length > 0 ? args[0] : DEFAULT_SNIPPET_ARG_START_MATCH; String endMatch = args != null && args.length > 1 ? args[1] : DEFAULT_SNIPPET_ARG_END_MATCH; String ellipsis = args != null && args.length > 2 ? args[2] : DEFAULT_SNIPPET_ARG_ELLIPSIS; int maxTokens = args != null && args.length > 3 ? Integer.parseInt(args[3]) : DEFAULT_SNIPPET_ARG_MAX_TOKENS; appendSearchIndexJoin( sb, filter, true, startMatch, endMatch, ellipsis, maxTokens, deferredSnippeting); } else { appendSearchIndexJoin(sb, filter, false, null, null, null, 0, false); } } public void appendSearchIndexJoin(StringBuilder sb, String filter, boolean snippetNeeded, String startMatch, String endMatch, String ellipsis, int maxTokens, boolean deferredSnippeting) { boolean isEmailAddress = false; String emailAddress = null; boolean isPhoneNumber = false; String phoneNumber = null; String numberE164 = null; // If the query consists of a single word, we can do snippetizing after-the-fact for a // performance boost. boolean singleTokenSearch = isSingleWordQuery(filter); if (filter.indexOf('@') != -1) { emailAddress = mDbHelper.get().extractAddressFromEmailAddress(filter); isEmailAddress = !TextUtils.isEmpty(emailAddress); } else { isPhoneNumber = isPhoneNumber(filter); if (isPhoneNumber) { phoneNumber = PhoneNumberUtils.normalizeNumber(filter); numberE164 = PhoneNumberUtils.formatNumberToE164(phoneNumber, mDbHelper.get().getCountryIso()); } } final String SNIPPET_CONTACT_ID = "snippet_contact_id"; sb.append(" JOIN (SELECT " + SearchIndexColumns.CONTACT_ID + " AS " + SNIPPET_CONTACT_ID); if (snippetNeeded) { sb.append(", "); if (isEmailAddress) { sb.append("ifnull("); DatabaseUtils.appendEscapedSQLString(sb, startMatch); sb.append("||(SELECT MIN(" + Email.ADDRESS + ")"); sb.append(" FROM " + Tables.DATA_JOIN_RAW_CONTACTS); sb.append(" WHERE " + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID); sb.append("=" + RawContacts.CONTACT_ID + " AND " + Email.ADDRESS + " LIKE "); DatabaseUtils.appendEscapedSQLString(sb, filter + "%"); sb.append(")||"); DatabaseUtils.appendEscapedSQLString(sb, endMatch); sb.append(","); // Optimization for single-token search (do only if requested). if (singleTokenSearch && deferredSnippeting) { sb.append(SearchIndexColumns.CONTENT); } else { appendSnippetFunction(sb, startMatch, endMatch, ellipsis, maxTokens); } sb.append(")"); } else if (isPhoneNumber) { sb.append("ifnull("); DatabaseUtils.appendEscapedSQLString(sb, startMatch); sb.append("||(SELECT MIN(" + Phone.NUMBER + ")"); sb.append(" FROM " + Tables.DATA_JOIN_RAW_CONTACTS + " JOIN " + Tables.PHONE_LOOKUP); sb.append(" ON " + DataColumns.CONCRETE_ID); sb.append("=" + Tables.PHONE_LOOKUP + "." + PhoneLookupColumns.DATA_ID); sb.append(" WHERE " + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID); sb.append("=" + RawContacts.CONTACT_ID); sb.append(" AND " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(phoneNumber); sb.append("%'"); if (!TextUtils.isEmpty(numberE164)) { sb.append(" OR " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(numberE164); sb.append("%'"); } sb.append(")||"); DatabaseUtils.appendEscapedSQLString(sb, endMatch); sb.append(","); // Optimization for single-token search (do only if requested). if (singleTokenSearch && deferredSnippeting) { sb.append(SearchIndexColumns.CONTENT); } else { appendSnippetFunction(sb, startMatch, endMatch, ellipsis, maxTokens); } sb.append(")"); } else { final String normalizedFilter = NameNormalizer.normalize(filter); if (!TextUtils.isEmpty(normalizedFilter)) { // Optimization for single-token search (do only if requested).. if (singleTokenSearch && deferredSnippeting) { sb.append(SearchIndexColumns.CONTENT); } else { sb.append("(CASE WHEN EXISTS (SELECT 1 FROM "); sb.append(Tables.RAW_CONTACTS + " AS rc INNER JOIN "); sb.append(Tables.NAME_LOOKUP + " AS nl ON (rc." + RawContacts._ID); sb.append("=nl." + NameLookupColumns.RAW_CONTACT_ID); sb.append(") WHERE nl." + NameLookupColumns.NORMALIZED_NAME); sb.append(" GLOB '" + normalizedFilter + "*' AND "); sb.append("nl." + NameLookupColumns.NAME_TYPE + "="); sb.append(NameLookupType.NAME_COLLATION_KEY + " AND "); sb.append(Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID); sb.append("=rc." + RawContacts.CONTACT_ID); sb.append(") THEN NULL ELSE "); appendSnippetFunction(sb, startMatch, endMatch, ellipsis, maxTokens); sb.append(" END)"); } } else { sb.append("NULL"); } } sb.append(" AS " + SearchSnippetColumns.SNIPPET); } sb.append(" FROM " + Tables.SEARCH_INDEX); sb.append(" WHERE "); sb.append(Tables.SEARCH_INDEX + " MATCH '"); if (isEmailAddress) { // we know that the emailAddress contains a @. This phrase search should be // scoped against "content:" only, but unfortunately SQLite doesn't support // phrases and scoped columns at once. This is fine in this case however, because: // - We can't erronously match against name, as name is all-hex (so the @ can't match) // - We can't match against tokens, because phone-numbers can't contain @ final String sanitizedEmailAddress = emailAddress == null ? "" : sanitizeMatch(emailAddress); sb.append("\""); sb.append(sanitizedEmailAddress); sb.append("*\""); } else if (isPhoneNumber) { // normalized version of the phone number (phoneNumber can only have + and digits) final String phoneNumberCriteria = " OR tokens:" + phoneNumber + "*"; // international version of this number (numberE164 can only have + and digits) final String numberE164Criteria = (numberE164 != null && !TextUtils.equals(numberE164, phoneNumber)) ? " OR tokens:" + numberE164 + "*" : ""; // combine all criteria final String commonCriteria = phoneNumberCriteria + numberE164Criteria; // search in content sb.append(SearchIndexManager.getFtsMatchQuery(filter, FtsQueryBuilder.getDigitsQueryBuilder(commonCriteria))); } else { // general case: not a phone number, not an email-address sb.append(SearchIndexManager.getFtsMatchQuery(filter, FtsQueryBuilder.SCOPED_NAME_NORMALIZING)); } // Omit results in "Other Contacts". sb.append("' AND " + SNIPPET_CONTACT_ID + " IN " + Tables.DEFAULT_DIRECTORY + ")"); sb.append(" ON (" + Contacts._ID + "=" + SNIPPET_CONTACT_ID + ")"); } private static String sanitizeMatch(String filter) { return filter.replace("'", "").replace("*", "").replace("-", "").replace("\"", ""); } private void appendSnippetFunction( StringBuilder sb, String startMatch, String endMatch, String ellipsis, int maxTokens) { sb.append("snippet(" + Tables.SEARCH_INDEX + ","); DatabaseUtils.appendEscapedSQLString(sb, startMatch); sb.append(","); DatabaseUtils.appendEscapedSQLString(sb, endMatch); sb.append(","); DatabaseUtils.appendEscapedSQLString(sb, ellipsis); // The index of the column used for the snippet, "content" sb.append(",1,"); sb.append(maxTokens); sb.append(")"); } private void setTablesAndProjectionMapForRawContacts(SQLiteQueryBuilder qb, Uri uri) { StringBuilder sb = new StringBuilder(); sb.append(Views.RAW_CONTACTS); qb.setTables(sb.toString()); qb.setProjectionMap(sRawContactsProjectionMap); appendAccountFromParameter(qb, uri); } private void setTablesAndProjectionMapForRawEntities(SQLiteQueryBuilder qb, Uri uri) { qb.setTables(Views.RAW_ENTITIES); qb.setProjectionMap(sRawEntityProjectionMap); appendAccountFromParameter(qb, uri); } private void setTablesAndProjectionMapForData(SQLiteQueryBuilder qb, Uri uri, String[] projection, boolean distinct) { setTablesAndProjectionMapForData(qb, uri, projection, distinct, false, null); } private void setTablesAndProjectionMapForData(SQLiteQueryBuilder qb, Uri uri, String[] projection, boolean distinct, boolean addSipLookupColumns) { setTablesAndProjectionMapForData(qb, uri, projection, distinct, addSipLookupColumns, null); } /** * @param usageType when non-null {@link Tables#DATA_USAGE_STAT} is joined with the specified * type. */ private void setTablesAndProjectionMapForData(SQLiteQueryBuilder qb, Uri uri, String[] projection, boolean distinct, Integer usageType) { setTablesAndProjectionMapForData(qb, uri, projection, distinct, false, usageType); } private void setTablesAndProjectionMapForData(SQLiteQueryBuilder qb, Uri uri, String[] projection, boolean distinct, boolean addSipLookupColumns, Integer usageType) { StringBuilder sb = new StringBuilder(); sb.append(Views.DATA); sb.append(" data"); appendContactPresenceJoin(sb, projection, RawContacts.CONTACT_ID); appendContactStatusUpdateJoin(sb, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); appendDataPresenceJoin(sb, projection, DataColumns.CONCRETE_ID); appendDataStatusUpdateJoin(sb, projection, DataColumns.CONCRETE_ID); if (usageType != null) { appendDataUsageStatJoin(sb, usageType, DataColumns.CONCRETE_ID); } qb.setTables(sb.toString()); boolean useDistinct = distinct || !mDbHelper.get().isInProjection(projection, DISTINCT_DATA_PROHIBITING_COLUMNS); qb.setDistinct(useDistinct); final ProjectionMap projectionMap; if (addSipLookupColumns) { projectionMap = useDistinct ? sDistinctDataSipLookupProjectionMap : sDataSipLookupProjectionMap; } else { projectionMap = useDistinct ? sDistinctDataProjectionMap : sDataProjectionMap; } qb.setProjectionMap(projectionMap); appendAccountFromParameter(qb, uri); } private void setTableAndProjectionMapForStatusUpdates(SQLiteQueryBuilder qb, String[] projection) { StringBuilder sb = new StringBuilder(); sb.append(Views.DATA); sb.append(" data"); appendDataPresenceJoin(sb, projection, DataColumns.CONCRETE_ID); appendDataStatusUpdateJoin(sb, projection, DataColumns.CONCRETE_ID); qb.setTables(sb.toString()); qb.setProjectionMap(sStatusUpdatesProjectionMap); } private void setTablesAndProjectionMapForStreamItems(SQLiteQueryBuilder qb) { qb.setTables(Views.STREAM_ITEMS); qb.setProjectionMap(sStreamItemsProjectionMap); } private void setTablesAndProjectionMapForStreamItemPhotos(SQLiteQueryBuilder qb) { qb.setTables(Tables.PHOTO_FILES + " JOIN " + Tables.STREAM_ITEM_PHOTOS + " ON (" + StreamItemPhotosColumns.CONCRETE_PHOTO_FILE_ID + "=" + PhotoFilesColumns.CONCRETE_ID + ") JOIN " + Tables.STREAM_ITEMS + " ON (" + StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=" + StreamItemsColumns.CONCRETE_ID + ")" + " JOIN " + Tables.RAW_CONTACTS + " ON (" + StreamItemsColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ")"); qb.setProjectionMap(sStreamItemPhotosProjectionMap); } private void setTablesAndProjectionMapForEntities(SQLiteQueryBuilder qb, Uri uri, String[] projection) { StringBuilder sb = new StringBuilder(); sb.append(Views.ENTITIES); sb.append(" data"); appendContactPresenceJoin(sb, projection, Contacts.Entity.CONTACT_ID); appendContactStatusUpdateJoin(sb, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); appendDataPresenceJoin(sb, projection, Contacts.Entity.DATA_ID); appendDataStatusUpdateJoin(sb, projection, Contacts.Entity.DATA_ID); qb.setTables(sb.toString()); qb.setProjectionMap(sEntityProjectionMap); appendAccountFromParameter(qb, uri); } private void appendContactStatusUpdateJoin(StringBuilder sb, String[] projection, String lastStatusUpdateIdColumn) { if (mDbHelper.get().isInProjection(projection, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_STATUS_LABEL, Contacts.CONTACT_STATUS_TIMESTAMP)) { sb.append(" LEFT OUTER JOIN " + Tables.STATUS_UPDATES + " " + ContactsStatusUpdatesColumns.ALIAS + " ON (" + lastStatusUpdateIdColumn + "=" + ContactsStatusUpdatesColumns.CONCRETE_DATA_ID + ")"); } } private void appendDataStatusUpdateJoin(StringBuilder sb, String[] projection, String dataIdColumn) { if (mDbHelper.get().isInProjection(projection, StatusUpdates.STATUS, StatusUpdates.STATUS_RES_PACKAGE, StatusUpdates.STATUS_ICON, StatusUpdates.STATUS_LABEL, StatusUpdates.STATUS_TIMESTAMP)) { sb.append(" LEFT OUTER JOIN " + Tables.STATUS_UPDATES + " ON (" + StatusUpdatesColumns.CONCRETE_DATA_ID + "=" + dataIdColumn + ")"); } } private void appendDataUsageStatJoin(StringBuilder sb, int usageType, String dataIdColumn) { sb.append(" LEFT OUTER JOIN " + Tables.DATA_USAGE_STAT + " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "=" + dataIdColumn + " AND " + DataUsageStatColumns.CONCRETE_USAGE_TYPE + "=" + usageType + ")"); } private void appendContactPresenceJoin(StringBuilder sb, String[] projection, String contactIdColumn) { if (mDbHelper.get().isInProjection(projection, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_CHAT_CAPABILITY)) { sb.append(" LEFT OUTER JOIN " + Tables.AGGREGATED_PRESENCE + " ON (" + contactIdColumn + " = " + AggregatedPresenceColumns.CONCRETE_CONTACT_ID + ")"); } } private void appendDataPresenceJoin(StringBuilder sb, String[] projection, String dataIdColumn) { if (mDbHelper.get().isInProjection(projection, Data.PRESENCE, Data.CHAT_CAPABILITY)) { sb.append(" LEFT OUTER JOIN " + Tables.PRESENCE + " ON (" + StatusUpdates.DATA_ID + "=" + dataIdColumn + ")"); } } private boolean appendLocalDirectorySelectionIfNeeded(SQLiteQueryBuilder qb, long directoryId) { if (directoryId == Directory.DEFAULT) { qb.appendWhere(Contacts._ID + " IN " + Tables.DEFAULT_DIRECTORY); return true; } else if (directoryId == Directory.LOCAL_INVISIBLE){ qb.appendWhere(Contacts._ID + " NOT IN " + Tables.DEFAULT_DIRECTORY); return true; } return false; } private void appendAccountFromParameter(SQLiteQueryBuilder qb, Uri uri) { final String accountName = getQueryParameter(uri, RawContacts.ACCOUNT_NAME); final String accountType = getQueryParameter(uri, RawContacts.ACCOUNT_TYPE); final String dataSet = getQueryParameter(uri, RawContacts.DATA_SET); final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType); if (partialUri) { // Throw when either account is incomplete throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE", uri)); } // Accounts are valid by only checking one parameter, since we've // already ruled out partial accounts. final boolean validAccount = !TextUtils.isEmpty(accountName); if (validAccount) { String toAppend = RawContacts.ACCOUNT_NAME + "=" + DatabaseUtils.sqlEscapeString(accountName) + " AND " + RawContacts.ACCOUNT_TYPE + "=" + DatabaseUtils.sqlEscapeString(accountType); if (dataSet == null) { toAppend += " AND " + RawContacts.DATA_SET + " IS NULL"; } else { toAppend += " AND " + RawContacts.DATA_SET + "=" + DatabaseUtils.sqlEscapeString(dataSet); } qb.appendWhere(toAppend); } else { qb.appendWhere("1"); } } private String appendAccountToSelection(Uri uri, String selection) { final String accountName = getQueryParameter(uri, RawContacts.ACCOUNT_NAME); final String accountType = getQueryParameter(uri, RawContacts.ACCOUNT_TYPE); final String dataSet = getQueryParameter(uri, RawContacts.DATA_SET); final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType); if (partialUri) { // Throw when either account is incomplete throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE", uri)); } // Accounts are valid by only checking one parameter, since we've // already ruled out partial accounts. final boolean validAccount = !TextUtils.isEmpty(accountName); if (validAccount) { StringBuilder selectionSb = new StringBuilder(RawContacts.ACCOUNT_NAME + "=" + DatabaseUtils.sqlEscapeString(accountName) + " AND " + RawContacts.ACCOUNT_TYPE + "=" + DatabaseUtils.sqlEscapeString(accountType)); if (dataSet == null) { selectionSb.append(" AND " + RawContacts.DATA_SET + " IS NULL"); } else { selectionSb.append(" AND " + RawContacts.DATA_SET + "=") .append(DatabaseUtils.sqlEscapeString(dataSet)); } if (!TextUtils.isEmpty(selection)) { selectionSb.append(" AND ("); selectionSb.append(selection); selectionSb.append(')'); } return selectionSb.toString(); } else { return selection; } } /** * Gets the value of the "limit" URI query parameter. * * @return A string containing a non-negative integer, or <code>null</code> if * the parameter is not set, or is set to an invalid value. */ private String getLimit(Uri uri) { String limitParam = getQueryParameter(uri, ContactsContract.LIMIT_PARAM_KEY); if (limitParam == null) { return null; } // make sure that the limit is a non-negative integer try { int l = Integer.parseInt(limitParam); if (l < 0) { Log.w(TAG, "Invalid limit parameter: " + limitParam); return null; } return String.valueOf(l); } catch (NumberFormatException ex) { Log.w(TAG, "Invalid limit parameter: " + limitParam); return null; } } @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { if (mode.equals("r")) { waitForAccess(mReadAccessLatch); } else { waitForAccess(mWriteAccessLatch); } if (mapsToProfileDb(uri)) { switchToProfileMode(); return mProfileProvider.openAssetFile(uri, mode); } else { switchToContactMode(); return openAssetFileLocal(uri, mode); } } public AssetFileDescriptor openAssetFileLocal(Uri uri, String mode) throws FileNotFoundException { // Default active DB to the contacts DB if none has been set. if (mActiveDb.get() == null) { if (mode.equals("r")) { mActiveDb.set(mContactsHelper.getReadableDatabase()); } else { mActiveDb.set(mContactsHelper.getWritableDatabase()); } } int match = sUriMatcher.match(uri); switch (match) { case CONTACTS_ID_PHOTO: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); return openPhotoAssetFile(mActiveDb.get(), uri, mode, Data._ID + "=" + Contacts.PHOTO_ID + " AND " + RawContacts.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}); } case CONTACTS_ID_DISPLAY_PHOTO: { if (!mode.equals("r")) { throw new IllegalArgumentException( "Display photos retrieved by contact ID can only be read."); } long contactId = Long.parseLong(uri.getPathSegments().get(1)); Cursor c = mActiveDb.get().query(Tables.CONTACTS, new String[]{Contacts.PHOTO_FILE_ID}, Contacts._ID + "=?", new String[]{String.valueOf(contactId)}, null, null, null); try { if (c.moveToFirst()) { long photoFileId = c.getLong(0); return openDisplayPhotoForRead(photoFileId); } else { // No contact for this ID. throw new FileNotFoundException(uri.toString()); } } finally { c.close(); } } case PROFILE_DISPLAY_PHOTO: { if (!mode.equals("r")) { throw new IllegalArgumentException( "Display photos retrieved by contact ID can only be read."); } Cursor c = mActiveDb.get().query(Tables.CONTACTS, new String[]{Contacts.PHOTO_FILE_ID}, null, null, null, null, null); try { if (c.moveToFirst()) { long photoFileId = c.getLong(0); return openDisplayPhotoForRead(photoFileId); } else { // No profile record. throw new FileNotFoundException(uri.toString()); } } finally { c.close(); } } case CONTACTS_LOOKUP_PHOTO: case CONTACTS_LOOKUP_ID_PHOTO: case CONTACTS_LOOKUP_DISPLAY_PHOTO: case CONTACTS_LOOKUP_ID_DISPLAY_PHOTO: { if (!mode.equals("r")) { throw new IllegalArgumentException( "Photos retrieved by contact lookup key can only be read."); } List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } boolean forDisplayPhoto = (match == CONTACTS_LOOKUP_ID_DISPLAY_PHOTO || match == CONTACTS_LOOKUP_DISPLAY_PHOTO); String lookupKey = pathSegments.get(2); String[] projection = new String[]{Contacts.PHOTO_ID, Contacts.PHOTO_FILE_ID}; if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, projection); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, null, null, null, null, null, Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { try { c.moveToFirst(); if (forDisplayPhoto) { long photoFileId = c.getLong(c.getColumnIndex(Contacts.PHOTO_FILE_ID)); return openDisplayPhotoForRead(photoFileId); } else { long photoId = c.getLong(c.getColumnIndex(Contacts.PHOTO_ID)); return openPhotoAssetFile(mActiveDb.get(), uri, mode, Data._ID + "=?", new String[]{String.valueOf(photoId)}); } } finally { c.close(); } } } SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(qb, uri, projection); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); Cursor c = qb.query(mActiveDb.get(), projection, Contacts._ID + "=?", new String[]{String.valueOf(contactId)}, null, null, null); try { c.moveToFirst(); if (forDisplayPhoto) { long photoFileId = c.getLong(c.getColumnIndex(Contacts.PHOTO_FILE_ID)); return openDisplayPhotoForRead(photoFileId); } else { long photoId = c.getLong(c.getColumnIndex(Contacts.PHOTO_ID)); return openPhotoAssetFile(mActiveDb.get(), uri, mode, Data._ID + "=?", new String[]{String.valueOf(photoId)}); } } finally { c.close(); } } case RAW_CONTACTS_ID_DISPLAY_PHOTO: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); boolean writeable = !mode.equals("r"); // Find the primary photo data record for this raw contact. SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String[] projection = new String[]{Data._ID, Photo.PHOTO_FILE_ID}; setTablesAndProjectionMapForData(qb, uri, projection, false); long photoMimetypeId = mDbHelper.get().getMimeTypeId(Photo.CONTENT_ITEM_TYPE); Cursor c = qb.query(mActiveDb.get(), projection, Data.RAW_CONTACT_ID + "=? AND " + DataColumns.MIMETYPE_ID + "=?", new String[]{String.valueOf(rawContactId), String.valueOf(photoMimetypeId)}, null, null, Data.IS_PRIMARY + " DESC"); long dataId = 0; long photoFileId = 0; try { if (c.getCount() >= 1) { c.moveToFirst(); dataId = c.getLong(0); photoFileId = c.getLong(1); } } finally { c.close(); } // If writeable, open a writeable file descriptor that we can monitor. // When the caller finishes writing content, we'll process the photo and // update the data record. if (writeable) { return openDisplayPhotoForWrite(rawContactId, dataId, uri, mode); } else { return openDisplayPhotoForRead(photoFileId); } } case DISPLAY_PHOTO: { long photoFileId = ContentUris.parseId(uri); if (!mode.equals("r")) { throw new IllegalArgumentException( "Display photos retrieved by key can only be read."); } return openDisplayPhotoForRead(photoFileId); } case DATA_ID: { long dataId = Long.parseLong(uri.getPathSegments().get(1)); long photoMimetypeId = mDbHelper.get().getMimeTypeId(Photo.CONTENT_ITEM_TYPE); return openPhotoAssetFile(mActiveDb.get(), uri, mode, Data._ID + "=? AND " + DataColumns.MIMETYPE_ID + "=" + photoMimetypeId, new String[]{String.valueOf(dataId)}); } case PROFILE_AS_VCARD: { // When opening a contact as file, we pass back contents as a // vCard-encoded stream. We build into a local buffer first, // then pipe into MemoryFile once the exact size is known. final ByteArrayOutputStream localStream = new ByteArrayOutputStream(); outputRawContactsAsVCard(uri, localStream, null, null); return buildAssetFileDescriptor(localStream); } case CONTACTS_AS_VCARD: { // When opening a contact as file, we pass back contents as a // vCard-encoded stream. We build into a local buffer first, // then pipe into MemoryFile once the exact size is known. final ByteArrayOutputStream localStream = new ByteArrayOutputStream(); outputRawContactsAsVCard(uri, localStream, null, null); return buildAssetFileDescriptor(localStream); } case CONTACTS_AS_MULTI_VCARD: { final String lookupKeys = uri.getPathSegments().get(2); final String[] loopupKeyList = lookupKeys.split(":"); final StringBuilder inBuilder = new StringBuilder(); Uri queryUri = Contacts.CONTENT_URI; int index = 0; // SQLite has limits on how many parameters can be used // so the IDs are concatenated to a query string here instead for (String lookupKey : loopupKeyList) { if (index == 0) { inBuilder.append("("); } else { inBuilder.append(","); } // TODO: Figure out what to do if the profile contact is in the list. long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); inBuilder.append(contactId); index++; } inBuilder.append(')'); final String selection = Contacts._ID + " IN " + inBuilder.toString(); // When opening a contact as file, we pass back contents as a // vCard-encoded stream. We build into a local buffer first, // then pipe into MemoryFile once the exact size is known. final ByteArrayOutputStream localStream = new ByteArrayOutputStream(); outputRawContactsAsVCard(queryUri, localStream, selection, null); return buildAssetFileDescriptor(localStream); } default: throw new FileNotFoundException(mDbHelper.get().exceptionMessage( "File does not exist", uri)); } } private AssetFileDescriptor openPhotoAssetFile(SQLiteDatabase db, Uri uri, String mode, String selection, String[] selectionArgs) throws FileNotFoundException { if (!"r".equals(mode)) { throw new FileNotFoundException(mDbHelper.get().exceptionMessage("Mode " + mode + " not supported.", uri)); } String sql = "SELECT " + Photo.PHOTO + " FROM " + Views.DATA + " WHERE " + selection; try { return makeAssetFileDescriptor( DatabaseUtils.blobFileDescriptorForQuery(db, sql, selectionArgs)); } catch (SQLiteDoneException e) { // this will happen if the DB query returns no rows (i.e. contact does not exist) throw new FileNotFoundException(uri.toString()); } } /** * Opens a display photo from the photo store for reading. * @param photoFileId The display photo file ID * @return An asset file descriptor that allows the file to be read. * @throws FileNotFoundException If no photo file for the given ID exists. */ private AssetFileDescriptor openDisplayPhotoForRead(long photoFileId) throws FileNotFoundException { PhotoStore.Entry entry = mPhotoStore.get().get(photoFileId); if (entry != null) { try { return makeAssetFileDescriptor( ParcelFileDescriptor.open(new File(entry.path), ParcelFileDescriptor.MODE_READ_ONLY), entry.size); } catch (FileNotFoundException fnfe) { scheduleBackgroundTask(BACKGROUND_TASK_CLEANUP_PHOTOS); throw fnfe; } } else { scheduleBackgroundTask(BACKGROUND_TASK_CLEANUP_PHOTOS); throw new FileNotFoundException("No photo file found for ID " + photoFileId); } } /** * Opens a file descriptor for a photo to be written. When the caller completes writing * to the file (closing the output stream), the image will be parsed out and processed. * If processing succeeds, the given raw contact ID's primary photo record will be * populated with the inserted image (if no primary photo record exists, the data ID can * be left as 0, and a new data record will be inserted). * @param rawContactId Raw contact ID this photo entry should be associated with. * @param dataId Data ID for a photo mimetype that will be updated with the inserted * image. May be set to 0, in which case the inserted image will trigger creation * of a new primary photo image data row for the raw contact. * @param uri The URI being used to access this file. * @param mode Read/write mode string. * @return An asset file descriptor the caller can use to write an image file for the * raw contact. */ private AssetFileDescriptor openDisplayPhotoForWrite(long rawContactId, long dataId, Uri uri, String mode) { try { ParcelFileDescriptor[] pipeFds = ParcelFileDescriptor.createPipe(); PipeMonitor pipeMonitor = new PipeMonitor(rawContactId, dataId, pipeFds[0]); pipeMonitor.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[]) null); return new AssetFileDescriptor(pipeFds[1], 0, AssetFileDescriptor.UNKNOWN_LENGTH); } catch (IOException ioe) { Log.e(TAG, "Could not create temp image file in mode " + mode); return null; } } /** * Async task that monitors the given file descriptor (the read end of a pipe) for * the writer finishing. If the data from the pipe contains a valid image, the image * is either inserted into the given raw contact or updated in the given data row. */ private class PipeMonitor extends AsyncTask<Object, Object, Object> { private final ParcelFileDescriptor mDescriptor; private final long mRawContactId; private final long mDataId; private PipeMonitor(long rawContactId, long dataId, ParcelFileDescriptor descriptor) { mRawContactId = rawContactId; mDataId = dataId; mDescriptor = descriptor; } @Override protected Object doInBackground(Object... params) { AutoCloseInputStream is = new AutoCloseInputStream(mDescriptor); try { Bitmap b = BitmapFactory.decodeStream(is); if (b != null) { waitForAccess(mWriteAccessLatch); PhotoProcessor processor = new PhotoProcessor(b, mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim); // Store the compressed photo in the photo store. PhotoStore photoStore = ContactsContract.isProfileId(mRawContactId) ? mProfilePhotoStore : mContactsPhotoStore; long photoFileId = photoStore.insert(processor); // Depending on whether we already had a data row to attach the photo // to, do an update or insert. if (mDataId != 0) { // Update the data record with the new photo. ContentValues updateValues = new ContentValues(); // Signal that photo processing has already been handled. updateValues.put(DataRowHandlerForPhoto.SKIP_PROCESSING_KEY, true); if (photoFileId != 0) { updateValues.put(Photo.PHOTO_FILE_ID, photoFileId); } updateValues.put(Photo.PHOTO, processor.getThumbnailPhotoBytes()); update(ContentUris.withAppendedId(Data.CONTENT_URI, mDataId), updateValues, null, null); } else { // Insert a new primary data record with the photo. ContentValues insertValues = new ContentValues(); // Signal that photo processing has already been handled. insertValues.put(DataRowHandlerForPhoto.SKIP_PROCESSING_KEY, true); insertValues.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); insertValues.put(Data.IS_PRIMARY, 1); if (photoFileId != 0) { insertValues.put(Photo.PHOTO_FILE_ID, photoFileId); } insertValues.put(Photo.PHOTO, processor.getThumbnailPhotoBytes()); insert(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(mRawContactId)) .appendPath(RawContacts.Data.CONTENT_DIRECTORY).build(), insertValues); } } } catch (IOException e) { throw new RuntimeException(e); } return null; } } private static final String CONTACT_MEMORY_FILE_NAME = "contactAssetFile"; /** * Returns an {@link AssetFileDescriptor} backed by the * contents of the given {@link ByteArrayOutputStream}. */ private AssetFileDescriptor buildAssetFileDescriptor(ByteArrayOutputStream stream) { try { stream.flush(); final byte[] byteData = stream.toByteArray(); return makeAssetFileDescriptor( ParcelFileDescriptor.fromData(byteData, CONTACT_MEMORY_FILE_NAME), byteData.length); } catch (IOException e) { Log.w(TAG, "Problem writing stream into an ParcelFileDescriptor: " + e.toString()); return null; } } private AssetFileDescriptor makeAssetFileDescriptor(ParcelFileDescriptor fd) { return makeAssetFileDescriptor(fd, AssetFileDescriptor.UNKNOWN_LENGTH); } private AssetFileDescriptor makeAssetFileDescriptor(ParcelFileDescriptor fd, long length) { return fd != null ? new AssetFileDescriptor(fd, 0, length) : null; } /** * Output {@link RawContacts} matching the requested selection in the vCard * format to the given {@link OutputStream}. This method returns silently if * any errors encountered. */ private void outputRawContactsAsVCard(Uri uri, OutputStream stream, String selection, String[] selectionArgs) { final Context context = this.getContext(); int vcardconfig = VCardConfig.VCARD_TYPE_DEFAULT; if(uri.getBooleanQueryParameter( Contacts.QUERY_PARAMETER_VCARD_NO_PHOTO, false)) { vcardconfig |= VCardConfig.FLAG_REFRAIN_IMAGE_EXPORT; } final VCardComposer composer = new VCardComposer(context, vcardconfig, false); Writer writer = null; final Uri rawContactsUri; if (mapsToProfileDb(uri)) { // Pre-authorize the URI, since the caller would have already gone through the // permission check to get here, but the pre-authorization at the top level wouldn't // carry over to the raw contact. rawContactsUri = preAuthorizeUri(RawContactsEntity.PROFILE_CONTENT_URI); } else { rawContactsUri = RawContactsEntity.CONTENT_URI; } try { writer = new BufferedWriter(new OutputStreamWriter(stream)); if (!composer.init(uri, selection, selectionArgs, null, rawContactsUri)) { Log.w(TAG, "Failed to init VCardComposer"); return; } while (!composer.isAfterLast()) { writer.write(composer.createOneEntry()); } } catch (IOException e) { Log.e(TAG, "IOException: " + e); } finally { composer.terminate(); if (writer != null) { try { writer.close(); } catch (IOException e) { Log.w(TAG, "IOException during closing output stream: " + e); } } } } @Override public String getType(Uri uri) { waitForAccess(mReadAccessLatch); final int match = sUriMatcher.match(uri); switch (match) { case CONTACTS: return Contacts.CONTENT_TYPE; case CONTACTS_LOOKUP: case CONTACTS_ID: case CONTACTS_LOOKUP_ID: case PROFILE: return Contacts.CONTENT_ITEM_TYPE; case CONTACTS_AS_VCARD: case CONTACTS_AS_MULTI_VCARD: case PROFILE_AS_VCARD: return Contacts.CONTENT_VCARD_TYPE; case CONTACTS_ID_PHOTO: case CONTACTS_LOOKUP_PHOTO: case CONTACTS_LOOKUP_ID_PHOTO: case CONTACTS_ID_DISPLAY_PHOTO: case CONTACTS_LOOKUP_DISPLAY_PHOTO: case CONTACTS_LOOKUP_ID_DISPLAY_PHOTO: case RAW_CONTACTS_ID_DISPLAY_PHOTO: case DISPLAY_PHOTO: return "image/jpeg"; case RAW_CONTACTS: case PROFILE_RAW_CONTACTS: return RawContacts.CONTENT_TYPE; case RAW_CONTACTS_ID: case PROFILE_RAW_CONTACTS_ID: return RawContacts.CONTENT_ITEM_TYPE; case DATA: case PROFILE_DATA: return Data.CONTENT_TYPE; case DATA_ID: long id = ContentUris.parseId(uri); if (ContactsContract.isProfileId(id)) { return mProfileHelper.getDataMimeType(id); } else { return mContactsHelper.getDataMimeType(id); } case PHONES: return Phone.CONTENT_TYPE; case PHONES_ID: return Phone.CONTENT_ITEM_TYPE; case PHONE_LOOKUP: return PhoneLookup.CONTENT_TYPE; case EMAILS: return Email.CONTENT_TYPE; case EMAILS_ID: return Email.CONTENT_ITEM_TYPE; case POSTALS: return StructuredPostal.CONTENT_TYPE; case POSTALS_ID: return StructuredPostal.CONTENT_ITEM_TYPE; case AGGREGATION_EXCEPTIONS: return AggregationExceptions.CONTENT_TYPE; case AGGREGATION_EXCEPTION_ID: return AggregationExceptions.CONTENT_ITEM_TYPE; case SETTINGS: return Settings.CONTENT_TYPE; case AGGREGATION_SUGGESTIONS: return Contacts.CONTENT_TYPE; case SEARCH_SUGGESTIONS: return SearchManager.SUGGEST_MIME_TYPE; case SEARCH_SHORTCUT: return SearchManager.SHORTCUT_MIME_TYPE; case DIRECTORIES: return Directory.CONTENT_TYPE; case DIRECTORIES_ID: return Directory.CONTENT_ITEM_TYPE; case STREAM_ITEMS: return StreamItems.CONTENT_TYPE; case STREAM_ITEMS_ID: return StreamItems.CONTENT_ITEM_TYPE; case STREAM_ITEMS_ID_PHOTOS: return StreamItems.StreamItemPhotos.CONTENT_TYPE; case STREAM_ITEMS_ID_PHOTOS_ID: return StreamItems.StreamItemPhotos.CONTENT_ITEM_TYPE; case STREAM_ITEMS_PHOTOS: throw new UnsupportedOperationException("Not supported for write-only URI " + uri); default: return mLegacyApiSupport.getType(uri); } } public String[] getDefaultProjection(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case CONTACTS: case CONTACTS_LOOKUP: case CONTACTS_ID: case CONTACTS_LOOKUP_ID: case AGGREGATION_SUGGESTIONS: case PROFILE: return sContactsProjectionMap.getColumnNames(); case CONTACTS_ID_ENTITIES: case PROFILE_ENTITIES: return sEntityProjectionMap.getColumnNames(); case CONTACTS_AS_VCARD: case CONTACTS_AS_MULTI_VCARD: case PROFILE_AS_VCARD: return sContactsVCardProjectionMap.getColumnNames(); case RAW_CONTACTS: case RAW_CONTACTS_ID: case PROFILE_RAW_CONTACTS: case PROFILE_RAW_CONTACTS_ID: return sRawContactsProjectionMap.getColumnNames(); case DATA_ID: case PHONES: case PHONES_ID: case EMAILS: case EMAILS_ID: case POSTALS: case POSTALS_ID: case PROFILE_DATA: return sDataProjectionMap.getColumnNames(); case PHONE_LOOKUP: return sPhoneLookupProjectionMap.getColumnNames(); case AGGREGATION_EXCEPTIONS: case AGGREGATION_EXCEPTION_ID: return sAggregationExceptionsProjectionMap.getColumnNames(); case SETTINGS: return sSettingsProjectionMap.getColumnNames(); case DIRECTORIES: case DIRECTORIES_ID: return sDirectoryProjectionMap.getColumnNames(); default: return null; } } private class StructuredNameLookupBuilder extends NameLookupBuilder { public StructuredNameLookupBuilder(NameSplitter splitter) { super(splitter); } @Override protected void insertNameLookup(long rawContactId, long dataId, int lookupType, String name) { mDbHelper.get().insertNameLookup(rawContactId, dataId, lookupType, name); } @Override protected String[] getCommonNicknameClusters(String normalizedName) { return mCommonNicknameCache.getCommonNicknameClusters(normalizedName); } } public void appendContactFilterAsNestedQuery(StringBuilder sb, String filterParam) { sb.append("(" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM " + Tables.RAW_CONTACTS + " JOIN " + Tables.NAME_LOOKUP + " ON(" + RawContactsColumns.CONCRETE_ID + "=" + NameLookupColumns.RAW_CONTACT_ID + ")" + " WHERE normalized_name GLOB '"); sb.append(NameNormalizer.normalize(filterParam)); sb.append("*' AND " + NameLookupColumns.NAME_TYPE + " IN(" + CONTACT_LOOKUP_NAME_TYPES + "))"); } public boolean isPhoneNumber(String filter) { boolean atLeastOneDigit = false; int len = filter.length(); for (int i = 0; i < len; i++) { char c = filter.charAt(i); if (c >= '0' && c <= '9') { atLeastOneDigit = true; } else if (c != '*' && c != '#' && c != '+' && c != 'N' && c != '.' && c != ';' && c != '-' && c != '(' && c != ')' && c != ' ') { return false; } } return atLeastOneDigit; } /** * Takes components of a name from the query parameters and returns a cursor with those * components as well as all missing components. There is no database activity involved * in this so the call can be made on the UI thread. */ private Cursor completeName(Uri uri, String[] projection) { if (projection == null) { projection = sDataProjectionMap.getColumnNames(); } ContentValues values = new ContentValues(); DataRowHandlerForStructuredName handler = (DataRowHandlerForStructuredName) getDataRowHandler(StructuredName.CONTENT_ITEM_TYPE); copyQueryParamsToContentValues(values, uri, StructuredName.DISPLAY_NAME, StructuredName.PREFIX, StructuredName.GIVEN_NAME, StructuredName.MIDDLE_NAME, StructuredName.FAMILY_NAME, StructuredName.SUFFIX, StructuredName.PHONETIC_NAME, StructuredName.PHONETIC_FAMILY_NAME, StructuredName.PHONETIC_MIDDLE_NAME, StructuredName.PHONETIC_GIVEN_NAME ); handler.fixStructuredNameComponents(values, values); MatrixCursor cursor = new MatrixCursor(projection); Object[] row = new Object[projection.length]; for (int i = 0; i < projection.length; i++) { row[i] = values.get(projection[i]); } cursor.addRow(row); return cursor; } private void copyQueryParamsToContentValues(ContentValues values, Uri uri, String... columns) { for (String column : columns) { String param = uri.getQueryParameter(column); if (param != null) { values.put(column, param); } } } /** * Inserts an argument at the beginning of the selection arg list. */ private String[] insertSelectionArg(String[] selectionArgs, String arg) { if (selectionArgs == null) { return new String[] {arg}; } else { int newLength = selectionArgs.length + 1; String[] newSelectionArgs = new String[newLength]; newSelectionArgs[0] = arg; System.arraycopy(selectionArgs, 0, newSelectionArgs, 1, selectionArgs.length); return newSelectionArgs; } } private String[] appendProjectionArg(String[] projection, String arg) { if (projection == null) { return null; } final int length = projection.length; String[] newProjection = new String[length + 1]; System.arraycopy(projection, 0, newProjection, 0, length); newProjection[length] = arg; return newProjection; } protected Account getDefaultAccount() { AccountManager accountManager = AccountManager.get(getContext()); try { Account[] accounts = accountManager.getAccountsByType(DEFAULT_ACCOUNT_TYPE); if (accounts != null && accounts.length > 0) { return accounts[0]; } } catch (Throwable e) { Log.e(TAG, "Cannot determine the default account for contacts compatibility", e); } return null; } /** * Returns true if the specified account type and data set is writable. */ protected boolean isWritableAccountWithDataSet(String accountTypeAndDataSet) { if (accountTypeAndDataSet == null) { return true; } Boolean writable = mAccountWritability.get(accountTypeAndDataSet); if (writable != null) { return writable; } IContentService contentService = ContentResolver.getContentService(); try { // TODO(dsantoro): Need to update this logic to allow for sub-accounts. for (SyncAdapterType sync : contentService.getSyncAdapterTypes()) { if (ContactsContract.AUTHORITY.equals(sync.authority) && accountTypeAndDataSet.equals(sync.accountType)) { writable = sync.supportsUploading(); break; } } } catch (RemoteException e) { Log.e(TAG, "Could not acquire sync adapter types"); } if (writable == null) { writable = false; } mAccountWritability.put(accountTypeAndDataSet, writable); return writable; } /* package */ static boolean readBooleanQueryParameter(Uri uri, String parameter, boolean defaultValue) { // Manually parse the query, which is much faster than calling uri.getQueryParameter String query = uri.getEncodedQuery(); if (query == null) { return defaultValue; } int index = query.indexOf(parameter); if (index == -1) { return defaultValue; } index += parameter.length(); return !matchQueryParameter(query, index, "=0", false) && !matchQueryParameter(query, index, "=false", true); } private static boolean matchQueryParameter(String query, int index, String value, boolean ignoreCase) { int length = value.length(); return query.regionMatches(ignoreCase, index, value, 0, length) && (query.length() == index + length || query.charAt(index + length) == '&'); } /** * A fast re-implementation of {@link Uri#getQueryParameter} */ /* package */ static String getQueryParameter(Uri uri, String parameter) { String query = uri.getEncodedQuery(); if (query == null) { return null; } int queryLength = query.length(); int parameterLength = parameter.length(); String value; int index = 0; while (true) { index = query.indexOf(parameter, index); if (index == -1) { return null; } // Should match against the whole parameter instead of its suffix. // e.g. The parameter "param" must not be found in "some_param=val". if (index > 0) { char prevChar = query.charAt(index - 1); if (prevChar != '?' && prevChar != '&') { // With "some_param=val1&param=val2", we should find second "param" occurrence. index += parameterLength; continue; } } index += parameterLength; if (queryLength == index) { return null; } if (query.charAt(index) == '=') { index++; break; } } int ampIndex = query.indexOf('&', index); if (ampIndex == -1) { value = query.substring(index); } else { value = query.substring(index, ampIndex); } return Uri.decode(value); } protected boolean isAggregationUpgradeNeeded() { if (!mContactAggregator.isEnabled()) { return false; } int version = Integer.parseInt(mContactsHelper.getProperty( PROPERTY_AGGREGATION_ALGORITHM, "1")); return version < PROPERTY_AGGREGATION_ALGORITHM_VERSION; } protected void upgradeAggregationAlgorithmInBackground() { // This upgrade will affect very few contacts, so it can be performed on the // main thread during the initial boot after an OTA Log.i(TAG, "Upgrading aggregation algorithm"); int count = 0; long start = SystemClock.currentThreadTimeMillis(); SQLiteDatabase db = null; try { switchToContactMode(); db = mContactsHelper.getWritableDatabase(); mActiveDb.set(db); db.beginTransaction(); Cursor cursor = db.query(true, Tables.RAW_CONTACTS + " r1 JOIN " + Tables.RAW_CONTACTS + " r2", new String[]{"r1." + RawContacts._ID}, "r1." + RawContacts._ID + "!=r2." + RawContacts._ID + " AND r1." + RawContacts.CONTACT_ID + "=r2." + RawContacts.CONTACT_ID + " AND r1." + RawContacts.ACCOUNT_NAME + "=r2." + RawContacts.ACCOUNT_NAME + " AND r1." + RawContacts.ACCOUNT_TYPE + "=r2." + RawContacts.ACCOUNT_TYPE + " AND r1." + RawContacts.DATA_SET + "=r2." + RawContacts.DATA_SET, null, null, null, null, null); try { while (cursor.moveToNext()) { long rawContactId = cursor.getLong(0); mContactAggregator.markForAggregation(rawContactId, RawContacts.AGGREGATION_MODE_DEFAULT, true); count++; } } finally { cursor.close(); } mContactAggregator.aggregateInTransaction(mTransactionContext.get(), db); updateSearchIndexInTransaction(); db.setTransactionSuccessful(); mContactsHelper.setProperty(PROPERTY_AGGREGATION_ALGORITHM, String.valueOf(PROPERTY_AGGREGATION_ALGORITHM_VERSION)); } finally { if (db != null) { db.endTransaction(); } long end = SystemClock.currentThreadTimeMillis(); Log.i(TAG, "Aggregation algorithm upgraded for " + count + " contacts, in " + (end - start) + "ms"); } } /* Visible for testing */ boolean isPhone() { if (!sIsPhoneInitialized) { sIsPhone = new TelephonyManager(getContext()).isVoiceCapable(); sIsPhoneInitialized = true; } return sIsPhone; } private boolean handleDataUsageFeedback(Uri uri) { final long currentTimeMillis = System.currentTimeMillis(); final String usageType = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); final String[] ids = uri.getLastPathSegment().trim().split(","); final ArrayList<Long> dataIds = new ArrayList<Long>(); for (String id : ids) { dataIds.add(Long.valueOf(id)); } final boolean successful; if (TextUtils.isEmpty(usageType)) { Log.w(TAG, "Method for data usage feedback isn't specified. Ignoring."); successful = false; } else { successful = updateDataUsageStat(dataIds, usageType, currentTimeMillis) > 0; } // Handle old API. This doesn't affect the result of this entire method. final String[] questionMarks = new String[ids.length]; Arrays.fill(questionMarks, "?"); final String where = Data._ID + " IN (" + TextUtils.join(",", questionMarks) + ")"; final Cursor cursor = mActiveDb.get().query( Views.DATA, new String[] { Data.CONTACT_ID }, where, ids, null, null, null); try { while (cursor.moveToNext()) { mSelectionArgs1[0] = cursor.getString(0); ContentValues values2 = new ContentValues(); values2.put(Contacts.LAST_TIME_CONTACTED, currentTimeMillis); mActiveDb.get().update(Tables.CONTACTS, values2, Contacts._ID + "=?", mSelectionArgs1); mActiveDb.get().execSQL(UPDATE_TIMES_CONTACTED_CONTACTS_TABLE, mSelectionArgs1); mActiveDb.get().execSQL(UPDATE_TIMES_CONTACTED_RAWCONTACTS_TABLE, mSelectionArgs1); } } finally { cursor.close(); } return successful; } /** * Update {@link Tables#DATA_USAGE_STAT}. * * @return the number of rows affected. */ @VisibleForTesting /* package */ int updateDataUsageStat( List<Long> dataIds, String type, long currentTimeMillis) { final int typeInt = sDataUsageTypeMap.get(type); final String where = DataUsageStatColumns.DATA_ID + " =? AND " + DataUsageStatColumns.USAGE_TYPE_INT + " =?"; final String[] columns = new String[] { DataUsageStatColumns._ID, DataUsageStatColumns.TIMES_USED }; final ContentValues values = new ContentValues(); for (Long dataId : dataIds) { final String[] args = new String[] { dataId.toString(), String.valueOf(typeInt) }; mActiveDb.get().beginTransaction(); try { final Cursor cursor = mActiveDb.get().query(Tables.DATA_USAGE_STAT, columns, where, args, null, null, null); try { if (cursor.getCount() > 0) { if (!cursor.moveToFirst()) { Log.e(TAG, "moveToFirst() failed while getAccount() returned non-zero."); } else { values.clear(); values.put(DataUsageStatColumns.TIMES_USED, cursor.getInt(1) + 1); values.put(DataUsageStatColumns.LAST_TIME_USED, currentTimeMillis); mActiveDb.get().update(Tables.DATA_USAGE_STAT, values, DataUsageStatColumns._ID + " =?", new String[] { cursor.getString(0) }); } } else { values.clear(); values.put(DataUsageStatColumns.DATA_ID, dataId); values.put(DataUsageStatColumns.USAGE_TYPE_INT, typeInt); values.put(DataUsageStatColumns.TIMES_USED, 1); values.put(DataUsageStatColumns.LAST_TIME_USED, currentTimeMillis); mActiveDb.get().insert(Tables.DATA_USAGE_STAT, null, values); } mActiveDb.get().setTransactionSuccessful(); } finally { cursor.close(); } } finally { mActiveDb.get().endTransaction(); } } return dataIds.size(); } /** * Returns a sort order String for promoting data rows (email addresses, phone numbers, etc.) * associated with a primary account. The primary account should be supplied from applications * with {@link ContactsContract#PRIMARY_ACCOUNT_NAME} and * {@link ContactsContract#PRIMARY_ACCOUNT_TYPE}. Null will be returned when the primary * account isn't available. */ private String getAccountPromotionSortOrder(Uri uri) { final String primaryAccountName = uri.getQueryParameter(ContactsContract.PRIMARY_ACCOUNT_NAME); final String primaryAccountType = uri.getQueryParameter(ContactsContract.PRIMARY_ACCOUNT_TYPE); // Data rows associated with primary account should be promoted. if (!TextUtils.isEmpty(primaryAccountName)) { StringBuilder sb = new StringBuilder(); sb.append("(CASE WHEN " + RawContacts.ACCOUNT_NAME + "="); DatabaseUtils.appendEscapedSQLString(sb, primaryAccountName); if (!TextUtils.isEmpty(primaryAccountType)) { sb.append(" AND " + RawContacts.ACCOUNT_TYPE + "="); DatabaseUtils.appendEscapedSQLString(sb, primaryAccountType); } sb.append(" THEN 0 ELSE 1 END)"); return sb.toString(); } else { return null; } } /** * Checks the URI for a deferred snippeting request * @return a boolean indicating if a deferred snippeting request is in the RI */ private boolean deferredSnippetingRequested(Uri uri) { String deferredSnippeting = getQueryParameter(uri, SearchSnippetColumns.DEFERRED_SNIPPETING_KEY); return !TextUtils.isEmpty(deferredSnippeting) && deferredSnippeting.equals("1"); } /** * Checks if query is a single word or not. * @return a boolean indicating if the query is one word or not */ private boolean isSingleWordQuery(String query) { return query.split(QUERY_TOKENIZER_REGEX).length == 1; } /** * Checks the projection for a SNIPPET column indicating that a snippet is needed * @return a boolean indicating if a snippet is needed or not. */ private boolean snippetNeeded(String [] projection) { return mDbHelper.get().isInProjection(projection, SearchSnippetColumns.SNIPPET); } }
true
true
protected Cursor queryLocal(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, long directoryId) { if (VERBOSE_LOGGING) { Log.v(TAG, "query: " + uri); } // Default active DB to the contacts DB if none has been set. if (mActiveDb.get() == null) { mActiveDb.set(mContactsHelper.getReadableDatabase()); } SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String groupBy = null; String limit = getLimit(uri); boolean snippetDeferred = false; // The expression used in bundleLetterCountExtras() to get count. String addressBookIndexerCountExpression = null; final int match = sUriMatcher.match(uri); switch (match) { case SYNCSTATE: case PROFILE_SYNCSTATE: return mDbHelper.get().getSyncState().query(mActiveDb.get(), projection, selection, selectionArgs, sortOrder); case CONTACTS: { setTablesAndProjectionMapForContacts(qb, uri, projection); appendLocalDirectorySelectionIfNeeded(qb, directoryId); break; } case CONTACTS_ID: { long contactId = ContentUris.parseId(uri); setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP: case CONTACTS_LOOKUP_ID: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 4) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, projection); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey))); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP_DATA: case CONTACTS_LOOKUP_ID_DATA: case CONTACTS_LOOKUP_PHOTO: case CONTACTS_LOOKUP_ID_PHOTO: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForData(lookupQb, uri, projection, false); if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) { qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); } lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Data.CONTACT_ID, contactId, Data.LOOKUP_KEY, lookupKey); if (c != null) { return c; } // TODO see if the contact exists but has no data rows (rare) } setTablesAndProjectionMapForData(qb, uri, projection, false); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) { qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); } qb.appendWhere(" AND " + Data.CONTACT_ID + "=?"); break; } case CONTACTS_ID_STREAM_ITEMS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(StreamItems.CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_STREAM_ITEMS: case CONTACTS_LOOKUP_ID_STREAM_ITEMS: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItems(lookupQb); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, StreamItems.CONTACT_ID, contactId, StreamItems.CONTACT_LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForStreamItems(qb); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_AS_VCARD: { final String lookupKey = Uri.encode(uri.getPathSegments().get(2)); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_AS_MULTI_VCARD: { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); String currentDateString = dateFormat.format(new Date()).toString(); return mActiveDb.get().rawQuery( "SELECT" + " 'vcards_' || ? || '.vcf' AS " + OpenableColumns.DISPLAY_NAME + "," + " NULL AS " + OpenableColumns.SIZE, new String[] { currentDateString }); } case CONTACTS_FILTER: { String filterParam = ""; boolean deferredSnipRequested = deferredSnippetingRequested(uri); if (uri.getPathSegments().size() > 2) { filterParam = uri.getLastPathSegment(); } setTablesAndProjectionMapForContactsWithSnippet( qb, uri, projection, filterParam, directoryId, deferredSnipRequested); snippetDeferred = isSingleWordQuery(filterParam) && deferredSnipRequested && snippetNeeded(projection); break; } case CONTACTS_STREQUENT_FILTER: case CONTACTS_STREQUENT: { // Basically the resultant SQL should look like this: // (SQL for listing starred items) // UNION ALL // (SQL for listing frequently contacted items) // ORDER BY ... final boolean phoneOnly = readBooleanQueryParameter( uri, ContactsContract.STREQUENT_PHONE_ONLY, false); if (match == CONTACTS_STREQUENT_FILTER && uri.getPathSegments().size() > 3) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(Contacts._ID + " IN "); appendContactFilterAsNestedQuery(sb, filterParam); selection = DbQueryUtils.concatenateClauses(selection, sb.toString()); } String[] subProjection = null; if (projection != null) { subProjection = appendProjectionArg(projection, TIMES_USED_SORT_COLUMN); } // Build the first query for starred setTablesAndProjectionMapForContacts(qb, uri, projection, false); qb.setProjectionMap(phoneOnly ? sStrequentPhoneOnlyStarredProjectionMap : sStrequentStarredProjectionMap); if (phoneOnly) { qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.HAS_PHONE_NUMBER + "=1")); } qb.setStrict(true); final String starredQuery = qb.buildQuery(subProjection, Contacts.STARRED + "=1", Contacts._ID, null, null, null); // Reset the builder. qb = new SQLiteQueryBuilder(); qb.setStrict(true); // Build the second query for frequent part. final String frequentQuery; if (phoneOnly) { final StringBuilder tableBuilder = new StringBuilder(); // In phone only mode, we need to look at view_data instead of // contacts/raw_contacts to obtain actual phone numbers. One problem is that // view_data is much larger than view_contacts, so our query might become much // slower. // // To avoid the possible slow down, we start from data usage table and join // view_data to the table, assuming data usage table is quite smaller than // data rows (almost always it should be), and we don't want any phone // numbers not used by the user. This way sqlite is able to drop a number of // rows in view_data in the early stage of data lookup. tableBuilder.append(Tables.DATA_USAGE_STAT + " INNER JOIN " + Views.DATA + " " + Tables.DATA + " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "=" + DataColumns.CONCRETE_ID + " AND " + DataUsageStatColumns.CONCRETE_USAGE_TYPE + "=" + DataUsageStatColumns.USAGE_TYPE_INT_CALL + ")"); appendContactPresenceJoin(tableBuilder, projection, RawContacts.CONTACT_ID); appendContactStatusUpdateJoin(tableBuilder, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(tableBuilder.toString()); qb.setProjectionMap(sStrequentPhoneOnlyFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.STARRED + "=0 OR " + Contacts.STARRED + " IS NULL", MimetypesColumns.MIMETYPE + " IN (" + "'" + Phone.CONTENT_ITEM_TYPE + "', " + "'" + SipAddress.CONTENT_ITEM_TYPE + "')")); frequentQuery = qb.buildQuery(subProjection, null, null, null, null, null); } else { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, "(" + Contacts.STARRED + " =0 OR " + Contacts.STARRED + " IS NULL)")); frequentQuery = qb.buildQuery(subProjection, null, Contacts._ID, null, null, null); } // Put them together final String unionQuery = qb.buildUnionQuery(new String[] {starredQuery, frequentQuery}, STREQUENT_ORDER_BY, STREQUENT_LIMIT); // Here, we need to use selection / selectionArgs (supplied from users) "twice", // as we want them both for starred items and for frequently contacted items. // // e.g. if the user specify selection = "starred =?" and selectionArgs = "0", // the resultant SQL should be like: // SELECT ... WHERE starred =? AND ... // UNION ALL // SELECT ... WHERE starred =? AND ... String[] doubledSelectionArgs = null; if (selectionArgs != null) { final int length = selectionArgs.length; doubledSelectionArgs = new String[length * 2]; System.arraycopy(selectionArgs, 0, doubledSelectionArgs, 0, length); System.arraycopy(selectionArgs, 0, doubledSelectionArgs, length, length); } Cursor cursor = mActiveDb.get().rawQuery(unionQuery, doubledSelectionArgs); if (cursor != null) { cursor.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI); } return cursor; } case CONTACTS_FREQUENT: { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); groupBy = Contacts._ID; if (!TextUtils.isEmpty(sortOrder)) { sortOrder = FREQUENT_ORDER_BY + ", " + sortOrder; } else { sortOrder = FREQUENT_ORDER_BY; } break; } case CONTACTS_GROUP: { setTablesAndProjectionMapForContacts(qb, uri, projection); if (uri.getPathSegments().size() > 2) { qb.appendWhere(CONTACTS_IN_GROUP_SELECT); String groupMimeTypeId = String.valueOf( mDbHelper.get().getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); selectionArgs = insertSelectionArg(selectionArgs, groupMimeTypeId); } break; } case PROFILE: { setTablesAndProjectionMapForContacts(qb, uri, projection); break; } case PROFILE_ENTITIES: { setTablesAndProjectionMapForEntities(qb, uri, projection); break; } case PROFILE_AS_VCARD: { qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); break; } case CONTACTS_ID_DATA: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_ID_PHOTO: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); break; } case CONTACTS_ID_ENTITIES: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_ENTITIES: case CONTACTS_LOOKUP_ID_ENTITIES: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForEntities(lookupQb, uri, projection); lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts.Entity.CONTACT_ID, contactId, Contacts.Entity.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey))); qb.appendWhere(" AND " + Contacts.Entity.CONTACT_ID + "=?"); break; } case STREAM_ITEMS: { setTablesAndProjectionMapForStreamItems(qb); break; } case STREAM_ITEMS_ID: { setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(StreamItems._ID + "=?"); break; } case STREAM_ITEMS_LIMIT: { MatrixCursor cursor = new MatrixCursor(new String[]{StreamItems.MAX_ITEMS}, 1); cursor.addRow(new Object[]{MAX_STREAM_ITEMS_PER_RAW_CONTACT}); return cursor; } case STREAM_ITEMS_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); break; } case STREAM_ITEMS_ID_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?"); break; } case STREAM_ITEMS_ID_PHOTOS_ID: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); selectionArgs = insertSelectionArg(selectionArgs, streamItemPhotoId); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=? AND " + StreamItemPhotosColumns.CONCRETE_ID + "=?"); break; } case PHOTO_DIMENSIONS: { MatrixCursor cursor = new MatrixCursor( new String[]{DisplayPhoto.DISPLAY_MAX_DIM, DisplayPhoto.THUMBNAIL_MAX_DIM}, 1); cursor.addRow(new Object[]{mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim}); return cursor; } case PHONES: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + "=" + mDbHelper.get().getMimeTypeIdForPhone()); // Dedupe phone numbers per contact. groupBy = RawContacts.CONTACT_ID + ", " + Data.DATA1; // In this case, because we dedupe phone numbers, the address book indexer needs // to take it into account too. (Otherwise headers will appear in wrong positions.) // So use count(distinct pair(CONTACT_ID, PHONE NUMBER)) instead of count(*). // But because there's no such thing as pair() on sqlite, we use // CONTACT_ID || ',' || PHONE NUMBER instead. // This only slows down the query by 14% with 10,000 contacts. addressBookIndexerCountExpression = "DISTINCT " + RawContacts.CONTACT_ID + "||','||" + Data.DATA1; break; } case PHONES_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForPhone()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PHONES_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_CALL; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForPhone()); if (uri.getPathSegments().size() > 2) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(" AND ("); boolean hasCondition = false; boolean orNeeded = false; final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery( filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING); if (ftsMatchQuery.length() > 0) { sb.append(Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH '"); sb.append(ftsMatchQuery); sb.append("')"); orNeeded = true; hasCondition = true; } String number = PhoneNumberUtils.normalizeNumber(filterParam); if (!TextUtils.isEmpty(number)) { if (orNeeded) { sb.append(" OR "); } sb.append(Data._ID + " IN (SELECT DISTINCT " + PhoneLookupColumns.DATA_ID + " FROM " + Tables.PHONE_LOOKUP + " WHERE " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(number); sb.append("%')"); hasCondition = true; } if (!hasCondition) { // If it is neither a phone number nor a name, the query should return // an empty cursor. Let's ensure that. sb.append("0"); } sb.append(")"); qb.appendWhere(sb); } groupBy = "(CASE WHEN " + PhoneColumns.NORMALIZED_NUMBER + " IS NOT NULL THEN " + PhoneColumns.NORMALIZED_NUMBER + " ELSE " + Phone.NUMBER + " END), " + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + PHONE_FILTER_SORT_ORDER; } else { sortOrder = PHONE_FILTER_SORT_ORDER; } } break; } case EMAILS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForEmail()); break; } case EMAILS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForEmail() + " AND " + Data._ID + "=?"); break; } case EMAILS_LOOKUP: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForEmail()); if (uri.getPathSegments().size() > 2) { String email = uri.getLastPathSegment(); String address = mDbHelper.get().extractAddressFromEmailAddress(email); selectionArgs = insertSelectionArg(selectionArgs, address); qb.appendWhere(" AND UPPER(" + Email.DATA + ")=UPPER(?)"); } break; } case EMAILS_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); String filterParam = null; if (uri.getPathSegments().size() > 3) { filterParam = uri.getLastPathSegment(); if (TextUtils.isEmpty(filterParam)) { filterParam = null; } } if (filterParam == null) { // If the filter is unspecified, return nothing qb.appendWhere(" AND 0"); } else { StringBuilder sb = new StringBuilder(); sb.append(" AND " + Data._ID + " IN ("); sb.append( "SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE " + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.get().getMimeTypeIdForEmail()); sb.append(" AND " + Data.DATA1 + " LIKE "); DatabaseUtils.appendEscapedSQLString(sb, filterParam + '%'); if (!filterParam.contains("@")) { sb.append( " UNION SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE +" + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.get().getMimeTypeIdForEmail()); sb.append(" AND " + Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH '"); final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery( filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING); sb.append(ftsMatchQuery); sb.append("')"); } sb.append(")"); qb.appendWhere(sb); } groupBy = Email.DATA + "," + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + EMAIL_FILTER_SORT_ORDER; } else { sortOrder = EMAIL_FILTER_SORT_ORDER; } } break; } case POSTALS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForStructuredPostal()); break; } case POSTALS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForStructuredPostal()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case RAW_CONTACTS: case PROFILE_RAW_CONTACTS: { setTablesAndProjectionMapForRawContacts(qb, uri); break; } case RAW_CONTACTS_ID: case PROFILE_RAW_CONTACTS_ID: { long rawContactId = ContentUris.parseId(uri); setTablesAndProjectionMapForRawContacts(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case RAW_CONTACTS_DATA: case PROFILE_RAW_CONTACTS_ID_DATA: { int segment = match == RAW_CONTACTS_DATA ? 1 : 2; long rawContactId = Long.parseLong(uri.getPathSegments().get(segment)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + Data.RAW_CONTACT_ID + "=?"); break; } case RAW_CONTACTS_ID_STREAM_ITEMS: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=?"); break; } case RAW_CONTACTS_ID_STREAM_ITEMS_ID: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); long streamItemId = Long.parseLong(uri.getPathSegments().get(3)); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(streamItemId)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=? AND " + StreamItems._ID + "=?"); break; } case PROFILE_RAW_CONTACTS_ID_ENTITIES: { long rawContactId = Long.parseLong(uri.getPathSegments().get(2)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForRawEntities(qb, uri); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case DATA: case PROFILE_DATA: { setTablesAndProjectionMapForData(qb, uri, projection, false); break; } case DATA_ID: case PROFILE_DATA_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PROFILE_PHOTO: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); break; } case PHONE_LOOKUP: { // Phone lookup cannot be combined with a selection selection = null; selectionArgs = null; if (uri.getBooleanQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, false)) { if (TextUtils.isEmpty(sortOrder)) { // Default the sort order to something reasonable so we get consistent // results when callers don't request an ordering sortOrder = Contacts.DISPLAY_NAME + " ASC"; } String sipAddress = uri.getPathSegments().size() > 1 ? Uri.decode(uri.getLastPathSegment()) : ""; setTablesAndProjectionMapForData(qb, uri, null, false, true); StringBuilder sb = new StringBuilder(); selectionArgs = mDbHelper.get().buildSipContactQuery(sb, sipAddress); selection = sb.toString(); } else { if (TextUtils.isEmpty(sortOrder)) { // Default the sort order to something reasonable so we get consistent // results when callers don't request an ordering sortOrder = " length(lookup.normalized_number) DESC"; } String number = uri.getPathSegments().size() > 1 ? uri.getLastPathSegment() : ""; String numberE164 = PhoneNumberUtils.formatNumberToE164(number, mDbHelper.get().getCurrentCountryIso()); String normalizedNumber = PhoneNumberUtils.normalizeNumber(number); mDbHelper.get().buildPhoneLookupAndContactQuery( qb, normalizedNumber, numberE164); qb.setProjectionMap(sPhoneLookupProjectionMap); } break; } case GROUPS: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); appendAccountFromParameter(qb, uri); break; } case GROUPS_ID: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(Groups._ID + "=?"); break; } case GROUPS_SUMMARY: { final boolean returnGroupCountPerAccount = readBooleanQueryParameter(uri, Groups.PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT, false); String tables = Views.GROUPS + " AS " + Tables.GROUPS; if (hasColumn(projection, Groups.SUMMARY_COUNT)) { tables = tables + Joins.GROUP_MEMBER_COUNT; } qb.setTables(tables); qb.setProjectionMap(returnGroupCountPerAccount ? sGroupsSummaryProjectionMapWithGroupCountPerAccount : sGroupsSummaryProjectionMap); appendAccountFromParameter(qb, uri); groupBy = GroupsColumns.CONCRETE_ID; break; } case AGGREGATION_EXCEPTIONS: { qb.setTables(Tables.AGGREGATION_EXCEPTIONS); qb.setProjectionMap(sAggregationExceptionsProjectionMap); break; } case AGGREGATION_SUGGESTIONS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); String filter = null; if (uri.getPathSegments().size() > 3) { filter = uri.getPathSegments().get(3); } final int maxSuggestions; if (limit != null) { maxSuggestions = Integer.parseInt(limit); } else { maxSuggestions = DEFAULT_MAX_SUGGESTIONS; } ArrayList<AggregationSuggestionParameter> parameters = null; List<String> query = uri.getQueryParameters("query"); if (query != null && !query.isEmpty()) { parameters = new ArrayList<AggregationSuggestionParameter>(query.size()); for (String parameter : query) { int offset = parameter.indexOf(':'); parameters.add(offset == -1 ? new AggregationSuggestionParameter( AggregationSuggestions.PARAMETER_MATCH_NAME, parameter) : new AggregationSuggestionParameter( parameter.substring(0, offset), parameter.substring(offset + 1))); } } setTablesAndProjectionMapForContacts(qb, uri, projection); return mAggregator.get().queryAggregationSuggestions(qb, projection, contactId, maxSuggestions, filter, parameters); } case SETTINGS: { qb.setTables(Tables.SETTINGS); qb.setProjectionMap(sSettingsProjectionMap); appendAccountFromParameter(qb, uri); // When requesting specific columns, this query requires // late-binding of the GroupMembership MIME-type. final String groupMembershipMimetypeId = Long.toString(mDbHelper.get() .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); if (projection != null && projection.length != 0 && mDbHelper.get().isInProjection(projection, Settings.UNGROUPED_COUNT)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } if (projection != null && projection.length != 0 && mDbHelper.get().isInProjection( projection, Settings.UNGROUPED_WITH_PHONES)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } break; } case STATUS_UPDATES: case PROFILE_STATUS_UPDATES: { setTableAndProjectionMapForStatusUpdates(qb, projection); break; } case STATUS_UPDATES_ID: { setTableAndProjectionMapForStatusUpdates(qb, projection); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(DataColumns.CONCRETE_ID + "=?"); break; } case SEARCH_SUGGESTIONS: { return mGlobalSearchSupport.handleSearchSuggestionsQuery( mActiveDb.get(), uri, projection, limit); } case SEARCH_SHORTCUT: { String lookupKey = uri.getLastPathSegment(); String filter = getQueryParameter( uri, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA); return mGlobalSearchSupport.handleSearchShortcutRefresh( mActiveDb.get(), projection, lookupKey, filter); } case RAW_CONTACT_ENTITIES: case PROFILE_RAW_CONTACT_ENTITIES: { setTablesAndProjectionMapForRawEntities(qb, uri); break; } case RAW_CONTACT_ENTITY_ID: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForRawEntities(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case PROVIDER_STATUS: { return queryProviderStatus(uri, projection); } case DIRECTORIES : { qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); break; } case DIRECTORIES_ID : { long id = ContentUris.parseId(uri); qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(id)); qb.appendWhere(Directory._ID + "=?"); break; } case COMPLETE_NAME: { return completeName(uri, projection); } default: return mLegacyApiSupport.query(uri, projection, selection, selectionArgs, sortOrder, limit); } qb.setStrict(true); Cursor cursor = query(mActiveDb.get(), qb, projection, selection, selectionArgs, sortOrder, groupBy, limit); if (readBooleanQueryParameter(uri, ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, false)) { cursor = bundleLetterCountExtras(cursor, mActiveDb.get(), qb, selection, selectionArgs, sortOrder, addressBookIndexerCountExpression); } if (snippetDeferred) { cursor = addDeferredSnippetingExtra(cursor); } return cursor; }
protected Cursor queryLocal(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, long directoryId) { if (VERBOSE_LOGGING) { Log.v(TAG, "query: " + uri); } // Default active DB to the contacts DB if none has been set. if (mActiveDb.get() == null) { mActiveDb.set(mContactsHelper.getReadableDatabase()); } SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String groupBy = null; String limit = getLimit(uri); boolean snippetDeferred = false; // The expression used in bundleLetterCountExtras() to get count. String addressBookIndexerCountExpression = null; final int match = sUriMatcher.match(uri); switch (match) { case SYNCSTATE: case PROFILE_SYNCSTATE: return mDbHelper.get().getSyncState().query(mActiveDb.get(), projection, selection, selectionArgs, sortOrder); case CONTACTS: { setTablesAndProjectionMapForContacts(qb, uri, projection); appendLocalDirectorySelectionIfNeeded(qb, directoryId); break; } case CONTACTS_ID: { long contactId = ContentUris.parseId(uri); setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP: case CONTACTS_LOOKUP_ID: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 4) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, projection); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey))); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP_DATA: case CONTACTS_LOOKUP_ID_DATA: case CONTACTS_LOOKUP_PHOTO: case CONTACTS_LOOKUP_ID_PHOTO: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForData(lookupQb, uri, projection, false); if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) { qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); } lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Data.CONTACT_ID, contactId, Data.LOOKUP_KEY, lookupKey); if (c != null) { return c; } // TODO see if the contact exists but has no data rows (rare) } setTablesAndProjectionMapForData(qb, uri, projection, false); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); if (match == CONTACTS_LOOKUP_PHOTO || match == CONTACTS_LOOKUP_ID_PHOTO) { qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); } qb.appendWhere(" AND " + Data.CONTACT_ID + "=?"); break; } case CONTACTS_ID_STREAM_ITEMS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(StreamItems.CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_STREAM_ITEMS: case CONTACTS_LOOKUP_ID_STREAM_ITEMS: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItems(lookupQb); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, StreamItems.CONTACT_ID, contactId, StreamItems.CONTACT_LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForStreamItems(qb); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_AS_VCARD: { final String lookupKey = Uri.encode(uri.getPathSegments().get(2)); long contactId = lookupContactIdByLookupKey(mActiveDb.get(), lookupKey); qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_AS_MULTI_VCARD: { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); String currentDateString = dateFormat.format(new Date()).toString(); return mActiveDb.get().rawQuery( "SELECT" + " 'vcards_' || ? || '.vcf' AS " + OpenableColumns.DISPLAY_NAME + "," + " NULL AS " + OpenableColumns.SIZE, new String[] { currentDateString }); } case CONTACTS_FILTER: { String filterParam = ""; boolean deferredSnipRequested = deferredSnippetingRequested(uri); if (uri.getPathSegments().size() > 2) { filterParam = uri.getLastPathSegment(); } setTablesAndProjectionMapForContactsWithSnippet( qb, uri, projection, filterParam, directoryId, deferredSnipRequested); snippetDeferred = isSingleWordQuery(filterParam) && deferredSnipRequested && snippetNeeded(projection); break; } case CONTACTS_STREQUENT_FILTER: case CONTACTS_STREQUENT: { // Basically the resultant SQL should look like this: // (SQL for listing starred items) // UNION ALL // (SQL for listing frequently contacted items) // ORDER BY ... final boolean phoneOnly = readBooleanQueryParameter( uri, ContactsContract.STREQUENT_PHONE_ONLY, false); if (match == CONTACTS_STREQUENT_FILTER && uri.getPathSegments().size() > 3) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(Contacts._ID + " IN "); appendContactFilterAsNestedQuery(sb, filterParam); selection = DbQueryUtils.concatenateClauses(selection, sb.toString()); } String[] subProjection = null; if (projection != null) { subProjection = appendProjectionArg(projection, TIMES_USED_SORT_COLUMN); } // Build the first query for starred setTablesAndProjectionMapForContacts(qb, uri, projection, false); qb.setProjectionMap(phoneOnly ? sStrequentPhoneOnlyStarredProjectionMap : sStrequentStarredProjectionMap); if (phoneOnly) { qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.HAS_PHONE_NUMBER + "=1")); } qb.setStrict(true); final String starredQuery = qb.buildQuery(subProjection, Contacts.STARRED + "=1", Contacts._ID, null, null, null); // Reset the builder. qb = new SQLiteQueryBuilder(); qb.setStrict(true); // Build the second query for frequent part. final String frequentQuery; if (phoneOnly) { final StringBuilder tableBuilder = new StringBuilder(); // In phone only mode, we need to look at view_data instead of // contacts/raw_contacts to obtain actual phone numbers. One problem is that // view_data is much larger than view_contacts, so our query might become much // slower. // // To avoid the possible slow down, we start from data usage table and join // view_data to the table, assuming data usage table is quite smaller than // data rows (almost always it should be), and we don't want any phone // numbers not used by the user. This way sqlite is able to drop a number of // rows in view_data in the early stage of data lookup. tableBuilder.append(Tables.DATA_USAGE_STAT + " INNER JOIN " + Views.DATA + " " + Tables.DATA + " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "=" + DataColumns.CONCRETE_ID + " AND " + DataUsageStatColumns.CONCRETE_USAGE_TYPE + "=" + DataUsageStatColumns.USAGE_TYPE_INT_CALL + ")"); appendContactPresenceJoin(tableBuilder, projection, RawContacts.CONTACT_ID); appendContactStatusUpdateJoin(tableBuilder, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(tableBuilder.toString()); qb.setProjectionMap(sStrequentPhoneOnlyFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.STARRED + "=0 OR " + Contacts.STARRED + " IS NULL", MimetypesColumns.MIMETYPE + " IN (" + "'" + Phone.CONTENT_ITEM_TYPE + "', " + "'" + SipAddress.CONTENT_ITEM_TYPE + "')")); frequentQuery = qb.buildQuery(subProjection, null, null, null, null, null); } else { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, "(" + Contacts.STARRED + " =0 OR " + Contacts.STARRED + " IS NULL)")); frequentQuery = qb.buildQuery(subProjection, null, Contacts._ID, null, null, null); } // Put them together final String unionQuery = qb.buildUnionQuery(new String[] {starredQuery, frequentQuery}, STREQUENT_ORDER_BY, STREQUENT_LIMIT); // Here, we need to use selection / selectionArgs (supplied from users) "twice", // as we want them both for starred items and for frequently contacted items. // // e.g. if the user specify selection = "starred =?" and selectionArgs = "0", // the resultant SQL should be like: // SELECT ... WHERE starred =? AND ... // UNION ALL // SELECT ... WHERE starred =? AND ... String[] doubledSelectionArgs = null; if (selectionArgs != null) { final int length = selectionArgs.length; doubledSelectionArgs = new String[length * 2]; System.arraycopy(selectionArgs, 0, doubledSelectionArgs, 0, length); System.arraycopy(selectionArgs, 0, doubledSelectionArgs, length, length); } Cursor cursor = mActiveDb.get().rawQuery(unionQuery, doubledSelectionArgs); if (cursor != null) { cursor.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI); } return cursor; } case CONTACTS_FREQUENT: { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); groupBy = Contacts._ID; if (!TextUtils.isEmpty(sortOrder)) { sortOrder = FREQUENT_ORDER_BY + ", " + sortOrder; } else { sortOrder = FREQUENT_ORDER_BY; } break; } case CONTACTS_GROUP: { setTablesAndProjectionMapForContacts(qb, uri, projection); if (uri.getPathSegments().size() > 2) { qb.appendWhere(CONTACTS_IN_GROUP_SELECT); String groupMimeTypeId = String.valueOf( mDbHelper.get().getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); selectionArgs = insertSelectionArg(selectionArgs, groupMimeTypeId); } break; } case PROFILE: { setTablesAndProjectionMapForContacts(qb, uri, projection); break; } case PROFILE_ENTITIES: { setTablesAndProjectionMapForEntities(qb, uri, projection); break; } case PROFILE_AS_VCARD: { qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); break; } case CONTACTS_ID_DATA: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_ID_PHOTO: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); break; } case CONTACTS_ID_ENTITIES: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_ENTITIES: case CONTACTS_LOOKUP_ID_ENTITIES: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.get().exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForEntities(lookupQb, uri, projection); lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, mActiveDb.get(), uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts.Entity.CONTACT_ID, contactId, Contacts.Entity.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(mActiveDb.get(), lookupKey))); qb.appendWhere(" AND " + Contacts.Entity.CONTACT_ID + "=?"); break; } case STREAM_ITEMS: { setTablesAndProjectionMapForStreamItems(qb); break; } case STREAM_ITEMS_ID: { setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(StreamItems._ID + "=?"); break; } case STREAM_ITEMS_LIMIT: { MatrixCursor cursor = new MatrixCursor(new String[]{StreamItems.MAX_ITEMS}, 1); cursor.addRow(new Object[]{MAX_STREAM_ITEMS_PER_RAW_CONTACT}); return cursor; } case STREAM_ITEMS_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); break; } case STREAM_ITEMS_ID_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?"); break; } case STREAM_ITEMS_ID_PHOTOS_ID: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); selectionArgs = insertSelectionArg(selectionArgs, streamItemPhotoId); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=? AND " + StreamItemPhotosColumns.CONCRETE_ID + "=?"); break; } case PHOTO_DIMENSIONS: { MatrixCursor cursor = new MatrixCursor( new String[]{DisplayPhoto.DISPLAY_MAX_DIM, DisplayPhoto.THUMBNAIL_MAX_DIM}, 1); cursor.addRow(new Object[]{mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim}); return cursor; } case PHONES: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + "=" + mDbHelper.get().getMimeTypeIdForPhone()); // Dedupe phone numbers per contact. groupBy = RawContacts.CONTACT_ID + ", " + Data.DATA1; // In this case, because we dedupe phone numbers, the address book indexer needs // to take it into account too. (Otherwise headers will appear in wrong positions.) // So use count(distinct pair(CONTACT_ID, PHONE NUMBER)) instead of count(*). // But because there's no such thing as pair() on sqlite, we use // CONTACT_ID || ',' || PHONE NUMBER instead. // This only slows down the query by 14% with 10,000 contacts. addressBookIndexerCountExpression = "DISTINCT " + RawContacts.CONTACT_ID + "||','||" + Data.DATA1; break; } case PHONES_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForPhone()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PHONES_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_CALL; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForPhone()); if (uri.getPathSegments().size() > 2) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(" AND ("); boolean hasCondition = false; boolean orNeeded = false; final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery( filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING); if (ftsMatchQuery.length() > 0) { sb.append(Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH '"); sb.append(ftsMatchQuery); sb.append("')"); orNeeded = true; hasCondition = true; } String number = PhoneNumberUtils.normalizeNumber(filterParam); if (!TextUtils.isEmpty(number)) { if (orNeeded) { sb.append(" OR "); } sb.append(Data._ID + " IN (SELECT DISTINCT " + PhoneLookupColumns.DATA_ID + " FROM " + Tables.PHONE_LOOKUP + " WHERE " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(number); sb.append("%')"); hasCondition = true; } if (!hasCondition) { // If it is neither a phone number nor a name, the query should return // an empty cursor. Let's ensure that. sb.append("0"); } sb.append(")"); qb.appendWhere(sb); } groupBy = "(CASE WHEN " + PhoneColumns.NORMALIZED_NUMBER + " IS NOT NULL THEN " + PhoneColumns.NORMALIZED_NUMBER + " ELSE " + Phone.NUMBER + " END), " + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + PHONE_FILTER_SORT_ORDER; } else { sortOrder = PHONE_FILTER_SORT_ORDER; } } break; } case EMAILS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForEmail()); break; } case EMAILS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForEmail() + " AND " + Data._ID + "=?"); break; } case EMAILS_LOOKUP: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForEmail()); if (uri.getPathSegments().size() > 2) { String email = uri.getLastPathSegment(); String address = mDbHelper.get().extractAddressFromEmailAddress(email); selectionArgs = insertSelectionArg(selectionArgs, address); qb.appendWhere(" AND UPPER(" + Email.DATA + ")=UPPER(?)"); } // unless told otherwise, we'll return visible before invisible contacts if (sortOrder == null) { sortOrder = "(" + RawContacts.CONTACT_ID + " IN " + Tables.DEFAULT_DIRECTORY + ") DESC"; } break; } case EMAILS_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); String filterParam = null; if (uri.getPathSegments().size() > 3) { filterParam = uri.getLastPathSegment(); if (TextUtils.isEmpty(filterParam)) { filterParam = null; } } if (filterParam == null) { // If the filter is unspecified, return nothing qb.appendWhere(" AND 0"); } else { StringBuilder sb = new StringBuilder(); sb.append(" AND " + Data._ID + " IN ("); sb.append( "SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE " + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.get().getMimeTypeIdForEmail()); sb.append(" AND " + Data.DATA1 + " LIKE "); DatabaseUtils.appendEscapedSQLString(sb, filterParam + '%'); if (!filterParam.contains("@")) { sb.append( " UNION SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE +" + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.get().getMimeTypeIdForEmail()); sb.append(" AND " + Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH '"); final String ftsMatchQuery = SearchIndexManager.getFtsMatchQuery( filterParam, FtsQueryBuilder.UNSCOPED_NORMALIZING); sb.append(ftsMatchQuery); sb.append("')"); } sb.append(")"); qb.appendWhere(sb); } groupBy = Email.DATA + "," + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + EMAIL_FILTER_SORT_ORDER; } else { sortOrder = EMAIL_FILTER_SORT_ORDER; } } break; } case POSTALS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForStructuredPostal()); break; } case POSTALS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + DataColumns.MIMETYPE_ID + " = " + mDbHelper.get().getMimeTypeIdForStructuredPostal()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case RAW_CONTACTS: case PROFILE_RAW_CONTACTS: { setTablesAndProjectionMapForRawContacts(qb, uri); break; } case RAW_CONTACTS_ID: case PROFILE_RAW_CONTACTS_ID: { long rawContactId = ContentUris.parseId(uri); setTablesAndProjectionMapForRawContacts(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case RAW_CONTACTS_DATA: case PROFILE_RAW_CONTACTS_ID_DATA: { int segment = match == RAW_CONTACTS_DATA ? 1 : 2; long rawContactId = Long.parseLong(uri.getPathSegments().get(segment)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + Data.RAW_CONTACT_ID + "=?"); break; } case RAW_CONTACTS_ID_STREAM_ITEMS: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=?"); break; } case RAW_CONTACTS_ID_STREAM_ITEMS_ID: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); long streamItemId = Long.parseLong(uri.getPathSegments().get(3)); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(streamItemId)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=? AND " + StreamItems._ID + "=?"); break; } case PROFILE_RAW_CONTACTS_ID_ENTITIES: { long rawContactId = Long.parseLong(uri.getPathSegments().get(2)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForRawEntities(qb, uri); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case DATA: case PROFILE_DATA: { setTablesAndProjectionMapForData(qb, uri, projection, false); break; } case DATA_ID: case PROFILE_DATA_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PROFILE_PHOTO: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); break; } case PHONE_LOOKUP: { // Phone lookup cannot be combined with a selection selection = null; selectionArgs = null; if (uri.getBooleanQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, false)) { if (TextUtils.isEmpty(sortOrder)) { // Default the sort order to something reasonable so we get consistent // results when callers don't request an ordering sortOrder = Contacts.DISPLAY_NAME + " ASC"; } String sipAddress = uri.getPathSegments().size() > 1 ? Uri.decode(uri.getLastPathSegment()) : ""; setTablesAndProjectionMapForData(qb, uri, null, false, true); StringBuilder sb = new StringBuilder(); selectionArgs = mDbHelper.get().buildSipContactQuery(sb, sipAddress); selection = sb.toString(); } else { if (TextUtils.isEmpty(sortOrder)) { // Default the sort order to something reasonable so we get consistent // results when callers don't request an ordering sortOrder = " length(lookup.normalized_number) DESC"; } String number = uri.getPathSegments().size() > 1 ? uri.getLastPathSegment() : ""; String numberE164 = PhoneNumberUtils.formatNumberToE164(number, mDbHelper.get().getCurrentCountryIso()); String normalizedNumber = PhoneNumberUtils.normalizeNumber(number); mDbHelper.get().buildPhoneLookupAndContactQuery( qb, normalizedNumber, numberE164); qb.setProjectionMap(sPhoneLookupProjectionMap); } break; } case GROUPS: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); appendAccountFromParameter(qb, uri); break; } case GROUPS_ID: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(Groups._ID + "=?"); break; } case GROUPS_SUMMARY: { final boolean returnGroupCountPerAccount = readBooleanQueryParameter(uri, Groups.PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT, false); String tables = Views.GROUPS + " AS " + Tables.GROUPS; if (hasColumn(projection, Groups.SUMMARY_COUNT)) { tables = tables + Joins.GROUP_MEMBER_COUNT; } qb.setTables(tables); qb.setProjectionMap(returnGroupCountPerAccount ? sGroupsSummaryProjectionMapWithGroupCountPerAccount : sGroupsSummaryProjectionMap); appendAccountFromParameter(qb, uri); groupBy = GroupsColumns.CONCRETE_ID; break; } case AGGREGATION_EXCEPTIONS: { qb.setTables(Tables.AGGREGATION_EXCEPTIONS); qb.setProjectionMap(sAggregationExceptionsProjectionMap); break; } case AGGREGATION_SUGGESTIONS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); String filter = null; if (uri.getPathSegments().size() > 3) { filter = uri.getPathSegments().get(3); } final int maxSuggestions; if (limit != null) { maxSuggestions = Integer.parseInt(limit); } else { maxSuggestions = DEFAULT_MAX_SUGGESTIONS; } ArrayList<AggregationSuggestionParameter> parameters = null; List<String> query = uri.getQueryParameters("query"); if (query != null && !query.isEmpty()) { parameters = new ArrayList<AggregationSuggestionParameter>(query.size()); for (String parameter : query) { int offset = parameter.indexOf(':'); parameters.add(offset == -1 ? new AggregationSuggestionParameter( AggregationSuggestions.PARAMETER_MATCH_NAME, parameter) : new AggregationSuggestionParameter( parameter.substring(0, offset), parameter.substring(offset + 1))); } } setTablesAndProjectionMapForContacts(qb, uri, projection); return mAggregator.get().queryAggregationSuggestions(qb, projection, contactId, maxSuggestions, filter, parameters); } case SETTINGS: { qb.setTables(Tables.SETTINGS); qb.setProjectionMap(sSettingsProjectionMap); appendAccountFromParameter(qb, uri); // When requesting specific columns, this query requires // late-binding of the GroupMembership MIME-type. final String groupMembershipMimetypeId = Long.toString(mDbHelper.get() .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); if (projection != null && projection.length != 0 && mDbHelper.get().isInProjection(projection, Settings.UNGROUPED_COUNT)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } if (projection != null && projection.length != 0 && mDbHelper.get().isInProjection( projection, Settings.UNGROUPED_WITH_PHONES)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } break; } case STATUS_UPDATES: case PROFILE_STATUS_UPDATES: { setTableAndProjectionMapForStatusUpdates(qb, projection); break; } case STATUS_UPDATES_ID: { setTableAndProjectionMapForStatusUpdates(qb, projection); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(DataColumns.CONCRETE_ID + "=?"); break; } case SEARCH_SUGGESTIONS: { return mGlobalSearchSupport.handleSearchSuggestionsQuery( mActiveDb.get(), uri, projection, limit); } case SEARCH_SHORTCUT: { String lookupKey = uri.getLastPathSegment(); String filter = getQueryParameter( uri, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA); return mGlobalSearchSupport.handleSearchShortcutRefresh( mActiveDb.get(), projection, lookupKey, filter); } case RAW_CONTACT_ENTITIES: case PROFILE_RAW_CONTACT_ENTITIES: { setTablesAndProjectionMapForRawEntities(qb, uri); break; } case RAW_CONTACT_ENTITY_ID: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForRawEntities(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case PROVIDER_STATUS: { return queryProviderStatus(uri, projection); } case DIRECTORIES : { qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); break; } case DIRECTORIES_ID : { long id = ContentUris.parseId(uri); qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(id)); qb.appendWhere(Directory._ID + "=?"); break; } case COMPLETE_NAME: { return completeName(uri, projection); } default: return mLegacyApiSupport.query(uri, projection, selection, selectionArgs, sortOrder, limit); } qb.setStrict(true); Cursor cursor = query(mActiveDb.get(), qb, projection, selection, selectionArgs, sortOrder, groupBy, limit); if (readBooleanQueryParameter(uri, ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, false)) { cursor = bundleLetterCountExtras(cursor, mActiveDb.get(), qb, selection, selectionArgs, sortOrder, addressBookIndexerCountExpression); } if (snippetDeferred) { cursor = addDeferredSnippetingExtra(cursor); } return cursor; }
diff --git a/dotnet/sonar/sonar-plugin-dotnet-cpd/src/main/java/org/sonar/plugin/dotnet/cpd/DotnetCpdPlugin.java b/dotnet/sonar/sonar-plugin-dotnet-cpd/src/main/java/org/sonar/plugin/dotnet/cpd/DotnetCpdPlugin.java index fab9c2905..706cba983 100644 --- a/dotnet/sonar/sonar-plugin-dotnet-cpd/src/main/java/org/sonar/plugin/dotnet/cpd/DotnetCpdPlugin.java +++ b/dotnet/sonar/sonar-plugin-dotnet-cpd/src/main/java/org/sonar/plugin/dotnet/cpd/DotnetCpdPlugin.java @@ -1,72 +1,72 @@ /** * Maven and Sonar plugin for .Net * Copyright (C) 2010 Jose Chillan and Alexandre Victoor * mailto: [email protected] or [email protected] * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugin.dotnet.cpd; import org.sonar.api.Plugin; import org.sonar.api.Extension; import java.util.ArrayList; import java.util.List; /** * This class is the container for all others extensions */ public class DotnetCpdPlugin implements Plugin { public static final String KEY = "dotnet-cpd"; public final static String CPD_MINIMUM_TOKENS_PROPERTY = "sonar.dotnet.cpd.minimumTokens"; public final static String CPD_MINIMUM_TOKENS_DEFAULT_VALUE = "100"; // The key which uniquely identifies your plugin among all others Sonar // plugins public String getKey() { return KEY; } public String getName() { return "Dotnet cpd plugin"; } public String getDescription() { return "Copy/Paste detector for dotnet projects"; } // This is where you're going to declare all your Sonar extensions public List<Class<? extends Extension>> getExtensions() { List<Class<? extends Extension>> list = new ArrayList<Class<? extends Extension>>(); list.add(CpdSensor.class); - list.add(SumDuplicationsDecorator.class); - list.add(DuplicationDensityDecorator.class); - list.add(CsCpdMapping.class); + //list.add(SumDuplicationsDecorator.class); + //list.add(DuplicationDensityDecorator.class); + //list.add(CsCpdMapping.class); return list; } @Override public String toString() { return getKey(); } }
true
true
public List<Class<? extends Extension>> getExtensions() { List<Class<? extends Extension>> list = new ArrayList<Class<? extends Extension>>(); list.add(CpdSensor.class); list.add(SumDuplicationsDecorator.class); list.add(DuplicationDensityDecorator.class); list.add(CsCpdMapping.class); return list; }
public List<Class<? extends Extension>> getExtensions() { List<Class<? extends Extension>> list = new ArrayList<Class<? extends Extension>>(); list.add(CpdSensor.class); //list.add(SumDuplicationsDecorator.class); //list.add(DuplicationDensityDecorator.class); //list.add(CsCpdMapping.class); return list; }
diff --git a/src/framework/java/com/flexive/shared/FxContext.java b/src/framework/java/com/flexive/shared/FxContext.java index 6b50db9d..99dfe368 100644 --- a/src/framework/java/com/flexive/shared/FxContext.java +++ b/src/framework/java/com/flexive/shared/FxContext.java @@ -1,826 +1,826 @@ /*************************************************************** * This file is part of the [fleXive](R) framework. * * Copyright (c) 1999-2010 * UCS - unique computing solutions gmbh (http://www.ucs.at) * All rights reserved * * The [fleXive](R) project is free software; you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public * License version 2.1 or higher as published by the Free Software Foundation. * * The GNU Lesser General Public License can be found at * http://www.gnu.org/licenses/lgpl.html. * A copy is found in the textfile LGPL.txt and important notices to the * license from the author are found in LICENSE.txt distributed with * these libraries. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * For further information about UCS - unique computing solutions gmbh, * please see the company website: http://www.ucs.at * * For further information about [fleXive](R), please see the * project website: http://www.flexive.org * * * This copyright notice MUST APPEAR in all copies of the file! ***************************************************************/ package com.flexive.shared; import com.flexive.shared.configuration.DivisionData; import com.flexive.shared.exceptions.*; import com.flexive.shared.interfaces.AccountEngine; import com.flexive.shared.security.UserTicket; import com.flexive.shared.structure.FxEnvironment; import com.flexive.shared.tree.FxTreeMode; import com.flexive.core.flatstorage.FxFlatStorageManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.Serializable; import java.net.URLDecoder; import java.util.Locale; import java.util.Map; import java.util.HashMap; import java.util.Collections; /** * The [fleXive] context - user session specific data like UserTickets, etc. * * @author Daniel Lichtenberger ([email protected]), UCS - unique computing solutions gmbh (http://www.ucs.at) * @author Gregor Schober ([email protected]), UCS - unique computing solutions gmbh (http://www.ucs.at) * @author Markus Plesser ([email protected]), UCS - unique computing solutions gmbh (http://www.ucs.at) */ public class FxContext implements Serializable { private static final long serialVersionUID = -54895743895893486L; /** * Global division id */ public final static int DIV_GLOBAL_CONFIGURATION = 0; /** * Undefined division id */ public final static int DIV_UNDEFINED = -1; /** * Session key set if the user successfully logged into the admin area */ public static final String ADMIN_AUTHENTICATED = "$flexive_admin_auth$"; /** * Session key for the session division ID. */ public static final String SESSION_DIVISIONID = "$flexive_division_id$"; private static final Log LOG = LogFactory.getLog(FxContext.class); private static ThreadLocal<FxContext> info = new ThreadLocal<FxContext>() { }; private static boolean MANUAL_INIT_CALLED = false; private final String requestURI; private final String remoteHost; private final boolean webDAV; private final String serverName; private final int serverPort; private final Map<Object, Object> attributes = new HashMap<Object, Object>(); private String sessionID; private boolean treeWasModified; private String contextPath; private String requestUriNoContext; private boolean globalAuthenticated; private int division; private int runAsSystem; private UserTicket ticket; private long nodeId = -1; private FxTreeMode treeMode; private DivisionData divisionData; private static UserTicket getLastUserTicket(HttpSession session) { return (UserTicket) session.getAttribute("LAST_USERTICKET"); } private static void setLastUserTicket(HttpSession session, UserTicket lastUserTicket) { session.setAttribute("LAST_USERTICKET", lastUserTicket); } public UserTicket getTicket() { if (getRunAsSystem()) { return ticket.cloneAsGlobalSupervisor(); } return ticket; } public void setTicket(UserTicket ticket) { this.ticket = ticket; } /** * Get the current users active tree node id, used for FxSQL tree queries * * @return the current users active tree node id * @deprecated will be removed as soon as tree search is fixed */ public long getNodeId() { return nodeId; } /** * Set the current users active tree node id used for FxSQL tree queries * * @param nodeId active tree node id * @deprecated will be removed as soon as tree search is fixed */ public void setNodeId(long nodeId) { this.nodeId = nodeId; } /** * Get the current users tree mode, used for FxSQL tree queries * * @return the current users active tree node id * @deprecated will be removed as soon as tree search is fixed */ public FxTreeMode getTreeMode() { return treeMode; } /** * Set the current users tree mode, used for FxSQL tree queries * * @return the current users active tree node id * @deprecated will be removed as soon as tree search is fixed */ public void setTreeMode(FxTreeMode treeMode) { this.treeMode = treeMode; } /** * Returns true if the tree was modified within this thread by the * user belonging to this thread. * * @return true if the tree was modified */ public boolean getTreeWasModified() { return treeWasModified; } /** * Flag the tree as modified */ public void setTreeWasModified() { this.treeWasModified = true; CacheAdmin.setTreeWasModified(); } /** * Get the current users preferred locale (based on his preferred language) * * @return the current users preferred locale (based on his preferred language) */ public Locale getLocale() { return ticket.getLanguage().getLocale(); } /** * Get the current users preferred language * * @return the current users preferred language */ public FxLanguage getLanguage() { return ticket.getLanguage(); } /** * Tries to login a user. * <p/> * The next getUserTicket() call will return the new ticket. * * @param loginname the unique user name * @param password the password * @param takeOver the take over flag * @throws FxLoginFailedException if the login failed * @throws FxAccountInUseException if take over was false and the account is in use */ public void login(String loginname, String password, boolean takeOver) throws FxLoginFailedException, FxAccountInUseException { // Anything to do at all? if (ticket != null && ticket.getLoginName().equals(loginname)) { return; } // Try the login AccountEngine acc = EJBLookup.getAccountEngine(); acc.login(loginname, password, takeOver); setTicket(acc.getUserTicket()); } /** * Logout of the current user. * * @throws FxLogoutFailedException if the function fails */ public void logout() throws FxLogoutFailedException { AccountEngine acc = EJBLookup.getAccountEngine(); acc.logout(); setTicket(acc.getUserTicket()); } /** * Override the used ticket. * Please do not use this method! Its only purpose is to feed FxContext with a * UserTicket when no user is logged in - ie during system startup * * @param ticket ticket to override with */ public void overrideTicket(UserTicket ticket) { if (!getRunAsSystem()) { setTicket(ticket); } } /** * Constructor * * @param request the request * @param divisionId the division * @param isWebdav true if this is an webdav request */ private FxContext(HttpServletRequest request, int divisionId, boolean isWebdav) { this.sessionID = request.getSession().getId(); this.requestURI = request.getRequestURI(); this.contextPath = request.getContextPath(); this.serverName = request.getServerName(); this.serverPort = request.getServerPort(); this.requestUriNoContext = request.getRequestURI().substring(request.getContextPath().length()); this.webDAV = isWebdav; if (this.webDAV) { // Cut away servlet path, eg. "/webdav/" this.requestUriNoContext = this.requestUriNoContext.substring(request.getServletPath().length()); } this.globalAuthenticated = request.getSession().getAttribute(ADMIN_AUTHENTICATED) != null; this.remoteHost = request.getRemoteHost(); this.division = divisionId; } /** * Gets the user ticket from the ejb layer, and stores it in the session as 'last used user ticket' * * @param session the session * @return the user ticket */ public static UserTicket getTicketFromEJB(final HttpSession session) { UserTicket ticket = EJBLookup.getAccountEngine().getUserTicket(); setLastUserTicket(session, ticket); return ticket; } /** * Constructor */ private FxContext() { sessionID = "EJB_" + System.currentTimeMillis(); requestURI = ""; division = -1; remoteHost = "127.0.0.1 (SYSTEM)"; webDAV = false; serverName = "localhost"; serverPort = 80; } /** * Returns true if the division is the global configuration division. * * @return true if the division is the global configuration division */ public boolean isGlobalConfigDivision() { return division == DivisionData.DIVISION_GLOBAL; } /** * Return true if the current context runs in the test division. * * @return true if the current context runs in the test division. */ public boolean isTestDivision() { return division == DivisionData.DIVISION_TEST; } /** * Returns the id of the division. * <p/> * * @return the id of the division. */ public int getDivisionId() { return this.division; } /** * Changes the division ID. Use with care! * (Currently needed for embedded container testing.) * * @param division the division id */ public void setDivisionId(int division) { this.division = division; } /** * Changes the context path (Currently needed for embedded container testing.) * * @param contextPath the context path */ public void setContextPath(String contextPath) { this.contextPath = contextPath; } /** * Runs all further calls as SYSTEM user with full permissions until stopRunAsSystem * gets called. Multiple calls to this function get stacked and the runAsSystem * flag is only removed when the stack is empty. */ public void runAsSystem() { runAsSystem++; } /** * Removes one runeAsSystem flag from the stack. */ public void stopRunAsSystem() { if (runAsSystem <= 0) { LOG.fatal("stopRunAsSystem called with no system flag on the stack"); } else runAsSystem--; } /** * Returns true if all calls are done without permission checks for the time beeing. * * @return true if all calls are done without permission checks for the time beeing */ public boolean getRunAsSystem() { return runAsSystem != 0; } /** * Returns the session id, which is unique at call time * * @return the session's id */ public String getSessionId() { return sessionID; } /** * Sets the session ID. * * @param sessionID the new session ID */ public void setSessionID(String sessionID) { this.sessionID = sessionID; } /** * Returns the request URI. * <p/> * This URI contains the context path, use getRelativeRequestURI() to retrieve the path * without it. * * @return the request URI */ public String getRequestURI() { return requestURI; } /** * Returns the decoded relative request URI. * <p/> * This function is the same as calling getRelativeRequestURI(true). * * @return the URI without its context path */ public String getRelativeRequestURI() { return getRelativeRequestURI(true); } /** * Returns the relative request URI. * * @param decode if set to true the URI will be decoded (eg "%20" to a space), using UTF-8 * @return the URI without its context path */ @SuppressWarnings("deprecation") public String getRelativeRequestURI(boolean decode) { String result = requestURI.substring(contextPath.length()); if (decode) { try { result = URLDecoder.decode(result, "UTF-8"); } catch (Throwable t) { System.out.print("Failed to decode the URI using UTF-8, using fallback decoding. msg=" + t.getMessage()); result = URLDecoder.decode(result); } } return result; } /** * Returns the name of the server handling this request, e.g. www.flexive.com * * @return the name of the server handling this request, e.g. www.flexive.com */ public String getServerName() { return serverName; } /** * Returns the port of the server handling this request, e.g. 80 * * @return the port of the server handling this request, e.g. 80 */ public int getServerPort() { return serverPort; } /** * Returns the full server URL including the port for this request, e.g. http://www.flexive.com:8080 * * @return the full server URL including the port for this request, e.g. http://www.flexive.com:8080 */ public String getServer() { return "http://" + serverName + (serverPort != 80 ? ":" + serverPort : ""); } /** * Returns the calling remote host. * * @return the remote host. */ public String getRemoteHost() { return remoteHost; } /** * Returns the id of the appication the request was made in. * <p/> * In webapps the application id equals the context path * * @return the id of the appication the request was made in. */ public String getApplicationId() { return (contextPath != null && contextPath.length() > 0 && contextPath.charAt(0) == '/') ? contextPath.substring(1) : contextPath; } /** * Returns the absolute path for the given resource (i.e. the application name + the path). * * @param path the path of the resource (e.g. /pub/css/demo.css) * @return the absolute path for the given resource */ public String getAbsolutePath(String path) { return "/" + getApplicationId() + path; } /** * Reload the UserTicket, needed i.e. when language settings change */ public void _reloadUserTicket() { setTicket(EJBLookup.getAccountEngine().getUserTicket()); } /** * Returns true if this request is triggered by a webdav operation. * * @return true if this request is triggered by a webdav operation */ public boolean isWebDAV() { return webDAV; } /** * Return true if the user successfully authenticated for the * global configuration area * * @return true if the user successfully authenticated for the global configuration */ public boolean isGlobalAuthenticated() { return globalAuthenticated; } /** * Authorize the user for the global configuration area * * @param globalAuthenticated true if the user should be authorized for the global configuration */ public void setGlobalAuthenticated(boolean globalAuthenticated) { this.globalAuthenticated = globalAuthenticated; } /** * Returns the request URI without its context. * * @return the request URI without its context. */ public String getRequestUriNoContext() { return requestUriNoContext; } /** * Return the context path of this request. * * @return the context path of this request. */ public String getContextPath() { return contextPath; } public DivisionData getDivisionData() { if (divisionData == null) { if (!DivisionData.isValidDivisionId(division)) { throw new IllegalArgumentException("Unable to obtain DivisionData: Division not defined (" + division + ")"); } try { divisionData = EJBLookup.getGlobalConfigurationEngine().getDivisionData(division); } catch (FxApplicationException e) { throw e.asRuntimeException(); } } return divisionData; } /** * Returns an independent copy of this context. Also clones the user ticket. * * @return an independent copy of this context * @since 3.1 */ public FxContext copy() { final FxContext result = new FxContext(); result.setTicket(ticket.copy()); result.setDivisionId(division); result.setContextPath(contextPath); result.setGlobalAuthenticated(globalAuthenticated); result.setNodeId(nodeId); result.setSessionID(sessionID); if (treeWasModified) { result.setTreeWasModified(); } return result; } /** * Stores the FxContext instance in the current thread. Will overwrite an existing context. * * @since 3.1 */ public void replace() { info.set(this); } /** * Store a value under the given key in the current request's FxContext. * <p> * A value stored in the context exists for the entire time of the fleXive request, for a * web request this is slightly shorter than request scope. The main advantage is that the * fleXive context is available for any request, not just requests from a web application, * and that no overhead for setting or retrieving values exists. * </p> * * @param key the attribute key * @param value the attribute value. If null, the attribute will be removed. * @since 3.1 */ public void setAttribute(Object key, Object value) { if (value == null) { attributes.remove(key); } else { attributes.put(key, value); } } /** * Return the value stored under the given key. * <p> * A value stored in the context exists for the entire time of the fleXive request, for a * web request this is slightly shorter than request scope. The main advantage is that the * fleXive context is available for any request, not just requests from a web application, * and that no overhead for setting or retrieving values exists. * </p> * * @param key the attribute key * @return the value stored under the given key. * @since 3.1 */ public Object getAttribute(Object key) { return attributes.get(key); } /** * Return a (unmodifiable) map of all attributes stored in the context. * * @return a (unmodifiable) map of all attributes stored in the context. * @since 3.1 */ public Map<Object, Object> getAttributeMap() { return Collections.unmodifiableMap(attributes); } /** * Stores the needed informations about the sessions. * * @param request the users request * @param dynamicContent is the content dynamic? * @param divisionId the division id * @param isWebdav true if this is an webdav request * @return FxContext */ public static FxContext storeInfos(HttpServletRequest request, boolean dynamicContent, int divisionId, boolean isWebdav) { FxContext si = new FxContext(request, divisionId, isWebdav); // Set basic informations needed for the user ticket retrieval info.set(si); // Do user ticket retrieval and store it in the threadlocal final HttpSession session = request.getSession(); if (session.getAttribute(SESSION_DIVISIONID) == null) { session.setAttribute(SESSION_DIVISIONID, divisionId); } if (dynamicContent || isWebdav) { UserTicket last = getLastUserTicket(session); // Always determine the current user ticket for dynamic pages and webdav requests. // This takes about 1 x 5ms for every request on a development machine si.setTicket(getTicketFromEJB(session)); if (si.ticket.isGuest()) { try { if (last == null) si.ticket.setLanguage(EJBLookup.getLanguageEngine().load(request.getLocale().getLanguage())); else si.ticket.setLanguage(last.getLanguage()); } catch (FxInvalidLanguageException e) { - if (LOG.isInfoEnabled()) { - LOG.info("Failed to use request locale from browser - unknown language: " + request.getLocale().getLanguage()); + if (LOG.isDebugEnabled()) { + LOG.debug("Failed to use request locale from browser - unknown language: " + request.getLocale().getLanguage()); } } catch (FxApplicationException e) { if (LOG.isInfoEnabled()) { LOG.info("Failed to use request locale from browser: " + e.getMessage(), e); } } } } else { // For static content like images we use the last user ticket stored in the session // to speed up the request. si.setTicket(getLastUserTicket(session)); if (si.ticket != null) { if (si.ticket.isGuest() && (si.ticket.getACLAssignments() == null || si.ticket.getACLAssignments().length == 0)) { //reload from EJB layer if we have a guest ticket with no ACL assignments //this can happen during initial loading si.setTicket(getTicketFromEJB(session)); } } if (si.ticket == null) { si.setTicket(getTicketFromEJB(session)); } } info.set(si); return si; } /** * Performs a cleanup of the stored informations. */ public static void cleanup() { if (info.get() != null) { info.remove(); } } /** * Helper method to bootstrap a [fleXive] system outside an application server * (e.g. in unit tests or an standalone application). Should only be called on application * startup. Will initialize a FxContext in the current thread with guest user privileges. * * @param divisionId the desired division ID (will determin the application datasource) * @param applicationName the application name (mostly used as "imaginary context path") * @since 3.1 */ public static synchronized void initializeSystem(int divisionId, String applicationName) { get().setDivisionId(divisionId); get().setContextPath(applicationName); get().setTicket(EJBLookup.getAccountEngine().getGuestTicket()); // initialize flat storage, if available FxFlatStorageManager.getInstance().getDefaultStorage(); // force flexive initialization get().runAsSystem(); try { CacheAdmin.getEnvironment(); } finally { get().stopRunAsSystem(); } if (MANUAL_INIT_CALLED && divisionId == -2) { // don't replace userticket return; } // load guest ticket get().setTicket(EJBLookup.getAccountEngine().getGuestTicket()); MANUAL_INIT_CALLED = true; } /** * Returns a string representation of the object. * * @return a string representation of the object. */ @Override public String toString() { return this.getClass() + "[sessionId:" + sessionID + ";requestUri:" + requestURI + "]"; } // ------ static accessors for frequently used operations ----------- /** * Gets the session information for the running thread * * @return the session information for the running thread */ public static FxContext get() { FxContext result = info.get(); if (result == null) { result = new FxContext(); info.set(result); } return result; } /** * Returns the user ticket associated to the current thread. * * @return the user ticket associated to the current thread. */ public static UserTicket getUserTicket() { final FxContext context = get(); if (context == null) { throw new NullPointerException("FxContext not set in current thread."); } return context.getTicket(); } /** * Replace the threadlocal context with another one. * This method provides a mean to escalate the current context to other threads. * As a safeguard, the context can only be replaced if the current UserTicket is <code>null</code> * * @param context the FxContext to use as replacement * @deprecated use {@link com.flexive.shared.FxContext#replace()} */ @Deprecated public static void replace(FxContext context) { if (FxContext.getUserTicket() == null) context.replace(); } /** * Shortcut for {@code FxContext.get().runAsSystem()}. * * @since 3.1 */ public static void startRunningAsSystem() { FxContext.get().runAsSystem(); } /** * Shortcut for {@code FxContext.get().stopRunAsSystem()}. * * @since 3.1 */ public static void stopRunningAsSystem() { FxContext.get().stopRunAsSystem(); } /** * Get a FxContext instance to use at the EJB layer. * The returned context is a guest user only! * This method should only be used internally (for use in different threads, etc.) * * @param template the template to use for the division * @return FxContext */ public static FxContext _getEJBContext(FxContext template) { FxContext ctx = new FxContext(); ctx.division = template.division; return ctx; } }
true
true
public static FxContext storeInfos(HttpServletRequest request, boolean dynamicContent, int divisionId, boolean isWebdav) { FxContext si = new FxContext(request, divisionId, isWebdav); // Set basic informations needed for the user ticket retrieval info.set(si); // Do user ticket retrieval and store it in the threadlocal final HttpSession session = request.getSession(); if (session.getAttribute(SESSION_DIVISIONID) == null) { session.setAttribute(SESSION_DIVISIONID, divisionId); } if (dynamicContent || isWebdav) { UserTicket last = getLastUserTicket(session); // Always determine the current user ticket for dynamic pages and webdav requests. // This takes about 1 x 5ms for every request on a development machine si.setTicket(getTicketFromEJB(session)); if (si.ticket.isGuest()) { try { if (last == null) si.ticket.setLanguage(EJBLookup.getLanguageEngine().load(request.getLocale().getLanguage())); else si.ticket.setLanguage(last.getLanguage()); } catch (FxInvalidLanguageException e) { if (LOG.isInfoEnabled()) { LOG.info("Failed to use request locale from browser - unknown language: " + request.getLocale().getLanguage()); } } catch (FxApplicationException e) { if (LOG.isInfoEnabled()) { LOG.info("Failed to use request locale from browser: " + e.getMessage(), e); } } } } else { // For static content like images we use the last user ticket stored in the session // to speed up the request. si.setTicket(getLastUserTicket(session)); if (si.ticket != null) { if (si.ticket.isGuest() && (si.ticket.getACLAssignments() == null || si.ticket.getACLAssignments().length == 0)) { //reload from EJB layer if we have a guest ticket with no ACL assignments //this can happen during initial loading si.setTicket(getTicketFromEJB(session)); } } if (si.ticket == null) { si.setTicket(getTicketFromEJB(session)); } } info.set(si); return si; }
public static FxContext storeInfos(HttpServletRequest request, boolean dynamicContent, int divisionId, boolean isWebdav) { FxContext si = new FxContext(request, divisionId, isWebdav); // Set basic informations needed for the user ticket retrieval info.set(si); // Do user ticket retrieval and store it in the threadlocal final HttpSession session = request.getSession(); if (session.getAttribute(SESSION_DIVISIONID) == null) { session.setAttribute(SESSION_DIVISIONID, divisionId); } if (dynamicContent || isWebdav) { UserTicket last = getLastUserTicket(session); // Always determine the current user ticket for dynamic pages and webdav requests. // This takes about 1 x 5ms for every request on a development machine si.setTicket(getTicketFromEJB(session)); if (si.ticket.isGuest()) { try { if (last == null) si.ticket.setLanguage(EJBLookup.getLanguageEngine().load(request.getLocale().getLanguage())); else si.ticket.setLanguage(last.getLanguage()); } catch (FxInvalidLanguageException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to use request locale from browser - unknown language: " + request.getLocale().getLanguage()); } } catch (FxApplicationException e) { if (LOG.isInfoEnabled()) { LOG.info("Failed to use request locale from browser: " + e.getMessage(), e); } } } } else { // For static content like images we use the last user ticket stored in the session // to speed up the request. si.setTicket(getLastUserTicket(session)); if (si.ticket != null) { if (si.ticket.isGuest() && (si.ticket.getACLAssignments() == null || si.ticket.getACLAssignments().length == 0)) { //reload from EJB layer if we have a guest ticket with no ACL assignments //this can happen during initial loading si.setTicket(getTicketFromEJB(session)); } } if (si.ticket == null) { si.setTicket(getTicketFromEJB(session)); } } info.set(si); return si; }
diff --git a/fstcomp/composer/rules/rtcomp/c/CRuntimeFeatureSelection.java b/fstcomp/composer/rules/rtcomp/c/CRuntimeFeatureSelection.java index a6702e98b..57f43533a 100644 --- a/fstcomp/composer/rules/rtcomp/c/CRuntimeFeatureSelection.java +++ b/fstcomp/composer/rules/rtcomp/c/CRuntimeFeatureSelection.java @@ -1,183 +1,185 @@ package composer.rules.rtcomp.c; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import metadata.CompositionMetadataStore; public class CRuntimeFeatureSelection { CompositionMetadataStore meta; private File cnfFile; private String headerContents; private String cFileContents; public CRuntimeFeatureSelection(CompositionMetadataStore meta, File cnfFile) { this.meta = meta; this.cnfFile = cnfFile; } public void process() { headerContents = "#ifndef FEATURESELECT_H\n" + "#define FEATURESELECT_H\n" + "/*\n" + " * DO NOT EDIT! THIS FILE IS AUTOGENERATED BY fstcomp \n" + " */\n" + "\n" + "" + ""; // a global variable per feature for (String feature: meta.getFeatures()) { headerContents += "int __SELECTED_FEATURE_" + feature + ";\n\n"; } cFileContents = "#include \"featureselect.h\"\n\n" + "/*\n" + " * DO NOT EDIT! THIS FILE IS AUTOGENERATED BY fstcomp \n" + " */\n" + "\n"; cFileContents += "int select_one() {\n" + "\tint choice;\n" + "\treturn choice;\n" + "}\n\n" + "void select_features() {\n"; for (String feature: meta.getFeatures()) { cFileContents += "\t__SELECTED_FEATURE_" + feature + " = select_one();\n"; } cFileContents += "}\n\n"; processRestrictions(); headerContents += "\n\nint select_one();\n"; headerContents += "void select_features();\n"; headerContents += "void select_helpers();\n"; headerContents += "int valid_product();\n"; headerContents += "#endif\n"; } public void saveTo(String filebasename) throws IOException { process(); FileWriter headerfile = null; try { headerfile = new FileWriter(filebasename + ".h"); headerfile.write(headerContents); } finally { if (headerfile != null) { headerfile.close(); } } FileWriter cfile = null; try { cfile = new FileWriter(filebasename + ".c"); cfile.write(cFileContents); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (cfile != null) { cfile.close(); } } } public void processRestrictions() { Scanner scanner = null; try { scanner = new Scanner(cnfFile); } catch (FileNotFoundException e) { System.out.println("model restrictions file not found!"); System.out.println("looked in: " + cnfFile); throw new RuntimeException(); } scanner.useDelimiter("\\A"); String cnf = scanner.next(); scanner.close(); cnf = cnf.replaceAll("//[^\\n]*", ""); //strip comments + cnf = cnf.replaceAll(" \\n", " "); + cnf = cnf.replaceAll("\\n", " "); cnf = cnf.replaceAll("xor ", "^ "); cnf = cnf.replaceAll("and ", "&& "); - cnf = cnf.replaceAll("or ", "|| "); + cnf = cnf.replaceAll("or ", "|| "); cnf = cnf.replaceAll("not ", "! "); cnf = cnf.replaceAll(" \\n", " "); cnf = cnf.replaceAll("\\n", " "); cnf = cnf.replaceAll(" \\r", " "); cnf = cnf.replaceAll("\\r", " "); cnf = cnf.replaceAll("\\(", "( "); cnf = cnf.replaceAll("\\)", " )"); Pattern varsRegEx = Pattern.compile("[a-zA-Z_]+[a-zA-Z0-9_]+"); Matcher matcher = varsRegEx.matcher(cnf); Set<String> variables = new HashSet<String>(); Set<String> nonterminals = new HashSet<String>(); if (!matcher.find()) { System.out.println("Expected at least one production in cnfFile, none found!!"); throw new RuntimeException(); } matcher.reset();// start from the beginning again // Find all matches while (matcher.find()) { variables.add(matcher.group()); } for (String var: variables) { String replacement; if (meta.getFeatures().contains(var)) { replacement = "__SELECTED_FEATURE_" + var; } else { replacement = "__GUIDSL_NON_TERMINAL_" + var; nonterminals.add(replacement); } cnf = cnf.replaceAll(' ' + var + ' ', ' ' + replacement + ' '); } //cosmetics cnf = cnf.replaceAll("\\) \\)","))"); cnf = cnf.replaceAll("\\( \\(","(("); cnf = cnf.replaceAll("! ","!"); headerContents += "int __GUIDSL_ROOT_PRODUCTION;\n"; for (String nt: nonterminals) { headerContents += "int " + nt + ";\n"; } StringBuffer res = new StringBuffer(); res.append("\nvoid select_helpers() {\n"); res.append("\t__GUIDSL_ROOT_PRODUCTION = 1;\n"); for (String nt: nonterminals) { //res.append("\t" + nt + " = select_one();\n"); res.append("\t" + nt + " = 1;\n"); } res.append("}\n\n"); res.append("int valid_product() {\n"); res.append("\t return " + cnf + ";\n"); res.append("}\n"); cFileContents += res.toString(); } }
false
true
public void processRestrictions() { Scanner scanner = null; try { scanner = new Scanner(cnfFile); } catch (FileNotFoundException e) { System.out.println("model restrictions file not found!"); System.out.println("looked in: " + cnfFile); throw new RuntimeException(); } scanner.useDelimiter("\\A"); String cnf = scanner.next(); scanner.close(); cnf = cnf.replaceAll("//[^\\n]*", ""); //strip comments cnf = cnf.replaceAll("xor ", "^ "); cnf = cnf.replaceAll("and ", "&& "); cnf = cnf.replaceAll("or ", "|| "); cnf = cnf.replaceAll("not ", "! "); cnf = cnf.replaceAll(" \\n", " "); cnf = cnf.replaceAll("\\n", " "); cnf = cnf.replaceAll(" \\r", " "); cnf = cnf.replaceAll("\\r", " "); cnf = cnf.replaceAll("\\(", "( "); cnf = cnf.replaceAll("\\)", " )"); Pattern varsRegEx = Pattern.compile("[a-zA-Z_]+[a-zA-Z0-9_]+"); Matcher matcher = varsRegEx.matcher(cnf); Set<String> variables = new HashSet<String>(); Set<String> nonterminals = new HashSet<String>(); if (!matcher.find()) { System.out.println("Expected at least one production in cnfFile, none found!!"); throw new RuntimeException(); } matcher.reset();// start from the beginning again // Find all matches while (matcher.find()) { variables.add(matcher.group()); } for (String var: variables) { String replacement; if (meta.getFeatures().contains(var)) { replacement = "__SELECTED_FEATURE_" + var; } else { replacement = "__GUIDSL_NON_TERMINAL_" + var; nonterminals.add(replacement); } cnf = cnf.replaceAll(' ' + var + ' ', ' ' + replacement + ' '); } //cosmetics cnf = cnf.replaceAll("\\) \\)","))"); cnf = cnf.replaceAll("\\( \\(","(("); cnf = cnf.replaceAll("! ","!"); headerContents += "int __GUIDSL_ROOT_PRODUCTION;\n"; for (String nt: nonterminals) { headerContents += "int " + nt + ";\n"; } StringBuffer res = new StringBuffer(); res.append("\nvoid select_helpers() {\n"); res.append("\t__GUIDSL_ROOT_PRODUCTION = 1;\n"); for (String nt: nonterminals) { //res.append("\t" + nt + " = select_one();\n"); res.append("\t" + nt + " = 1;\n"); } res.append("}\n\n"); res.append("int valid_product() {\n"); res.append("\t return " + cnf + ";\n"); res.append("}\n"); cFileContents += res.toString(); }
public void processRestrictions() { Scanner scanner = null; try { scanner = new Scanner(cnfFile); } catch (FileNotFoundException e) { System.out.println("model restrictions file not found!"); System.out.println("looked in: " + cnfFile); throw new RuntimeException(); } scanner.useDelimiter("\\A"); String cnf = scanner.next(); scanner.close(); cnf = cnf.replaceAll("//[^\\n]*", ""); //strip comments cnf = cnf.replaceAll(" \\n", " "); cnf = cnf.replaceAll("\\n", " "); cnf = cnf.replaceAll("xor ", "^ "); cnf = cnf.replaceAll("and ", "&& "); cnf = cnf.replaceAll("or ", "|| "); cnf = cnf.replaceAll("not ", "! "); cnf = cnf.replaceAll(" \\n", " "); cnf = cnf.replaceAll("\\n", " "); cnf = cnf.replaceAll(" \\r", " "); cnf = cnf.replaceAll("\\r", " "); cnf = cnf.replaceAll("\\(", "( "); cnf = cnf.replaceAll("\\)", " )"); Pattern varsRegEx = Pattern.compile("[a-zA-Z_]+[a-zA-Z0-9_]+"); Matcher matcher = varsRegEx.matcher(cnf); Set<String> variables = new HashSet<String>(); Set<String> nonterminals = new HashSet<String>(); if (!matcher.find()) { System.out.println("Expected at least one production in cnfFile, none found!!"); throw new RuntimeException(); } matcher.reset();// start from the beginning again // Find all matches while (matcher.find()) { variables.add(matcher.group()); } for (String var: variables) { String replacement; if (meta.getFeatures().contains(var)) { replacement = "__SELECTED_FEATURE_" + var; } else { replacement = "__GUIDSL_NON_TERMINAL_" + var; nonterminals.add(replacement); } cnf = cnf.replaceAll(' ' + var + ' ', ' ' + replacement + ' '); } //cosmetics cnf = cnf.replaceAll("\\) \\)","))"); cnf = cnf.replaceAll("\\( \\(","(("); cnf = cnf.replaceAll("! ","!"); headerContents += "int __GUIDSL_ROOT_PRODUCTION;\n"; for (String nt: nonterminals) { headerContents += "int " + nt + ";\n"; } StringBuffer res = new StringBuffer(); res.append("\nvoid select_helpers() {\n"); res.append("\t__GUIDSL_ROOT_PRODUCTION = 1;\n"); for (String nt: nonterminals) { //res.append("\t" + nt + " = select_one();\n"); res.append("\t" + nt + " = 1;\n"); } res.append("}\n\n"); res.append("int valid_product() {\n"); res.append("\t return " + cnf + ";\n"); res.append("}\n"); cFileContents += res.toString(); }
diff --git a/kundera-core/src/main/java/com/impetus/kundera/lifecycle/states/ManagedState.java b/kundera-core/src/main/java/com/impetus/kundera/lifecycle/states/ManagedState.java index 0569c5e83..0b19008e5 100644 --- a/kundera-core/src/main/java/com/impetus/kundera/lifecycle/states/ManagedState.java +++ b/kundera-core/src/main/java/com/impetus/kundera/lifecycle/states/ManagedState.java @@ -1,236 +1,236 @@ /******************************************************************************* * * Copyright 2012 Impetus Infotech. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. ******************************************************************************/ package com.impetus.kundera.lifecycle.states; import javax.persistence.PersistenceContextType; import com.impetus.kundera.client.Client; import com.impetus.kundera.client.EnhanceEntity; import com.impetus.kundera.graph.Node; import com.impetus.kundera.graph.ObjectGraphUtils; import com.impetus.kundera.lifecycle.NodeStateContext; import com.impetus.kundera.metadata.KunderaMetadataManager; import com.impetus.kundera.metadata.model.EntityMetadata; import com.impetus.kundera.persistence.EntityReader; import com.impetus.kundera.utils.ObjectUtils; /** * @author amresh * */ public class ManagedState extends NodeState { @Override public void initialize(NodeStateContext nodeStateContext) { } @Override public void handlePersist(NodeStateContext nodeStateContext) { // Ignored, entity remains in the same state // Cascade persist operation for related entities for whom cascade=ALL // or PERSIST recursivelyPerformOperation(nodeStateContext, OPERATION.PERSIST); } @Override public void handleRemove(NodeStateContext nodeStateContext) { // Managed ---> Removed moveNodeToNextState(nodeStateContext, new RemovedState()); // Mark entity for removal in persistence context nodeStateContext.setDirty(true); // Recurse remove operation for all related entities for whom // cascade=ALL or REMOVE recursivelyPerformOperation(nodeStateContext, OPERATION.REMOVE); } @Override public void handleRefresh(NodeStateContext nodeStateContext) { // TODO: Refresh entity state from the database // Cascade refresh operation for all related entities for whom // cascade=ALL or REFRESH recursivelyPerformOperation(nodeStateContext, OPERATION.REFRESH); } @Override public void handleMerge(NodeStateContext nodeStateContext) { // Ignored, entity remains in the same state // Mark this entity for saving in database depending upon whether it's // deep equals to the // one in persistence cache // nodeStateContext.setDirty(true); // Add this node into persistence cache nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node) nodeStateContext); // Cascade merge operation for all related entities for whom cascade=ALL // or MERGE recursivelyPerformOperation(nodeStateContext, OPERATION.MERGE); } @Override public void handleFind(NodeStateContext nodeStateContext) { //Fetch Node data from Client Client client = nodeStateContext.getClient(); Class<?> nodeDataClass = nodeStateContext.getDataClass(); EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(nodeDataClass); String entityId = ObjectGraphUtils.getEntityId(nodeStateContext.getNodeId()); Object nodeData = null; // Node data EntityReader reader = client.getReader(); EnhanceEntity ee = reader.findById(entityId, entityMetadata, client); //Recursively retrieve relationship entities (if there are any) if (ee != null && ee.getEntity() != null) { Object entity = ee.getEntity(); if ((entityMetadata.getRelationNames() == null || entityMetadata.getRelationNames().isEmpty()) && !entityMetadata.isRelationViaJoinTable()) { //There is no relation (not even via Join Table), Construct Node out of this enhance entity, // put into Persistence Cache, and just return. nodeData = entity; nodeStateContext.setData(nodeData); nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node)nodeStateContext); nodeStateContext.setDirty(false); // This node is fresh and hence NOT dirty // One time set as required for rollback. -// Object original = ObjectUtils.deepCopy((Node) nodeStateContext); + // Object original = ObjectUtils.deepCopy((Node) nodeStateContext); Object original = ((Node) nodeStateContext).clone(); ((Node)nodeStateContext).setOriginalNode((Node) original); return; } else { //This entity has associated entities, find them recursively. nodeData = reader.recursivelyFindEntities(ee.getEntity(), ee.getRelations(), entityMetadata, nodeStateContext.getPersistenceDelegator()); } } //Construct Node out of this entity and put into Persistence Cache if(nodeData != null) { nodeStateContext.setData(nodeData); nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node)nodeStateContext); // This node is fresh and hence NOT dirty nodeStateContext.setDirty(false); // One time set as required for rollback. - Object original = ObjectUtils.deepCopy((Node) nodeStateContext); + Object original = ((Node) nodeStateContext).clone(); ((Node)nodeStateContext).setOriginalNode((Node) original); } //No state change, Node to remain in Managed state } @Override public void handleClose(NodeStateContext nodeStateContext) { handleDetach(nodeStateContext); } @Override public void handleClear(NodeStateContext nodeStateContext) { handleDetach(nodeStateContext); } @Override public void handleFlush(NodeStateContext nodeStateContext) { // Entity state to remain as Managed // Flush this node to database Client client = nodeStateContext.getClient(); client.persist((Node) nodeStateContext); // logNodeEvent("FLUSHED", this, nodeStateContext.getNodeId()); // Since node is flushed, mark it as NOT dirty nodeStateContext.setDirty(false); } @Override public void handleLock(NodeStateContext nodeStateContext) { } @Override public void handleDetach(NodeStateContext nodeStateContext) { // Managed ---> Detached moveNodeToNextState(nodeStateContext, new DetachedState()); // Cascade detach operation to all referenced entities for whom // cascade=ALL or DETACH recursivelyPerformOperation(nodeStateContext, OPERATION.DETACH); } @Override public void handleCommit(NodeStateContext nodeStateContext) { nodeStateContext.setCurrentNodeState(new DetachedState()); } @Override public void handleRollback(NodeStateContext nodeStateContext) { // If persistence context is EXTENDED, Next state should be Transient // If persistence context is TRANSACTIONAL, Next state should be // detached if (PersistenceContextType.EXTENDED.equals(nodeStateContext.getPersistenceCache().getPersistenceContextType())) { moveNodeToNextState(nodeStateContext, new TransientState()); } else if (PersistenceContextType.TRANSACTION.equals(nodeStateContext.getPersistenceCache() .getPersistenceContextType())) { moveNodeToNextState(nodeStateContext, new DetachedState()); } } @Override public void handleGetReference(NodeStateContext nodeStateContext) { } @Override public void handleContains(NodeStateContext nodeStateContext) { } }
false
true
public void handleFind(NodeStateContext nodeStateContext) { //Fetch Node data from Client Client client = nodeStateContext.getClient(); Class<?> nodeDataClass = nodeStateContext.getDataClass(); EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(nodeDataClass); String entityId = ObjectGraphUtils.getEntityId(nodeStateContext.getNodeId()); Object nodeData = null; // Node data EntityReader reader = client.getReader(); EnhanceEntity ee = reader.findById(entityId, entityMetadata, client); //Recursively retrieve relationship entities (if there are any) if (ee != null && ee.getEntity() != null) { Object entity = ee.getEntity(); if ((entityMetadata.getRelationNames() == null || entityMetadata.getRelationNames().isEmpty()) && !entityMetadata.isRelationViaJoinTable()) { //There is no relation (not even via Join Table), Construct Node out of this enhance entity, // put into Persistence Cache, and just return. nodeData = entity; nodeStateContext.setData(nodeData); nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node)nodeStateContext); nodeStateContext.setDirty(false); // This node is fresh and hence NOT dirty // One time set as required for rollback. // Object original = ObjectUtils.deepCopy((Node) nodeStateContext); Object original = ((Node) nodeStateContext).clone(); ((Node)nodeStateContext).setOriginalNode((Node) original); return; } else { //This entity has associated entities, find them recursively. nodeData = reader.recursivelyFindEntities(ee.getEntity(), ee.getRelations(), entityMetadata, nodeStateContext.getPersistenceDelegator()); } } //Construct Node out of this entity and put into Persistence Cache if(nodeData != null) { nodeStateContext.setData(nodeData); nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node)nodeStateContext); // This node is fresh and hence NOT dirty nodeStateContext.setDirty(false); // One time set as required for rollback. Object original = ObjectUtils.deepCopy((Node) nodeStateContext); ((Node)nodeStateContext).setOriginalNode((Node) original); } //No state change, Node to remain in Managed state }
public void handleFind(NodeStateContext nodeStateContext) { //Fetch Node data from Client Client client = nodeStateContext.getClient(); Class<?> nodeDataClass = nodeStateContext.getDataClass(); EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(nodeDataClass); String entityId = ObjectGraphUtils.getEntityId(nodeStateContext.getNodeId()); Object nodeData = null; // Node data EntityReader reader = client.getReader(); EnhanceEntity ee = reader.findById(entityId, entityMetadata, client); //Recursively retrieve relationship entities (if there are any) if (ee != null && ee.getEntity() != null) { Object entity = ee.getEntity(); if ((entityMetadata.getRelationNames() == null || entityMetadata.getRelationNames().isEmpty()) && !entityMetadata.isRelationViaJoinTable()) { //There is no relation (not even via Join Table), Construct Node out of this enhance entity, // put into Persistence Cache, and just return. nodeData = entity; nodeStateContext.setData(nodeData); nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node)nodeStateContext); nodeStateContext.setDirty(false); // This node is fresh and hence NOT dirty // One time set as required for rollback. // Object original = ObjectUtils.deepCopy((Node) nodeStateContext); Object original = ((Node) nodeStateContext).clone(); ((Node)nodeStateContext).setOriginalNode((Node) original); return; } else { //This entity has associated entities, find them recursively. nodeData = reader.recursivelyFindEntities(ee.getEntity(), ee.getRelations(), entityMetadata, nodeStateContext.getPersistenceDelegator()); } } //Construct Node out of this entity and put into Persistence Cache if(nodeData != null) { nodeStateContext.setData(nodeData); nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node)nodeStateContext); // This node is fresh and hence NOT dirty nodeStateContext.setDirty(false); // One time set as required for rollback. Object original = ((Node) nodeStateContext).clone(); ((Node)nodeStateContext).setOriginalNode((Node) original); } //No state change, Node to remain in Managed state }
diff --git a/src/so/sauru/sr_gallery/OrganizeActivity.java b/src/so/sauru/sr_gallery/OrganizeActivity.java index ed929f4..39db529 100644 --- a/src/so/sauru/sr_gallery/OrganizeActivity.java +++ b/src/so/sauru/sr_gallery/OrganizeActivity.java @@ -1,408 +1,410 @@ package so.sauru.sr_gallery; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.Locale; import so.sauru.UriUtils; import android.app.ActionBar; import android.app.AlertDialog; import android.app.FragmentTransaction; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.NavUtils; import android.support.v4.view.ViewPager; import android.text.Editable; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class OrganizeActivity extends FragmentActivity implements ActionBar.TabListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which * will keep every loaded fragment in memory. If this becomes too memory * intensive, it may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; /* my variables */ static ArrayList<Uri> uriList = new ArrayList<Uri> (); ArrayList<File> fileList = new ArrayList<File> (); static final String GALLORG = "GallOrg"; static String new_album = new String(); static File gallorg_root = null; static File gallorg_dest = null; static ArrayAdapter<CharSequence> aaAlbums; static Spinner spAlbums; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_organize); // Set up the action bar. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter( getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab(actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } /* real works (added by me) started here... */ getUriList(); } private void getUriList() { Intent intent = getIntent(); Bundle extras = intent.getExtras(); uriList.clear(); if (Intent.ACTION_SEND.equals(intent.getAction())) { if (extras != null) { Uri contentUri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM); Log.d(GALLORG, "SEND URI:" + contentUri.toString()); uriList.add(contentUri); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.gallorg, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent settingsIntent = new Intent(this, SettingsActivity.class); startActivity(settingsIntent); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a DummySectionFragment (defined as a static inner class // below) with the page number as its lone argument. Fragment fragment; if (position == 0) { fragment = new FileSectionFragment(); } else { fragment = new DummySectionFragment(); } Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1); fragment.setArguments(args); return fragment; } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_orgtab_1_file).toUpperCase(l); case 1: return getString(R.string.title_orgtab_2_meta).toUpperCase(l); case 2: return getString(R.string.title_orgtab_3_exif).toUpperCase(l); } return null; } } /** * A dummy fragment representing a section of the app, but that simply * displays dummy text. */ public static class DummySectionFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ public static final String ARG_SECTION_NUMBER = "section_number"; public DummySectionFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_organize_dummy, container, false); TextView dummyTextView = (TextView) rootView .findViewById(R.id.section_label); dummyTextView.setText(Integer.toString(getArguments().getInt( ARG_SECTION_NUMBER))); return rootView; } } public static class FileSectionFragment extends Fragment { public FileSectionFragment() { } /** gallorg view with shared contents **/ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rV = inflater.inflate(R.layout.fragment_gallorg_file, container, false); EditText etUri = (EditText) rV.findViewById(R.id.go_file_uri_value); EditText etPath = (EditText) rV.findViewById(R.id.go_file_path_value); EditText etName = (EditText) rV.findViewById(R.id.go_file_name_value); EditText etSize = (EditText) rV.findViewById(R.id.go_file_size_value); EditText etDate = (EditText) rV.findViewById(R.id.go_file_date_value); EditText etHash = (EditText) rV.findViewById(R.id.go_file_hash_value); /** get file information and show it **/ Log.d(GALLORG, uriList.toString()); if (uriList.size() == 1) { Uri tU = uriList.get(0); File tF = UriUtils.getFileFromUri(tU, this.getActivity()); SimpleDateFormat dF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); etUri.setText(tU.toString()); etPath.setText(tF.getParent()); etName.setText(tF.getName()); etSize.setText(tF.length()/1024 + "KB"); etDate.setText(dF.format(new Date(tF.lastModified()))); etHash.setText("Not implemented yet"); rV.findViewById(R.id.go_image_thumbs).setVisibility(View.GONE); } else if (uriList.size() > 0) { etUri.setText("Bulk"); etPath.setText("Bulk"); etName.setText("Bulk"); } else { etUri.setText("Empty"); etPath.setText("Empty"); etName.setText("Empty"); rV.findViewById(R.id.go_single_image).setVisibility(View.GONE); Log.e(GALLORG, "Error! empty URI list: " + uriList.toString()); // TODO: more error handling here. } /** get directory from... **/ SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); String pref_gallery_root = prefs.getString("gallorg_root", getString(R.string.pref_gallery_root_default)); if (pref_gallery_root.equals(getString(R.string .pref_gallery_root_default))) { gallorg_root = Environment .getExternalStoragePublicDirectory(Environment .DIRECTORY_PICTURES); } else { gallorg_root = new File(pref_gallery_root); } Log.d(GALLORG, gallorg_root.getPath()); /** generate album list from gallery root. **/ ArrayList<CharSequence> dirStrList = new ArrayList<CharSequence> (); dirStrList.add(getString(R.string.go_list_camera)); /* to restore to Camera */ if (gallorg_root.exists() && gallorg_root.isDirectory()) { ArrayList<File> dirList = new ArrayList<File> (Arrays. asList(gallorg_root.listFiles())); Collections.sort(dirList); Iterator<File> e = dirList.iterator(); /* now just support 1-level subdirectory. */ while (e.hasNext()) { File t = (File) e.next(); if (t.isDirectory()) { dirStrList.add(t.getName()); } } } else { Toast.makeText(getActivity(), "gallorg_root does not exist or...", Toast.LENGTH_SHORT).show(); } dirStrList.add(getString(R.string.go_list_new)); /* for new folder creation. */ Log.d(GALLORG, dirStrList.toString()); spAlbums = (Spinner) rV.findViewById(R.id.go_albums_spinner); aaAlbums = new ArrayAdapter <CharSequence> (this - .getActivity(), - android.R.layout.simple_spinner_dropdown_item, dirStrList); + .getActivity(), android.R.layout + .simple_spinner_item, dirStrList); + aaAlbums.setDropDownViewResource(android.R.layout + .simple_spinner_dropdown_item); spAlbums.setAdapter(aaAlbums); spAlbums.setOnItemSelectedListener(new OnAlbumSelectedListener()); rV.findViewById(R.id.go_action_move) .setOnClickListener(new OnBtnClickListener()); rV.findViewById(R.id.go_action_cancel) .setOnClickListener(new OnBtnClickListener()); return rV; } public class OnBtnClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.go_action_move: Toast.makeText(getActivity(), "MOVE", Toast.LENGTH_SHORT).show(); break; case R.id.go_action_cancel: Toast.makeText(getActivity(), "CANCEL", Toast.LENGTH_SHORT).show(); break; default: Toast.makeText(getActivity(), "WHAT", Toast.LENGTH_SHORT).show(); } } } public class OnAlbumSelectedListener implements OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { String selected = parent.getItemAtPosition(pos).toString(); if (selected.equals(getString(R.string.go_list_camera))) { gallorg_dest = new File(Environment .getExternalStoragePublicDirectory(Environment .DIRECTORY_DCIM) + "/Camera"); } else if (selected.equals(getString(R.string.go_list_new))) { getNewAlbum(); return; } else { gallorg_dest = new File(gallorg_root + "/" + selected); } Log.d(GALLORG, "gallorg dest is " + gallorg_dest.toString()); Toast.makeText(parent.getContext(), "dest is " + gallorg_dest.toString(), Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } public void getNewAlbum() { AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle(R.string.go_newalbum_title); alert.setMessage(R.string.go_newalbum_desc); final EditText input = new EditText(getActivity()); alert.setView(input); alert.setPositiveButton(R.string.generic_ok, new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new_album = input.getText().toString().trim(); Log.d(GALLORG, "new album name: " + new_album); aaAlbums.add(new_album); aaAlbums.notifyDataSetChanged(); spAlbums.setSelection(spAlbums.getCount() - 1); } }); alert.setNegativeButton(R.string.generic_cancel, new DialogInterface .OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alert.show(); } } } } /* vim: set ts=2 sw=2: */
true
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rV = inflater.inflate(R.layout.fragment_gallorg_file, container, false); EditText etUri = (EditText) rV.findViewById(R.id.go_file_uri_value); EditText etPath = (EditText) rV.findViewById(R.id.go_file_path_value); EditText etName = (EditText) rV.findViewById(R.id.go_file_name_value); EditText etSize = (EditText) rV.findViewById(R.id.go_file_size_value); EditText etDate = (EditText) rV.findViewById(R.id.go_file_date_value); EditText etHash = (EditText) rV.findViewById(R.id.go_file_hash_value); /** get file information and show it **/ Log.d(GALLORG, uriList.toString()); if (uriList.size() == 1) { Uri tU = uriList.get(0); File tF = UriUtils.getFileFromUri(tU, this.getActivity()); SimpleDateFormat dF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); etUri.setText(tU.toString()); etPath.setText(tF.getParent()); etName.setText(tF.getName()); etSize.setText(tF.length()/1024 + "KB"); etDate.setText(dF.format(new Date(tF.lastModified()))); etHash.setText("Not implemented yet"); rV.findViewById(R.id.go_image_thumbs).setVisibility(View.GONE); } else if (uriList.size() > 0) { etUri.setText("Bulk"); etPath.setText("Bulk"); etName.setText("Bulk"); } else { etUri.setText("Empty"); etPath.setText("Empty"); etName.setText("Empty"); rV.findViewById(R.id.go_single_image).setVisibility(View.GONE); Log.e(GALLORG, "Error! empty URI list: " + uriList.toString()); // TODO: more error handling here. } /** get directory from... **/ SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); String pref_gallery_root = prefs.getString("gallorg_root", getString(R.string.pref_gallery_root_default)); if (pref_gallery_root.equals(getString(R.string .pref_gallery_root_default))) { gallorg_root = Environment .getExternalStoragePublicDirectory(Environment .DIRECTORY_PICTURES); } else { gallorg_root = new File(pref_gallery_root); } Log.d(GALLORG, gallorg_root.getPath()); /** generate album list from gallery root. **/ ArrayList<CharSequence> dirStrList = new ArrayList<CharSequence> (); dirStrList.add(getString(R.string.go_list_camera)); /* to restore to Camera */ if (gallorg_root.exists() && gallorg_root.isDirectory()) { ArrayList<File> dirList = new ArrayList<File> (Arrays. asList(gallorg_root.listFiles())); Collections.sort(dirList); Iterator<File> e = dirList.iterator(); /* now just support 1-level subdirectory. */ while (e.hasNext()) { File t = (File) e.next(); if (t.isDirectory()) { dirStrList.add(t.getName()); } } } else { Toast.makeText(getActivity(), "gallorg_root does not exist or...", Toast.LENGTH_SHORT).show(); } dirStrList.add(getString(R.string.go_list_new)); /* for new folder creation. */ Log.d(GALLORG, dirStrList.toString()); spAlbums = (Spinner) rV.findViewById(R.id.go_albums_spinner); aaAlbums = new ArrayAdapter <CharSequence> (this .getActivity(), android.R.layout.simple_spinner_dropdown_item, dirStrList); spAlbums.setAdapter(aaAlbums); spAlbums.setOnItemSelectedListener(new OnAlbumSelectedListener()); rV.findViewById(R.id.go_action_move) .setOnClickListener(new OnBtnClickListener()); rV.findViewById(R.id.go_action_cancel) .setOnClickListener(new OnBtnClickListener()); return rV; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rV = inflater.inflate(R.layout.fragment_gallorg_file, container, false); EditText etUri = (EditText) rV.findViewById(R.id.go_file_uri_value); EditText etPath = (EditText) rV.findViewById(R.id.go_file_path_value); EditText etName = (EditText) rV.findViewById(R.id.go_file_name_value); EditText etSize = (EditText) rV.findViewById(R.id.go_file_size_value); EditText etDate = (EditText) rV.findViewById(R.id.go_file_date_value); EditText etHash = (EditText) rV.findViewById(R.id.go_file_hash_value); /** get file information and show it **/ Log.d(GALLORG, uriList.toString()); if (uriList.size() == 1) { Uri tU = uriList.get(0); File tF = UriUtils.getFileFromUri(tU, this.getActivity()); SimpleDateFormat dF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); etUri.setText(tU.toString()); etPath.setText(tF.getParent()); etName.setText(tF.getName()); etSize.setText(tF.length()/1024 + "KB"); etDate.setText(dF.format(new Date(tF.lastModified()))); etHash.setText("Not implemented yet"); rV.findViewById(R.id.go_image_thumbs).setVisibility(View.GONE); } else if (uriList.size() > 0) { etUri.setText("Bulk"); etPath.setText("Bulk"); etName.setText("Bulk"); } else { etUri.setText("Empty"); etPath.setText("Empty"); etName.setText("Empty"); rV.findViewById(R.id.go_single_image).setVisibility(View.GONE); Log.e(GALLORG, "Error! empty URI list: " + uriList.toString()); // TODO: more error handling here. } /** get directory from... **/ SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getActivity()); String pref_gallery_root = prefs.getString("gallorg_root", getString(R.string.pref_gallery_root_default)); if (pref_gallery_root.equals(getString(R.string .pref_gallery_root_default))) { gallorg_root = Environment .getExternalStoragePublicDirectory(Environment .DIRECTORY_PICTURES); } else { gallorg_root = new File(pref_gallery_root); } Log.d(GALLORG, gallorg_root.getPath()); /** generate album list from gallery root. **/ ArrayList<CharSequence> dirStrList = new ArrayList<CharSequence> (); dirStrList.add(getString(R.string.go_list_camera)); /* to restore to Camera */ if (gallorg_root.exists() && gallorg_root.isDirectory()) { ArrayList<File> dirList = new ArrayList<File> (Arrays. asList(gallorg_root.listFiles())); Collections.sort(dirList); Iterator<File> e = dirList.iterator(); /* now just support 1-level subdirectory. */ while (e.hasNext()) { File t = (File) e.next(); if (t.isDirectory()) { dirStrList.add(t.getName()); } } } else { Toast.makeText(getActivity(), "gallorg_root does not exist or...", Toast.LENGTH_SHORT).show(); } dirStrList.add(getString(R.string.go_list_new)); /* for new folder creation. */ Log.d(GALLORG, dirStrList.toString()); spAlbums = (Spinner) rV.findViewById(R.id.go_albums_spinner); aaAlbums = new ArrayAdapter <CharSequence> (this .getActivity(), android.R.layout .simple_spinner_item, dirStrList); aaAlbums.setDropDownViewResource(android.R.layout .simple_spinner_dropdown_item); spAlbums.setAdapter(aaAlbums); spAlbums.setOnItemSelectedListener(new OnAlbumSelectedListener()); rV.findViewById(R.id.go_action_move) .setOnClickListener(new OnBtnClickListener()); rV.findViewById(R.id.go_action_cancel) .setOnClickListener(new OnBtnClickListener()); return rV; }
diff --git a/src/org/gridlab/gridsphere/provider/portletui/beans/FileInputBean.java b/src/org/gridlab/gridsphere/provider/portletui/beans/FileInputBean.java index ef9474a2a..2a5e7cd7e 100644 --- a/src/org/gridlab/gridsphere/provider/portletui/beans/FileInputBean.java +++ b/src/org/gridlab/gridsphere/provider/portletui/beans/FileInputBean.java @@ -1,120 +1,121 @@ /** * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.provider.portletui.beans; import org.apache.commons.fileupload.DiskFileUpload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.gridlab.gridsphere.portlet.PortletRequest; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; /** * A <code>FileInputBean</code> provides a file upload element */ public class FileInputBean extends InputBean implements TagBean { public static final int MAX_UPLOAD_SIZE = 1024 * 1024; public static final String TEMP_DIR = "/tmp"; public static final String SUBMIT_STYLE = "portlet-form-button"; public static String NAME = "fi"; private FileItem savedFileItem = null; /** * Constructs a default file input bean */ public FileInputBean() { super(NAME); this.cssStyle = SUBMIT_STYLE; this.inputtype = "file"; } /** * Constructs a file input bean from a portlet request and bean identifier * * @param request the portlet request * @param beanId the bean identifier * @throws IOException if an I/O exception occurs */ public FileInputBean(PortletRequest request, String beanId) throws IOException { super(NAME); this.cssStyle = SUBMIT_STYLE; this.inputtype = "file"; this.request = request; this.beanId = beanId; } public FileInputBean(PortletRequest request, String beanId, FileItem fileItem) throws IOException { super(NAME); this.cssStyle = SUBMIT_STYLE; this.inputtype = "file"; this.request = request; this.beanId = beanId; savedFileItem = fileItem; } /** * Returns the uploaded file name * * @return the uploaded file name */ public String getFileName() { if (savedFileItem != null) { return savedFileItem.getName(); } else { return ""; } } /** * Returns the uploaded file size * * @return the uploaded file size */ public long getFileSize() { if (savedFileItem != null) { return savedFileItem.getSize(); } else { return 0; } } /** * Saves the file to the supplied file location path * * @param filePath the path to save the file * @throws IOException if an I/O error occurs saving the file */ public void saveFile(String filePath) throws IOException { - if (!filePath.endsWith("/")) filePath += "/"; + String pathChar = File.separator; + if (!filePath.endsWith(pathChar)) filePath += pathChar; File file = new File(filePath); try { if (!file.exists()) file.createNewFile(); if (savedFileItem != null) savedFileItem.write(file); } catch (Exception e) { throw new IOException("Unable to save file: " + e); } } /** * Returns with the InputStream of savedFileItem * @return InputStream * @throws IOException */ public InputStream getInputStream() throws IOException { return (savedFileItem != null) ? savedFileItem.getInputStream() : null; } }
true
true
public void saveFile(String filePath) throws IOException { if (!filePath.endsWith("/")) filePath += "/"; File file = new File(filePath); try { if (!file.exists()) file.createNewFile(); if (savedFileItem != null) savedFileItem.write(file); } catch (Exception e) { throw new IOException("Unable to save file: " + e); } }
public void saveFile(String filePath) throws IOException { String pathChar = File.separator; if (!filePath.endsWith(pathChar)) filePath += pathChar; File file = new File(filePath); try { if (!file.exists()) file.createNewFile(); if (savedFileItem != null) savedFileItem.write(file); } catch (Exception e) { throw new IOException("Unable to save file: " + e); } }
diff --git a/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java b/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java index 14a417596..036505e1b 100644 --- a/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java +++ b/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java @@ -1,744 +1,744 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.client.gui.panel; import java.awt.Color; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JTextPane; import javax.swing.SpinnerNumberModel; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import javax.swing.text.StyledDocument; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.client.gui.Canvas; import net.sf.freecol.client.gui.i18n.Messages; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.ColonyTradeItem; import net.sf.freecol.common.model.DiplomaticTrade; import net.sf.freecol.common.model.GoldTradeItem; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.GoodsTradeItem; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Player.Stance; import net.sf.freecol.common.model.Settlement; import net.sf.freecol.common.model.StanceTradeItem; import net.sf.freecol.common.model.TradeItem; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.UnitTradeItem; import org.w3c.dom.Element; import cz.autel.dmi.HIGLayout; /** * The panel that allows negotiations between players. */ public final class NegotiationDialog extends FreeColDialog implements ActionListener { private static final String SEND = "send", ACCEPT = "accept", CANCEL = "cancel"; private static Logger logger = Logger.getLogger(NegotiationDialog.class.getName()); private FreeColClient freeColClient; private DiplomaticTrade agreement; private JButton acceptButton, cancelButton, sendButton; private StanceTradeItemPanel stance; private GoldTradeItemPanel goldOffer, goldDemand; private ColonyTradeItemPanel colonyOffer, colonyDemand; private GoodsTradeItemPanel goodsOffer, goodsDemand; //private UnitTradeItemPanel unitOffer, unitDemand; private JTextPane summary; private final Unit unit; private final Settlement settlement; private Player player; private Player otherPlayer; private Player sender; private Player recipient; private boolean canAccept; /** * Creates a new <code>NegotiationDialog</code> instance. * * @param parent a <code>Canvas</code> value * @param unit an <code>Unit</code> value * @param settlement a <code>Settlement</code> value */ public NegotiationDialog(Canvas parent, Unit unit, Settlement settlement) { this(parent, unit, settlement, null); } /** * Creates a new <code>NegotiationDialog</code> instance. * * @param parent a <code>Canvas</code> value * @param unit an <code>Unit</code> value * @param settlement a <code>Settlement</code> value * @param agreement a <code>DiplomaticTrade</code> with the offer */ public NegotiationDialog(Canvas parent, Unit unit, Settlement settlement, DiplomaticTrade agreement) { super(parent); setFocusCycleRoot(true); this.unit = unit; this.settlement = settlement; this.freeColClient = parent.getClient(); this.player = freeColClient.getMyPlayer(); this.sender = unit.getOwner(); this.recipient = settlement.getOwner(); this.canAccept = agreement != null; // a new offer can't be accepted if (agreement == null) { this.agreement = new DiplomaticTrade(unit.getGame(), sender, recipient); } else { this.agreement = agreement; } if (sender == player) { this.otherPlayer = recipient; } else { this.otherPlayer = sender; } if (player.getStance(otherPlayer) == Stance.WAR) { if (!hasPeaceOffer()) { Stance stance = Stance.PEACE; this.agreement.add(new StanceTradeItem(freeColClient.getGame(), player, otherPlayer, stance)); } } summary = new JTextPane(); summary.setOpaque(false); summary.setEditable(false); StyledDocument document = summary.getStyledDocument(); //Initialize some styles. Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE); Style regular = document.addStyle("regular", def); StyleConstants.setFontFamily(def, "Dialog"); StyleConstants.setBold(def, true); StyleConstants.setFontSize(def, 12); Style buttonStyle = document.addStyle("button", regular); StyleConstants.setForeground(buttonStyle, LINK_COLOR); } /** * Set up the dialog. * */ public void initialize() { int foreignGold = 0; Element report = getCanvas().getClient().getInGameController().getForeignAffairsReport(); int number = report.getChildNodes().getLength(); for (int i = 0; i < number; i++) { Element enemyElement = (Element) report.getChildNodes().item(i); - Player enemy = (Player) getCanvas().getClient().getGame().getFreeColGameObject(enemyElement.getAttribute("nation")); + Player enemy = (Player) getCanvas().getClient().getGame().getFreeColGameObject(enemyElement.getAttribute("player")); if (enemy == otherPlayer) { foreignGold = Integer.parseInt(enemyElement.getAttribute("gold")); break; } } sendButton = new JButton(Messages.message("negotiationDialog.send")); sendButton.addActionListener(this); sendButton.setActionCommand(SEND); FreeColPanel.enterPressesWhenFocused(sendButton); acceptButton = new JButton(Messages.message("negotiationDialog.accept")); acceptButton.addActionListener(this); acceptButton.setActionCommand(ACCEPT); FreeColPanel.enterPressesWhenFocused(acceptButton); acceptButton.setEnabled(canAccept); cancelButton = new JButton(Messages.message("negotiationDialog.cancel")); cancelButton.addActionListener(this); cancelButton.setActionCommand(CANCEL); setCancelComponent(cancelButton); FreeColPanel.enterPressesWhenFocused(cancelButton); updateSummary(); stance = new StanceTradeItemPanel(this, player, otherPlayer); goldDemand = new GoldTradeItemPanel(this, otherPlayer, foreignGold); goldOffer = new GoldTradeItemPanel(this, player, player.getGold()); colonyDemand = new ColonyTradeItemPanel(this, otherPlayer); colonyOffer = new ColonyTradeItemPanel(this, player); /** TODO: UnitTrade unitDemand = new UnitTradeItemPanel(this, otherPlayer); unitOffer = new UnitTradeItemPanel(this, player); */ int numberOfTradeItems = 4; int extraRows = 2; // headline and buttons int[] widths = {200, 10, 300, 10, 200}; int[] heights = new int[2 * (numberOfTradeItems + extraRows) - 1]; for (int index = 1; index < heights.length; index += 2) { heights[index] = 10; } setLayout(new HIGLayout(widths, heights)); int demandColumn = 1; int summaryColumn = 3; int offerColumn = 5; int row = 1; add(new JLabel(Messages.message("negotiationDialog.demand")), higConst.rc(row, demandColumn)); add(new JLabel(Messages.message("negotiationDialog.offer")), higConst.rc(row, offerColumn)); row += 2; add(stance, higConst.rc(row, offerColumn)); row += 2; add(goldDemand, higConst.rc(row, demandColumn)); add(goldOffer, higConst.rc(row, offerColumn)); add(summary, higConst.rcwh(row, summaryColumn, 1, 5)); row += 2; if (unit.isCarrier()) { goodsDemand = new GoodsTradeItemPanel(this, otherPlayer, settlement.getGoodsContainer().getGoods()); add(goodsDemand, higConst.rc(row, demandColumn)); goodsOffer = new GoodsTradeItemPanel(this, player, unit.getGoodsContainer().getGoods()); add(goodsOffer, higConst.rc(row, offerColumn)); } else { add(colonyDemand, higConst.rc(row, demandColumn)); add(colonyOffer, higConst.rc(row, offerColumn)); } row += 2; /** TODO: UnitTrade add(unitDemand, higConst.rc(row, demandColumn)); add(unitOffer, higConst.rc(row, offerColumn)); */ row += 2; add(sendButton, higConst.rc(row, demandColumn, "")); add(acceptButton, higConst.rc(row, summaryColumn, "")); add(cancelButton, higConst.rc(row, offerColumn, "")); } private void updateSummary() { try { StyledDocument document = summary.getStyledDocument(); document.remove(0, document.getLength()); String input = Messages.message("negotiationDialog.summary"); int start = input.indexOf('%'); if (start == -1) { // no variables present insertText(input.substring(0)); return; } else if (start > 0) { // output any string before the first occurence of '%' insertText(input.substring(0, start)); } int end; loop: while ((end = input.indexOf('%', start + 1)) >= 0) { String var = input.substring(start, end + 1); if (var.equals("%nation%")) { insertText(sender.getNationAsString()); start = end + 1; continue loop; } else if (var.equals("%offers%")) { insertOffers(); start = end + 1; continue loop; } else if (var.equals("%demands%")) { insertDemands(); start = end + 1; continue loop; } else { // found no variable to replace: either a single '%', or // some unnecessary variable insertText(input.substring(start, end)); start = end; } } // output any string after the last occurence of '%' if (start < input.length()) { insertText(input.substring(start)); } } catch(Exception e) { logger.warning("Failed to update summary: " + e.toString()); } } private void insertText(String text) throws Exception { StyledDocument document = summary.getStyledDocument(); document.insertString(document.getLength(), text, document.getStyle("regular")); } private void insertOffers() { insertTradeItemDescriptions(sender); } private void insertDemands() { insertTradeItemDescriptions(recipient); } private void insertTradeItemDescriptions(Player itemSource) { StyledDocument document = summary.getStyledDocument(); List<TradeItem> items = agreement.getTradeItems(); boolean foundItem = false; for (int index = 0; index < items.size(); index++) { TradeItem item = items.get(index); if (item.getSource() == itemSource) { foundItem = true; String description = ""; if (item instanceof StanceTradeItem) { description = Player.getStanceAsString(((StanceTradeItem) item).getStance()); } else if (item instanceof GoldTradeItem) { String gold = String.valueOf(((GoldTradeItem) item).getGold()); description = Messages.message("tradeItem.gold.long", "%amount%", gold); } else if (item instanceof ColonyTradeItem) { description = Messages.message("tradeItem.colony.long", "%colony%", ((ColonyTradeItem) item).getColony().getName()); } else if (item instanceof GoodsTradeItem) { description = String.valueOf(((GoodsTradeItem) item).getGoods().getAmount()) + " " + ((GoodsTradeItem) item).getGoods().getName(); } else if (item instanceof UnitTradeItem) { description = ((UnitTradeItem) item).getUnit().getName(); } try { JButton button = new JButton(description); button.setMargin(new Insets(0,0,0,0)); button.setOpaque(false); button.setForeground(LINK_COLOR); button.setAlignmentY(0.8f); button.setBorder(BorderFactory.createEmptyBorder()); button.addActionListener(this); button.setActionCommand(String.valueOf(index)); StyleConstants.setComponent(document.getStyle("button"), button); document.insertString(document.getLength(), " ", document.getStyle("button")); if (index < items.size() - 1) { document.insertString(document.getLength(), ", ", document.getStyle("regular")); } else { return; } } catch(Exception e) { logger.warning(e.toString()); } } } if (!foundItem) { try { document.insertString(document.getLength(), Messages.message("negotiationDialog.nothing"), document.getStyle("regular")); } catch(Exception e) { logger.warning(e.toString()); } } } private boolean hasPeaceOffer() { return (getStance() != null); } /** * Adds a <code>ColonyTradeItem</code> to the list of TradeItems. * * @param source a <code>Player</code> value * @param colony a <code>Colony</code> value */ public void addColonyTradeItem(Player source, Colony colony) { Player destination; if (source == otherPlayer) { destination = player; } else { destination = otherPlayer; } agreement.add(new ColonyTradeItem(freeColClient.getGame(), source, destination, colony)); } /** * Adds a <code>GoldTradeItem</code> to the list of TradeItems. * * @param source a <code>Player</code> value * @param amount an <code>int</code> value */ public void addGoldTradeItem(Player source, int amount) { Player destination; if (source == otherPlayer) { destination = player; } else { destination = otherPlayer; } agreement.add(new GoldTradeItem(freeColClient.getGame(), source, destination, amount)); } /** * Adds a <code>GoodsTradeItem</code> to the list of TradeItems. * * @param source a <code>Player</code> value * @param goods a <code>Goods</code> value */ public void addGoodsTradeItem(Player source, Goods goods) { Player destination; if (source == otherPlayer) { destination = player; } else { destination = otherPlayer; } agreement.add(new GoodsTradeItem(freeColClient.getGame(), source, destination, goods, settlement)); } /** * Sets the <code>stance</code> between the players. * * @param stance a <code>Stance</code> value */ public void setStance(Stance stance) { agreement.add(new StanceTradeItem(freeColClient.getGame(), otherPlayer, player, stance)); } /** * Returns the stance being offered, or Integer.MIN_VALUE if none * is being offered. * * @return a <code>Stance</code> value */ public Stance getStance() { return agreement.getStance(); } /** * Analyzes an event and calls the right external methods to take care of * the user's request. * * @param event The incoming action event */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals(CANCEL)) { setResponse(null); } else if (command.equals(ACCEPT)) { agreement.setAccept(true); setResponse(agreement); } else if (command.equals(SEND)) { setResponse(agreement); } else { int index = Integer.parseInt(command); agreement.remove(index); initialize(); } } public class ColonyTradeItemPanel extends JPanel implements ActionListener { private JComboBox colonyBox; private JButton addButton; private Player player; private NegotiationDialog negotiationDialog; /** * Creates a new <code>ColonyTradeItemPanel</code> instance. * * @param parent a <code>NegotiationDialog</code> value * @param source a <code>Player</code> value */ public ColonyTradeItemPanel(NegotiationDialog parent, Player source) { this.player = source; this.negotiationDialog = parent; addButton = new JButton(Messages.message("negotiationDialog.add")); addButton.addActionListener(this); addButton.setActionCommand("add"); colonyBox = new JComboBox(); updateColonyBox(); setLayout(new HIGLayout(new int[] {0}, new int[] {0, 0, 0})); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK), BorderFactory.createEmptyBorder(5, 5, 5, 5))); add(new JLabel(Messages.message("tradeItem.colony")), higConst.rc(1, 1)); add(colonyBox, higConst.rc(2, 1)); add(addButton, higConst.rc(3, 1)); } private void updateColonyBox() { if (!player.isEuropean()) { return; } // Remove all action listeners, so the update has no effect (except // updating the list). ActionListener[] listeners = colonyBox.getActionListeners(); for (ActionListener al : listeners) { colonyBox.removeActionListener(al); } colonyBox.removeAllItems(); List<Colony> colonies = player.getColonies(); Collections.sort(colonies, freeColClient.getClientOptions().getColonyComparator()); Iterator<Colony> colonyIterator = colonies.iterator(); while (colonyIterator.hasNext()) { colonyBox.addItem(colonyIterator.next()); } for(ActionListener al : listeners) { colonyBox.addActionListener(al); } } /** * Analyzes an event and calls the right external methods to take care of * the user's request. * * @param event The incoming action event */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("add")) { negotiationDialog.addColonyTradeItem(player, (Colony) colonyBox.getSelectedItem()); updateSummary(); } } } public class GoodsTradeItemPanel extends JPanel implements ActionListener { private JComboBox goodsBox; private JButton addButton; private Player player; private NegotiationDialog negotiationDialog; /** * Creates a new <code>GoodsTradeItemPanel</code> instance. * * @param parent a <code>NegotiationDialog</code> value * @param source a <code>Player</code> value * @param allGoods a <code>List</code> of <code>Goods</code> values */ public GoodsTradeItemPanel(NegotiationDialog parent, Player source, List<Goods> allGoods) { this.player = source; this.negotiationDialog = parent; addButton = new JButton(Messages.message("negotiationDialog.add")); addButton.addActionListener(this); addButton.setActionCommand("add"); goodsBox = new JComboBox(); JLabel label = new JLabel(Messages.message("tradeItem.goods")); if (allGoods == null) { label.setEnabled(false); addButton.setEnabled(false); goodsBox.setEnabled(false); } else { updateGoodsBox(allGoods); } setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK), BorderFactory.createEmptyBorder(5, 5, 5, 5))); setLayout(new HIGLayout(new int[] {0}, new int[] {0, 0, 0})); add(label, higConst.rc(1, 1)); add(goodsBox, higConst.rc(2, 1)); add(addButton, higConst.rc(3, 1)); setSize(getPreferredSize()); } private void updateGoodsBox(List<Goods> allGoods) { // Remove all action listeners, so the update has no effect (except // updating the list). ActionListener[] listeners = goodsBox.getActionListeners(); for (ActionListener al : listeners) { goodsBox.removeActionListener(al); } goodsBox.removeAllItems(); Iterator<Goods> goodsIterator = allGoods.iterator(); while (goodsIterator.hasNext()) { goodsBox.addItem(goodsIterator.next()); } for(ActionListener al : listeners) { goodsBox.addActionListener(al); } } /** * Analyzes an event and calls the right external methods to take care of * the user's request. * * @param event The incoming action event */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("add")) { negotiationDialog.addGoodsTradeItem(player, (Goods) goodsBox.getSelectedItem()); updateSummary(); } } } public class StanceTradeItemPanel extends JPanel implements ActionListener { class StanceItem { private Stance value; StanceItem(Stance value) { this.value = value; } public String toString() { return Player.getStanceAsString(value); } Stance getValue() { return value; } public boolean equals(Object other) { if (other == null || !(other instanceof StanceItem)) { return false; } return value.equals(((StanceItem) other).value); } } private JComboBox stanceBox; private JButton addButton; private NegotiationDialog negotiationDialog; /** * Creates a new <code>StanceTradeItemPanel</code> instance. * * @param parent a <code>NegotiationDialog</code> value * @param source a <code>Player</code> value */ public StanceTradeItemPanel(NegotiationDialog parent, Player source, Player target) { this.negotiationDialog = parent; addButton = new JButton(Messages.message("negotiationDialog.add")); addButton.addActionListener(this); addButton.setActionCommand("add"); stanceBox = new JComboBox(); Stance stance = source.getStance(target); if (stance != Stance.WAR) stanceBox.addItem(new StanceItem(Stance.WAR)); if (stance == Stance.WAR) stanceBox.addItem(new StanceItem(Stance.CEASE_FIRE)); if (stance != Stance.PEACE) stanceBox.addItem(new StanceItem(Stance.PEACE)); if (stance != Stance.ALLIANCE) stanceBox.addItem(new StanceItem(Stance.ALLIANCE)); if (parent.hasPeaceOffer()) { stanceBox.setSelectedItem(new StanceItem(parent.getStance())); } setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK), BorderFactory.createEmptyBorder(5, 5, 5, 5))); setLayout(new HIGLayout(new int[] {0}, new int[] {0, 0, 0})); add(new JLabel(Messages.message("tradeItem.stance")), higConst.rc(1, 1)); add(stanceBox, higConst.rc(2, 1)); add(addButton, higConst.rc(3, 1)); } /** * Analyzes an event and calls the right external methods to take care of * the user's request. * * @param event The incoming action event */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("add")) { StanceItem stance = (StanceItem) stanceBox.getSelectedItem(); negotiationDialog.setStance(stance.getValue()); updateSummary(); } } } public class GoldTradeItemPanel extends JPanel implements ActionListener { private JSpinner spinner; private JButton addButton; private Player player; private NegotiationDialog negotiationDialog; /** * Creates a new <code>GoldTradeItemPanel</code> instance. * * @param parent a <code>NegotiationDialog</code> value * @param source a <code>Player</code> value */ public GoldTradeItemPanel(NegotiationDialog parent, Player source, int gold) { this.player = source; this.negotiationDialog = parent; addButton = new JButton(Messages.message("negotiationDialog.add")); addButton.addActionListener(this); addButton.setActionCommand("add"); spinner = new JSpinner(new SpinnerNumberModel(0, 0, gold, 1)); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK), BorderFactory.createEmptyBorder(5, 5, 5, 5))); setLayout(new HIGLayout(new int[] {0}, new int[] {0, 0, 0})); add(new JLabel(Messages.message("tradeItem.gold")), higConst.rc(1, 1)); add(spinner, higConst.rc(2, 1)); add(addButton, higConst.rc(3, 1)); } /** * Analyzes an event and calls the right external methods to take care of * the user's request. * * @param event The incoming action event */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if (command.equals("add")) { int amount = ((Integer) spinner.getValue()).intValue(); negotiationDialog.addGoldTradeItem(player, amount); updateSummary(); } } } }
true
true
public void initialize() { int foreignGold = 0; Element report = getCanvas().getClient().getInGameController().getForeignAffairsReport(); int number = report.getChildNodes().getLength(); for (int i = 0; i < number; i++) { Element enemyElement = (Element) report.getChildNodes().item(i); Player enemy = (Player) getCanvas().getClient().getGame().getFreeColGameObject(enemyElement.getAttribute("nation")); if (enemy == otherPlayer) { foreignGold = Integer.parseInt(enemyElement.getAttribute("gold")); break; } } sendButton = new JButton(Messages.message("negotiationDialog.send")); sendButton.addActionListener(this); sendButton.setActionCommand(SEND); FreeColPanel.enterPressesWhenFocused(sendButton); acceptButton = new JButton(Messages.message("negotiationDialog.accept")); acceptButton.addActionListener(this); acceptButton.setActionCommand(ACCEPT); FreeColPanel.enterPressesWhenFocused(acceptButton); acceptButton.setEnabled(canAccept); cancelButton = new JButton(Messages.message("negotiationDialog.cancel")); cancelButton.addActionListener(this); cancelButton.setActionCommand(CANCEL); setCancelComponent(cancelButton); FreeColPanel.enterPressesWhenFocused(cancelButton); updateSummary(); stance = new StanceTradeItemPanel(this, player, otherPlayer); goldDemand = new GoldTradeItemPanel(this, otherPlayer, foreignGold); goldOffer = new GoldTradeItemPanel(this, player, player.getGold()); colonyDemand = new ColonyTradeItemPanel(this, otherPlayer); colonyOffer = new ColonyTradeItemPanel(this, player); /** TODO: UnitTrade unitDemand = new UnitTradeItemPanel(this, otherPlayer); unitOffer = new UnitTradeItemPanel(this, player); */ int numberOfTradeItems = 4; int extraRows = 2; // headline and buttons int[] widths = {200, 10, 300, 10, 200}; int[] heights = new int[2 * (numberOfTradeItems + extraRows) - 1]; for (int index = 1; index < heights.length; index += 2) { heights[index] = 10; } setLayout(new HIGLayout(widths, heights)); int demandColumn = 1; int summaryColumn = 3; int offerColumn = 5; int row = 1; add(new JLabel(Messages.message("negotiationDialog.demand")), higConst.rc(row, demandColumn)); add(new JLabel(Messages.message("negotiationDialog.offer")), higConst.rc(row, offerColumn)); row += 2; add(stance, higConst.rc(row, offerColumn)); row += 2; add(goldDemand, higConst.rc(row, demandColumn)); add(goldOffer, higConst.rc(row, offerColumn)); add(summary, higConst.rcwh(row, summaryColumn, 1, 5)); row += 2; if (unit.isCarrier()) { goodsDemand = new GoodsTradeItemPanel(this, otherPlayer, settlement.getGoodsContainer().getGoods()); add(goodsDemand, higConst.rc(row, demandColumn)); goodsOffer = new GoodsTradeItemPanel(this, player, unit.getGoodsContainer().getGoods()); add(goodsOffer, higConst.rc(row, offerColumn)); } else { add(colonyDemand, higConst.rc(row, demandColumn)); add(colonyOffer, higConst.rc(row, offerColumn)); } row += 2; /** TODO: UnitTrade add(unitDemand, higConst.rc(row, demandColumn)); add(unitOffer, higConst.rc(row, offerColumn)); */ row += 2; add(sendButton, higConst.rc(row, demandColumn, "")); add(acceptButton, higConst.rc(row, summaryColumn, "")); add(cancelButton, higConst.rc(row, offerColumn, "")); }
public void initialize() { int foreignGold = 0; Element report = getCanvas().getClient().getInGameController().getForeignAffairsReport(); int number = report.getChildNodes().getLength(); for (int i = 0; i < number; i++) { Element enemyElement = (Element) report.getChildNodes().item(i); Player enemy = (Player) getCanvas().getClient().getGame().getFreeColGameObject(enemyElement.getAttribute("player")); if (enemy == otherPlayer) { foreignGold = Integer.parseInt(enemyElement.getAttribute("gold")); break; } } sendButton = new JButton(Messages.message("negotiationDialog.send")); sendButton.addActionListener(this); sendButton.setActionCommand(SEND); FreeColPanel.enterPressesWhenFocused(sendButton); acceptButton = new JButton(Messages.message("negotiationDialog.accept")); acceptButton.addActionListener(this); acceptButton.setActionCommand(ACCEPT); FreeColPanel.enterPressesWhenFocused(acceptButton); acceptButton.setEnabled(canAccept); cancelButton = new JButton(Messages.message("negotiationDialog.cancel")); cancelButton.addActionListener(this); cancelButton.setActionCommand(CANCEL); setCancelComponent(cancelButton); FreeColPanel.enterPressesWhenFocused(cancelButton); updateSummary(); stance = new StanceTradeItemPanel(this, player, otherPlayer); goldDemand = new GoldTradeItemPanel(this, otherPlayer, foreignGold); goldOffer = new GoldTradeItemPanel(this, player, player.getGold()); colonyDemand = new ColonyTradeItemPanel(this, otherPlayer); colonyOffer = new ColonyTradeItemPanel(this, player); /** TODO: UnitTrade unitDemand = new UnitTradeItemPanel(this, otherPlayer); unitOffer = new UnitTradeItemPanel(this, player); */ int numberOfTradeItems = 4; int extraRows = 2; // headline and buttons int[] widths = {200, 10, 300, 10, 200}; int[] heights = new int[2 * (numberOfTradeItems + extraRows) - 1]; for (int index = 1; index < heights.length; index += 2) { heights[index] = 10; } setLayout(new HIGLayout(widths, heights)); int demandColumn = 1; int summaryColumn = 3; int offerColumn = 5; int row = 1; add(new JLabel(Messages.message("negotiationDialog.demand")), higConst.rc(row, demandColumn)); add(new JLabel(Messages.message("negotiationDialog.offer")), higConst.rc(row, offerColumn)); row += 2; add(stance, higConst.rc(row, offerColumn)); row += 2; add(goldDemand, higConst.rc(row, demandColumn)); add(goldOffer, higConst.rc(row, offerColumn)); add(summary, higConst.rcwh(row, summaryColumn, 1, 5)); row += 2; if (unit.isCarrier()) { goodsDemand = new GoodsTradeItemPanel(this, otherPlayer, settlement.getGoodsContainer().getGoods()); add(goodsDemand, higConst.rc(row, demandColumn)); goodsOffer = new GoodsTradeItemPanel(this, player, unit.getGoodsContainer().getGoods()); add(goodsOffer, higConst.rc(row, offerColumn)); } else { add(colonyDemand, higConst.rc(row, demandColumn)); add(colonyOffer, higConst.rc(row, offerColumn)); } row += 2; /** TODO: UnitTrade add(unitDemand, higConst.rc(row, demandColumn)); add(unitOffer, higConst.rc(row, offerColumn)); */ row += 2; add(sendButton, higConst.rc(row, demandColumn, "")); add(acceptButton, higConst.rc(row, summaryColumn, "")); add(cancelButton, higConst.rc(row, offerColumn, "")); }
diff --git a/shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/NewProjectPlugin.java b/shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/NewProjectPlugin.java index 5f822d5c..a93f108e 100644 --- a/shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/NewProjectPlugin.java +++ b/shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/NewProjectPlugin.java @@ -1,206 +1,206 @@ /* * JBoss, by Red Hat. * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.seam.forge.shell.plugins.builtin; import java.io.IOException; import javax.inject.Inject; import javax.inject.Named; import org.apache.maven.model.Model; import org.jboss.seam.forge.parser.JavaParser; import org.jboss.seam.forge.parser.java.JavaClass; import org.jboss.seam.forge.project.Project; import org.jboss.seam.forge.project.Resource; import org.jboss.seam.forge.project.facets.DependencyFacet; import org.jboss.seam.forge.project.facets.JavaSourceFacet; import org.jboss.seam.forge.project.facets.MavenCoreFacet; import org.jboss.seam.forge.project.facets.MetadataFacet; import org.jboss.seam.forge.project.facets.ResourceFacet; import org.jboss.seam.forge.project.resources.FileResource; import org.jboss.seam.forge.project.resources.ResourceException; import org.jboss.seam.forge.project.resources.builtin.DirectoryResource; import org.jboss.seam.forge.project.services.ProjectFactory; import org.jboss.seam.forge.project.services.ResourceFactory; import org.jboss.seam.forge.project.util.ResourceUtil; import org.jboss.seam.forge.shell.PromptType; import org.jboss.seam.forge.shell.Shell; import org.jboss.seam.forge.shell.plugins.DefaultCommand; import org.jboss.seam.forge.shell.plugins.Help; import org.jboss.seam.forge.shell.plugins.Option; import org.jboss.seam.forge.shell.plugins.Plugin; import org.jboss.seam.forge.shell.plugins.Topic; import org.jboss.seam.forge.shell.util.Files; /** * @author <a href="mailto:[email protected]">Lincoln Baxter, III</a> */ @Named("new-project") @Topic("Project") @Help("Create a new project in an empty directory.") public class NewProjectPlugin implements Plugin { @Inject private Shell shell; @Inject private ProjectFactory projectFactory; @Inject private ResourceFactory factory; @SuppressWarnings("unchecked") @DefaultCommand public void create( @Option(name = "named", description = "The name of the new project", required = true) final String name, @Option(name = "topLevelPackage", description = "The top level package for your Java source files [e.g: \"com.example.project\"] ", required = true, type = PromptType.JAVA_PACKAGE) final String groupId, @Option(name = "projectFolder", description = "The folder in which to create this project [e.g: \"~/Desktop/...\"] ", required = false) final Resource<?> projectFolder, @Option(name = "createMain", description = "Toggle creation of a simple Main() script in the root package", required = false, defaultValue = "false", flagOnly = true) final boolean createMain ) throws IOException { DirectoryResource dir = shell.getCurrentDirectory(); try { if (projectFolder instanceof FileResource<?>) { // FIXME this is ugly if (!((FileResource<?>) projectFolder).exists()) { ((FileResource<?>) projectFolder).mkdirs(); } Resource<?> parent = projectFolder.getParent(); dir = (DirectoryResource) parent.getChild(projectFolder.getName()); } else { dir = dir.getChildDirectory(name); } } catch (ResourceException e) { // ask } if (projectFactory.containsProject(dir) || !shell.promptBoolean("Use [" + dir.getFullyQualifiedName() + "] as project directory?")) { if (projectFactory.containsProject(dir)) { shell.println("***ERROR*** [" + dir.getFullyQualifiedName() + "] already contains a project; please use a different folder."); } DirectoryResource defaultDir; if (shell.getCurrentResource() == null) { defaultDir = ResourceUtil.getContextDirectory(factory.getResourceFrom(Files.getWorkingDirectory())); } else { defaultDir = shell.getCurrentDirectory(); } DirectoryResource newDir = shell.getCurrentDirectory(); do { shell.println(); FileResource<?> temp; if (!projectFactory.containsProject(newDir)) { temp = shell.promptFile( "Where would you like to create the project? [Press ENTER to use the current directory: " + newDir + "]", defaultDir); } else { temp = shell.promptFile("Where would you like to create the project?"); } if (!temp.exists()) { temp.mkdirs(); } - newDir = newDir.createFrom(temp); + newDir = newDir.createFrom(temp.getUnderlyingResourceObject()); if (projectFactory.containsProject(newDir)) { newDir = null; } } while ((newDir == null) || !(newDir instanceof DirectoryResource)); dir = newDir; } if (!dir.exists()) { dir.mkdirs(); } Project project = projectFactory.createProject(dir, MavenCoreFacet.class, DependencyFacet.class, MetadataFacet.class, JavaSourceFacet.class, ResourceFacet.class); MavenCoreFacet maven = project.getFacet(MavenCoreFacet.class); Model pom = maven.getPOM(); pom.setArtifactId(name); pom.setGroupId(groupId); pom.setPackaging("jar"); DependencyFacet deps = project.getFacet(DependencyFacet.class); deps.addRepository("jboss", "https://repository.jboss.org/nexus/content/groups/public/"); maven.setPOM(pom); if (createMain) { project.getFacet(JavaSourceFacet.class).saveJavaClass(JavaParser .create(JavaClass.class) .setPackage(groupId) .setName("Main") .addMethod("public static void main(String[] args) {}") .setBody("System.out.println(\"Hi there! I was forged as part of the project you call " + name + ".\");") .getOrigin()); } project.getFacet(ResourceFacet.class).createResource("<forge/>".toCharArray(), "META-INF/forge.xml"); /* * Only change the environment after success! */ shell.setCurrentResource(project.getProjectRoot()); shell.println("***SUCCESS*** Created project [" + name + "] in new working directory [" + dir + "]"); } }
true
true
public void create( @Option(name = "named", description = "The name of the new project", required = true) final String name, @Option(name = "topLevelPackage", description = "The top level package for your Java source files [e.g: \"com.example.project\"] ", required = true, type = PromptType.JAVA_PACKAGE) final String groupId, @Option(name = "projectFolder", description = "The folder in which to create this project [e.g: \"~/Desktop/...\"] ", required = false) final Resource<?> projectFolder, @Option(name = "createMain", description = "Toggle creation of a simple Main() script in the root package", required = false, defaultValue = "false", flagOnly = true) final boolean createMain ) throws IOException { DirectoryResource dir = shell.getCurrentDirectory(); try { if (projectFolder instanceof FileResource<?>) { // FIXME this is ugly if (!((FileResource<?>) projectFolder).exists()) { ((FileResource<?>) projectFolder).mkdirs(); } Resource<?> parent = projectFolder.getParent(); dir = (DirectoryResource) parent.getChild(projectFolder.getName()); } else { dir = dir.getChildDirectory(name); } } catch (ResourceException e) { // ask } if (projectFactory.containsProject(dir) || !shell.promptBoolean("Use [" + dir.getFullyQualifiedName() + "] as project directory?")) { if (projectFactory.containsProject(dir)) { shell.println("***ERROR*** [" + dir.getFullyQualifiedName() + "] already contains a project; please use a different folder."); } DirectoryResource defaultDir; if (shell.getCurrentResource() == null) { defaultDir = ResourceUtil.getContextDirectory(factory.getResourceFrom(Files.getWorkingDirectory())); } else { defaultDir = shell.getCurrentDirectory(); } DirectoryResource newDir = shell.getCurrentDirectory(); do { shell.println(); FileResource<?> temp; if (!projectFactory.containsProject(newDir)) { temp = shell.promptFile( "Where would you like to create the project? [Press ENTER to use the current directory: " + newDir + "]", defaultDir); } else { temp = shell.promptFile("Where would you like to create the project?"); } if (!temp.exists()) { temp.mkdirs(); } newDir = newDir.createFrom(temp); if (projectFactory.containsProject(newDir)) { newDir = null; } } while ((newDir == null) || !(newDir instanceof DirectoryResource)); dir = newDir; } if (!dir.exists()) { dir.mkdirs(); } Project project = projectFactory.createProject(dir, MavenCoreFacet.class, DependencyFacet.class, MetadataFacet.class, JavaSourceFacet.class, ResourceFacet.class); MavenCoreFacet maven = project.getFacet(MavenCoreFacet.class); Model pom = maven.getPOM(); pom.setArtifactId(name); pom.setGroupId(groupId); pom.setPackaging("jar"); DependencyFacet deps = project.getFacet(DependencyFacet.class); deps.addRepository("jboss", "https://repository.jboss.org/nexus/content/groups/public/"); maven.setPOM(pom); if (createMain) { project.getFacet(JavaSourceFacet.class).saveJavaClass(JavaParser .create(JavaClass.class) .setPackage(groupId) .setName("Main") .addMethod("public static void main(String[] args) {}") .setBody("System.out.println(\"Hi there! I was forged as part of the project you call " + name + ".\");") .getOrigin()); } project.getFacet(ResourceFacet.class).createResource("<forge/>".toCharArray(), "META-INF/forge.xml"); /* * Only change the environment after success! */ shell.setCurrentResource(project.getProjectRoot()); shell.println("***SUCCESS*** Created project [" + name + "] in new working directory [" + dir + "]"); }
public void create( @Option(name = "named", description = "The name of the new project", required = true) final String name, @Option(name = "topLevelPackage", description = "The top level package for your Java source files [e.g: \"com.example.project\"] ", required = true, type = PromptType.JAVA_PACKAGE) final String groupId, @Option(name = "projectFolder", description = "The folder in which to create this project [e.g: \"~/Desktop/...\"] ", required = false) final Resource<?> projectFolder, @Option(name = "createMain", description = "Toggle creation of a simple Main() script in the root package", required = false, defaultValue = "false", flagOnly = true) final boolean createMain ) throws IOException { DirectoryResource dir = shell.getCurrentDirectory(); try { if (projectFolder instanceof FileResource<?>) { // FIXME this is ugly if (!((FileResource<?>) projectFolder).exists()) { ((FileResource<?>) projectFolder).mkdirs(); } Resource<?> parent = projectFolder.getParent(); dir = (DirectoryResource) parent.getChild(projectFolder.getName()); } else { dir = dir.getChildDirectory(name); } } catch (ResourceException e) { // ask } if (projectFactory.containsProject(dir) || !shell.promptBoolean("Use [" + dir.getFullyQualifiedName() + "] as project directory?")) { if (projectFactory.containsProject(dir)) { shell.println("***ERROR*** [" + dir.getFullyQualifiedName() + "] already contains a project; please use a different folder."); } DirectoryResource defaultDir; if (shell.getCurrentResource() == null) { defaultDir = ResourceUtil.getContextDirectory(factory.getResourceFrom(Files.getWorkingDirectory())); } else { defaultDir = shell.getCurrentDirectory(); } DirectoryResource newDir = shell.getCurrentDirectory(); do { shell.println(); FileResource<?> temp; if (!projectFactory.containsProject(newDir)) { temp = shell.promptFile( "Where would you like to create the project? [Press ENTER to use the current directory: " + newDir + "]", defaultDir); } else { temp = shell.promptFile("Where would you like to create the project?"); } if (!temp.exists()) { temp.mkdirs(); } newDir = newDir.createFrom(temp.getUnderlyingResourceObject()); if (projectFactory.containsProject(newDir)) { newDir = null; } } while ((newDir == null) || !(newDir instanceof DirectoryResource)); dir = newDir; } if (!dir.exists()) { dir.mkdirs(); } Project project = projectFactory.createProject(dir, MavenCoreFacet.class, DependencyFacet.class, MetadataFacet.class, JavaSourceFacet.class, ResourceFacet.class); MavenCoreFacet maven = project.getFacet(MavenCoreFacet.class); Model pom = maven.getPOM(); pom.setArtifactId(name); pom.setGroupId(groupId); pom.setPackaging("jar"); DependencyFacet deps = project.getFacet(DependencyFacet.class); deps.addRepository("jboss", "https://repository.jboss.org/nexus/content/groups/public/"); maven.setPOM(pom); if (createMain) { project.getFacet(JavaSourceFacet.class).saveJavaClass(JavaParser .create(JavaClass.class) .setPackage(groupId) .setName("Main") .addMethod("public static void main(String[] args) {}") .setBody("System.out.println(\"Hi there! I was forged as part of the project you call " + name + ".\");") .getOrigin()); } project.getFacet(ResourceFacet.class).createResource("<forge/>".toCharArray(), "META-INF/forge.xml"); /* * Only change the environment after success! */ shell.setCurrentResource(project.getProjectRoot()); shell.println("***SUCCESS*** Created project [" + name + "] in new working directory [" + dir + "]"); }
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java index ca6fa6cb..090b3e49 100644 --- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java +++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/internal/webapp/WebappRegistrationHelper.java @@ -1,1102 +1,1102 @@ // ======================================================================== // Copyright (c) 2009 Intalio, Inc. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // Contributors: // Hugues Malphettes - initial API and implementation // ======================================================================== package org.eclipse.jetty.osgi.boot.internal.webapp; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import org.eclipse.jetty.deploy.AppProvider; import org.eclipse.jetty.deploy.ContextDeployer; import org.eclipse.jetty.deploy.DeploymentManager; import org.eclipse.jetty.deploy.WebAppDeployer; import org.eclipse.jetty.osgi.boot.JettyBootstrapActivator; import org.eclipse.jetty.osgi.boot.OSGiAppProvider; import org.eclipse.jetty.osgi.boot.OSGiWebappConstants; import org.eclipse.jetty.osgi.boot.internal.jsp.TldLocatableURLClassloader; import org.eclipse.jetty.osgi.boot.internal.serverfactory.ServerInstanceWrapper; import org.eclipse.jetty.osgi.boot.utils.BundleClassLoaderHelper; import org.eclipse.jetty.osgi.boot.utils.BundleFileLocatorHelper; import org.eclipse.jetty.osgi.boot.utils.WebappRegistrationCustomizer; import org.eclipse.jetty.osgi.boot.utils.internal.DefaultBundleClassLoaderHelper; import org.eclipse.jetty.osgi.boot.utils.internal.DefaultFileLocatorHelper; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.handler.RequestLogHandler; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.webapp.WebAppContext; import org.eclipse.jetty.xml.XmlConfiguration; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * Bridges the jetty deployers with the OSGi lifecycle where applications are * managed inside OSGi-bundles. * <p> * This class should be called as a consequence of the activation of a new * service that is a ContextHandler.<br/> * This way the new webapps are exposed as OSGi services. * </p> * <p> * Helper methods to register a bundle that is a web-application or a context. * </p> * Limitations: * <ul> * <li>support for jarred webapps is somewhat limited.</li> * </ul> */ public class WebappRegistrationHelper { private static Logger __logger = Log.getLogger(WebappRegistrationHelper.class.getName()); private static boolean INITIALIZED = false; /** * By default set to: {@link DefaultBundleClassLoaderHelper}. It supports * equinox and apache-felix fragment bundles that are specific to an OSGi * implementation should set a different implementation. */ public static BundleClassLoaderHelper BUNDLE_CLASS_LOADER_HELPER = null; /** * By default set to: {@link DefaultBundleClassLoaderHelper}. It supports * equinox and apache-felix fragment bundles that are specific to an OSGi * implementation should set a different implementation. */ public static BundleFileLocatorHelper BUNDLE_FILE_LOCATOR_HELPER = null; /** * By default set to: {@link DefaultBundleClassLoaderHelper}. It supports * equinox and apache-felix fragment bundles that are specific to an OSGi * implementation should set a different implementation. * <p> * Several of those objects can be added here: For example we could have an optional fragment that setups * a specific implementation of JSF for the whole of jetty-osgi. * </p> */ public static Collection<WebappRegistrationCustomizer> JSP_REGISTRATION_HELPERS = new ArrayList<WebappRegistrationCustomizer>(); private Server _server; private ContextHandlerCollection _ctxtHandler; /** * this class loader loads the jars inside {$jetty.home}/lib/ext it is meant * as a migration path and for jars that are not OSGi ready. also gives * access to the jsp jars. */ // private URLClassLoader _libExtClassLoader; /** * This is the class loader that should be the parent classloader of any * webapp classloader. It is in fact the _libExtClassLoader with a trick to * let the TldScanner find the jars where the tld files are. */ private ClassLoader _commonParentClassLoaderForWebapps; private DeploymentManager _deploymentManager; private OSGiAppProvider _provider; public WebappRegistrationHelper(Server server) { _server = server; staticInit(); } public WebappRegistrationHelper(ServerInstanceWrapper wrapper, Server server) { _server = server; _commonParentClassLoaderForWebapps = wrapper.getParentClassLoaderForWebapps(); _ctxtHandler = wrapper.getContextHandlerCollection(); staticInit(); } // Inject the customizing classes that might be defined in fragment bundles. private static synchronized void staticInit() { if (!INITIALIZED) { INITIALIZED = true; // setup the custom BundleClassLoaderHelper try { BUNDLE_CLASS_LOADER_HELPER = (BundleClassLoaderHelper)Class.forName(BundleClassLoaderHelper.CLASS_NAME).newInstance(); } catch (Throwable t) { // System.err.println("support for equinox and felix"); BUNDLE_CLASS_LOADER_HELPER = new DefaultBundleClassLoaderHelper(); } // setup the custom FileLocatorHelper try { BUNDLE_FILE_LOCATOR_HELPER = (BundleFileLocatorHelper)Class.forName(BundleFileLocatorHelper.CLASS_NAME).newInstance(); } catch (Throwable t) { // System.err.println("no jsp/jasper support"); BUNDLE_FILE_LOCATOR_HELPER = new DefaultFileLocatorHelper(); } } } /** * Removes quotes around system property values before we try to make them * into file pathes. */ public static String stripQuotesIfPresent(String filePath) { if (filePath == null) return null; if ((filePath.startsWith("\"") || filePath.startsWith("'")) && (filePath.endsWith("\"") || filePath.endsWith("'"))) return filePath.substring(1,filePath.length() - 1); return filePath; } /** * Look for the home directory of jetty as defined by the system property * 'jetty.home'. If undefined, look at the current bundle and uses its own * jettyhome folder for this feature. * <p> * Special case: inside eclipse-SDK:<br/> * If the bundle is jarred, see if we are inside eclipse-PDE itself. In that * case, look for the installation directory of eclipse-PDE, try to create a * jettyhome folder there and install the sample jettyhome folder at that * location. This makes the installation in eclipse-SDK easier. <br/> * This is a bit redundant with the work done by the jetty configuration * launcher. * </p> * * @param context * @throws Exception */ public void setup(BundleContext context, Map<String, String> configProperties) throws Exception { Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false); if (enUrls != null && enUrls.hasMoreElements()) { URL url = (URL) enUrls.nextElement(); if (url != null) { //bug 317231: there is a fragment that defines the jetty configuration file. //let's use that as the jetty home. url = DefaultFileLocatorHelper.getLocalURL(url); if (url.getProtocol().equals("file")) { //ok good. File jettyxml = new File(url.toURI()); File jettyhome = jettyxml.getParentFile().getParentFile(); System.setProperty("jetty.home", jettyhome.getAbsolutePath()); } } } File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle()); // debug: // new File("~/proj/eclipse-install/eclipse-3.5.1-SDK-jetty7/" + // "dropins/jetty7/plugins/org.eclipse.jetty.osgi.boot_0.0.1.001-SNAPSHOT.jar"); boolean bootBundleCanBeJarred = true; String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home")); if (jettyHome == null || jettyHome.length() == 0) { if (_installLocation != null) { if (_installLocation.getName().endsWith(".jar")) { jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation); } if (jettyHome == null && _installLocation != null && _installLocation.isDirectory()) { jettyHome = _installLocation.getAbsolutePath() + "/jettyhome"; bootBundleCanBeJarred = false; } } } if (jettyHome == null || (!bootBundleCanBeJarred && !_installLocation.isDirectory())) { // String install = _installLocation != null?_installLocation.getCanonicalPath():" unresolved_install_location"; // throw new IllegalArgumentException("The system property -Djetty.home" + " must be set to a directory or the bundle " // + context.getBundle().getSymbolicName() + " installed here " + install + " must be unjarred."); } else { // in case we stripped the quotes. System.setProperty("jetty.home",jettyHome); } String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs")); if (jettyLogs == null || jettyLogs.length() == 0) { System.setProperty("jetty.logs",jettyHome + "/logs"); } if (jettyHome != null) { try { System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath()); } catch (Throwable t) { System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath()); } } else { // System.err.println("JETTY_HOME is not set"); } ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); try { // passing this bundle's classloader as the context classlaoder // makes sure there is access to all the jetty's bundles File jettyHomeF = jettyHome != null ? new File(jettyHome) : null; ClassLoader libExtClassLoader = null; try { libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoader(jettyHomeF,_server, JettyBootstrapActivator.class.getClassLoader()); } catch (MalformedURLException e) { e.printStackTrace(); } Thread.currentThread().setContextClassLoader(libExtClassLoader); String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml"); StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,"); Map<Object,Object> id_map = new HashMap<Object,Object>(); id_map.put("Server",_server); Map<Object,Object> properties = new HashMap<Object,Object>(); if (jettyHome != null) { properties.put("jetty.home",jettyHome); } - properties.put("jetty.host",System.getProperty("jetty.host","")); - properties.put("jetty.port",System.getProperty("jetty.port","8080")); - properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl","8443")); + properties.put("jetty.host",System.getProperty("jetty.host")); + properties.put("jetty.port",System.getProperty("jetty.port")); + properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl")); while (tokenizer.hasMoreTokens()) { String etcFile = tokenizer.nextToken().trim(); File conffile = null; enUrls = null; if (etcFile.indexOf(":") != -1) { conffile = Resource.newResource(etcFile).getFile(); } else if (etcFile.startsWith("/")) { conffile = new File(etcFile); } else if (jettyHomeF != null) { conffile = new File(jettyHomeF, etcFile); } else { int last = etcFile.lastIndexOf('/'); String path = last != -1 && last < etcFile.length() -2 ? etcFile.substring(0, last) : "/"; if (!path.startsWith("/")) { path = "/" + path; } String pattern = last != -1 && last < etcFile.length() -2 ? etcFile.substring(last+1) : etcFile; enUrls = context.getBundle().findEntries(path, pattern, false); if (pattern.equals("jetty.xml") && (enUrls == null || !enUrls.hasMoreElements())) { path = "/jettyhome" + path; pattern = "jetty-osgi-default.xml"; enUrls = context.getBundle().findEntries(path, pattern, false); System.err.println("Configuring jetty with the default embedded configuration:" + "bundle org.eclipse.jetty.boot.osgi /jettyhome/etc/jetty-osgi-default.xml"); } } if (conffile != null && !conffile.exists()) { __logger.warn("Unable to resolve the xml configuration file for jetty " + etcFile); if ("etc/jetty.xml".equals(etcFile)) { // Missing jetty.xml file, so create a minimal Jetty configuration __logger.info("Configuring default server on 8080"); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(8080); _server.addConnector(connector); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); _server.setHandler(handlers); } } else { InputStream is = null; try { // Execute a Jetty configuration file XmlConfiguration config = null; if (conffile != null && conffile.exists()) { is = new FileInputStream(conffile); config =new XmlConfiguration(is); } else if (enUrls != null && enUrls.hasMoreElements()) { URL url = (URL) enUrls.nextElement(); if (url != null) { //bug 317231: there is a fragment that defines the jetty configuration file. //let's use that as the jetty home. is = url.openStream(); config = new XmlConfiguration(is); } else { System.err.println("Could not locate " + etcFile + " inside " + context.getBundle().getSymbolicName()); continue; } } else { //it did not work. continue; } config.setIdMap(id_map); config.setProperties(properties); config.configure(); id_map=config.getIdMap(); } catch (SAXParseException saxparse) { Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse); throw saxparse; } finally { if (is != null) try { is.close(); } catch (IOException ioe) {} } } } init(); //now that we have an app provider we can call the registration customizer. try { URL[] jarsWithTlds = getJarsWithTlds(); _commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,jarsWithTlds); } catch (MalformedURLException e) { e.printStackTrace(); } _server.start(); } catch (Throwable t) { t.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(contextCl); } } /** * Must be called after the server is configured. * * Locate the actual instance of the ContextDeployer and WebAppDeployer that * was created when configuring the server through jetty.xml. If there is no * such thing it won't be possible to deploy webapps from a context and we * throw IllegalStateExceptions. */ private void init() { if (_ctxtHandler != null) { return; } // Get the context handler _ctxtHandler = (ContextHandlerCollection)_server.getChildHandlerByClass(ContextHandlerCollection.class); // get a deployerManager List<DeploymentManager> deployers = _server.getBeans(DeploymentManager.class); if (deployers != null && !deployers.isEmpty()) { _deploymentManager = deployers.get(0); for (AppProvider provider : _deploymentManager.getAppProviders()) { if (provider instanceof OSGiAppProvider) { _provider=(OSGiAppProvider)provider; break; } } if (_provider == null) { //create it on the fly with reasonable default values. try { _provider = new OSGiAppProvider(); if (System.getProperty("jetty.home") != null) { _provider.setMonitoredDir( Resource.newResource(getDefaultOSGiContextsHome( new File(System.getProperty("jetty.home"))).toURI())); } } catch (IOException e) { e.printStackTrace(); } _deploymentManager.addAppProvider(_provider); } } if (_ctxtHandler == null || _provider==null) throw new IllegalStateException("ERROR: No ContextHandlerCollection or OSGiAppProvider configured"); } /** * Deploy a new web application on the jetty server. * * @param bundle * The bundle * @param webappFolderPath * The path to the root of the webapp. Must be a path relative to * bundle; either an absolute path. * @param contextPath * The context path. Must start with "/" * @param extraClasspath * @param overrideBundleInstallLocation * @param webXmlPath * @param defaultWebXmlPath * TODO: parameter description * @return The contexthandler created and started * @throws Exception */ public ContextHandler registerWebapplication(Bundle bundle, String webappFolderPath, String contextPath, String extraClasspath, String overrideBundleInstallLocation, String webXmlPath, String defaultWebXmlPath) throws Exception { File bundleInstall = overrideBundleInstallLocation == null?BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(bundle):new File( overrideBundleInstallLocation); File webapp = null; if (webappFolderPath != null && webappFolderPath.length() != 0 && !webappFolderPath.equals(".")) { if (webappFolderPath.startsWith("/") || webappFolderPath.startsWith("file:/")) { webapp = new File(webappFolderPath); } else { webapp = new File(bundleInstall,webappFolderPath); } } else { webapp = bundleInstall; } if (!webapp.exists()) { throw new IllegalArgumentException("Unable to locate " + webappFolderPath + " inside " + (bundleInstall != null?bundleInstall.getAbsolutePath():"unlocated bundle '" + bundle.getSymbolicName() + "'")); } return registerWebapplication(bundle,webappFolderPath,webapp,contextPath,extraClasspath,bundleInstall,webXmlPath,defaultWebXmlPath); } /** * TODO: refactor this into the createContext method of OSGiAppProvider. * @see WebAppDeployer#scan() * @param contributor * @param webapp * @param contextPath * @param extraClasspath * @param bundleInstall * @param webXmlPath * @param defaultWebXmlPath * @return The contexthandler created and started * @throws Exception */ public ContextHandler registerWebapplication(Bundle contributor, String pathInBundleToWebApp, File webapp, String contextPath, String extraClasspath, File bundleInstall, String webXmlPath, String defaultWebXmlPath) throws Exception { ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); String[] oldServerClasses = null; WebAppContext context = null; try { // make sure we provide access to all the jetty bundles by going // through this bundle. OSGiWebappClassLoader composite = createWebappClassLoader(contributor); // configure with access to all jetty classes and also all the classes // that the contributor gives access to. Thread.currentThread().setContextClassLoader(composite); context = new WebAppContext(webapp.getAbsolutePath(),contextPath); context.setExtraClasspath(extraClasspath); if (webXmlPath != null && webXmlPath.length() != 0) { File webXml = null; if (webXmlPath.startsWith("/") || webXmlPath.startsWith("file:/")) { webXml = new File(webXmlPath); } else { webXml = new File(bundleInstall,webXmlPath); } if (webXml.exists()) { context.setDescriptor(webXml.getAbsolutePath()); } } if (defaultWebXmlPath == null || defaultWebXmlPath.length() == 0) { //use the one defined by the OSGiAppProvider. defaultWebXmlPath = _provider.getDefaultsDescriptor(); } if (defaultWebXmlPath != null && defaultWebXmlPath.length() != 0) { File defaultWebXml = null; if (defaultWebXmlPath.startsWith("/") || defaultWebXmlPath.startsWith("file:/")) { defaultWebXml = new File(webXmlPath); } else { defaultWebXml = new File(bundleInstall,defaultWebXmlPath); } if (defaultWebXml.exists()) { context.setDefaultsDescriptor(defaultWebXml.getAbsolutePath()); } } //other parameters that might be defines on the OSGiAppProvider: context.setParentLoaderPriority(_provider.isParentLoaderPriority()); configureWebAppContext(context,contributor); configureWebappClassLoader(contributor,context,composite); // @see // org.eclipse.jetty.webapp.JettyWebXmlConfiguration#configure(WebAppContext) // during initialization of the webapp all the jetty packages are // visible // through the webapp classloader. oldServerClasses = context.getServerClasses(); context.setServerClasses(null); _provider.addContext(contributor,pathInBundleToWebApp,context); return context; } finally { if (context != null && oldServerClasses != null) { context.setServerClasses(oldServerClasses); } Thread.currentThread().setContextClassLoader(contextCl); } } /** * Stop a ContextHandler and remove it from the collection. * * @see ContextDeployer#undeploy * @param contextHandler * @throws Exception */ public void unregister(ContextHandler contextHandler) throws Exception { contextHandler.stop(); _ctxtHandler.removeHandler(contextHandler); } /** * @return The default folder in which the context files of the osgi bundles * are located and watched. Or null when the system property * "jetty.osgi.contexts.home" is not defined. * If the configuration file defines the OSGiAppProvider's context. * This will not be taken into account. */ File getDefaultOSGiContextsHome(File jettyHome) { String jettyContextsHome = System.getProperty("jetty.osgi.contexts.home"); if (jettyContextsHome != null) { File contextsHome = new File(jettyContextsHome); if (!contextsHome.exists() || !contextsHome.isDirectory()) { throw new IllegalArgumentException("the ${jetty.osgi.contexts.home} '" + jettyContextsHome + " must exist and be a folder"); } return contextsHome; } return new File(jettyHome, "/contexts"); } File getOSGiContextsHome() { return _provider.getContextXmlDirAsFile(); } /** * This type of registration relies on jetty's complete context xml file. * Context encompasses jndi and all other things. This makes the definition * of the webapp a lot more self-contained. * * @param contributor * @param contextFileRelativePath * @param extraClasspath * @param overrideBundleInstallLocation * @return The contexthandler created and started * @throws Exception */ public ContextHandler registerContext(Bundle contributor, String contextFileRelativePath, String extraClasspath, String overrideBundleInstallLocation) throws Exception { File contextsHome = _provider.getContextXmlDirAsFile(); if (contextsHome != null) { File prodContextFile = new File(contextsHome,contributor.getSymbolicName() + "/" + contextFileRelativePath); if (prodContextFile.exists()) { return registerContext(contributor,contextFileRelativePath,prodContextFile,extraClasspath,overrideBundleInstallLocation); } } File contextFile = overrideBundleInstallLocation != null?new File(overrideBundleInstallLocation,contextFileRelativePath):new File( BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(contributor),contextFileRelativePath); if (contextFile.exists()) { return registerContext(contributor,contextFileRelativePath,contextFile,extraClasspath,overrideBundleInstallLocation); } else { if (contextFileRelativePath.startsWith("./")) { contextFileRelativePath = contextFileRelativePath.substring(1); } if (!contextFileRelativePath.startsWith("/")) { contextFileRelativePath = "/" + contextFileRelativePath; } File overrideBundleInstallLocationF = overrideBundleInstallLocation != null ? Resource.newResource(overrideBundleInstallLocation).getFile() : null; if (overrideBundleInstallLocationF == null) { URL contextURL = contributor.getEntry(contextFileRelativePath); if (contextURL != null) { return registerContext(contributor,contextFileRelativePath,contextURL.openStream(),extraClasspath,overrideBundleInstallLocation); } } else { JarFile zipFile = null; try { zipFile = new JarFile(overrideBundleInstallLocation); ZipEntry entry = zipFile.getEntry(contextFileRelativePath.substring(1)); return registerContext(contributor,contextFileRelativePath,zipFile.getInputStream(entry),extraClasspath,overrideBundleInstallLocation); } catch (Throwable t) { } finally { if (zipFile != null) try { zipFile.close(); } catch (IOException ioe) { } } } throw new IllegalArgumentException("Could not find the context " + "file " + contextFileRelativePath + " for the bundle " + contributor.getSymbolicName() + (overrideBundleInstallLocation != null?" using the install location " + overrideBundleInstallLocation:"")); } } /** * This type of registration relies on jetty's complete context xml file. * Context encompasses jndi and all other things. This makes the definition * of the webapp a lot more self-contained. * * @param webapp * @param contextPath * @param classInBundle * @throws Exception */ private ContextHandler registerContext(Bundle contributor, String pathInBundle, File contextFile, String extraClasspath, String overrideBundleInstallLocation) throws Exception { InputStream contextFileInputStream = null; try { contextFileInputStream = new BufferedInputStream(new FileInputStream(contextFile)); return registerContext(contributor, pathInBundle, contextFileInputStream,extraClasspath,overrideBundleInstallLocation); } finally { if (contextFileInputStream != null) try { contextFileInputStream.close(); } catch (IOException ioe) { } } } /** * @param contributor * @param contextFileInputStream * @return The ContextHandler created and registered or null if it did not * happen. * @throws Exception */ private ContextHandler registerContext(Bundle contributor, String pathInsideBundle, InputStream contextFileInputStream, String extraClasspath, String overrideBundleInstallLocation) throws Exception { ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); String[] oldServerClasses = null; WebAppContext webAppContext = null; try { // make sure we provide access to all the jetty bundles by going // through this bundle. OSGiWebappClassLoader composite = createWebappClassLoader(contributor); // configure with access to all jetty classes and also all the // classes // that the contributor gives access to. Thread.currentThread().setContextClassLoader(composite); ContextHandler context = createContextHandler(contributor,contextFileInputStream,extraClasspath,overrideBundleInstallLocation); if (context == null) { return null;// did not happen } // ok now register this webapp. we checked when we started jetty // that there // was at least one such handler for webapps. //the actual registration must happen via the new Deployment API. // _ctxtHandler.addHandler(context); configureWebappClassLoader(contributor,context,composite); if (context instanceof WebAppContext) { webAppContext = (WebAppContext)context; // @see // org.eclipse.jetty.webapp.JettyWebXmlConfiguration#configure(WebAppContext) oldServerClasses = webAppContext.getServerClasses(); webAppContext.setServerClasses(null); } _provider.addContext(contributor, pathInsideBundle, context); return context; } finally { if (webAppContext != null) { webAppContext.setServerClasses(oldServerClasses); } Thread.currentThread().setContextClassLoader(contextCl); } } /** * TODO: right now only the jetty-jsp bundle is scanned for common taglibs. * Should support a way to plug more bundles that contain taglibs. * * The jasper TldScanner expects a URLClassloader to parse a jar for the * /META-INF/*.tld it may contain. We place the bundles that we know contain * such tag-libraries. Please note that it will work if and only if the * bundle is a jar (!) Currently we just hardcode the bundle that contains * the jstl implemenation. * * A workaround when the tld cannot be parsed with this method is to copy * and paste it inside the WEB-INF of the webapplication where it is used. * * Support only 2 types of packaging for the bundle: - the bundle is a jar * (recommended for runtime.) - the bundle is a folder and contain jars in * the root and/or in the lib folder (nice for PDE developement situations) * Unsupported: the bundle is a jar that embeds more jars. * * @return * @throws Exception */ private URL[] getJarsWithTlds() throws Exception { ArrayList<URL> res = new ArrayList<URL>(); for (WebappRegistrationCustomizer regCustomizer : JSP_REGISTRATION_HELPERS) { URL[] urls = regCustomizer.getJarsWithTlds(_provider, BUNDLE_FILE_LOCATOR_HELPER); for (URL url : urls) { if (!res.contains(url)) res.add(url); } } if (!res.isEmpty()) return res.toArray(new URL[res.size()]); else return null; } /** * Applies the properties of WebAppDeployer as defined in jetty.xml. * * @see {WebAppDeployer#scan} around the comment * <code>// configure it</code> */ protected void configureWebAppContext(WebAppContext wah, Bundle contributor) { // rfc66 wah.setAttribute(OSGiWebappConstants.RFC66_OSGI_BUNDLE_CONTEXT,contributor.getBundleContext()); //spring-dm-1.2.1 looks for the BundleContext as a different attribute. //not a spec... but if we want to support //org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext //then we need to do this to: wah.setAttribute("org.springframework.osgi.web." + BundleContext.class.getName(), contributor.getBundleContext()); } /** * @See {@link ContextDeployer#scan} * @param contextFile * @return */ protected ContextHandler createContextHandler(Bundle bundle, File contextFile, String extraClasspath, String overrideBundleInstallLocation) { try { return createContextHandler(bundle,new BufferedInputStream(new FileInputStream(contextFile)),extraClasspath,overrideBundleInstallLocation); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } /** * @See {@link ContextDeployer#scan} * @param contextFile * @return */ @SuppressWarnings("unchecked") protected ContextHandler createContextHandler(Bundle bundle, InputStream contextInputStream, String extraClasspath, String overrideBundleInstallLocation) { /* * Do something identical to what the ContextProvider would have done: * XmlConfiguration xmlConfiguration=new * XmlConfiguration(resource.getURL()); HashMap properties = new * HashMap(); properties.put("Server", _contexts.getServer()); if * (_configMgr!=null) properties.putAll(_configMgr.getProperties()); * * xmlConfiguration.setProperties(properties); ContextHandler * context=(ContextHandler)xmlConfiguration.configure(); * context.setAttributes(new AttributesMap(_contextAttributes)); */ try { XmlConfiguration xmlConfiguration = new XmlConfiguration(contextInputStream); HashMap properties = new HashMap(); properties.put("Server",_server); // insert the bundle's location as a property. setThisBundleHomeProperty(bundle,properties,overrideBundleInstallLocation); xmlConfiguration.setProperties(properties); ContextHandler context = (ContextHandler)xmlConfiguration.configure(); if (context instanceof WebAppContext) { ((WebAppContext)context).setExtraClasspath(extraClasspath); ((WebAppContext)context).setParentLoaderPriority(_provider.isParentLoaderPriority()); if (_provider.getDefaultsDescriptor() != null && _provider.getDefaultsDescriptor().length() != 0) { ((WebAppContext)context).setDefaultsDescriptor(_provider.getDefaultsDescriptor()); } } // rfc-66: context.setAttribute(OSGiWebappConstants.RFC66_OSGI_BUNDLE_CONTEXT,bundle.getBundleContext()); //spring-dm-1.2.1 looks for the BundleContext as a different attribute. //not a spec... but if we want to support //org.springframework.osgi.web.context.support.OsgiBundleXmlWebApplicationContext //then we need to do this to: context.setAttribute("org.springframework.osgi.web." + BundleContext.class.getName(), bundle.getBundleContext()); return context; } catch (FileNotFoundException e) { return null; } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (contextInputStream != null) try { contextInputStream.close(); } catch (IOException ioe) { } } return null; } /** * Configure a classloader onto the context. If the context is a * WebAppContext, build a WebAppClassLoader that has access to all the jetty * classes thanks to the classloader of the JettyBootStrapper bundle and * also has access to the classloader of the bundle that defines this * context. * <p> * If the context is not a WebAppContext, same but with a simpler * URLClassLoader. Note that the URLClassLoader is pretty much fake: it * delegate all actual classloading to the parent classloaders. * </p> * <p> * The URL[] returned by the URLClassLoader create contained specifically * the jars that some j2ee tools expect and look into. For example the jars * that contain tld files for jasper's jstl support. * </p> * <p> * Also as the jars in the lib folder and the classes in the classes folder * might already be in the OSGi classloader we filter them out of the * WebAppClassLoader * </p> * * @param context * @param contributor * @param webapp * @param contextPath * @param classInBundle * @throws Exception */ protected void configureWebappClassLoader(Bundle contributor, ContextHandler context, OSGiWebappClassLoader webappClassLoader) throws Exception { if (context instanceof WebAppContext) { WebAppContext webappCtxt = (WebAppContext)context; context.setClassLoader(webappClassLoader); webappClassLoader.setWebappContext(webappCtxt); } else { context.setClassLoader(webappClassLoader); } } /** * No matter what the type of webapp, we create a WebappClassLoader. */ protected OSGiWebappClassLoader createWebappClassLoader(Bundle contributor) throws Exception { // we use a temporary WebAppContext object. // if this is a real webapp we will set it on it a bit later: once we // know. OSGiWebappClassLoader webappClassLoader = new OSGiWebappClassLoader(_commonParentClassLoaderForWebapps,new WebAppContext(),contributor); return webappClassLoader; } /** * Set the property &quot;this.bundle.install&quot; to point to the location * of the bundle. Useful when <SystemProperty name="this.bundle.home"/> is * used. */ private void setThisBundleHomeProperty(Bundle bundle, HashMap<String, Object> properties, String overrideBundleInstallLocation) { try { File location = overrideBundleInstallLocation != null?new File(overrideBundleInstallLocation):BUNDLE_FILE_LOCATOR_HELPER .getBundleInstallLocation(bundle); properties.put("this.bundle.install",location.getCanonicalPath()); } catch (Throwable t) { System.err.println("Unable to set 'this.bundle.install' " + " for the bundle " + bundle.getSymbolicName()); t.printStackTrace(); } } }
true
true
public void setup(BundleContext context, Map<String, String> configProperties) throws Exception { Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false); if (enUrls != null && enUrls.hasMoreElements()) { URL url = (URL) enUrls.nextElement(); if (url != null) { //bug 317231: there is a fragment that defines the jetty configuration file. //let's use that as the jetty home. url = DefaultFileLocatorHelper.getLocalURL(url); if (url.getProtocol().equals("file")) { //ok good. File jettyxml = new File(url.toURI()); File jettyhome = jettyxml.getParentFile().getParentFile(); System.setProperty("jetty.home", jettyhome.getAbsolutePath()); } } } File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle()); // debug: // new File("~/proj/eclipse-install/eclipse-3.5.1-SDK-jetty7/" + // "dropins/jetty7/plugins/org.eclipse.jetty.osgi.boot_0.0.1.001-SNAPSHOT.jar"); boolean bootBundleCanBeJarred = true; String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home")); if (jettyHome == null || jettyHome.length() == 0) { if (_installLocation != null) { if (_installLocation.getName().endsWith(".jar")) { jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation); } if (jettyHome == null && _installLocation != null && _installLocation.isDirectory()) { jettyHome = _installLocation.getAbsolutePath() + "/jettyhome"; bootBundleCanBeJarred = false; } } } if (jettyHome == null || (!bootBundleCanBeJarred && !_installLocation.isDirectory())) { // String install = _installLocation != null?_installLocation.getCanonicalPath():" unresolved_install_location"; // throw new IllegalArgumentException("The system property -Djetty.home" + " must be set to a directory or the bundle " // + context.getBundle().getSymbolicName() + " installed here " + install + " must be unjarred."); } else { // in case we stripped the quotes. System.setProperty("jetty.home",jettyHome); } String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs")); if (jettyLogs == null || jettyLogs.length() == 0) { System.setProperty("jetty.logs",jettyHome + "/logs"); } if (jettyHome != null) { try { System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath()); } catch (Throwable t) { System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath()); } } else { // System.err.println("JETTY_HOME is not set"); } ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); try { // passing this bundle's classloader as the context classlaoder // makes sure there is access to all the jetty's bundles File jettyHomeF = jettyHome != null ? new File(jettyHome) : null; ClassLoader libExtClassLoader = null; try { libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoader(jettyHomeF,_server, JettyBootstrapActivator.class.getClassLoader()); } catch (MalformedURLException e) { e.printStackTrace(); } Thread.currentThread().setContextClassLoader(libExtClassLoader); String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml"); StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,"); Map<Object,Object> id_map = new HashMap<Object,Object>(); id_map.put("Server",_server); Map<Object,Object> properties = new HashMap<Object,Object>(); if (jettyHome != null) { properties.put("jetty.home",jettyHome); } properties.put("jetty.host",System.getProperty("jetty.host","")); properties.put("jetty.port",System.getProperty("jetty.port","8080")); properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl","8443")); while (tokenizer.hasMoreTokens()) { String etcFile = tokenizer.nextToken().trim(); File conffile = null; enUrls = null; if (etcFile.indexOf(":") != -1) { conffile = Resource.newResource(etcFile).getFile(); } else if (etcFile.startsWith("/")) { conffile = new File(etcFile); } else if (jettyHomeF != null) { conffile = new File(jettyHomeF, etcFile); } else { int last = etcFile.lastIndexOf('/'); String path = last != -1 && last < etcFile.length() -2 ? etcFile.substring(0, last) : "/"; if (!path.startsWith("/")) { path = "/" + path; } String pattern = last != -1 && last < etcFile.length() -2 ? etcFile.substring(last+1) : etcFile; enUrls = context.getBundle().findEntries(path, pattern, false); if (pattern.equals("jetty.xml") && (enUrls == null || !enUrls.hasMoreElements())) { path = "/jettyhome" + path; pattern = "jetty-osgi-default.xml"; enUrls = context.getBundle().findEntries(path, pattern, false); System.err.println("Configuring jetty with the default embedded configuration:" + "bundle org.eclipse.jetty.boot.osgi /jettyhome/etc/jetty-osgi-default.xml"); } } if (conffile != null && !conffile.exists()) { __logger.warn("Unable to resolve the xml configuration file for jetty " + etcFile); if ("etc/jetty.xml".equals(etcFile)) { // Missing jetty.xml file, so create a minimal Jetty configuration __logger.info("Configuring default server on 8080"); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(8080); _server.addConnector(connector); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); _server.setHandler(handlers); } } else { InputStream is = null; try { // Execute a Jetty configuration file XmlConfiguration config = null; if (conffile != null && conffile.exists()) { is = new FileInputStream(conffile); config =new XmlConfiguration(is); } else if (enUrls != null && enUrls.hasMoreElements()) { URL url = (URL) enUrls.nextElement(); if (url != null) { //bug 317231: there is a fragment that defines the jetty configuration file. //let's use that as the jetty home. is = url.openStream(); config = new XmlConfiguration(is); } else { System.err.println("Could not locate " + etcFile + " inside " + context.getBundle().getSymbolicName()); continue; } } else { //it did not work. continue; } config.setIdMap(id_map); config.setProperties(properties); config.configure(); id_map=config.getIdMap(); } catch (SAXParseException saxparse) { Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse); throw saxparse; } finally { if (is != null) try { is.close(); } catch (IOException ioe) {} } } } init(); //now that we have an app provider we can call the registration customizer. try { URL[] jarsWithTlds = getJarsWithTlds(); _commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,jarsWithTlds); } catch (MalformedURLException e) { e.printStackTrace(); } _server.start(); } catch (Throwable t) { t.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(contextCl); } }
public void setup(BundleContext context, Map<String, String> configProperties) throws Exception { Enumeration<?> enUrls = context.getBundle().findEntries("/etc", "jetty.xml", false); if (enUrls != null && enUrls.hasMoreElements()) { URL url = (URL) enUrls.nextElement(); if (url != null) { //bug 317231: there is a fragment that defines the jetty configuration file. //let's use that as the jetty home. url = DefaultFileLocatorHelper.getLocalURL(url); if (url.getProtocol().equals("file")) { //ok good. File jettyxml = new File(url.toURI()); File jettyhome = jettyxml.getParentFile().getParentFile(); System.setProperty("jetty.home", jettyhome.getAbsolutePath()); } } } File _installLocation = BUNDLE_FILE_LOCATOR_HELPER.getBundleInstallLocation(context.getBundle()); // debug: // new File("~/proj/eclipse-install/eclipse-3.5.1-SDK-jetty7/" + // "dropins/jetty7/plugins/org.eclipse.jetty.osgi.boot_0.0.1.001-SNAPSHOT.jar"); boolean bootBundleCanBeJarred = true; String jettyHome = stripQuotesIfPresent(System.getProperty("jetty.home")); if (jettyHome == null || jettyHome.length() == 0) { if (_installLocation != null) { if (_installLocation.getName().endsWith(".jar")) { jettyHome = JettyHomeHelper.setupJettyHomeInEclipsePDE(_installLocation); } if (jettyHome == null && _installLocation != null && _installLocation.isDirectory()) { jettyHome = _installLocation.getAbsolutePath() + "/jettyhome"; bootBundleCanBeJarred = false; } } } if (jettyHome == null || (!bootBundleCanBeJarred && !_installLocation.isDirectory())) { // String install = _installLocation != null?_installLocation.getCanonicalPath():" unresolved_install_location"; // throw new IllegalArgumentException("The system property -Djetty.home" + " must be set to a directory or the bundle " // + context.getBundle().getSymbolicName() + " installed here " + install + " must be unjarred."); } else { // in case we stripped the quotes. System.setProperty("jetty.home",jettyHome); } String jettyLogs = stripQuotesIfPresent(System.getProperty("jetty.logs")); if (jettyLogs == null || jettyLogs.length() == 0) { System.setProperty("jetty.logs",jettyHome + "/logs"); } if (jettyHome != null) { try { System.err.println("JETTY_HOME set to " + new File(jettyHome).getCanonicalPath()); } catch (Throwable t) { System.err.println("JETTY_HOME _set to " + new File(jettyHome).getAbsolutePath()); } } else { // System.err.println("JETTY_HOME is not set"); } ClassLoader contextCl = Thread.currentThread().getContextClassLoader(); try { // passing this bundle's classloader as the context classlaoder // makes sure there is access to all the jetty's bundles File jettyHomeF = jettyHome != null ? new File(jettyHome) : null; ClassLoader libExtClassLoader = null; try { libExtClassLoader = LibExtClassLoaderHelper.createLibEtcClassLoader(jettyHomeF,_server, JettyBootstrapActivator.class.getClassLoader()); } catch (MalformedURLException e) { e.printStackTrace(); } Thread.currentThread().setContextClassLoader(libExtClassLoader); String jettyetc = System.getProperty(OSGiWebappConstants.SYS_PROP_JETTY_ETC_FILES,"etc/jetty.xml"); StringTokenizer tokenizer = new StringTokenizer(jettyetc,";,"); Map<Object,Object> id_map = new HashMap<Object,Object>(); id_map.put("Server",_server); Map<Object,Object> properties = new HashMap<Object,Object>(); if (jettyHome != null) { properties.put("jetty.home",jettyHome); } properties.put("jetty.host",System.getProperty("jetty.host")); properties.put("jetty.port",System.getProperty("jetty.port")); properties.put("jetty.port.ssl",System.getProperty("jetty.port.ssl")); while (tokenizer.hasMoreTokens()) { String etcFile = tokenizer.nextToken().trim(); File conffile = null; enUrls = null; if (etcFile.indexOf(":") != -1) { conffile = Resource.newResource(etcFile).getFile(); } else if (etcFile.startsWith("/")) { conffile = new File(etcFile); } else if (jettyHomeF != null) { conffile = new File(jettyHomeF, etcFile); } else { int last = etcFile.lastIndexOf('/'); String path = last != -1 && last < etcFile.length() -2 ? etcFile.substring(0, last) : "/"; if (!path.startsWith("/")) { path = "/" + path; } String pattern = last != -1 && last < etcFile.length() -2 ? etcFile.substring(last+1) : etcFile; enUrls = context.getBundle().findEntries(path, pattern, false); if (pattern.equals("jetty.xml") && (enUrls == null || !enUrls.hasMoreElements())) { path = "/jettyhome" + path; pattern = "jetty-osgi-default.xml"; enUrls = context.getBundle().findEntries(path, pattern, false); System.err.println("Configuring jetty with the default embedded configuration:" + "bundle org.eclipse.jetty.boot.osgi /jettyhome/etc/jetty-osgi-default.xml"); } } if (conffile != null && !conffile.exists()) { __logger.warn("Unable to resolve the xml configuration file for jetty " + etcFile); if ("etc/jetty.xml".equals(etcFile)) { // Missing jetty.xml file, so create a minimal Jetty configuration __logger.info("Configuring default server on 8080"); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(8080); _server.addConnector(connector); HandlerCollection handlers = new HandlerCollection(); ContextHandlerCollection contexts = new ContextHandlerCollection(); RequestLogHandler requestLogHandler = new RequestLogHandler(); handlers.setHandlers(new Handler[] { contexts, new DefaultHandler(), requestLogHandler }); _server.setHandler(handlers); } } else { InputStream is = null; try { // Execute a Jetty configuration file XmlConfiguration config = null; if (conffile != null && conffile.exists()) { is = new FileInputStream(conffile); config =new XmlConfiguration(is); } else if (enUrls != null && enUrls.hasMoreElements()) { URL url = (URL) enUrls.nextElement(); if (url != null) { //bug 317231: there is a fragment that defines the jetty configuration file. //let's use that as the jetty home. is = url.openStream(); config = new XmlConfiguration(is); } else { System.err.println("Could not locate " + etcFile + " inside " + context.getBundle().getSymbolicName()); continue; } } else { //it did not work. continue; } config.setIdMap(id_map); config.setProperties(properties); config.configure(); id_map=config.getIdMap(); } catch (SAXParseException saxparse) { Log.getLogger(WebappRegistrationHelper.class.getName()).warn("Unable to configure the jetty/etc file " + etcFile,saxparse); throw saxparse; } finally { if (is != null) try { is.close(); } catch (IOException ioe) {} } } } init(); //now that we have an app provider we can call the registration customizer. try { URL[] jarsWithTlds = getJarsWithTlds(); _commonParentClassLoaderForWebapps = jarsWithTlds == null?libExtClassLoader:new TldLocatableURLClassloader(libExtClassLoader,jarsWithTlds); } catch (MalformedURLException e) { e.printStackTrace(); } _server.start(); } catch (Throwable t) { t.printStackTrace(); } finally { Thread.currentThread().setContextClassLoader(contextCl); } }
diff --git a/src/main/java/com/typesafe/config/impl/ConfigUtil.java b/src/main/java/com/typesafe/config/impl/ConfigUtil.java index 65ae09a..fff540e 100644 --- a/src/main/java/com/typesafe/config/impl/ConfigUtil.java +++ b/src/main/java/com/typesafe/config/impl/ConfigUtil.java @@ -1,118 +1,118 @@ package com.typesafe.config.impl; /** This is public just for the "config" package to use, don't touch it */ final public class ConfigUtil { static boolean equalsHandlingNull(Object a, Object b) { if (a == null && b != null) return false; else if (a != null && b == null) return false; else if (a == b) // catches null == null plus optimizes identity case return true; else return a.equals(b); } static String renderJsonString(String s) { StringBuilder sb = new StringBuilder(); sb.append('"'); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); switch (c) { case '"': sb.append("\\\""); break; case '\\': sb.append("\\\\"); break; case '\n': sb.append("\\n"); break; case '\b': sb.append("\\b"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; default: if (Character.isISOControl(c)) sb.append(String.format("\\u%04x", (int) c)); else sb.append(c); } } sb.append('"'); return sb.toString(); } static boolean isWhitespace(int codepoint) { switch (codepoint) { // try to hit the most common ASCII ones first, then the nonbreaking // spaces that Java brokenly leaves out of isWhitespace. case ' ': case '\n': case '\u00A0': case '\u2007': case '\u202F': return true; default: return Character.isWhitespace(codepoint); } } /** This is public just for the "config" package to use, don't touch it! */ public static String unicodeTrim(String s) { // this is dumb because it looks like there aren't any whitespace // characters that need surrogate encoding. But, points for // pedantic correctness! It's future-proof or something. // String.trim() actually is broken, since there are plenty of // non-ASCII whitespace characters. final int length = s.length(); if (length == 0) return s; int start = 0; - while (true) { + while (start < length) { char c = s.charAt(start); if (c == ' ' || c == '\n') { start += 1; } else { int cp = s.codePointAt(start); if (isWhitespace(cp)) start += Character.charCount(cp); else break; } } int end = length; - while (true) { + while (end > start) { char c = s.charAt(end - 1); if (c == ' ' || c == '\n') { --end; } else { int cp; int delta; if (Character.isLowSurrogate(c)) { cp = s.codePointAt(end - 2); delta = 2; } else { cp = s.codePointAt(end - 1); delta = 1; } if (isWhitespace(cp)) end -= delta; else break; } } return s.substring(start, end); } }
false
true
public static String unicodeTrim(String s) { // this is dumb because it looks like there aren't any whitespace // characters that need surrogate encoding. But, points for // pedantic correctness! It's future-proof or something. // String.trim() actually is broken, since there are plenty of // non-ASCII whitespace characters. final int length = s.length(); if (length == 0) return s; int start = 0; while (true) { char c = s.charAt(start); if (c == ' ' || c == '\n') { start += 1; } else { int cp = s.codePointAt(start); if (isWhitespace(cp)) start += Character.charCount(cp); else break; } } int end = length; while (true) { char c = s.charAt(end - 1); if (c == ' ' || c == '\n') { --end; } else { int cp; int delta; if (Character.isLowSurrogate(c)) { cp = s.codePointAt(end - 2); delta = 2; } else { cp = s.codePointAt(end - 1); delta = 1; } if (isWhitespace(cp)) end -= delta; else break; } } return s.substring(start, end); }
public static String unicodeTrim(String s) { // this is dumb because it looks like there aren't any whitespace // characters that need surrogate encoding. But, points for // pedantic correctness! It's future-proof or something. // String.trim() actually is broken, since there are plenty of // non-ASCII whitespace characters. final int length = s.length(); if (length == 0) return s; int start = 0; while (start < length) { char c = s.charAt(start); if (c == ' ' || c == '\n') { start += 1; } else { int cp = s.codePointAt(start); if (isWhitespace(cp)) start += Character.charCount(cp); else break; } } int end = length; while (end > start) { char c = s.charAt(end - 1); if (c == ' ' || c == '\n') { --end; } else { int cp; int delta; if (Character.isLowSurrogate(c)) { cp = s.codePointAt(end - 2); delta = 2; } else { cp = s.codePointAt(end - 1); delta = 1; } if (isWhitespace(cp)) end -= delta; else break; } } return s.substring(start, end); }
diff --git a/src/jpcsp/graphics/RE/software/RendererTemplate.java b/src/jpcsp/graphics/RE/software/RendererTemplate.java index acf7c913..b240a3ef 100644 --- a/src/jpcsp/graphics/RE/software/RendererTemplate.java +++ b/src/jpcsp/graphics/RE/software/RendererTemplate.java @@ -1,1574 +1,1575 @@ /* This file is part of jpcsp. Jpcsp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Jpcsp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Jpcsp. If not, see <http://www.gnu.org/licenses/>. */ package jpcsp.graphics.RE.software; import static jpcsp.graphics.GeCommands.LMODE_SEPARATE_SPECULAR_COLOR; import static jpcsp.graphics.GeCommands.SOP_REPLACE_STENCIL_VALUE; import static jpcsp.graphics.GeCommands.TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888; import static jpcsp.graphics.RE.software.ColorDoubling.doubleColor; import static jpcsp.graphics.RE.software.PixelColor.ONE; import static jpcsp.graphics.RE.software.PixelColor.ZERO; import static jpcsp.graphics.RE.software.PixelColor.absBGR; import static jpcsp.graphics.RE.software.PixelColor.add; import static jpcsp.graphics.RE.software.PixelColor.addBGR; import static jpcsp.graphics.RE.software.PixelColor.combineComponent; import static jpcsp.graphics.RE.software.PixelColor.getAlpha; import static jpcsp.graphics.RE.software.PixelColor.getBlue; import static jpcsp.graphics.RE.software.PixelColor.getColor; import static jpcsp.graphics.RE.software.PixelColor.getColorBGR; import static jpcsp.graphics.RE.software.PixelColor.getGreen; import static jpcsp.graphics.RE.software.PixelColor.getRed; import static jpcsp.graphics.RE.software.PixelColor.maxBGR; import static jpcsp.graphics.RE.software.PixelColor.minBGR; import static jpcsp.graphics.RE.software.PixelColor.multiply; import static jpcsp.graphics.RE.software.PixelColor.multiplyBGR; import static jpcsp.graphics.RE.software.PixelColor.multiplyComponent; import static jpcsp.graphics.RE.software.PixelColor.setAlpha; import static jpcsp.graphics.RE.software.PixelColor.setBGR; import static jpcsp.graphics.RE.software.PixelColor.substractBGR; import static jpcsp.graphics.RE.software.TextureReader.pixelToTexel; import static jpcsp.graphics.RE.software.TextureWrap.wrap; import static jpcsp.util.Utilities.dot3; import static jpcsp.util.Utilities.max; import static jpcsp.util.Utilities.min; import static jpcsp.util.Utilities.normalize3; import static jpcsp.util.Utilities.round; import jpcsp.graphics.GeCommands; import jpcsp.graphics.VideoEngine; import jpcsp.graphics.RE.software.Rasterizer.Range; import jpcsp.util.DurationStatistics; /** * @author gid15 * */ public class RendererTemplate { public static boolean hasMemInt; public static boolean needSourceDepthRead; public static boolean needDestinationDepthRead; public static boolean needDepthWrite; public static boolean needTextureUV; public static boolean needScissoringX; public static boolean needScissoringY; public static boolean transform2D; public static boolean clearMode; public static boolean clearModeColor; public static boolean clearModeStencil; public static boolean clearModeDepth; public static int nearZ; public static int farZ; public static boolean colorTestFlagEnabled; public static int colorTestFunc; public static boolean alphaTestFlagEnabled; public static int alphaFunc; public static int alphaRef; public static boolean stencilTestFlagEnabled; public static int stencilFunc; public static int stencilRef; public static int stencilOpFail; public static int stencilOpZFail; public static int stencilOpZPass; public static boolean depthTestFlagEnabled; public static int depthFunc; public static boolean blendFlagEnabled; public static int blendEquation; public static int blendSrc; public static int blendDst; public static int sfix; public static int dfix; public static boolean colorLogicOpFlagEnabled; public static int logicOp; public static int colorMask; public static boolean depthMask; public static boolean textureFlagEnabled; public static boolean useVertexTexture; public static boolean lightingFlagEnabled; public static boolean sameVertexColor; public static boolean setVertexPrimaryColor; public static boolean primaryColorSetGlobally; public static boolean isTriangle; public static boolean matFlagAmbient; public static boolean matFlagDiffuse; public static boolean matFlagSpecular; public static boolean useVertexColor; public static boolean textureColorDoubled; public static int lightMode; public static int texMapMode; public static int texProjMapMode; public static float texTranslateX; public static float texTranslateY; public static float texScaleX; public static float texScaleY; public static int texWrapS; public static int texWrapT; public static int textureFunc; public static boolean textureAlphaUsed; public static int psm; public static boolean isLogTraceEnabled; public static boolean collectStatistics; private static DurationStatistics statistics; public RendererTemplate() { if (collectStatistics) { if (statistics == null) { statistics = new DurationStatistics(String.format("Duration %s", getClass().getName())); } } } public DurationStatistics getStatistics() { return statistics; } public void render(final BasePrimitiveRenderer renderer) { doRender(renderer); } private static void doRenderStart(final BasePrimitiveRenderer renderer) { if (isLogTraceEnabled) { final PrimitiveState prim = renderer.prim; String comment; if (isTriangle) { if (transform2D) { comment = "Triangle doRender 2D"; } else { comment = "Triangle doRender 3D"; } } else { if (transform2D) { comment = "Sprite doRender 2D"; } else { comment = "Sprite doRender 3D"; } } VideoEngine.log.trace(String.format("%s (%d,%d)-(%d,%d) skip=%d", comment, prim.pxMin, prim.pyMin, prim.pxMax, prim.pyMax, renderer.imageWriterSkipEOL)); } renderer.preRender(); if (collectStatistics) { if (isTriangle) { if (transform2D) { RESoftware.triangleRender2DStatistics.start(); } else { RESoftware.triangleRender3DStatistics.start(); } } else { RESoftware.spriteRenderStatistics.start(); } statistics.start(); } } private static void doRenderEnd(final BasePrimitiveRenderer renderer) { if (collectStatistics) { statistics.end(); if (isTriangle) { if (transform2D) { RESoftware.triangleRender2DStatistics.end(); } else { RESoftware.triangleRender3DStatistics.end(); } } else { RESoftware.spriteRenderStatistics.end(); } } renderer.postRender(); } private static void doRender(final BasePrimitiveRenderer renderer) { final PixelState pixel = renderer.pixel; final PrimitiveState prim = renderer.prim; final IRendererWriter rendererWriter = renderer.rendererWriter; final IRandomTextureAccess textureAccess = renderer.textureAccess; doRenderStart(renderer); int stencilRefAlpha = 0; if (stencilTestFlagEnabled && !clearMode && stencilRef != 0) { if (stencilOpFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZPass == SOP_REPLACE_STENCIL_VALUE) { // Prepare stencilRef as a ready-to-use alpha value stencilRefAlpha = renderer.stencilRef << 24; } } int notColorMask = 0xFFFFFFFF; if (!clearMode && colorMask != 0x00000000) { notColorMask = ~renderer.colorMask; } int alpha, a, b, g, r; final int textureWidthMask = renderer.textureWidth - 1; final int textureHeightMask = renderer.textureHeight - 1; final float textureWidthFloat = renderer.textureWidth; final float textureHeightFloat = renderer.textureHeight; final int alphaRef = renderer.alphaRef; final int sourceDepth = (int) prim.p2z; float v = prim.vStart; float u = 0f; Range range = null; Rasterizer rasterizer = null; float t1uw = 0f; float t1vw = 0f; float t2uw = 0f; float t2vw = 0f; float t3uw = 0f; float t3vw = 0f; if (isTriangle) { if (!transform2D) { t1uw = prim.t1u * prim.p1wInverted; t1vw = prim.t1v * prim.p1wInverted; t2uw = prim.t2u * prim.p2wInverted; t2vw = prim.t2v * prim.p2wInverted; t3uw = prim.t3u * prim.p3wInverted; t3vw = prim.t3v * prim.p3wInverted; } range = new Range(); // No need to use a Rasterizer when rendering very small area. // The overhead of the Rasterizer would lead to slower rendering. if (prim.destinationWidth >= Rasterizer.MINIMUM_WIDTH && prim.destinationHeight >= Rasterizer.MINIMUM_HEIGHT) { rasterizer = new Rasterizer(prim.p1x, prim.p1y, prim.p2x, prim.p2y, prim.p3x, prim.p3y, prim.pyMin, prim.pyMax); rasterizer.setY(prim.pyMin); } } int fbIndex = 0; int depthIndex = 0; int depthOffset = 0; final int[] memInt = renderer.memInt; if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex = renderer.fbAddress >> 2; depthIndex = renderer.depthAddress >> 2; depthOffset = (renderer.depthAddress >> 1) & 1; } // Use local variables instead of "pixel" members. // The Java JIT is then producing a slightly faster code. int pixelSource = pixel.source; int pixelSourceDepth = pixel.sourceDepth; int pixelDestination = 0; int pixelDestinationDepth = 0; int pixelPrimaryColor = pixel.primaryColor; int pixelSecondaryColor = pixel.secondaryColor; int pixelX = 0; int pixelY = 0; float pixelU = 0f; float pixelV = 0f; for (int y = prim.pyMin; y <= prim.pyMax; y++) { pixelY = y; int startX = prim.pxMin; int endX = prim.pxMax; if (isTriangle && rasterizer != null) { rasterizer.getNextRange(range); startX = max(range.xMin, startX); endX = min(range.xMax, endX); if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Rasterizer line (%d-%d,%d)", startX, endX, pixelY)); } } if (isTriangle && startX > endX) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex += prim.destinationWidth + renderer.imageWriterSkipEOL; if (needDepthWrite || needDestinationDepthRead) { depthOffset += prim.destinationWidth + renderer.depthWriterSkipEOL; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(prim.destinationWidth + renderer.imageWriterSkipEOL, prim.destinationWidth + renderer.depthWriterSkipEOL); } } else { if (needTextureUV && (!isTriangle || transform2D)) { u = prim.uStart; } if (isTriangle) { int startSkip = startX - prim.pxMin; if (startSkip > 0) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex += startSkip; if (needDepthWrite || needDestinationDepthRead) { depthOffset += startSkip; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(startSkip, startSkip); } if (transform2D) { u += startSkip * prim.uStep; } } pixel.x = startX; pixel.y = pixelY; prim.computeTriangleWeights(pixel); } for (int x = startX; x <= endX; x++) { if (isTriangle && !pixel.isInsideTriangle()) { // Pixel not inside triangle, skip the pixel if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d) outside triangle (%f, %f, %f)", x, pixelY, pixel.triangleWeight1, pixel.triangleWeight2, pixel.triangleWeight3)); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } } else { if (transform2D) { pixel.newPixel2D(); } else { pixel.newPixel3D(); } pixelX = x; if (needTextureUV) { if (isTriangle && !transform2D) { // Compute the mapped texture u,v coordinates // based on the Barycentric coordinates. // Apply a perspective correction by weighting the coordinates // by their "w" value. // See http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness u = pixel.getTriangleWeightedValue(t1uw, t2uw, t3uw); v = pixel.getTriangleWeightedValue(t1vw, t2vw, t3vw); float weightInverted = 1.f / pixel.getTriangleWeightedValue(prim.p1wInverted, prim.p2wInverted, prim.p3wInverted); pixelU = u * weightInverted; pixelV = v * weightInverted; } else { pixelU = u; pixelV = v; } } if (needSourceDepthRead) { if (isTriangle) { pixelSourceDepth = round(pixel.getTriangleWeightedValue(prim.p1z, prim.p2z, prim.p3z)); } else { pixelSourceDepth = sourceDepth; } } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { pixelDestination = memInt[fbIndex]; if (needDestinationDepthRead) { if (depthOffset == 0) { pixelDestinationDepth = memInt[depthIndex] & 0x0000FFFF; } else { pixelDestinationDepth = memInt[depthIndex] >>> 16; } } } else { rendererWriter.readCurrent(pixel); pixelDestination = pixel.destination; if (needDestinationDepthRead) { pixelDestinationDepth = pixel.destinationDepth; } } // Use a dummy "do { } while (false);" loop to allow to exit // quickly from the pixel rendering when a filter does not pass. // When a filter does not pass, the following is executed: // rendererWriter.skip(1, 1); // Skip the pixel // continue; do { if (setVertexPrimaryColor) { if (isTriangle) { if (sameVertexColor) { pixelPrimaryColor = pixel.c1; } else { pixelPrimaryColor = pixel.getTriangleColorWeightedValue(); } } } // // Material Flags // if (lightingFlagEnabled && !transform2D && useVertexColor && isTriangle) { if (matFlagAmbient) { pixel.materialAmbient = pixelPrimaryColor; } if (matFlagDiffuse) { pixel.materialDiffuse = pixelPrimaryColor; } if (matFlagSpecular) { pixel.materialSpecular = pixelPrimaryColor; } } // // Lighting // if (lightingFlagEnabled && !transform2D) { renderer.lightingFilter.filter(pixel); pixelPrimaryColor = pixel.primaryColor; pixelSecondaryColor = pixel.secondaryColor; } // // Texture // if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) { // // TextureMapping // if (!transform2D) { switch (texMapMode) { case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV: if (texScaleX != 1f) { pixelU *= renderer.texScaleX; } if (texTranslateX != 0f) { pixelU += renderer.texTranslateX; } if (texScaleY != 1f) { pixelV *= renderer.texScaleY; } if (texTranslateY != 0f) { pixelV += renderer.texTranslateY; } break; case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX: switch (texProjMapMode) { case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_POSITION: final float[] V = pixel.getV(); pixelU = V[0] * pixel.textureMatrix[0] + V[1] * pixel.textureMatrix[4] + V[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12]; pixelV = V[0] * pixel.textureMatrix[1] + V[1] * pixel.textureMatrix[5] + V[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13]; pixel.q = V[0] * pixel.textureMatrix[2] + V[1] * pixel.textureMatrix[6] + V[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14]; break; case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES: float tu = pixelU; float tv = pixelV; pixelU = tu * pixel.textureMatrix[0] + tv * pixel.textureMatrix[4] + pixel.textureMatrix[12]; pixelV = tu * pixel.textureMatrix[1] + tv * pixel.textureMatrix[5] + pixel.textureMatrix[13]; pixel.q = tu * pixel.textureMatrix[2] + tv * pixel.textureMatrix[6] + pixel.textureMatrix[14]; break; case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL: final float[] normalizedN = pixel.getNormalizedN(); pixelU = normalizedN[0] * pixel.textureMatrix[0] + normalizedN[1] * pixel.textureMatrix[4] + normalizedN[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12]; pixelV = normalizedN[0] * pixel.textureMatrix[1] + normalizedN[1] * pixel.textureMatrix[5] + normalizedN[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13]; pixel.q = normalizedN[0] * pixel.textureMatrix[2] + normalizedN[1] * pixel.textureMatrix[6] + normalizedN[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14]; break; case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMAL: final float[] N = pixel.getN(); pixelU = N[0] * pixel.textureMatrix[0] + N[1] * pixel.textureMatrix[4] + N[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12]; pixelV = N[0] * pixel.textureMatrix[1] + N[1] * pixel.textureMatrix[5] + N[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13]; pixel.q = N[0] * pixel.textureMatrix[2] + N[1] * pixel.textureMatrix[6] + N[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14]; break; } break; case GeCommands.TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: // Implementation based on shader.vert/ApplyTexture: // // vec3 Nn = normalize(N); // vec3 Ve = vec3(gl_ModelViewMatrix * V); // float k = gl_FrontMaterial.shininess; // vec3 Lu = gl_LightSource[texShade.x].position.xyz - Ve.xyz * gl_LightSource[texShade.x].position.w; // vec3 Lv = gl_LightSource[texShade.y].position.xyz - Ve.xyz * gl_LightSource[texShade.y].position.w; // float Pu = psp_lightKind[texShade.x] == 0 ? dot(Nn, normalize(Lu)) : pow(dot(Nn, normalize(Lu + vec3(0.0, 0.0, 1.0))), k); // float Pv = psp_lightKind[texShade.y] == 0 ? dot(Nn, normalize(Lv)) : pow(dot(Nn, normalize(Lv + vec3(0.0, 0.0, 1.0))), k); // T.xyz = vec3(0.5*vec2(1.0 + Pu, 1.0 + Pv), 1.0); // final float[] Ve = new float[3]; final float[] Ne = new float[3]; final float[] Lu = new float[3]; final float[] Lv = new float[3]; pixel.getVe(Ve); pixel.getNormalizedNe(Ne); for (int i = 0; i < 3; i++) { Lu[i] = renderer.envMapLightPosU[i] - Ve[i] * renderer.envMapLightPosU[3]; Lv[i] = renderer.envMapLightPosV[i] - Ve[i] * renderer.envMapLightPosV[3]; } float Pu; if (renderer.envMapDiffuseLightU) { normalize3(Lu, Lu); Pu = dot3(Ne, Lu); } else { Lu[2] += 1f; normalize3(Lu, Lu); Pu = (float) Math.pow(dot3(Ne, Lu), renderer.envMapShininess); } float Pv; if (renderer.envMapDiffuseLightV) { normalize3(Lv, Lv); Pv = dot3(Ne, Lv); } else { Lv[2] += 1f; normalize3(Lv, Lv); Pv = (float) Math.pow(dot3(Ne, Lv), renderer.envMapShininess); } pixelU = (Pu + 1f) * 0.5f; pixelV = (Pv + 1f) * 0.5f; pixel.q = 1f; break; } } // // TextureWrap // if (texWrapS == GeCommands.TWRAP_WRAP_MODE_REPEAT) { if (transform2D) { pixelU = wrap(pixelU, textureWidthMask); } else { pixelU = wrap(pixelU); } } if (texWrapT == GeCommands.TWRAP_WRAP_MODE_REPEAT) { if (transform2D) { pixelV = wrap(pixelV, textureHeightMask); } else { pixelV = wrap(pixelV); } } // // TextureReader // if (transform2D) { pixelSource = textureAccess.readPixel(pixelToTexel(pixelU), pixelToTexel(pixelV)); } else { pixelSource = textureAccess.readPixel(pixelToTexel(pixelU * textureWidthFloat), pixelToTexel(pixelV * textureHeightFloat)); } // // TextureFunction // switch (textureFunc) { case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE: if (textureAlphaUsed) { pixelSource = multiply(pixelSource, pixelPrimaryColor); } else { pixelSource = multiply(pixelSource | 0xFF000000, pixelPrimaryColor); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_DECAL: if (textureAlphaUsed) { alpha = getAlpha(pixelSource); a = getAlpha(pixelPrimaryColor); b = combineComponent(getBlue(pixelPrimaryColor), getBlue(pixelSource), alpha); g = combineComponent(getGreen(pixelPrimaryColor), getGreen(pixelSource), alpha); r = combineComponent(getRed(pixelPrimaryColor), getRed(pixelSource), alpha); pixelSource = getColor(a, b, g, r); } else { pixelSource = (pixelSource & 0x00FFFFFF) | (pixelPrimaryColor & 0xFF000000); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_BLEND: if (textureAlphaUsed) { a = multiplyComponent(getAlpha(pixelSource), getAlpha(pixelPrimaryColor)); b = combineComponent(getBlue(pixelPrimaryColor), renderer.texEnvColorB, getBlue(pixelSource)); g = combineComponent(getGreen(pixelPrimaryColor), renderer.texEnvColorG, getGreen(pixelSource)); r = combineComponent(getRed(pixelPrimaryColor), renderer.texEnvColorR, getRed(pixelSource)); pixelSource = getColor(a, b, g, r); } else { a = getAlpha(pixelPrimaryColor); b = combineComponent(getBlue(pixelPrimaryColor), renderer.texEnvColorB, getBlue(pixelSource)); g = combineComponent(getGreen(pixelPrimaryColor), renderer.texEnvColorG, getGreen(pixelSource)); r = combineComponent(getRed(pixelPrimaryColor), renderer.texEnvColorR, getRed(pixelSource)); pixelSource = getColor(a, b, g, r); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_REPLACE: if (!textureAlphaUsed) { pixelSource = (pixelSource & 0x00FFFFFF) | (pixelPrimaryColor & 0xFF000000); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_ADD: if (textureAlphaUsed) { a = multiplyComponent(getAlpha(pixelSource), getAlpha(pixelPrimaryColor)); pixelSource = setAlpha(addBGR(pixelSource, pixelPrimaryColor), a); } else { pixelSource = add(pixelSource & 0x00FFFFFF, pixelPrimaryColor); } break; } // // ColorDoubling // if (textureColorDoubled) { if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelSource = doubleColor(pixelSource); pixelSecondaryColor = doubleColor(pixelSecondaryColor); } else { pixelSource = doubleColor(pixelSource); } } // // SourceColor // if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelSource = add(pixelSource, pixelSecondaryColor); } } else { // // ColorDoubling // if (textureColorDoubled) { if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelPrimaryColor = doubleColor(pixelPrimaryColor); pixelSecondaryColor = doubleColor(pixelSecondaryColor); } else if (!primaryColorSetGlobally) { pixelPrimaryColor = doubleColor(pixelPrimaryColor); } } // // SourceColor // if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelSource = add(pixelPrimaryColor, pixelSecondaryColor); } else { pixelSource = pixelPrimaryColor; } } // // ScissorTest // if (transform2D) { if (needScissoringX && needScissoringY) { if (!(pixelX >= renderer.scissorX1 && pixelX <= renderer.scissorX2 && pixelY >= renderer.scissorY1 && pixelY <= renderer.scissorY2)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } else if (needScissoringX) { if (!(pixelX >= renderer.scissorX1 && pixelX <= renderer.scissorX2)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } else if (needScissoringY) { if (!(pixelY >= renderer.scissorY1 && pixelY <= renderer.scissorY2)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } } // // ScissorDepthTest // if (!transform2D && !clearMode) { if (nearZ != 0x0000 || farZ != 0xFFFF) { if (!(pixelSourceDepth >= renderer.nearZ && pixelSourceDepth <= renderer.farZ)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } } // // ColorTest // if (colorTestFlagEnabled && !clearMode) { switch (colorTestFunc) { case GeCommands.CTST_COLOR_FUNCTION_ALWAYS_PASS_PIXEL: // Nothing to do break; case GeCommands.CTST_COLOR_FUNCTION_NEVER_PASS_PIXEL: if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_MATCHES: if ((pixelSource & renderer.colorTestMsk) != renderer.colorTestRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_DIFFERS: if ((pixelSource & renderer.colorTestMsk) == renderer.colorTestRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; } } // // AlphaTest // if (alphaTestFlagEnabled && !clearMode) { switch (alphaFunc) { case GeCommands.ATST_ALWAYS_PASS_PIXEL: // Nothing to do break; case GeCommands.ATST_NEVER_PASS_PIXEL: if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.ATST_PASS_PIXEL_IF_MATCHES: if (getAlpha(pixelSource) != alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_DIFFERS: if (getAlpha(pixelSource) == alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_LESS: if (getAlpha(pixelSource) >= alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_LESS_OR_EQUAL: // No test if alphaRef==0xFF if (RendererTemplate.alphaRef < 0xFF) { if (getAlpha(pixelSource) > alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } break; case GeCommands.ATST_PASS_PIXEL_IF_GREATER: if (getAlpha(pixelSource) <= alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL: // No test if alphaRef==0x00 if (RendererTemplate.alphaRef > 0x00) { if (getAlpha(pixelSource) < alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } break; } } // // StencilTest // if (stencilTestFlagEnabled && !clearMode) { switch (stencilFunc) { case GeCommands.STST_FUNCTION_NEVER_PASS_STENCIL_TEST: if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST: // Nothing to do break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_MATCHES: if ((getAlpha(pixelDestination) & renderer.stencilMask) != renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_DIFFERS: if ((getAlpha(pixelDestination) & renderer.stencilMask) == renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS: if ((getAlpha(pixelDestination) & renderer.stencilMask) >= renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL: if ((getAlpha(pixelDestination) & renderer.stencilMask) > renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER: if ((getAlpha(pixelDestination) & renderer.stencilMask) <= renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL: if ((getAlpha(pixelDestination) & renderer.stencilMask) < renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; } } // // DepthTest // if (depthTestFlagEnabled && !clearMode) { switch (depthFunc) { case GeCommands.ZTST_FUNCTION_NEVER_PASS_PIXEL: if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.ZTST_FUNCTION_ALWAYS_PASS_PIXEL: // No filter required break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_EQUAL: if (pixelSourceDepth != pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_ISNOT_EQUAL: if (pixelSourceDepth == pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS: if (pixelSourceDepth >= pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS_OR_EQUAL: if (pixelSourceDepth > pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER: if (pixelSourceDepth <= pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL: if (pixelSourceDepth < pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; } } // // AlphaBlend // if (blendFlagEnabled && !clearMode) { int filteredSrc; int filteredDst; switch (blendEquation) { case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ADD: if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF && blendDst == GeCommands.ALPHA_FIX && dfix == 0x000000) { // Nothing to do, this is a NOP } else if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF && blendDst == GeCommands.ALPHA_FIX && dfix == 0xFFFFFF) { pixelSource = PixelColor.add(pixelSource, pixelDestination & 0x00FFFFFF); } else if (blendSrc == GeCommands.ALPHA_SOURCE_ALPHA && blendDst == GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA) { // This is the most common case and can be optimized int srcAlpha = pixelSource >>> 24; if (srcAlpha == ZERO) { // Set color of destination pixelSource = (pixelSource & 0xFF000000) | (pixelDestination & 0x00FFFFFF); } else if (srcAlpha == ONE) { // Nothing to change } else { int oneMinusSrcAlpha = ONE - srcAlpha; filteredSrc = multiplyBGR(pixelSource, srcAlpha, srcAlpha, srcAlpha); filteredDst = multiplyBGR(pixelDestination, oneMinusSrcAlpha, oneMinusSrcAlpha, oneMinusSrcAlpha); pixelSource = setBGR(pixelSource, addBGR(filteredSrc, filteredDst)); } } else { filteredSrc = multiplyBGR(pixelSource, blendSrc(pixelSource, pixelDestination, renderer.sfix)); filteredDst = multiplyBGR(pixelDestination, blendDst(pixelSource, pixelDestination, renderer.dfix)); pixelSource = setBGR(pixelSource, addBGR(filteredSrc, filteredDst)); } break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT: filteredSrc = multiplyBGR(pixelSource, blendSrc(pixelSource, pixelDestination, renderer.sfix)); filteredDst = multiplyBGR(pixelDestination, blendDst(pixelSource, pixelDestination, renderer.dfix)); pixelSource = setBGR(pixelSource, substractBGR(filteredSrc, filteredDst)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT: filteredSrc = multiplyBGR(pixelSource, blendSrc(pixelSource, pixelDestination, renderer.sfix)); filteredDst = multiplyBGR(pixelDestination, blendDst(pixelSource, pixelDestination, renderer.dfix)); pixelSource = setBGR(pixelSource, substractBGR(filteredDst, filteredSrc)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE: // Source and destination factors are not applied pixelSource = setBGR(pixelSource, minBGR(pixelSource, pixelDestination)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE: // Source and destination factors are not applied pixelSource = setBGR(pixelSource, maxBGR(pixelSource, pixelDestination)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE: // Source and destination factors are not applied pixelSource = setBGR(pixelSource, absBGR(pixelSource, pixelDestination)); break; } } // // StencilOpZPass // if (stencilTestFlagEnabled && !clearMode) { switch (stencilOpZPass) { case GeCommands.SOP_KEEP_STENCIL_VALUE: pixelSource = (pixelSource & 0x00FFFFFF) | (pixelDestination & 0xFF000000); break; case GeCommands.SOP_ZERO_STENCIL_VALUE: pixelSource &= 0x00FFFFFF; break; case GeCommands.SOP_REPLACE_STENCIL_VALUE: if (stencilRef == 0) { // SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent // to SOP_ZERO_STENCIL_VALUE pixelSource &= 0x00FFFFFF; } else { pixelSource = (pixelSource & 0x00FFFFFF) | stencilRefAlpha; } + break; case GeCommands.SOP_INVERT_STENCIL_VALUE: pixelSource = (pixelSource & 0x00FFFFFF) | ((~pixelDestination) & 0xFF000000); break; case GeCommands.SOP_INCREMENT_STENCIL_VALUE: alpha = pixelDestination & 0xFF000000; if (alpha != 0xFF000000) { alpha += 0x01000000; } pixelSource = (pixelSource & 0x00FFFFFF) | alpha; break; case GeCommands.SOP_DECREMENT_STENCIL_VALUE: alpha = pixelDestination & 0xFF000000; if (alpha != 0x00000000) { alpha -= 0x01000000; } pixelSource = (pixelSource & 0x00FFFFFF) | alpha; break; } } // // ColorLogicalOperation // if (colorLogicOpFlagEnabled && !clearMode) { switch (logicOp) { case GeCommands.LOP_CLEAR: pixelSource = ZERO; break; case GeCommands.LOP_AND: pixelSource &= pixelDestination; break; case GeCommands.LOP_REVERSE_AND: pixelSource &= (~pixelDestination); break; case GeCommands.LOP_COPY: // This is a NOP break; case GeCommands.LOP_INVERTED_AND: pixelSource = (~pixelSource) & pixelDestination; break; case GeCommands.LOP_NO_OPERATION: pixelSource = pixelDestination; break; case GeCommands.LOP_EXLUSIVE_OR: pixelSource ^= pixelDestination; break; case GeCommands.LOP_OR: pixelSource |= pixelDestination; break; case GeCommands.LOP_NEGATED_OR: pixelSource = ~(pixelSource | pixelDestination); break; case GeCommands.LOP_EQUIVALENCE: pixelSource = ~(pixelSource ^ pixelDestination); break; case GeCommands.LOP_INVERTED: pixelSource = ~pixelDestination; break; case GeCommands.LOP_REVERSE_OR: pixelSource |= (~pixelDestination); break; case GeCommands.LOP_INVERTED_COPY: pixelSource = ~pixelSource; break; case GeCommands.LOP_INVERTED_OR: pixelSource = (~pixelSource) | pixelDestination; break; case GeCommands.LOP_NEGATED_AND: pixelSource = ~(pixelSource & pixelDestination); break; case GeCommands.LOP_SET: pixelSource = 0xFFFFFFFF; break; } } // // ColorMask // if (clearMode) { if (clearModeColor) { if (!clearModeStencil) { pixelSource = (pixelSource & 0x00FFFFFF) | (pixelDestination & 0xFF000000); } } else { if (clearModeStencil) { pixelSource = (pixelSource & 0xFF000000) | (pixelDestination & 0x00FFFFFF); } else { pixelSource = pixelDestination; } } } else { if (colorMask != 0x00000000) { pixelSource = (pixelSource & notColorMask) | (pixelDestination & colorMask); } } // // DepthMask // if (needDepthWrite) { if (clearMode) { if (!clearModeDepth) { pixelSourceDepth = pixelDestinationDepth; } } else if (!depthTestFlagEnabled) { // Depth writes are disabled when the depth test is not enabled. pixelSourceDepth = pixelDestinationDepth; } else if (!depthMask) { pixelSourceDepth = pixelDestinationDepth; } } // // Filter passed // if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), passed=true, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { memInt[fbIndex] = pixelSource; fbIndex++; if (needDepthWrite) { if (depthOffset == 0) { memInt[depthIndex] = (memInt[depthIndex] & 0xFFFF0000) | (pixelSourceDepth & 0x0000FFFF); depthOffset = 1; } else { memInt[depthIndex] = (memInt[depthIndex] & 0x0000FFFF) | (pixelSourceDepth << 16); depthIndex++; depthOffset = 0; } } else if (needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { pixel.source = pixelSource; if (needDepthWrite) { pixel.sourceDepth = pixelSourceDepth; } rendererWriter.writeNext(pixel); } } while (false); } if (needTextureUV && (!isTriangle || transform2D)) { u += prim.uStep; } if (isTriangle) { prim.deltaXTriangleWeigths(pixel); } } int skip = prim.pxMax - endX; if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex += skip + renderer.imageWriterSkipEOL; if (needDepthWrite || needDestinationDepthRead) { depthOffset += skip + renderer.depthWriterSkipEOL; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(skip + renderer.imageWriterSkipEOL, skip + renderer.depthWriterSkipEOL); } } if (needTextureUV && (!isTriangle || transform2D)) { v += prim.vStep; } } doRenderEnd(renderer); } protected static int stencilOpFail(int destination, int stencilRefAlpha) { int alpha; switch (stencilOpFail) { case GeCommands.SOP_KEEP_STENCIL_VALUE: return destination; case GeCommands.SOP_ZERO_STENCIL_VALUE: return destination & 0x00FFFFFF; case GeCommands.SOP_REPLACE_STENCIL_VALUE: if (stencilRef == 0) { // SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent // to SOP_ZERO_STENCIL_VALUE return destination & 0x00FFFFFF; } return (destination & 0x00FFFFFF) | stencilRefAlpha; case GeCommands.SOP_INVERT_STENCIL_VALUE: return destination ^ 0xFF000000; case GeCommands.SOP_INCREMENT_STENCIL_VALUE: alpha = destination & 0xFF000000; if (alpha != 0xFF000000) { alpha += 0x01000000; } return (destination & 0x00FFFFFF) | alpha; case GeCommands.SOP_DECREMENT_STENCIL_VALUE: alpha = destination & 0xFF000000; if (alpha != 0x00000000) { alpha -= 0x01000000; } return (destination & 0x00FFFFFF) | alpha; } return destination; } protected static int stencilOpZFail(int destination, int stencilRefAlpha) { int alpha; switch (stencilOpZFail) { case GeCommands.SOP_KEEP_STENCIL_VALUE: return destination; case GeCommands.SOP_ZERO_STENCIL_VALUE: return destination & 0x00FFFFFF; case GeCommands.SOP_REPLACE_STENCIL_VALUE: if (stencilRef == 0) { // SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent // to SOP_ZERO_STENCIL_VALUE return destination & 0x00FFFFFF; } return (destination & 0x00FFFFFF) | stencilRefAlpha; case GeCommands.SOP_INVERT_STENCIL_VALUE: return destination ^ 0xFF000000; case GeCommands.SOP_INCREMENT_STENCIL_VALUE: alpha = destination & 0xFF000000; if (alpha != 0xFF000000) { alpha += 0x01000000; } return (destination & 0x00FFFFFF) | alpha; case GeCommands.SOP_DECREMENT_STENCIL_VALUE: alpha = destination & 0xFF000000; if (alpha != 0x00000000) { alpha -= 0x01000000; } return (destination & 0x00FFFFFF) | alpha; } return destination; } protected static int blendSrc(int source, int destination, int fix) { int alpha; switch (blendSrc) { case GeCommands.ALPHA_SOURCE_COLOR: return source; case GeCommands.ALPHA_ONE_MINUS_SOURCE_COLOR: return 0xFFFFFFFF - source; case GeCommands.ALPHA_SOURCE_ALPHA: alpha = getAlpha(source); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA: alpha = ONE - getAlpha(source); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_DESTINATION_ALPHA: alpha = getAlpha(destination); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_ONE_MINUS_DESTINATION_ALPHA: alpha = ONE - getAlpha(destination); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_DOUBLE_SOURCE_ALPHA: alpha = getAlpha(source) << 1; return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_ONE_MINUS_DOUBLE_SOURCE_ALPHA: alpha = ONE - (getAlpha(source) << 1); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_DOUBLE_DESTINATION_ALPHA: alpha = getAlpha(destination) << 1; return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_ONE_MINUS_DOUBLE_DESTINATION_ALPHA: alpha = ONE - (getAlpha(destination) << 1); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_FIX: return fix; } return source; } protected static int blendDst(int source, int destination, int fix) { int alpha; switch (blendDst) { case GeCommands.ALPHA_DESTINATION_COLOR: return destination; case GeCommands.ALPHA_ONE_MINUS_DESTINATION_COLOR: return 0xFFFFFFFF - destination; case GeCommands.ALPHA_SOURCE_ALPHA: alpha = getAlpha(source); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA: alpha = ONE - getAlpha(source); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_DESTINATION_ALPHA: alpha = getAlpha(destination); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_ONE_MINUS_DESTINATION_ALPHA: alpha = ONE - getAlpha(destination); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_DOUBLE_SOURCE_ALPHA: alpha = getAlpha(source) << 1; return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_ONE_MINUS_DOUBLE_SOURCE_ALPHA: alpha = ONE - (getAlpha(source) << 1); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_DOUBLE_DESTINATION_ALPHA: alpha = getAlpha(destination) << 1; return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_ONE_MINUS_DOUBLE_DESTINATION_ALPHA: alpha = ONE - (getAlpha(destination) << 1); return getColorBGR(alpha, alpha, alpha); case GeCommands.ALPHA_FIX: return fix; } return destination; } }
true
true
private static void doRender(final BasePrimitiveRenderer renderer) { final PixelState pixel = renderer.pixel; final PrimitiveState prim = renderer.prim; final IRendererWriter rendererWriter = renderer.rendererWriter; final IRandomTextureAccess textureAccess = renderer.textureAccess; doRenderStart(renderer); int stencilRefAlpha = 0; if (stencilTestFlagEnabled && !clearMode && stencilRef != 0) { if (stencilOpFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZPass == SOP_REPLACE_STENCIL_VALUE) { // Prepare stencilRef as a ready-to-use alpha value stencilRefAlpha = renderer.stencilRef << 24; } } int notColorMask = 0xFFFFFFFF; if (!clearMode && colorMask != 0x00000000) { notColorMask = ~renderer.colorMask; } int alpha, a, b, g, r; final int textureWidthMask = renderer.textureWidth - 1; final int textureHeightMask = renderer.textureHeight - 1; final float textureWidthFloat = renderer.textureWidth; final float textureHeightFloat = renderer.textureHeight; final int alphaRef = renderer.alphaRef; final int sourceDepth = (int) prim.p2z; float v = prim.vStart; float u = 0f; Range range = null; Rasterizer rasterizer = null; float t1uw = 0f; float t1vw = 0f; float t2uw = 0f; float t2vw = 0f; float t3uw = 0f; float t3vw = 0f; if (isTriangle) { if (!transform2D) { t1uw = prim.t1u * prim.p1wInverted; t1vw = prim.t1v * prim.p1wInverted; t2uw = prim.t2u * prim.p2wInverted; t2vw = prim.t2v * prim.p2wInverted; t3uw = prim.t3u * prim.p3wInverted; t3vw = prim.t3v * prim.p3wInverted; } range = new Range(); // No need to use a Rasterizer when rendering very small area. // The overhead of the Rasterizer would lead to slower rendering. if (prim.destinationWidth >= Rasterizer.MINIMUM_WIDTH && prim.destinationHeight >= Rasterizer.MINIMUM_HEIGHT) { rasterizer = new Rasterizer(prim.p1x, prim.p1y, prim.p2x, prim.p2y, prim.p3x, prim.p3y, prim.pyMin, prim.pyMax); rasterizer.setY(prim.pyMin); } } int fbIndex = 0; int depthIndex = 0; int depthOffset = 0; final int[] memInt = renderer.memInt; if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex = renderer.fbAddress >> 2; depthIndex = renderer.depthAddress >> 2; depthOffset = (renderer.depthAddress >> 1) & 1; } // Use local variables instead of "pixel" members. // The Java JIT is then producing a slightly faster code. int pixelSource = pixel.source; int pixelSourceDepth = pixel.sourceDepth; int pixelDestination = 0; int pixelDestinationDepth = 0; int pixelPrimaryColor = pixel.primaryColor; int pixelSecondaryColor = pixel.secondaryColor; int pixelX = 0; int pixelY = 0; float pixelU = 0f; float pixelV = 0f; for (int y = prim.pyMin; y <= prim.pyMax; y++) { pixelY = y; int startX = prim.pxMin; int endX = prim.pxMax; if (isTriangle && rasterizer != null) { rasterizer.getNextRange(range); startX = max(range.xMin, startX); endX = min(range.xMax, endX); if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Rasterizer line (%d-%d,%d)", startX, endX, pixelY)); } } if (isTriangle && startX > endX) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex += prim.destinationWidth + renderer.imageWriterSkipEOL; if (needDepthWrite || needDestinationDepthRead) { depthOffset += prim.destinationWidth + renderer.depthWriterSkipEOL; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(prim.destinationWidth + renderer.imageWriterSkipEOL, prim.destinationWidth + renderer.depthWriterSkipEOL); } } else { if (needTextureUV && (!isTriangle || transform2D)) { u = prim.uStart; } if (isTriangle) { int startSkip = startX - prim.pxMin; if (startSkip > 0) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex += startSkip; if (needDepthWrite || needDestinationDepthRead) { depthOffset += startSkip; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(startSkip, startSkip); } if (transform2D) { u += startSkip * prim.uStep; } } pixel.x = startX; pixel.y = pixelY; prim.computeTriangleWeights(pixel); } for (int x = startX; x <= endX; x++) { if (isTriangle && !pixel.isInsideTriangle()) { // Pixel not inside triangle, skip the pixel if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d) outside triangle (%f, %f, %f)", x, pixelY, pixel.triangleWeight1, pixel.triangleWeight2, pixel.triangleWeight3)); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } } else { if (transform2D) { pixel.newPixel2D(); } else { pixel.newPixel3D(); } pixelX = x; if (needTextureUV) { if (isTriangle && !transform2D) { // Compute the mapped texture u,v coordinates // based on the Barycentric coordinates. // Apply a perspective correction by weighting the coordinates // by their "w" value. // See http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness u = pixel.getTriangleWeightedValue(t1uw, t2uw, t3uw); v = pixel.getTriangleWeightedValue(t1vw, t2vw, t3vw); float weightInverted = 1.f / pixel.getTriangleWeightedValue(prim.p1wInverted, prim.p2wInverted, prim.p3wInverted); pixelU = u * weightInverted; pixelV = v * weightInverted; } else { pixelU = u; pixelV = v; } } if (needSourceDepthRead) { if (isTriangle) { pixelSourceDepth = round(pixel.getTriangleWeightedValue(prim.p1z, prim.p2z, prim.p3z)); } else { pixelSourceDepth = sourceDepth; } } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { pixelDestination = memInt[fbIndex]; if (needDestinationDepthRead) { if (depthOffset == 0) { pixelDestinationDepth = memInt[depthIndex] & 0x0000FFFF; } else { pixelDestinationDepth = memInt[depthIndex] >>> 16; } } } else { rendererWriter.readCurrent(pixel); pixelDestination = pixel.destination; if (needDestinationDepthRead) { pixelDestinationDepth = pixel.destinationDepth; } } // Use a dummy "do { } while (false);" loop to allow to exit // quickly from the pixel rendering when a filter does not pass. // When a filter does not pass, the following is executed: // rendererWriter.skip(1, 1); // Skip the pixel // continue; do { if (setVertexPrimaryColor) { if (isTriangle) { if (sameVertexColor) { pixelPrimaryColor = pixel.c1; } else { pixelPrimaryColor = pixel.getTriangleColorWeightedValue(); } } } // // Material Flags // if (lightingFlagEnabled && !transform2D && useVertexColor && isTriangle) { if (matFlagAmbient) { pixel.materialAmbient = pixelPrimaryColor; } if (matFlagDiffuse) { pixel.materialDiffuse = pixelPrimaryColor; } if (matFlagSpecular) { pixel.materialSpecular = pixelPrimaryColor; } } // // Lighting // if (lightingFlagEnabled && !transform2D) { renderer.lightingFilter.filter(pixel); pixelPrimaryColor = pixel.primaryColor; pixelSecondaryColor = pixel.secondaryColor; } // // Texture // if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) { // // TextureMapping // if (!transform2D) { switch (texMapMode) { case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV: if (texScaleX != 1f) { pixelU *= renderer.texScaleX; } if (texTranslateX != 0f) { pixelU += renderer.texTranslateX; } if (texScaleY != 1f) { pixelV *= renderer.texScaleY; } if (texTranslateY != 0f) { pixelV += renderer.texTranslateY; } break; case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX: switch (texProjMapMode) { case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_POSITION: final float[] V = pixel.getV(); pixelU = V[0] * pixel.textureMatrix[0] + V[1] * pixel.textureMatrix[4] + V[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12]; pixelV = V[0] * pixel.textureMatrix[1] + V[1] * pixel.textureMatrix[5] + V[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13]; pixel.q = V[0] * pixel.textureMatrix[2] + V[1] * pixel.textureMatrix[6] + V[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14]; break; case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES: float tu = pixelU; float tv = pixelV; pixelU = tu * pixel.textureMatrix[0] + tv * pixel.textureMatrix[4] + pixel.textureMatrix[12]; pixelV = tu * pixel.textureMatrix[1] + tv * pixel.textureMatrix[5] + pixel.textureMatrix[13]; pixel.q = tu * pixel.textureMatrix[2] + tv * pixel.textureMatrix[6] + pixel.textureMatrix[14]; break; case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL: final float[] normalizedN = pixel.getNormalizedN(); pixelU = normalizedN[0] * pixel.textureMatrix[0] + normalizedN[1] * pixel.textureMatrix[4] + normalizedN[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12]; pixelV = normalizedN[0] * pixel.textureMatrix[1] + normalizedN[1] * pixel.textureMatrix[5] + normalizedN[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13]; pixel.q = normalizedN[0] * pixel.textureMatrix[2] + normalizedN[1] * pixel.textureMatrix[6] + normalizedN[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14]; break; case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMAL: final float[] N = pixel.getN(); pixelU = N[0] * pixel.textureMatrix[0] + N[1] * pixel.textureMatrix[4] + N[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12]; pixelV = N[0] * pixel.textureMatrix[1] + N[1] * pixel.textureMatrix[5] + N[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13]; pixel.q = N[0] * pixel.textureMatrix[2] + N[1] * pixel.textureMatrix[6] + N[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14]; break; } break; case GeCommands.TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: // Implementation based on shader.vert/ApplyTexture: // // vec3 Nn = normalize(N); // vec3 Ve = vec3(gl_ModelViewMatrix * V); // float k = gl_FrontMaterial.shininess; // vec3 Lu = gl_LightSource[texShade.x].position.xyz - Ve.xyz * gl_LightSource[texShade.x].position.w; // vec3 Lv = gl_LightSource[texShade.y].position.xyz - Ve.xyz * gl_LightSource[texShade.y].position.w; // float Pu = psp_lightKind[texShade.x] == 0 ? dot(Nn, normalize(Lu)) : pow(dot(Nn, normalize(Lu + vec3(0.0, 0.0, 1.0))), k); // float Pv = psp_lightKind[texShade.y] == 0 ? dot(Nn, normalize(Lv)) : pow(dot(Nn, normalize(Lv + vec3(0.0, 0.0, 1.0))), k); // T.xyz = vec3(0.5*vec2(1.0 + Pu, 1.0 + Pv), 1.0); // final float[] Ve = new float[3]; final float[] Ne = new float[3]; final float[] Lu = new float[3]; final float[] Lv = new float[3]; pixel.getVe(Ve); pixel.getNormalizedNe(Ne); for (int i = 0; i < 3; i++) { Lu[i] = renderer.envMapLightPosU[i] - Ve[i] * renderer.envMapLightPosU[3]; Lv[i] = renderer.envMapLightPosV[i] - Ve[i] * renderer.envMapLightPosV[3]; } float Pu; if (renderer.envMapDiffuseLightU) { normalize3(Lu, Lu); Pu = dot3(Ne, Lu); } else { Lu[2] += 1f; normalize3(Lu, Lu); Pu = (float) Math.pow(dot3(Ne, Lu), renderer.envMapShininess); } float Pv; if (renderer.envMapDiffuseLightV) { normalize3(Lv, Lv); Pv = dot3(Ne, Lv); } else { Lv[2] += 1f; normalize3(Lv, Lv); Pv = (float) Math.pow(dot3(Ne, Lv), renderer.envMapShininess); } pixelU = (Pu + 1f) * 0.5f; pixelV = (Pv + 1f) * 0.5f; pixel.q = 1f; break; } } // // TextureWrap // if (texWrapS == GeCommands.TWRAP_WRAP_MODE_REPEAT) { if (transform2D) { pixelU = wrap(pixelU, textureWidthMask); } else { pixelU = wrap(pixelU); } } if (texWrapT == GeCommands.TWRAP_WRAP_MODE_REPEAT) { if (transform2D) { pixelV = wrap(pixelV, textureHeightMask); } else { pixelV = wrap(pixelV); } } // // TextureReader // if (transform2D) { pixelSource = textureAccess.readPixel(pixelToTexel(pixelU), pixelToTexel(pixelV)); } else { pixelSource = textureAccess.readPixel(pixelToTexel(pixelU * textureWidthFloat), pixelToTexel(pixelV * textureHeightFloat)); } // // TextureFunction // switch (textureFunc) { case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE: if (textureAlphaUsed) { pixelSource = multiply(pixelSource, pixelPrimaryColor); } else { pixelSource = multiply(pixelSource | 0xFF000000, pixelPrimaryColor); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_DECAL: if (textureAlphaUsed) { alpha = getAlpha(pixelSource); a = getAlpha(pixelPrimaryColor); b = combineComponent(getBlue(pixelPrimaryColor), getBlue(pixelSource), alpha); g = combineComponent(getGreen(pixelPrimaryColor), getGreen(pixelSource), alpha); r = combineComponent(getRed(pixelPrimaryColor), getRed(pixelSource), alpha); pixelSource = getColor(a, b, g, r); } else { pixelSource = (pixelSource & 0x00FFFFFF) | (pixelPrimaryColor & 0xFF000000); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_BLEND: if (textureAlphaUsed) { a = multiplyComponent(getAlpha(pixelSource), getAlpha(pixelPrimaryColor)); b = combineComponent(getBlue(pixelPrimaryColor), renderer.texEnvColorB, getBlue(pixelSource)); g = combineComponent(getGreen(pixelPrimaryColor), renderer.texEnvColorG, getGreen(pixelSource)); r = combineComponent(getRed(pixelPrimaryColor), renderer.texEnvColorR, getRed(pixelSource)); pixelSource = getColor(a, b, g, r); } else { a = getAlpha(pixelPrimaryColor); b = combineComponent(getBlue(pixelPrimaryColor), renderer.texEnvColorB, getBlue(pixelSource)); g = combineComponent(getGreen(pixelPrimaryColor), renderer.texEnvColorG, getGreen(pixelSource)); r = combineComponent(getRed(pixelPrimaryColor), renderer.texEnvColorR, getRed(pixelSource)); pixelSource = getColor(a, b, g, r); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_REPLACE: if (!textureAlphaUsed) { pixelSource = (pixelSource & 0x00FFFFFF) | (pixelPrimaryColor & 0xFF000000); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_ADD: if (textureAlphaUsed) { a = multiplyComponent(getAlpha(pixelSource), getAlpha(pixelPrimaryColor)); pixelSource = setAlpha(addBGR(pixelSource, pixelPrimaryColor), a); } else { pixelSource = add(pixelSource & 0x00FFFFFF, pixelPrimaryColor); } break; } // // ColorDoubling // if (textureColorDoubled) { if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelSource = doubleColor(pixelSource); pixelSecondaryColor = doubleColor(pixelSecondaryColor); } else { pixelSource = doubleColor(pixelSource); } } // // SourceColor // if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelSource = add(pixelSource, pixelSecondaryColor); } } else { // // ColorDoubling // if (textureColorDoubled) { if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelPrimaryColor = doubleColor(pixelPrimaryColor); pixelSecondaryColor = doubleColor(pixelSecondaryColor); } else if (!primaryColorSetGlobally) { pixelPrimaryColor = doubleColor(pixelPrimaryColor); } } // // SourceColor // if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelSource = add(pixelPrimaryColor, pixelSecondaryColor); } else { pixelSource = pixelPrimaryColor; } } // // ScissorTest // if (transform2D) { if (needScissoringX && needScissoringY) { if (!(pixelX >= renderer.scissorX1 && pixelX <= renderer.scissorX2 && pixelY >= renderer.scissorY1 && pixelY <= renderer.scissorY2)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } else if (needScissoringX) { if (!(pixelX >= renderer.scissorX1 && pixelX <= renderer.scissorX2)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } else if (needScissoringY) { if (!(pixelY >= renderer.scissorY1 && pixelY <= renderer.scissorY2)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } } // // ScissorDepthTest // if (!transform2D && !clearMode) { if (nearZ != 0x0000 || farZ != 0xFFFF) { if (!(pixelSourceDepth >= renderer.nearZ && pixelSourceDepth <= renderer.farZ)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } } // // ColorTest // if (colorTestFlagEnabled && !clearMode) { switch (colorTestFunc) { case GeCommands.CTST_COLOR_FUNCTION_ALWAYS_PASS_PIXEL: // Nothing to do break; case GeCommands.CTST_COLOR_FUNCTION_NEVER_PASS_PIXEL: if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_MATCHES: if ((pixelSource & renderer.colorTestMsk) != renderer.colorTestRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_DIFFERS: if ((pixelSource & renderer.colorTestMsk) == renderer.colorTestRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; } } // // AlphaTest // if (alphaTestFlagEnabled && !clearMode) { switch (alphaFunc) { case GeCommands.ATST_ALWAYS_PASS_PIXEL: // Nothing to do break; case GeCommands.ATST_NEVER_PASS_PIXEL: if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.ATST_PASS_PIXEL_IF_MATCHES: if (getAlpha(pixelSource) != alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_DIFFERS: if (getAlpha(pixelSource) == alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_LESS: if (getAlpha(pixelSource) >= alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_LESS_OR_EQUAL: // No test if alphaRef==0xFF if (RendererTemplate.alphaRef < 0xFF) { if (getAlpha(pixelSource) > alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } break; case GeCommands.ATST_PASS_PIXEL_IF_GREATER: if (getAlpha(pixelSource) <= alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL: // No test if alphaRef==0x00 if (RendererTemplate.alphaRef > 0x00) { if (getAlpha(pixelSource) < alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } break; } } // // StencilTest // if (stencilTestFlagEnabled && !clearMode) { switch (stencilFunc) { case GeCommands.STST_FUNCTION_NEVER_PASS_STENCIL_TEST: if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST: // Nothing to do break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_MATCHES: if ((getAlpha(pixelDestination) & renderer.stencilMask) != renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_DIFFERS: if ((getAlpha(pixelDestination) & renderer.stencilMask) == renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS: if ((getAlpha(pixelDestination) & renderer.stencilMask) >= renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL: if ((getAlpha(pixelDestination) & renderer.stencilMask) > renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER: if ((getAlpha(pixelDestination) & renderer.stencilMask) <= renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL: if ((getAlpha(pixelDestination) & renderer.stencilMask) < renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; } } // // DepthTest // if (depthTestFlagEnabled && !clearMode) { switch (depthFunc) { case GeCommands.ZTST_FUNCTION_NEVER_PASS_PIXEL: if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.ZTST_FUNCTION_ALWAYS_PASS_PIXEL: // No filter required break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_EQUAL: if (pixelSourceDepth != pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_ISNOT_EQUAL: if (pixelSourceDepth == pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS: if (pixelSourceDepth >= pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS_OR_EQUAL: if (pixelSourceDepth > pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER: if (pixelSourceDepth <= pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL: if (pixelSourceDepth < pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; } } // // AlphaBlend // if (blendFlagEnabled && !clearMode) { int filteredSrc; int filteredDst; switch (blendEquation) { case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ADD: if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF && blendDst == GeCommands.ALPHA_FIX && dfix == 0x000000) { // Nothing to do, this is a NOP } else if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF && blendDst == GeCommands.ALPHA_FIX && dfix == 0xFFFFFF) { pixelSource = PixelColor.add(pixelSource, pixelDestination & 0x00FFFFFF); } else if (blendSrc == GeCommands.ALPHA_SOURCE_ALPHA && blendDst == GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA) { // This is the most common case and can be optimized int srcAlpha = pixelSource >>> 24; if (srcAlpha == ZERO) { // Set color of destination pixelSource = (pixelSource & 0xFF000000) | (pixelDestination & 0x00FFFFFF); } else if (srcAlpha == ONE) { // Nothing to change } else { int oneMinusSrcAlpha = ONE - srcAlpha; filteredSrc = multiplyBGR(pixelSource, srcAlpha, srcAlpha, srcAlpha); filteredDst = multiplyBGR(pixelDestination, oneMinusSrcAlpha, oneMinusSrcAlpha, oneMinusSrcAlpha); pixelSource = setBGR(pixelSource, addBGR(filteredSrc, filteredDst)); } } else { filteredSrc = multiplyBGR(pixelSource, blendSrc(pixelSource, pixelDestination, renderer.sfix)); filteredDst = multiplyBGR(pixelDestination, blendDst(pixelSource, pixelDestination, renderer.dfix)); pixelSource = setBGR(pixelSource, addBGR(filteredSrc, filteredDst)); } break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT: filteredSrc = multiplyBGR(pixelSource, blendSrc(pixelSource, pixelDestination, renderer.sfix)); filteredDst = multiplyBGR(pixelDestination, blendDst(pixelSource, pixelDestination, renderer.dfix)); pixelSource = setBGR(pixelSource, substractBGR(filteredSrc, filteredDst)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT: filteredSrc = multiplyBGR(pixelSource, blendSrc(pixelSource, pixelDestination, renderer.sfix)); filteredDst = multiplyBGR(pixelDestination, blendDst(pixelSource, pixelDestination, renderer.dfix)); pixelSource = setBGR(pixelSource, substractBGR(filteredDst, filteredSrc)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE: // Source and destination factors are not applied pixelSource = setBGR(pixelSource, minBGR(pixelSource, pixelDestination)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE: // Source and destination factors are not applied pixelSource = setBGR(pixelSource, maxBGR(pixelSource, pixelDestination)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE: // Source and destination factors are not applied pixelSource = setBGR(pixelSource, absBGR(pixelSource, pixelDestination)); break; } } // // StencilOpZPass // if (stencilTestFlagEnabled && !clearMode) { switch (stencilOpZPass) { case GeCommands.SOP_KEEP_STENCIL_VALUE: pixelSource = (pixelSource & 0x00FFFFFF) | (pixelDestination & 0xFF000000); break; case GeCommands.SOP_ZERO_STENCIL_VALUE: pixelSource &= 0x00FFFFFF; break; case GeCommands.SOP_REPLACE_STENCIL_VALUE: if (stencilRef == 0) { // SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent // to SOP_ZERO_STENCIL_VALUE pixelSource &= 0x00FFFFFF; } else { pixelSource = (pixelSource & 0x00FFFFFF) | stencilRefAlpha; } case GeCommands.SOP_INVERT_STENCIL_VALUE: pixelSource = (pixelSource & 0x00FFFFFF) | ((~pixelDestination) & 0xFF000000); break; case GeCommands.SOP_INCREMENT_STENCIL_VALUE: alpha = pixelDestination & 0xFF000000; if (alpha != 0xFF000000) { alpha += 0x01000000; } pixelSource = (pixelSource & 0x00FFFFFF) | alpha; break; case GeCommands.SOP_DECREMENT_STENCIL_VALUE: alpha = pixelDestination & 0xFF000000; if (alpha != 0x00000000) { alpha -= 0x01000000; } pixelSource = (pixelSource & 0x00FFFFFF) | alpha; break; } } // // ColorLogicalOperation // if (colorLogicOpFlagEnabled && !clearMode) { switch (logicOp) { case GeCommands.LOP_CLEAR: pixelSource = ZERO; break; case GeCommands.LOP_AND: pixelSource &= pixelDestination; break; case GeCommands.LOP_REVERSE_AND: pixelSource &= (~pixelDestination); break; case GeCommands.LOP_COPY: // This is a NOP break; case GeCommands.LOP_INVERTED_AND: pixelSource = (~pixelSource) & pixelDestination; break; case GeCommands.LOP_NO_OPERATION: pixelSource = pixelDestination; break; case GeCommands.LOP_EXLUSIVE_OR: pixelSource ^= pixelDestination; break; case GeCommands.LOP_OR: pixelSource |= pixelDestination; break; case GeCommands.LOP_NEGATED_OR: pixelSource = ~(pixelSource | pixelDestination); break; case GeCommands.LOP_EQUIVALENCE: pixelSource = ~(pixelSource ^ pixelDestination); break; case GeCommands.LOP_INVERTED: pixelSource = ~pixelDestination; break; case GeCommands.LOP_REVERSE_OR: pixelSource |= (~pixelDestination); break; case GeCommands.LOP_INVERTED_COPY: pixelSource = ~pixelSource; break; case GeCommands.LOP_INVERTED_OR: pixelSource = (~pixelSource) | pixelDestination; break; case GeCommands.LOP_NEGATED_AND: pixelSource = ~(pixelSource & pixelDestination); break; case GeCommands.LOP_SET: pixelSource = 0xFFFFFFFF; break; } } // // ColorMask // if (clearMode) { if (clearModeColor) { if (!clearModeStencil) { pixelSource = (pixelSource & 0x00FFFFFF) | (pixelDestination & 0xFF000000); } } else { if (clearModeStencil) { pixelSource = (pixelSource & 0xFF000000) | (pixelDestination & 0x00FFFFFF); } else { pixelSource = pixelDestination; } } } else { if (colorMask != 0x00000000) { pixelSource = (pixelSource & notColorMask) | (pixelDestination & colorMask); } } // // DepthMask // if (needDepthWrite) { if (clearMode) { if (!clearModeDepth) { pixelSourceDepth = pixelDestinationDepth; } } else if (!depthTestFlagEnabled) { // Depth writes are disabled when the depth test is not enabled. pixelSourceDepth = pixelDestinationDepth; } else if (!depthMask) { pixelSourceDepth = pixelDestinationDepth; } } // // Filter passed // if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), passed=true, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { memInt[fbIndex] = pixelSource; fbIndex++; if (needDepthWrite) { if (depthOffset == 0) { memInt[depthIndex] = (memInt[depthIndex] & 0xFFFF0000) | (pixelSourceDepth & 0x0000FFFF); depthOffset = 1; } else { memInt[depthIndex] = (memInt[depthIndex] & 0x0000FFFF) | (pixelSourceDepth << 16); depthIndex++; depthOffset = 0; } } else if (needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { pixel.source = pixelSource; if (needDepthWrite) { pixel.sourceDepth = pixelSourceDepth; } rendererWriter.writeNext(pixel); } } while (false); } if (needTextureUV && (!isTriangle || transform2D)) { u += prim.uStep; } if (isTriangle) { prim.deltaXTriangleWeigths(pixel); } } int skip = prim.pxMax - endX; if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex += skip + renderer.imageWriterSkipEOL; if (needDepthWrite || needDestinationDepthRead) { depthOffset += skip + renderer.depthWriterSkipEOL; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(skip + renderer.imageWriterSkipEOL, skip + renderer.depthWriterSkipEOL); } } if (needTextureUV && (!isTriangle || transform2D)) { v += prim.vStep; } } doRenderEnd(renderer); }
private static void doRender(final BasePrimitiveRenderer renderer) { final PixelState pixel = renderer.pixel; final PrimitiveState prim = renderer.prim; final IRendererWriter rendererWriter = renderer.rendererWriter; final IRandomTextureAccess textureAccess = renderer.textureAccess; doRenderStart(renderer); int stencilRefAlpha = 0; if (stencilTestFlagEnabled && !clearMode && stencilRef != 0) { if (stencilOpFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZPass == SOP_REPLACE_STENCIL_VALUE) { // Prepare stencilRef as a ready-to-use alpha value stencilRefAlpha = renderer.stencilRef << 24; } } int notColorMask = 0xFFFFFFFF; if (!clearMode && colorMask != 0x00000000) { notColorMask = ~renderer.colorMask; } int alpha, a, b, g, r; final int textureWidthMask = renderer.textureWidth - 1; final int textureHeightMask = renderer.textureHeight - 1; final float textureWidthFloat = renderer.textureWidth; final float textureHeightFloat = renderer.textureHeight; final int alphaRef = renderer.alphaRef; final int sourceDepth = (int) prim.p2z; float v = prim.vStart; float u = 0f; Range range = null; Rasterizer rasterizer = null; float t1uw = 0f; float t1vw = 0f; float t2uw = 0f; float t2vw = 0f; float t3uw = 0f; float t3vw = 0f; if (isTriangle) { if (!transform2D) { t1uw = prim.t1u * prim.p1wInverted; t1vw = prim.t1v * prim.p1wInverted; t2uw = prim.t2u * prim.p2wInverted; t2vw = prim.t2v * prim.p2wInverted; t3uw = prim.t3u * prim.p3wInverted; t3vw = prim.t3v * prim.p3wInverted; } range = new Range(); // No need to use a Rasterizer when rendering very small area. // The overhead of the Rasterizer would lead to slower rendering. if (prim.destinationWidth >= Rasterizer.MINIMUM_WIDTH && prim.destinationHeight >= Rasterizer.MINIMUM_HEIGHT) { rasterizer = new Rasterizer(prim.p1x, prim.p1y, prim.p2x, prim.p2y, prim.p3x, prim.p3y, prim.pyMin, prim.pyMax); rasterizer.setY(prim.pyMin); } } int fbIndex = 0; int depthIndex = 0; int depthOffset = 0; final int[] memInt = renderer.memInt; if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex = renderer.fbAddress >> 2; depthIndex = renderer.depthAddress >> 2; depthOffset = (renderer.depthAddress >> 1) & 1; } // Use local variables instead of "pixel" members. // The Java JIT is then producing a slightly faster code. int pixelSource = pixel.source; int pixelSourceDepth = pixel.sourceDepth; int pixelDestination = 0; int pixelDestinationDepth = 0; int pixelPrimaryColor = pixel.primaryColor; int pixelSecondaryColor = pixel.secondaryColor; int pixelX = 0; int pixelY = 0; float pixelU = 0f; float pixelV = 0f; for (int y = prim.pyMin; y <= prim.pyMax; y++) { pixelY = y; int startX = prim.pxMin; int endX = prim.pxMax; if (isTriangle && rasterizer != null) { rasterizer.getNextRange(range); startX = max(range.xMin, startX); endX = min(range.xMax, endX); if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Rasterizer line (%d-%d,%d)", startX, endX, pixelY)); } } if (isTriangle && startX > endX) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex += prim.destinationWidth + renderer.imageWriterSkipEOL; if (needDepthWrite || needDestinationDepthRead) { depthOffset += prim.destinationWidth + renderer.depthWriterSkipEOL; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(prim.destinationWidth + renderer.imageWriterSkipEOL, prim.destinationWidth + renderer.depthWriterSkipEOL); } } else { if (needTextureUV && (!isTriangle || transform2D)) { u = prim.uStart; } if (isTriangle) { int startSkip = startX - prim.pxMin; if (startSkip > 0) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex += startSkip; if (needDepthWrite || needDestinationDepthRead) { depthOffset += startSkip; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(startSkip, startSkip); } if (transform2D) { u += startSkip * prim.uStep; } } pixel.x = startX; pixel.y = pixelY; prim.computeTriangleWeights(pixel); } for (int x = startX; x <= endX; x++) { if (isTriangle && !pixel.isInsideTriangle()) { // Pixel not inside triangle, skip the pixel if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d) outside triangle (%f, %f, %f)", x, pixelY, pixel.triangleWeight1, pixel.triangleWeight2, pixel.triangleWeight3)); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } } else { if (transform2D) { pixel.newPixel2D(); } else { pixel.newPixel3D(); } pixelX = x; if (needTextureUV) { if (isTriangle && !transform2D) { // Compute the mapped texture u,v coordinates // based on the Barycentric coordinates. // Apply a perspective correction by weighting the coordinates // by their "w" value. // See http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness u = pixel.getTriangleWeightedValue(t1uw, t2uw, t3uw); v = pixel.getTriangleWeightedValue(t1vw, t2vw, t3vw); float weightInverted = 1.f / pixel.getTriangleWeightedValue(prim.p1wInverted, prim.p2wInverted, prim.p3wInverted); pixelU = u * weightInverted; pixelV = v * weightInverted; } else { pixelU = u; pixelV = v; } } if (needSourceDepthRead) { if (isTriangle) { pixelSourceDepth = round(pixel.getTriangleWeightedValue(prim.p1z, prim.p2z, prim.p3z)); } else { pixelSourceDepth = sourceDepth; } } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { pixelDestination = memInt[fbIndex]; if (needDestinationDepthRead) { if (depthOffset == 0) { pixelDestinationDepth = memInt[depthIndex] & 0x0000FFFF; } else { pixelDestinationDepth = memInt[depthIndex] >>> 16; } } } else { rendererWriter.readCurrent(pixel); pixelDestination = pixel.destination; if (needDestinationDepthRead) { pixelDestinationDepth = pixel.destinationDepth; } } // Use a dummy "do { } while (false);" loop to allow to exit // quickly from the pixel rendering when a filter does not pass. // When a filter does not pass, the following is executed: // rendererWriter.skip(1, 1); // Skip the pixel // continue; do { if (setVertexPrimaryColor) { if (isTriangle) { if (sameVertexColor) { pixelPrimaryColor = pixel.c1; } else { pixelPrimaryColor = pixel.getTriangleColorWeightedValue(); } } } // // Material Flags // if (lightingFlagEnabled && !transform2D && useVertexColor && isTriangle) { if (matFlagAmbient) { pixel.materialAmbient = pixelPrimaryColor; } if (matFlagDiffuse) { pixel.materialDiffuse = pixelPrimaryColor; } if (matFlagSpecular) { pixel.materialSpecular = pixelPrimaryColor; } } // // Lighting // if (lightingFlagEnabled && !transform2D) { renderer.lightingFilter.filter(pixel); pixelPrimaryColor = pixel.primaryColor; pixelSecondaryColor = pixel.secondaryColor; } // // Texture // if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) { // // TextureMapping // if (!transform2D) { switch (texMapMode) { case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV: if (texScaleX != 1f) { pixelU *= renderer.texScaleX; } if (texTranslateX != 0f) { pixelU += renderer.texTranslateX; } if (texScaleY != 1f) { pixelV *= renderer.texScaleY; } if (texTranslateY != 0f) { pixelV += renderer.texTranslateY; } break; case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX: switch (texProjMapMode) { case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_POSITION: final float[] V = pixel.getV(); pixelU = V[0] * pixel.textureMatrix[0] + V[1] * pixel.textureMatrix[4] + V[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12]; pixelV = V[0] * pixel.textureMatrix[1] + V[1] * pixel.textureMatrix[5] + V[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13]; pixel.q = V[0] * pixel.textureMatrix[2] + V[1] * pixel.textureMatrix[6] + V[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14]; break; case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES: float tu = pixelU; float tv = pixelV; pixelU = tu * pixel.textureMatrix[0] + tv * pixel.textureMatrix[4] + pixel.textureMatrix[12]; pixelV = tu * pixel.textureMatrix[1] + tv * pixel.textureMatrix[5] + pixel.textureMatrix[13]; pixel.q = tu * pixel.textureMatrix[2] + tv * pixel.textureMatrix[6] + pixel.textureMatrix[14]; break; case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL: final float[] normalizedN = pixel.getNormalizedN(); pixelU = normalizedN[0] * pixel.textureMatrix[0] + normalizedN[1] * pixel.textureMatrix[4] + normalizedN[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12]; pixelV = normalizedN[0] * pixel.textureMatrix[1] + normalizedN[1] * pixel.textureMatrix[5] + normalizedN[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13]; pixel.q = normalizedN[0] * pixel.textureMatrix[2] + normalizedN[1] * pixel.textureMatrix[6] + normalizedN[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14]; break; case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMAL: final float[] N = pixel.getN(); pixelU = N[0] * pixel.textureMatrix[0] + N[1] * pixel.textureMatrix[4] + N[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12]; pixelV = N[0] * pixel.textureMatrix[1] + N[1] * pixel.textureMatrix[5] + N[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13]; pixel.q = N[0] * pixel.textureMatrix[2] + N[1] * pixel.textureMatrix[6] + N[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14]; break; } break; case GeCommands.TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: // Implementation based on shader.vert/ApplyTexture: // // vec3 Nn = normalize(N); // vec3 Ve = vec3(gl_ModelViewMatrix * V); // float k = gl_FrontMaterial.shininess; // vec3 Lu = gl_LightSource[texShade.x].position.xyz - Ve.xyz * gl_LightSource[texShade.x].position.w; // vec3 Lv = gl_LightSource[texShade.y].position.xyz - Ve.xyz * gl_LightSource[texShade.y].position.w; // float Pu = psp_lightKind[texShade.x] == 0 ? dot(Nn, normalize(Lu)) : pow(dot(Nn, normalize(Lu + vec3(0.0, 0.0, 1.0))), k); // float Pv = psp_lightKind[texShade.y] == 0 ? dot(Nn, normalize(Lv)) : pow(dot(Nn, normalize(Lv + vec3(0.0, 0.0, 1.0))), k); // T.xyz = vec3(0.5*vec2(1.0 + Pu, 1.0 + Pv), 1.0); // final float[] Ve = new float[3]; final float[] Ne = new float[3]; final float[] Lu = new float[3]; final float[] Lv = new float[3]; pixel.getVe(Ve); pixel.getNormalizedNe(Ne); for (int i = 0; i < 3; i++) { Lu[i] = renderer.envMapLightPosU[i] - Ve[i] * renderer.envMapLightPosU[3]; Lv[i] = renderer.envMapLightPosV[i] - Ve[i] * renderer.envMapLightPosV[3]; } float Pu; if (renderer.envMapDiffuseLightU) { normalize3(Lu, Lu); Pu = dot3(Ne, Lu); } else { Lu[2] += 1f; normalize3(Lu, Lu); Pu = (float) Math.pow(dot3(Ne, Lu), renderer.envMapShininess); } float Pv; if (renderer.envMapDiffuseLightV) { normalize3(Lv, Lv); Pv = dot3(Ne, Lv); } else { Lv[2] += 1f; normalize3(Lv, Lv); Pv = (float) Math.pow(dot3(Ne, Lv), renderer.envMapShininess); } pixelU = (Pu + 1f) * 0.5f; pixelV = (Pv + 1f) * 0.5f; pixel.q = 1f; break; } } // // TextureWrap // if (texWrapS == GeCommands.TWRAP_WRAP_MODE_REPEAT) { if (transform2D) { pixelU = wrap(pixelU, textureWidthMask); } else { pixelU = wrap(pixelU); } } if (texWrapT == GeCommands.TWRAP_WRAP_MODE_REPEAT) { if (transform2D) { pixelV = wrap(pixelV, textureHeightMask); } else { pixelV = wrap(pixelV); } } // // TextureReader // if (transform2D) { pixelSource = textureAccess.readPixel(pixelToTexel(pixelU), pixelToTexel(pixelV)); } else { pixelSource = textureAccess.readPixel(pixelToTexel(pixelU * textureWidthFloat), pixelToTexel(pixelV * textureHeightFloat)); } // // TextureFunction // switch (textureFunc) { case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE: if (textureAlphaUsed) { pixelSource = multiply(pixelSource, pixelPrimaryColor); } else { pixelSource = multiply(pixelSource | 0xFF000000, pixelPrimaryColor); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_DECAL: if (textureAlphaUsed) { alpha = getAlpha(pixelSource); a = getAlpha(pixelPrimaryColor); b = combineComponent(getBlue(pixelPrimaryColor), getBlue(pixelSource), alpha); g = combineComponent(getGreen(pixelPrimaryColor), getGreen(pixelSource), alpha); r = combineComponent(getRed(pixelPrimaryColor), getRed(pixelSource), alpha); pixelSource = getColor(a, b, g, r); } else { pixelSource = (pixelSource & 0x00FFFFFF) | (pixelPrimaryColor & 0xFF000000); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_BLEND: if (textureAlphaUsed) { a = multiplyComponent(getAlpha(pixelSource), getAlpha(pixelPrimaryColor)); b = combineComponent(getBlue(pixelPrimaryColor), renderer.texEnvColorB, getBlue(pixelSource)); g = combineComponent(getGreen(pixelPrimaryColor), renderer.texEnvColorG, getGreen(pixelSource)); r = combineComponent(getRed(pixelPrimaryColor), renderer.texEnvColorR, getRed(pixelSource)); pixelSource = getColor(a, b, g, r); } else { a = getAlpha(pixelPrimaryColor); b = combineComponent(getBlue(pixelPrimaryColor), renderer.texEnvColorB, getBlue(pixelSource)); g = combineComponent(getGreen(pixelPrimaryColor), renderer.texEnvColorG, getGreen(pixelSource)); r = combineComponent(getRed(pixelPrimaryColor), renderer.texEnvColorR, getRed(pixelSource)); pixelSource = getColor(a, b, g, r); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_REPLACE: if (!textureAlphaUsed) { pixelSource = (pixelSource & 0x00FFFFFF) | (pixelPrimaryColor & 0xFF000000); } break; case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_ADD: if (textureAlphaUsed) { a = multiplyComponent(getAlpha(pixelSource), getAlpha(pixelPrimaryColor)); pixelSource = setAlpha(addBGR(pixelSource, pixelPrimaryColor), a); } else { pixelSource = add(pixelSource & 0x00FFFFFF, pixelPrimaryColor); } break; } // // ColorDoubling // if (textureColorDoubled) { if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelSource = doubleColor(pixelSource); pixelSecondaryColor = doubleColor(pixelSecondaryColor); } else { pixelSource = doubleColor(pixelSource); } } // // SourceColor // if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelSource = add(pixelSource, pixelSecondaryColor); } } else { // // ColorDoubling // if (textureColorDoubled) { if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelPrimaryColor = doubleColor(pixelPrimaryColor); pixelSecondaryColor = doubleColor(pixelSecondaryColor); } else if (!primaryColorSetGlobally) { pixelPrimaryColor = doubleColor(pixelPrimaryColor); } } // // SourceColor // if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) { pixelSource = add(pixelPrimaryColor, pixelSecondaryColor); } else { pixelSource = pixelPrimaryColor; } } // // ScissorTest // if (transform2D) { if (needScissoringX && needScissoringY) { if (!(pixelX >= renderer.scissorX1 && pixelX <= renderer.scissorX2 && pixelY >= renderer.scissorY1 && pixelY <= renderer.scissorY2)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } else if (needScissoringX) { if (!(pixelX >= renderer.scissorX1 && pixelX <= renderer.scissorX2)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } else if (needScissoringY) { if (!(pixelY >= renderer.scissorY1 && pixelY <= renderer.scissorY2)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } } // // ScissorDepthTest // if (!transform2D && !clearMode) { if (nearZ != 0x0000 || farZ != 0xFFFF) { if (!(pixelSourceDepth >= renderer.nearZ && pixelSourceDepth <= renderer.farZ)) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } } // // ColorTest // if (colorTestFlagEnabled && !clearMode) { switch (colorTestFunc) { case GeCommands.CTST_COLOR_FUNCTION_ALWAYS_PASS_PIXEL: // Nothing to do break; case GeCommands.CTST_COLOR_FUNCTION_NEVER_PASS_PIXEL: if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_MATCHES: if ((pixelSource & renderer.colorTestMsk) != renderer.colorTestRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_DIFFERS: if ((pixelSource & renderer.colorTestMsk) == renderer.colorTestRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; } } // // AlphaTest // if (alphaTestFlagEnabled && !clearMode) { switch (alphaFunc) { case GeCommands.ATST_ALWAYS_PASS_PIXEL: // Nothing to do break; case GeCommands.ATST_NEVER_PASS_PIXEL: if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.ATST_PASS_PIXEL_IF_MATCHES: if (getAlpha(pixelSource) != alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_DIFFERS: if (getAlpha(pixelSource) == alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_LESS: if (getAlpha(pixelSource) >= alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_LESS_OR_EQUAL: // No test if alphaRef==0xFF if (RendererTemplate.alphaRef < 0xFF) { if (getAlpha(pixelSource) > alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } break; case GeCommands.ATST_PASS_PIXEL_IF_GREATER: if (getAlpha(pixelSource) <= alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL: // No test if alphaRef==0x00 if (RendererTemplate.alphaRef > 0x00) { if (getAlpha(pixelSource) < alphaRef) { if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } } break; } } // // StencilTest // if (stencilTestFlagEnabled && !clearMode) { switch (stencilFunc) { case GeCommands.STST_FUNCTION_NEVER_PASS_STENCIL_TEST: if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST: // Nothing to do break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_MATCHES: if ((getAlpha(pixelDestination) & renderer.stencilMask) != renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_DIFFERS: if ((getAlpha(pixelDestination) & renderer.stencilMask) == renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS: if ((getAlpha(pixelDestination) & renderer.stencilMask) >= renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL: if ((getAlpha(pixelDestination) & renderer.stencilMask) > renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER: if ((getAlpha(pixelDestination) & renderer.stencilMask) <= renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL: if ((getAlpha(pixelDestination) & renderer.stencilMask) < renderer.stencilRef) { if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; } } // // DepthTest // if (depthTestFlagEnabled && !clearMode) { switch (depthFunc) { case GeCommands.ZTST_FUNCTION_NEVER_PASS_PIXEL: if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; case GeCommands.ZTST_FUNCTION_ALWAYS_PASS_PIXEL: // No filter required break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_EQUAL: if (pixelSourceDepth != pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_ISNOT_EQUAL: if (pixelSourceDepth == pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS: if (pixelSourceDepth >= pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS_OR_EQUAL: if (pixelSourceDepth > pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER: if (pixelSourceDepth <= pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL: if (pixelSourceDepth < pixelDestinationDepth) { if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) { pixelDestination = stencilOpZFail(pixelDestination, stencilRefAlpha); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex++; if (needDepthWrite || needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(1, 1); } continue; } break; } } // // AlphaBlend // if (blendFlagEnabled && !clearMode) { int filteredSrc; int filteredDst; switch (blendEquation) { case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ADD: if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF && blendDst == GeCommands.ALPHA_FIX && dfix == 0x000000) { // Nothing to do, this is a NOP } else if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF && blendDst == GeCommands.ALPHA_FIX && dfix == 0xFFFFFF) { pixelSource = PixelColor.add(pixelSource, pixelDestination & 0x00FFFFFF); } else if (blendSrc == GeCommands.ALPHA_SOURCE_ALPHA && blendDst == GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA) { // This is the most common case and can be optimized int srcAlpha = pixelSource >>> 24; if (srcAlpha == ZERO) { // Set color of destination pixelSource = (pixelSource & 0xFF000000) | (pixelDestination & 0x00FFFFFF); } else if (srcAlpha == ONE) { // Nothing to change } else { int oneMinusSrcAlpha = ONE - srcAlpha; filteredSrc = multiplyBGR(pixelSource, srcAlpha, srcAlpha, srcAlpha); filteredDst = multiplyBGR(pixelDestination, oneMinusSrcAlpha, oneMinusSrcAlpha, oneMinusSrcAlpha); pixelSource = setBGR(pixelSource, addBGR(filteredSrc, filteredDst)); } } else { filteredSrc = multiplyBGR(pixelSource, blendSrc(pixelSource, pixelDestination, renderer.sfix)); filteredDst = multiplyBGR(pixelDestination, blendDst(pixelSource, pixelDestination, renderer.dfix)); pixelSource = setBGR(pixelSource, addBGR(filteredSrc, filteredDst)); } break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT: filteredSrc = multiplyBGR(pixelSource, blendSrc(pixelSource, pixelDestination, renderer.sfix)); filteredDst = multiplyBGR(pixelDestination, blendDst(pixelSource, pixelDestination, renderer.dfix)); pixelSource = setBGR(pixelSource, substractBGR(filteredSrc, filteredDst)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT: filteredSrc = multiplyBGR(pixelSource, blendSrc(pixelSource, pixelDestination, renderer.sfix)); filteredDst = multiplyBGR(pixelDestination, blendDst(pixelSource, pixelDestination, renderer.dfix)); pixelSource = setBGR(pixelSource, substractBGR(filteredDst, filteredSrc)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE: // Source and destination factors are not applied pixelSource = setBGR(pixelSource, minBGR(pixelSource, pixelDestination)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE: // Source and destination factors are not applied pixelSource = setBGR(pixelSource, maxBGR(pixelSource, pixelDestination)); break; case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE: // Source and destination factors are not applied pixelSource = setBGR(pixelSource, absBGR(pixelSource, pixelDestination)); break; } } // // StencilOpZPass // if (stencilTestFlagEnabled && !clearMode) { switch (stencilOpZPass) { case GeCommands.SOP_KEEP_STENCIL_VALUE: pixelSource = (pixelSource & 0x00FFFFFF) | (pixelDestination & 0xFF000000); break; case GeCommands.SOP_ZERO_STENCIL_VALUE: pixelSource &= 0x00FFFFFF; break; case GeCommands.SOP_REPLACE_STENCIL_VALUE: if (stencilRef == 0) { // SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent // to SOP_ZERO_STENCIL_VALUE pixelSource &= 0x00FFFFFF; } else { pixelSource = (pixelSource & 0x00FFFFFF) | stencilRefAlpha; } break; case GeCommands.SOP_INVERT_STENCIL_VALUE: pixelSource = (pixelSource & 0x00FFFFFF) | ((~pixelDestination) & 0xFF000000); break; case GeCommands.SOP_INCREMENT_STENCIL_VALUE: alpha = pixelDestination & 0xFF000000; if (alpha != 0xFF000000) { alpha += 0x01000000; } pixelSource = (pixelSource & 0x00FFFFFF) | alpha; break; case GeCommands.SOP_DECREMENT_STENCIL_VALUE: alpha = pixelDestination & 0xFF000000; if (alpha != 0x00000000) { alpha -= 0x01000000; } pixelSource = (pixelSource & 0x00FFFFFF) | alpha; break; } } // // ColorLogicalOperation // if (colorLogicOpFlagEnabled && !clearMode) { switch (logicOp) { case GeCommands.LOP_CLEAR: pixelSource = ZERO; break; case GeCommands.LOP_AND: pixelSource &= pixelDestination; break; case GeCommands.LOP_REVERSE_AND: pixelSource &= (~pixelDestination); break; case GeCommands.LOP_COPY: // This is a NOP break; case GeCommands.LOP_INVERTED_AND: pixelSource = (~pixelSource) & pixelDestination; break; case GeCommands.LOP_NO_OPERATION: pixelSource = pixelDestination; break; case GeCommands.LOP_EXLUSIVE_OR: pixelSource ^= pixelDestination; break; case GeCommands.LOP_OR: pixelSource |= pixelDestination; break; case GeCommands.LOP_NEGATED_OR: pixelSource = ~(pixelSource | pixelDestination); break; case GeCommands.LOP_EQUIVALENCE: pixelSource = ~(pixelSource ^ pixelDestination); break; case GeCommands.LOP_INVERTED: pixelSource = ~pixelDestination; break; case GeCommands.LOP_REVERSE_OR: pixelSource |= (~pixelDestination); break; case GeCommands.LOP_INVERTED_COPY: pixelSource = ~pixelSource; break; case GeCommands.LOP_INVERTED_OR: pixelSource = (~pixelSource) | pixelDestination; break; case GeCommands.LOP_NEGATED_AND: pixelSource = ~(pixelSource & pixelDestination); break; case GeCommands.LOP_SET: pixelSource = 0xFFFFFFFF; break; } } // // ColorMask // if (clearMode) { if (clearModeColor) { if (!clearModeStencil) { pixelSource = (pixelSource & 0x00FFFFFF) | (pixelDestination & 0xFF000000); } } else { if (clearModeStencil) { pixelSource = (pixelSource & 0xFF000000) | (pixelDestination & 0x00FFFFFF); } else { pixelSource = pixelDestination; } } } else { if (colorMask != 0x00000000) { pixelSource = (pixelSource & notColorMask) | (pixelDestination & colorMask); } } // // DepthMask // if (needDepthWrite) { if (clearMode) { if (!clearModeDepth) { pixelSourceDepth = pixelDestinationDepth; } } else if (!depthTestFlagEnabled) { // Depth writes are disabled when the depth test is not enabled. pixelSourceDepth = pixelDestinationDepth; } else if (!depthMask) { pixelSourceDepth = pixelDestinationDepth; } } // // Filter passed // if (isLogTraceEnabled) { VideoEngine.log.trace(String.format("Pixel (%d,%d), passed=true, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", pixelX, pixelY, pixelU, pixelV, pixelSource, pixelDestination, pixelPrimaryColor, pixelSecondaryColor, pixelSourceDepth, pixelDestinationDepth)); } if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { memInt[fbIndex] = pixelSource; fbIndex++; if (needDepthWrite) { if (depthOffset == 0) { memInt[depthIndex] = (memInt[depthIndex] & 0xFFFF0000) | (pixelSourceDepth & 0x0000FFFF); depthOffset = 1; } else { memInt[depthIndex] = (memInt[depthIndex] & 0x0000FFFF) | (pixelSourceDepth << 16); depthIndex++; depthOffset = 0; } } else if (needDestinationDepthRead) { depthOffset++; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { pixel.source = pixelSource; if (needDepthWrite) { pixel.sourceDepth = pixelSourceDepth; } rendererWriter.writeNext(pixel); } } while (false); } if (needTextureUV && (!isTriangle || transform2D)) { u += prim.uStep; } if (isTriangle) { prim.deltaXTriangleWeigths(pixel); } } int skip = prim.pxMax - endX; if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) { fbIndex += skip + renderer.imageWriterSkipEOL; if (needDepthWrite || needDestinationDepthRead) { depthOffset += skip + renderer.depthWriterSkipEOL; depthIndex += depthOffset >> 1; depthOffset &= 1; } } else { rendererWriter.skip(skip + renderer.imageWriterSkipEOL, skip + renderer.depthWriterSkipEOL); } } if (needTextureUV && (!isTriangle || transform2D)) { v += prim.vStep; } } doRenderEnd(renderer); }
diff --git a/src/rpisdd/rpgme/gamelogic/quests/DateHelper.java b/src/rpisdd/rpgme/gamelogic/quests/DateHelper.java index 11697a0..d823700 100644 --- a/src/rpisdd/rpgme/gamelogic/quests/DateHelper.java +++ b/src/rpisdd/rpgme/gamelogic/quests/DateHelper.java @@ -1,47 +1,47 @@ package rpisdd.rpgme.gamelogic.quests; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; public class DateHelper { // Take in a date and format it, returning a reader-friendly string. // Later this could use words/phrases like "Tomorrow", "In a week", // "In an hour", etc. public static String formatDate(DateTime date) { - String formatDate = DateTimeFormat.forPattern("M/d/Y 'at' h:m a") + String formatDate = DateTimeFormat.forPattern("M/d/Y 'at' h:mm a") .print(date); return formatDate; } // Is date at least one minute ago from now? public static boolean oneMinuteAgo(DateTime date) { return oneDayAgo(date) || date.getMinuteOfDay() < DateTime.now().getMinuteOfDay(); } // Is date at least one day ago from now? public static boolean oneDayAgo(DateTime date) { return oneYearAgo(date) || date.getDayOfYear() < DateTime.now().getDayOfYear(); } // Is date at least one week ago from now? public static boolean oneWeekAgo(DateTime date) { return oneYearAgo(date) || date.getWeekOfWeekyear() < DateTime.now() .getWeekOfWeekyear(); } // Is day at least one month ago from now? public static boolean oneMonthAgo(DateTime date) { return oneYearAgo(date) || date.getMonthOfYear() < DateTime.now().getMonthOfYear(); } // Is day at least one year ago from now? public static boolean oneYearAgo(DateTime date) { return date.getYear() < DateTime.now().getYear(); } }
true
true
public static String formatDate(DateTime date) { String formatDate = DateTimeFormat.forPattern("M/d/Y 'at' h:m a") .print(date); return formatDate; }
public static String formatDate(DateTime date) { String formatDate = DateTimeFormat.forPattern("M/d/Y 'at' h:mm a") .print(date); return formatDate; }
diff --git a/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/admin/MetadataFieldRegistryServlet.java b/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/admin/MetadataFieldRegistryServlet.java index e3cf6bfea..bd8f6ab61 100644 --- a/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/admin/MetadataFieldRegistryServlet.java +++ b/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/admin/MetadataFieldRegistryServlet.java @@ -1,379 +1,389 @@ /* * MetadataFieldRegistryServlet.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND 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 THE COPYRIGHT * HOLDERS OR CONTRIBUTORS 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 org.dspace.app.webui.servlet.admin; import java.io.IOException; import java.sql.SQLException; import java.util.Locale; import java.util.ResourceBundle; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.servlet.DSpaceServlet; import org.dspace.app.webui.util.JSPManager; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.content.MetadataField; import org.dspace.content.MetadataSchema; import org.dspace.content.NonUniqueMetadataException; import org.dspace.core.Context; import org.dspace.core.I18nUtil; /** * Servlet for editing the Dublin Core registry * * @author Robert Tansley * @author Martin Hald * @version $Revision$ */ public class MetadataFieldRegistryServlet extends DSpaceServlet { /** Logger */ private static Logger log = Logger.getLogger(MetadataFieldRegistryServlet.class); private String clazz = "org.dspace.app.webui.servlet.admin.MetadataFieldRegistryServlet"; /** * @see org.dspace.app.webui.servlet.DSpaceServlet#doDSGet(org.dspace.core.Context, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // GET just displays the list of type int schemaID = getSchemaID(request); showTypes(context, request, response, schemaID); } /** * @see org.dspace.app.webui.servlet.DSpaceServlet#doDSPost(org.dspace.core.Context, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); int schemaID = getSchemaID(request); // Get access to the localized resource bundle Locale locale = context.getCurrentLocale(); ResourceBundle labels = ResourceBundle.getBundle("Messages", locale); if (button.equals("submit_update")) { // The sanity check will update the request error string if needed if (!sanityCheck(request, labels)) { showTypes(context, request, response, schemaID); context.abort(); return; } try { // Update the metadata for a DC type MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); dc.setElement(request.getParameter("element")); String qual = request.getParameter("qualifier"); if (qual.equals("")) { qual = null; } dc.setQualifier(qual); dc.setScopeNote(request.getParameter("scope_note")); dc.update(context); showTypes(context, request, response, schemaID); context.complete(); } catch (NonUniqueMetadataException e) { context.abort(); log.error(e); } } else if (button.equals("submit_add")) { // The sanity check will update the request error string if needed if (!sanityCheck(request, labels)) { showTypes(context, request, response, schemaID); context.abort(); return; } // Add a new DC type - simply add to the list, and let the user // edit with the main form try { MetadataField dc = new MetadataField(); dc.setSchemaID(schemaID); dc.setElement(request.getParameter("element")); String qual = request.getParameter("qualifier"); if (qual.equals("")) { qual = null; } dc.setQualifier(qual); dc.setScopeNote(request.getParameter("scope_note")); dc.create(context); showTypes(context, request, response, schemaID); context.complete(); } catch (NonUniqueMetadataException e) { // Record the exception as a warning log.warn(e); // Show the page again but with an error message to inform the // user that the metadata field was not created and why request.setAttribute("error", labels.getString(clazz + ".createfailed")); showTypes(context, request, response, schemaID); context.abort(); } } else if (button.equals("submit_delete")) { // Start delete process - go through verification step MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); request.setAttribute("type", dc); JSPManager.showJSP(request, response, "/dspace-admin/confirm-delete-mdfield.jsp"); } else if (button.equals("submit_confirm_delete")) { // User confirms deletion of type MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); - dc.delete(context); - showTypes(context, request, response, schemaID); + try + { + dc.delete(context); + request.setAttribute("failed", new Boolean(false)); + showTypes(context, request, response, schemaID); + } catch (Exception e) + { + request.setAttribute("type", dc); + request.setAttribute("failed", true); + JSPManager.showJSP(request, response, + "/dspace-admin/confirm-delete-mdfield.jsp"); + } context.complete(); } else if (button.equals("submit_move")) { // User requests that one or more metadata elements be moved to a // new metadata schema. Note that we change the default schema ID to // be the destination schema. try { schemaID = Integer.parseInt(request .getParameter("dc_dest_schema_id")); String[] param = request.getParameterValues("dc_field_id"); if (schemaID == 0 || param == null) { request.setAttribute("error", labels.getString(clazz + ".movearguments")); showTypes(context, request, response, schemaID); context.abort(); } else { for (int ii = 0; ii < param.length; ii++) { int fieldID = Integer.parseInt(param[ii]); MetadataField field = MetadataField.find(context, fieldID); field.setSchemaID(schemaID); field.update(context); } context.complete(); // Send the user to the metadata schema in which they just moved // the metadata fields response.sendRedirect(request.getContextPath() + "/dspace-admin/metadata-schema-registry?dc_schema_id=" + schemaID); } } catch (NonUniqueMetadataException e) { // Record the exception as a warning log.warn(e); // Show the page again but with an error message to inform the // user that the metadata field could not be moved request.setAttribute("error", labels.getString(clazz + ".movefailed")); showTypes(context, request, response, schemaID); context.abort(); } } else { // Cancel etc. pressed - show list again showTypes(context, request, response, schemaID); } } /** * Get the schema that we are currently working in from the HTTP request. If * not present then default to the DSpace Dublin Core schema (schemaID 1). * * @param request * @return the current schema ID */ private int getSchemaID(HttpServletRequest request) { int schemaID = MetadataSchema.DC_SCHEMA_ID; if (request.getParameter("dc_schema_id") != null) { schemaID = Integer.parseInt(request.getParameter("dc_schema_id")); } return schemaID; } /** * Show list of DC type * * @param context * Current DSpace context * @param request * Current HTTP request * @param response * Current HTTP response * @param schemaID * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ private void showTypes(Context context, HttpServletRequest request, HttpServletResponse response, int schemaID) throws ServletException, IOException, SQLException, AuthorizeException { // Find matching metadata fields MetadataField[] types = MetadataField .findAllInSchema(context, schemaID); request.setAttribute("types", types); // Pull the metadata schema object as well MetadataSchema schema = MetadataSchema.find(context, schemaID); request.setAttribute("schema", schema); // Pull all metadata schemas for the pulldown MetadataSchema[] schemas = MetadataSchema.findAll(context); request.setAttribute("schemas", schemas); JSPManager .showJSP(request, response, "/dspace-admin/list-metadata-fields.jsp"); } /** * Return false if the metadata field fail to pass the constraint tests. If * there is an error the request error String will be updated with an error * description. * * @param request * @param labels * @return true of false */ private boolean sanityCheck(HttpServletRequest request, ResourceBundle labels) { String element = request.getParameter("element"); if (element.length() == 0) { return error(request, labels.getString(clazz + ".elemempty")); } for (int ii = 0; ii < element.length(); ii++) { if (element.charAt(ii) == '.' || element.charAt(ii) == '_' || element.charAt(ii) == ' ') { return error(request, labels.getString(clazz + ".badelemchar")); } } if (element.length() > 64) { return error(request, labels.getString(clazz + ".elemtoolong")); } String qualifier = request.getParameter("qualifier"); if (qualifier == "") { qualifier = null; } if (qualifier != null) { if (qualifier.length() > 64) { return error(request, labels.getString(clazz + ".qualtoolong")); } for (int ii = 0; ii < qualifier.length(); ii++) { if (qualifier.charAt(ii) == '.' || qualifier.charAt(ii) == '_' || qualifier.charAt(ii) == ' ') { return error(request, labels.getString(clazz + ".badqualchar")); } } } return true; } /** * Bind the error text to the request object. * * @param request * @param text * @return false */ private boolean error(HttpServletRequest request, String text) { request.setAttribute("error", text); return false; } }
true
true
protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); int schemaID = getSchemaID(request); // Get access to the localized resource bundle Locale locale = context.getCurrentLocale(); ResourceBundle labels = ResourceBundle.getBundle("Messages", locale); if (button.equals("submit_update")) { // The sanity check will update the request error string if needed if (!sanityCheck(request, labels)) { showTypes(context, request, response, schemaID); context.abort(); return; } try { // Update the metadata for a DC type MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); dc.setElement(request.getParameter("element")); String qual = request.getParameter("qualifier"); if (qual.equals("")) { qual = null; } dc.setQualifier(qual); dc.setScopeNote(request.getParameter("scope_note")); dc.update(context); showTypes(context, request, response, schemaID); context.complete(); } catch (NonUniqueMetadataException e) { context.abort(); log.error(e); } } else if (button.equals("submit_add")) { // The sanity check will update the request error string if needed if (!sanityCheck(request, labels)) { showTypes(context, request, response, schemaID); context.abort(); return; } // Add a new DC type - simply add to the list, and let the user // edit with the main form try { MetadataField dc = new MetadataField(); dc.setSchemaID(schemaID); dc.setElement(request.getParameter("element")); String qual = request.getParameter("qualifier"); if (qual.equals("")) { qual = null; } dc.setQualifier(qual); dc.setScopeNote(request.getParameter("scope_note")); dc.create(context); showTypes(context, request, response, schemaID); context.complete(); } catch (NonUniqueMetadataException e) { // Record the exception as a warning log.warn(e); // Show the page again but with an error message to inform the // user that the metadata field was not created and why request.setAttribute("error", labels.getString(clazz + ".createfailed")); showTypes(context, request, response, schemaID); context.abort(); } } else if (button.equals("submit_delete")) { // Start delete process - go through verification step MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); request.setAttribute("type", dc); JSPManager.showJSP(request, response, "/dspace-admin/confirm-delete-mdfield.jsp"); } else if (button.equals("submit_confirm_delete")) { // User confirms deletion of type MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); dc.delete(context); showTypes(context, request, response, schemaID); context.complete(); } else if (button.equals("submit_move")) { // User requests that one or more metadata elements be moved to a // new metadata schema. Note that we change the default schema ID to // be the destination schema. try { schemaID = Integer.parseInt(request .getParameter("dc_dest_schema_id")); String[] param = request.getParameterValues("dc_field_id"); if (schemaID == 0 || param == null) { request.setAttribute("error", labels.getString(clazz + ".movearguments")); showTypes(context, request, response, schemaID); context.abort(); } else { for (int ii = 0; ii < param.length; ii++) { int fieldID = Integer.parseInt(param[ii]); MetadataField field = MetadataField.find(context, fieldID); field.setSchemaID(schemaID); field.update(context); } context.complete(); // Send the user to the metadata schema in which they just moved // the metadata fields response.sendRedirect(request.getContextPath() + "/dspace-admin/metadata-schema-registry?dc_schema_id=" + schemaID); } } catch (NonUniqueMetadataException e) { // Record the exception as a warning log.warn(e); // Show the page again but with an error message to inform the // user that the metadata field could not be moved request.setAttribute("error", labels.getString(clazz + ".movefailed")); showTypes(context, request, response, schemaID); context.abort(); } } else { // Cancel etc. pressed - show list again showTypes(context, request, response, schemaID); } }
protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { String button = UIUtil.getSubmitButton(request, "submit"); int schemaID = getSchemaID(request); // Get access to the localized resource bundle Locale locale = context.getCurrentLocale(); ResourceBundle labels = ResourceBundle.getBundle("Messages", locale); if (button.equals("submit_update")) { // The sanity check will update the request error string if needed if (!sanityCheck(request, labels)) { showTypes(context, request, response, schemaID); context.abort(); return; } try { // Update the metadata for a DC type MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); dc.setElement(request.getParameter("element")); String qual = request.getParameter("qualifier"); if (qual.equals("")) { qual = null; } dc.setQualifier(qual); dc.setScopeNote(request.getParameter("scope_note")); dc.update(context); showTypes(context, request, response, schemaID); context.complete(); } catch (NonUniqueMetadataException e) { context.abort(); log.error(e); } } else if (button.equals("submit_add")) { // The sanity check will update the request error string if needed if (!sanityCheck(request, labels)) { showTypes(context, request, response, schemaID); context.abort(); return; } // Add a new DC type - simply add to the list, and let the user // edit with the main form try { MetadataField dc = new MetadataField(); dc.setSchemaID(schemaID); dc.setElement(request.getParameter("element")); String qual = request.getParameter("qualifier"); if (qual.equals("")) { qual = null; } dc.setQualifier(qual); dc.setScopeNote(request.getParameter("scope_note")); dc.create(context); showTypes(context, request, response, schemaID); context.complete(); } catch (NonUniqueMetadataException e) { // Record the exception as a warning log.warn(e); // Show the page again but with an error message to inform the // user that the metadata field was not created and why request.setAttribute("error", labels.getString(clazz + ".createfailed")); showTypes(context, request, response, schemaID); context.abort(); } } else if (button.equals("submit_delete")) { // Start delete process - go through verification step MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); request.setAttribute("type", dc); JSPManager.showJSP(request, response, "/dspace-admin/confirm-delete-mdfield.jsp"); } else if (button.equals("submit_confirm_delete")) { // User confirms deletion of type MetadataField dc = MetadataField.find(context, UIUtil .getIntParameter(request, "dc_type_id")); try { dc.delete(context); request.setAttribute("failed", new Boolean(false)); showTypes(context, request, response, schemaID); } catch (Exception e) { request.setAttribute("type", dc); request.setAttribute("failed", true); JSPManager.showJSP(request, response, "/dspace-admin/confirm-delete-mdfield.jsp"); } context.complete(); } else if (button.equals("submit_move")) { // User requests that one or more metadata elements be moved to a // new metadata schema. Note that we change the default schema ID to // be the destination schema. try { schemaID = Integer.parseInt(request .getParameter("dc_dest_schema_id")); String[] param = request.getParameterValues("dc_field_id"); if (schemaID == 0 || param == null) { request.setAttribute("error", labels.getString(clazz + ".movearguments")); showTypes(context, request, response, schemaID); context.abort(); } else { for (int ii = 0; ii < param.length; ii++) { int fieldID = Integer.parseInt(param[ii]); MetadataField field = MetadataField.find(context, fieldID); field.setSchemaID(schemaID); field.update(context); } context.complete(); // Send the user to the metadata schema in which they just moved // the metadata fields response.sendRedirect(request.getContextPath() + "/dspace-admin/metadata-schema-registry?dc_schema_id=" + schemaID); } } catch (NonUniqueMetadataException e) { // Record the exception as a warning log.warn(e); // Show the page again but with an error message to inform the // user that the metadata field could not be moved request.setAttribute("error", labels.getString(clazz + ".movefailed")); showTypes(context, request, response, schemaID); context.abort(); } } else { // Cancel etc. pressed - show list again showTypes(context, request, response, schemaID); } }
diff --git a/fingerpaint/src/nl/tue/fingerpaint/client/gui/CustomTreeModel.java b/fingerpaint/src/nl/tue/fingerpaint/client/gui/CustomTreeModel.java index e752f85..dde5a33 100644 --- a/fingerpaint/src/nl/tue/fingerpaint/client/gui/CustomTreeModel.java +++ b/fingerpaint/src/nl/tue/fingerpaint/client/gui/CustomTreeModel.java @@ -1,385 +1,385 @@ package nl.tue.fingerpaint.client.gui; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import nl.tue.fingerpaint.client.Fingerpaint; import nl.tue.fingerpaint.client.gui.buttons.CircleDrawingToolToggleButton; import nl.tue.fingerpaint.client.gui.buttons.ComparePerformanceButton; import nl.tue.fingerpaint.client.gui.buttons.ExportDistributionButton; import nl.tue.fingerpaint.client.gui.buttons.ExportSingleGraphButton; import nl.tue.fingerpaint.client.gui.buttons.LoadInitDistButton; import nl.tue.fingerpaint.client.gui.buttons.LoadProtocolButton; import nl.tue.fingerpaint.client.gui.buttons.MixNowButton; import nl.tue.fingerpaint.client.gui.buttons.OverwriteSaveButton; import nl.tue.fingerpaint.client.gui.buttons.RemoveInitDistButton; import nl.tue.fingerpaint.client.gui.buttons.RemoveSavedProtButton; import nl.tue.fingerpaint.client.gui.buttons.ResetDistButton; import nl.tue.fingerpaint.client.gui.buttons.ResetProtocolButton; import nl.tue.fingerpaint.client.gui.buttons.SaveDistributionButton; import nl.tue.fingerpaint.client.gui.buttons.SaveItemPanelButton; import nl.tue.fingerpaint.client.gui.buttons.SaveProtocolButton; import nl.tue.fingerpaint.client.gui.buttons.SaveResultsButton; import nl.tue.fingerpaint.client.gui.buttons.SquareDrawingToolToggleButton; import nl.tue.fingerpaint.client.gui.buttons.ToggleColourButton; import nl.tue.fingerpaint.client.gui.buttons.ToggleDefineProtocol; import nl.tue.fingerpaint.client.gui.buttons.ViewSingleGraphButton; import nl.tue.fingerpaint.client.gui.celllists.LoadInitDistCellList; import nl.tue.fingerpaint.client.gui.celllists.LoadProtocolCellList; import nl.tue.fingerpaint.client.gui.celllists.LoadResultsCellList; import nl.tue.fingerpaint.client.gui.spinners.CursorSizeSpinner; import nl.tue.fingerpaint.client.gui.spinners.NrStepsSpinner; import nl.tue.fingerpaint.client.gui.spinners.StepSizeSpinner; import nl.tue.fingerpaint.client.model.ApplicationState; import nl.tue.fingerpaint.client.model.Geometry.StepAddedListener; import nl.tue.fingerpaint.client.model.RectangleGeometry; import nl.tue.fingerpaint.client.serverdata.ServerDataCache; import nl.tue.fingerpaint.shared.GeometryNames; import nl.tue.fingerpaint.shared.model.MixingProtocol; import nl.tue.fingerpaint.shared.model.MixingStep; import com.google.gwt.cell.client.ClickableTextCell; import com.google.gwt.cell.client.ValueUpdater; import com.google.gwt.user.cellview.client.CellBrowser; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.view.client.ListDataProvider; import com.google.gwt.view.client.SelectionChangeEvent; import com.google.gwt.view.client.SingleSelectionModel; import com.google.gwt.view.client.TreeViewModel; /** * The model that defines the nodes in the {@link CellBrowser} that is used as a * main menu. */ public class CustomTreeModel implements TreeViewModel { /** * Number of levels in the tree. Is used to determine when the browser * should be closed. */ private final static int NUM_LEVELS = 2; /** Reference to the "parent" class. Used for executing mixing runs. */ private Fingerpaint fp; /** * Reference to the state of the application, to update stuff there when a * menu item is selected. */ private ApplicationState as; /** A selection model that is shared along all levels. */ private final SingleSelectionModel<String> selectionModel = new SingleSelectionModel<String>(); /** Updater on the highest level. */ private final ValueUpdater<String> valueGeometryUpdater = new ValueUpdater<String>() { @Override public void update(String value) { as.setGeometryChoice(value); lastClickedLevel = 0; } }; /** Updater on level 1. */ private final ValueUpdater<String> valueMixerUpdater = new ValueUpdater<String>() { @Override public void update(String value) { as.setMixerChoice(value); lastClickedLevel = 1; } }; /** Indicate which level was clicked the last. */ private int lastClickedLevel = -1; /** * Creates the chosen geometry. */ private void createGeometry() { if (as.getGeometryChoice().equals(GeometryNames.RECT)) { as.setGeometry(new RectangleGeometry(Window.getClientHeight(), Window.getClientWidth(), 240, 400)); } else if (as.getGeometryChoice().equals(GeometryNames.SQR)) { int size = Math.min(Window.getClientHeight(), Window.getClientWidth()); as.setGeometry(new RectangleGeometry(size - 20, size - 20, 240, 240)); Logger.getLogger("").log(Level.INFO, "Length of distribution array: " + as.getGeometry().getDistribution().length); } else { // No valid mixer was selected Logger.getLogger("").log(Level.WARNING, "Invalid geometry selected"); } } /** * Construct a specific {@link TreeViewModel} that can be used in the * {@link CellBrowser} of the Fingerpaint application. * * @param parent * A reference to the Fingerpaint class. Used to execute mixing * protocols. * @param appState * Reference to the model that holds the state of the * application. */ public CustomTreeModel(Fingerpaint parent, ApplicationState appState) { this.fp = parent; this.as = appState; selectionModel .addSelectionChangeHandler(new SelectionChangeEvent.Handler() { @Override public void onSelectionChange(SelectionChangeEvent event) { String selected = selectionModel.getSelectedObject(); if (selected != null) { if (lastClickedLevel == NUM_LEVELS - 1) { as.setMixerChoice(selected); // "closes" Cellbrowser widget (clears whole // rootpanel) RootPanel.get().clear(); createGeometry(); createMixingWidgets(); } else if (lastClickedLevel == NUM_LEVELS - 2) { as.setGeometryChoice(selected); } } } }); } /** * Helper method that initialises the widgets for the mixing interface */ private void createMixingWidgets() { // Initialise a listener for when a new step is entered to the // protocol StepAddedListener l = new StepAddedListener() { @Override public void onStepAdded(MixingStep step) { addStep(step); } }; as.getGeometry().addStepAddedListener(l); // Initialise the cursorSizeSpinner so it can be added to the tool // selector popup GuiState.cursorSizeSpinner = new CursorSizeSpinner(as); // Initialise the toolSelectButton and add it to the menu panel // Also intialise the widgets in the submenu that this button toggles GuiState.squareDrawingTool = new SquareDrawingToolToggleButton(fp, as); GuiState.circleDrawingTool = new CircleDrawingToolToggleButton(fp, as); GuiState.mainMenuPanel.add(GuiState.toolSelectButton); // Initialise toggleButton and add to // menuPanel GuiState.toggleColor = new ToggleColourButton(as); GuiState.mainMenuPanel.add(GuiState.toggleColor); // Initialise the distribution buttons and add a button to access those // to the menu panel. Also add the 'clear canvas' to the main menu GuiState.resetDistButton = new ResetDistButton(as); GuiState.mainMenuPanel.add(GuiState.resetDistButton); GuiState.saveDistributionButton = new SaveDistributionButton(fp); GuiState.loadInitDistButton = new LoadInitDistButton(as); GuiState.loadInitDistCellList = new LoadInitDistCellList(as); GuiState.removeInitDistButton = new RemoveInitDistButton(as); GuiState.exportDistributionButton = new ExportDistributionButton(as); GuiState.mainMenuPanel.add(GuiState.distributionsButton); // Initialise the saveResultsButton and add it to the menuPanel GuiState.saveResultsButton = new SaveResultsButton(fp); GuiState.saveResultsButton.setEnabled(false); GuiState.mainMenuPanel.add(GuiState.saveResultsButton); // Initialise panel to save items GuiState.overwriteSaveButton = new OverwriteSaveButton(fp); GuiState.saveItemPanelButton = new SaveItemPanelButton(fp); GuiState.saveItemPanel.add(GuiState.saveItemVerticalPanel); GuiState.saveItemVerticalPanel.add(GuiState.saveNameTextBox); GuiState.saveItemVerticalPanel.add(GuiState.saveButtonsPanel); GuiState.saveButtonsPanel.add(GuiState.saveItemPanelButton); GuiState.saveButtonsPanel.add(GuiState.cancelSaveResultsButton); // Initialise panel to overwrite already saved items GuiState.overwriteSavePanel.add(GuiState.overwriteSaveVerticalPanel); GuiState.overwriteSaveVerticalPanel.add(GuiState.saveMessageLabel); GuiState.overwriteSaveVerticalPanel.add(GuiState.overwriteButtonsPanel); GuiState.overwriteButtonsPanel.add(GuiState.closeSaveButton); //Initialise the LoadResultsCellList and add the loadResultsButton - GuiState.menuPanel.add(GuiState.loadResultsButton); + GuiState.mainMenuPanel.add(GuiState.loadResultsButton); GuiState.LoadResultsCellList = new LoadResultsCellList(fp, as); // Initialise the removeSavedResultsButton and add it to the // menuPanel GuiState.removeResultsPanel.add(GuiState.removeResultsVerticalPanel); GuiState.mainMenuPanel.add(GuiState.removeSavedResultsButton); GuiState.viewSingleGraphButton = new ViewSingleGraphButton(fp, as); GuiState.exportSingleGraphButton = new ExportSingleGraphButton(fp); GuiState.mainMenuPanel.add(GuiState.viewSingleGraphButton); // Initialise the comparePerformanceButton and add it to the // menuPanel // createComparePerformanceButton(); GuiState.comparePerformanceButton = new ComparePerformanceButton(fp); GuiState.mainMenuPanel.add(GuiState.comparePerformanceButton); // Initialise a spinner for changing the length of a mixing protocol // step and add to menuPanel. GuiState.sizeSpinner = new StepSizeSpinner(as); GuiState.mainMenuPanel.add(GuiState.sizeLabel); GuiState.mainMenuPanel.add(GuiState.sizeSpinner); // Initialise the toggleButton that indicates whether a protocol is // being defined, or single steps have to be executed and add to // menu panel GuiState.toggleDefineProtocol = new ToggleDefineProtocol(fp); GuiState.mainMenuPanel.add(GuiState.toggleDefineProtocol); // Initialise a spinner for #steps GuiState.nrStepsSpinner = new NrStepsSpinner(as); // Initialise the resetProtocol button GuiState.resetProtocolButton = new ResetProtocolButton(fp); // Initialise the saveProtocolButton and add it to the menuPanel GuiState.saveProtocolButton = new SaveProtocolButton(fp); // Initialise the mixNow button GuiState.mixNowButton = new MixNowButton(fp, as); // Initialise the loadProtocolButton GuiState.loadProtocolButton = new LoadProtocolButton(as); GuiState.loadProtocolCellList = new LoadProtocolCellList(as); // Initialise the loadProtocolButton GuiState.removeSavedProtButton = new RemoveSavedProtButton(as); // Add all the protocol widgets to the menuPanel and hide them // initially. VerticalPanel protocolPanel = new VerticalPanel(); protocolPanel.add(GuiState.nrStepsLabel); protocolPanel.add(GuiState.nrStepsSpinner); protocolPanel.add(GuiState.labelProtocolLabel); protocolPanel.add(GuiState.labelProtocolRepresentation); protocolPanel.add(GuiState.mixNowButton); protocolPanel.add(GuiState.resetProtocolButton); protocolPanel.add(GuiState.saveProtocolButton); protocolPanel.add(GuiState.loadProtocolButton); protocolPanel.add(GuiState.removeSavedProtButton); GuiState.protocolPanelContainer.add(protocolPanel); GuiState.mainMenuPanel.add(GuiState.protocolPanelContainer); fp.setProtocolWidgetsVisible(false); // Add canvas and menuPanel to the page RootPanel.get().add(as.getGeometry().getCanvas()); GuiState.menuPanelInnerWrapper.add(GuiState.mainMenuPanel); GuiState.menuPanelInnerWrapper.add(GuiState.subLevel1MenuPanel); GuiState.menuPanelInnerWrapper.add(GuiState.subLevel2MenuPanel); GuiState.menuPanelOuterWrapper.add(GuiState.menuPanelInnerWrapper); RootPanel.get().add(GuiState.menuPanelOuterWrapper); GuiState.menuToggleButton.refreshMenuSize(); RootPanel.get().add(GuiState.menuToggleButton); } /** * Get the {@link com.google.gwt.view.client.TreeViewModel.NodeInfo} that * provides the children of the specified value. */ public <T> NodeInfo<?> getNodeInfo(T value) { // When the Tree is being initialised, the last clicked level will // be -1, // in other cases, we need to load the level after the currently // clicked one. if (lastClickedLevel < 0) { // LEVEL 0. - Geometry // We passed null as the root value. Return the Geometries. // Create a data provider that contains the list of Geometries. ListDataProvider<String> dataProvider = new ListDataProvider<String>( Arrays.asList(ServerDataCache.getGeometries())); // Return a node info that pairs the data provider and the cell. return new DefaultNodeInfo<String>(dataProvider, new ClickableTextCell(), selectionModel, valueGeometryUpdater); } else if (lastClickedLevel == 0) { // LEVEL 1 - Mixer (leaf) // We want the children of the Geometry. Return the mixers. ListDataProvider<String> dataProvider = new ListDataProvider<String>( Arrays.asList(ServerDataCache .getMixersForGeometry((String) value))); // Use the shared selection model. return new DefaultNodeInfo<String>(dataProvider, new ClickableTextCell(), selectionModel, valueMixerUpdater); } return null; } /** * Check if the specified value represents a leaf node. Leaf nodes cannot be * opened. */ // You can define your own definition of leaf-node here. public boolean isLeaf(Object value) { return lastClickedLevel == NUM_LEVELS - 1; } /** * If the {@code Define Protocol} checkbox is ticked, this method adds a new * {@code MixingStep} to the mixing protocol, and updates the text area * {@code taProtocolRepresentation} accordingly. * * @param step * The {@code MixingStep} to be added. */ private void addStep(MixingStep step) { GuiState.saveResultsButton.setEnabled(false); GuiState.viewSingleGraphButton.setEnabled(false); GuiState.labelProtocolLabel.setVisible(true); if (!GuiState.toggleDefineProtocol.isHidden()) { step.setStepSize(as.getStepSize()); as.addMixingStep(step); updateProtocolLabel(step); GuiState.mixNowButton.setEnabled(true); GuiState.saveProtocolButton.setEnabled(true); } else { MixingProtocol protocol = new MixingProtocol(); step.setStepSize(as.getStepSize()); protocol.addStep(step); fp.executeMixingRun(protocol, 1, false); } } /** * Updates the protocol label to show the textual representation of * {@code step} and adds this to the existing steps in the protocol. * * @param step * The new {@code Step} of which the textual representation * should be added. */ private void updateProtocolLabel(MixingStep step) { String oldProtocol = GuiState.labelProtocolRepresentation.getText(); String stepString = step.toString(); if (stepString.charAt(0) == 'B' || stepString.charAt(0) == 'T') { stepString = "&nbsp;" + stepString; } GuiState.labelProtocolRepresentation.setVisible(true); GuiState.labelProtocolRepresentation.getElement().setInnerHTML( oldProtocol + stepString + " "); } }
true
true
private void createMixingWidgets() { // Initialise a listener for when a new step is entered to the // protocol StepAddedListener l = new StepAddedListener() { @Override public void onStepAdded(MixingStep step) { addStep(step); } }; as.getGeometry().addStepAddedListener(l); // Initialise the cursorSizeSpinner so it can be added to the tool // selector popup GuiState.cursorSizeSpinner = new CursorSizeSpinner(as); // Initialise the toolSelectButton and add it to the menu panel // Also intialise the widgets in the submenu that this button toggles GuiState.squareDrawingTool = new SquareDrawingToolToggleButton(fp, as); GuiState.circleDrawingTool = new CircleDrawingToolToggleButton(fp, as); GuiState.mainMenuPanel.add(GuiState.toolSelectButton); // Initialise toggleButton and add to // menuPanel GuiState.toggleColor = new ToggleColourButton(as); GuiState.mainMenuPanel.add(GuiState.toggleColor); // Initialise the distribution buttons and add a button to access those // to the menu panel. Also add the 'clear canvas' to the main menu GuiState.resetDistButton = new ResetDistButton(as); GuiState.mainMenuPanel.add(GuiState.resetDistButton); GuiState.saveDistributionButton = new SaveDistributionButton(fp); GuiState.loadInitDistButton = new LoadInitDistButton(as); GuiState.loadInitDistCellList = new LoadInitDistCellList(as); GuiState.removeInitDistButton = new RemoveInitDistButton(as); GuiState.exportDistributionButton = new ExportDistributionButton(as); GuiState.mainMenuPanel.add(GuiState.distributionsButton); // Initialise the saveResultsButton and add it to the menuPanel GuiState.saveResultsButton = new SaveResultsButton(fp); GuiState.saveResultsButton.setEnabled(false); GuiState.mainMenuPanel.add(GuiState.saveResultsButton); // Initialise panel to save items GuiState.overwriteSaveButton = new OverwriteSaveButton(fp); GuiState.saveItemPanelButton = new SaveItemPanelButton(fp); GuiState.saveItemPanel.add(GuiState.saveItemVerticalPanel); GuiState.saveItemVerticalPanel.add(GuiState.saveNameTextBox); GuiState.saveItemVerticalPanel.add(GuiState.saveButtonsPanel); GuiState.saveButtonsPanel.add(GuiState.saveItemPanelButton); GuiState.saveButtonsPanel.add(GuiState.cancelSaveResultsButton); // Initialise panel to overwrite already saved items GuiState.overwriteSavePanel.add(GuiState.overwriteSaveVerticalPanel); GuiState.overwriteSaveVerticalPanel.add(GuiState.saveMessageLabel); GuiState.overwriteSaveVerticalPanel.add(GuiState.overwriteButtonsPanel); GuiState.overwriteButtonsPanel.add(GuiState.closeSaveButton); //Initialise the LoadResultsCellList and add the loadResultsButton GuiState.menuPanel.add(GuiState.loadResultsButton); GuiState.LoadResultsCellList = new LoadResultsCellList(fp, as); // Initialise the removeSavedResultsButton and add it to the // menuPanel GuiState.removeResultsPanel.add(GuiState.removeResultsVerticalPanel); GuiState.mainMenuPanel.add(GuiState.removeSavedResultsButton); GuiState.viewSingleGraphButton = new ViewSingleGraphButton(fp, as); GuiState.exportSingleGraphButton = new ExportSingleGraphButton(fp); GuiState.mainMenuPanel.add(GuiState.viewSingleGraphButton); // Initialise the comparePerformanceButton and add it to the // menuPanel // createComparePerformanceButton(); GuiState.comparePerformanceButton = new ComparePerformanceButton(fp); GuiState.mainMenuPanel.add(GuiState.comparePerformanceButton); // Initialise a spinner for changing the length of a mixing protocol // step and add to menuPanel. GuiState.sizeSpinner = new StepSizeSpinner(as); GuiState.mainMenuPanel.add(GuiState.sizeLabel); GuiState.mainMenuPanel.add(GuiState.sizeSpinner); // Initialise the toggleButton that indicates whether a protocol is // being defined, or single steps have to be executed and add to // menu panel GuiState.toggleDefineProtocol = new ToggleDefineProtocol(fp); GuiState.mainMenuPanel.add(GuiState.toggleDefineProtocol); // Initialise a spinner for #steps GuiState.nrStepsSpinner = new NrStepsSpinner(as); // Initialise the resetProtocol button GuiState.resetProtocolButton = new ResetProtocolButton(fp); // Initialise the saveProtocolButton and add it to the menuPanel GuiState.saveProtocolButton = new SaveProtocolButton(fp); // Initialise the mixNow button GuiState.mixNowButton = new MixNowButton(fp, as); // Initialise the loadProtocolButton GuiState.loadProtocolButton = new LoadProtocolButton(as); GuiState.loadProtocolCellList = new LoadProtocolCellList(as); // Initialise the loadProtocolButton GuiState.removeSavedProtButton = new RemoveSavedProtButton(as); // Add all the protocol widgets to the menuPanel and hide them // initially. VerticalPanel protocolPanel = new VerticalPanel(); protocolPanel.add(GuiState.nrStepsLabel); protocolPanel.add(GuiState.nrStepsSpinner); protocolPanel.add(GuiState.labelProtocolLabel); protocolPanel.add(GuiState.labelProtocolRepresentation); protocolPanel.add(GuiState.mixNowButton); protocolPanel.add(GuiState.resetProtocolButton); protocolPanel.add(GuiState.saveProtocolButton); protocolPanel.add(GuiState.loadProtocolButton); protocolPanel.add(GuiState.removeSavedProtButton); GuiState.protocolPanelContainer.add(protocolPanel); GuiState.mainMenuPanel.add(GuiState.protocolPanelContainer); fp.setProtocolWidgetsVisible(false); // Add canvas and menuPanel to the page RootPanel.get().add(as.getGeometry().getCanvas()); GuiState.menuPanelInnerWrapper.add(GuiState.mainMenuPanel); GuiState.menuPanelInnerWrapper.add(GuiState.subLevel1MenuPanel); GuiState.menuPanelInnerWrapper.add(GuiState.subLevel2MenuPanel); GuiState.menuPanelOuterWrapper.add(GuiState.menuPanelInnerWrapper); RootPanel.get().add(GuiState.menuPanelOuterWrapper); GuiState.menuToggleButton.refreshMenuSize(); RootPanel.get().add(GuiState.menuToggleButton); }
private void createMixingWidgets() { // Initialise a listener for when a new step is entered to the // protocol StepAddedListener l = new StepAddedListener() { @Override public void onStepAdded(MixingStep step) { addStep(step); } }; as.getGeometry().addStepAddedListener(l); // Initialise the cursorSizeSpinner so it can be added to the tool // selector popup GuiState.cursorSizeSpinner = new CursorSizeSpinner(as); // Initialise the toolSelectButton and add it to the menu panel // Also intialise the widgets in the submenu that this button toggles GuiState.squareDrawingTool = new SquareDrawingToolToggleButton(fp, as); GuiState.circleDrawingTool = new CircleDrawingToolToggleButton(fp, as); GuiState.mainMenuPanel.add(GuiState.toolSelectButton); // Initialise toggleButton and add to // menuPanel GuiState.toggleColor = new ToggleColourButton(as); GuiState.mainMenuPanel.add(GuiState.toggleColor); // Initialise the distribution buttons and add a button to access those // to the menu panel. Also add the 'clear canvas' to the main menu GuiState.resetDistButton = new ResetDistButton(as); GuiState.mainMenuPanel.add(GuiState.resetDistButton); GuiState.saveDistributionButton = new SaveDistributionButton(fp); GuiState.loadInitDistButton = new LoadInitDistButton(as); GuiState.loadInitDistCellList = new LoadInitDistCellList(as); GuiState.removeInitDistButton = new RemoveInitDistButton(as); GuiState.exportDistributionButton = new ExportDistributionButton(as); GuiState.mainMenuPanel.add(GuiState.distributionsButton); // Initialise the saveResultsButton and add it to the menuPanel GuiState.saveResultsButton = new SaveResultsButton(fp); GuiState.saveResultsButton.setEnabled(false); GuiState.mainMenuPanel.add(GuiState.saveResultsButton); // Initialise panel to save items GuiState.overwriteSaveButton = new OverwriteSaveButton(fp); GuiState.saveItemPanelButton = new SaveItemPanelButton(fp); GuiState.saveItemPanel.add(GuiState.saveItemVerticalPanel); GuiState.saveItemVerticalPanel.add(GuiState.saveNameTextBox); GuiState.saveItemVerticalPanel.add(GuiState.saveButtonsPanel); GuiState.saveButtonsPanel.add(GuiState.saveItemPanelButton); GuiState.saveButtonsPanel.add(GuiState.cancelSaveResultsButton); // Initialise panel to overwrite already saved items GuiState.overwriteSavePanel.add(GuiState.overwriteSaveVerticalPanel); GuiState.overwriteSaveVerticalPanel.add(GuiState.saveMessageLabel); GuiState.overwriteSaveVerticalPanel.add(GuiState.overwriteButtonsPanel); GuiState.overwriteButtonsPanel.add(GuiState.closeSaveButton); //Initialise the LoadResultsCellList and add the loadResultsButton GuiState.mainMenuPanel.add(GuiState.loadResultsButton); GuiState.LoadResultsCellList = new LoadResultsCellList(fp, as); // Initialise the removeSavedResultsButton and add it to the // menuPanel GuiState.removeResultsPanel.add(GuiState.removeResultsVerticalPanel); GuiState.mainMenuPanel.add(GuiState.removeSavedResultsButton); GuiState.viewSingleGraphButton = new ViewSingleGraphButton(fp, as); GuiState.exportSingleGraphButton = new ExportSingleGraphButton(fp); GuiState.mainMenuPanel.add(GuiState.viewSingleGraphButton); // Initialise the comparePerformanceButton and add it to the // menuPanel // createComparePerformanceButton(); GuiState.comparePerformanceButton = new ComparePerformanceButton(fp); GuiState.mainMenuPanel.add(GuiState.comparePerformanceButton); // Initialise a spinner for changing the length of a mixing protocol // step and add to menuPanel. GuiState.sizeSpinner = new StepSizeSpinner(as); GuiState.mainMenuPanel.add(GuiState.sizeLabel); GuiState.mainMenuPanel.add(GuiState.sizeSpinner); // Initialise the toggleButton that indicates whether a protocol is // being defined, or single steps have to be executed and add to // menu panel GuiState.toggleDefineProtocol = new ToggleDefineProtocol(fp); GuiState.mainMenuPanel.add(GuiState.toggleDefineProtocol); // Initialise a spinner for #steps GuiState.nrStepsSpinner = new NrStepsSpinner(as); // Initialise the resetProtocol button GuiState.resetProtocolButton = new ResetProtocolButton(fp); // Initialise the saveProtocolButton and add it to the menuPanel GuiState.saveProtocolButton = new SaveProtocolButton(fp); // Initialise the mixNow button GuiState.mixNowButton = new MixNowButton(fp, as); // Initialise the loadProtocolButton GuiState.loadProtocolButton = new LoadProtocolButton(as); GuiState.loadProtocolCellList = new LoadProtocolCellList(as); // Initialise the loadProtocolButton GuiState.removeSavedProtButton = new RemoveSavedProtButton(as); // Add all the protocol widgets to the menuPanel and hide them // initially. VerticalPanel protocolPanel = new VerticalPanel(); protocolPanel.add(GuiState.nrStepsLabel); protocolPanel.add(GuiState.nrStepsSpinner); protocolPanel.add(GuiState.labelProtocolLabel); protocolPanel.add(GuiState.labelProtocolRepresentation); protocolPanel.add(GuiState.mixNowButton); protocolPanel.add(GuiState.resetProtocolButton); protocolPanel.add(GuiState.saveProtocolButton); protocolPanel.add(GuiState.loadProtocolButton); protocolPanel.add(GuiState.removeSavedProtButton); GuiState.protocolPanelContainer.add(protocolPanel); GuiState.mainMenuPanel.add(GuiState.protocolPanelContainer); fp.setProtocolWidgetsVisible(false); // Add canvas and menuPanel to the page RootPanel.get().add(as.getGeometry().getCanvas()); GuiState.menuPanelInnerWrapper.add(GuiState.mainMenuPanel); GuiState.menuPanelInnerWrapper.add(GuiState.subLevel1MenuPanel); GuiState.menuPanelInnerWrapper.add(GuiState.subLevel2MenuPanel); GuiState.menuPanelOuterWrapper.add(GuiState.menuPanelInnerWrapper); RootPanel.get().add(GuiState.menuPanelOuterWrapper); GuiState.menuToggleButton.refreshMenuSize(); RootPanel.get().add(GuiState.menuToggleButton); }
diff --git a/Model/src/java/fr/cg95/cvq/dao/request/hibernate/RequestActionDAO.java b/Model/src/java/fr/cg95/cvq/dao/request/hibernate/RequestActionDAO.java index 4abe9c08c..bbae764d0 100644 --- a/Model/src/java/fr/cg95/cvq/dao/request/hibernate/RequestActionDAO.java +++ b/Model/src/java/fr/cg95/cvq/dao/request/hibernate/RequestActionDAO.java @@ -1,42 +1,42 @@ package fr.cg95.cvq.dao.request.hibernate; import java.math.BigInteger; import java.util.List; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import fr.cg95.cvq.business.request.RequestActionType; import fr.cg95.cvq.business.request.RequestAdminAction; import fr.cg95.cvq.business.request.RequestAdminAction.Type; import fr.cg95.cvq.dao.hibernate.GenericDAO; import fr.cg95.cvq.dao.hibernate.HibernateUtil; import fr.cg95.cvq.dao.request.IRequestActionDAO; /** * Implementation of the {@link IRequestActionDAO} interface. * * @author [email protected] */ public class RequestActionDAO extends GenericDAO implements IRequestActionDAO { @Override public boolean hasAction(final Long requestId, final RequestActionType type) { - return !BigInteger.ZERO.equals(HibernateUtil.getSession() + return !Long.valueOf(0).equals(HibernateUtil.getSession() .createQuery("select count(*) from RequestAction where request_id = :requestId and type = :type") .setLong("requestId", requestId).setString("type", type.toString()).uniqueResult()); } @SuppressWarnings("unchecked") @Override public List<RequestAdminAction> getAdminActions() { return HibernateUtil.getSession().createCriteria(RequestAdminAction.class) .addOrder(Order.desc("date")).list(); } @Override public boolean hasArchivesMigrationAction() { return HibernateUtil.getSession().createCriteria(RequestAdminAction.class) .add(Restrictions.eq("type", Type.ARCHIVES_MIGRATED)).uniqueResult() != null; } }
true
true
public boolean hasAction(final Long requestId, final RequestActionType type) { return !BigInteger.ZERO.equals(HibernateUtil.getSession() .createQuery("select count(*) from RequestAction where request_id = :requestId and type = :type") .setLong("requestId", requestId).setString("type", type.toString()).uniqueResult()); }
public boolean hasAction(final Long requestId, final RequestActionType type) { return !Long.valueOf(0).equals(HibernateUtil.getSession() .createQuery("select count(*) from RequestAction where request_id = :requestId and type = :type") .setLong("requestId", requestId).setString("type", type.toString()).uniqueResult()); }
diff --git a/src/main/java/com/google/gwtexpui/clippy/client/CopyableLabel.java b/src/main/java/com/google/gwtexpui/clippy/client/CopyableLabel.java index e2e91ed74..1beee4c86 100644 --- a/src/main/java/com/google/gwtexpui/clippy/client/CopyableLabel.java +++ b/src/main/java/com/google/gwtexpui/clippy/client/CopyableLabel.java @@ -1,223 +1,228 @@ // Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gwtexpui.clippy.client; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.DeferredCommand; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HasText; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextBox; import com.google.gwtexpui.safehtml.client.SafeHtml; import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder; import com.google.gwtexpui.user.client.UserAgent; /** * Label which permits the user to easily copy the complete content. * <p> * If the Flash plugin is available a "movie" is embedded that provides * one-click copying of the content onto the system clipboard. The label (if * visible) can also be clicked, switching from a label to an input box, * allowing the user to copy the text with a keyboard shortcut. */ public class CopyableLabel extends Composite implements HasText { private static final int SWF_WIDTH = 110; private static final int SWF_HEIGHT = 14; private static String swfUrl; private static boolean flashEnabled = true; static { ClippyResources.I.css().ensureInjected(); } public static boolean isFlashEnabled() { return flashEnabled; } public static void setFlashEnabled(final boolean on) { flashEnabled = on; } private static String swfUrl() { if (swfUrl == null) { swfUrl = GWT.getModuleBaseURL() + "gwtexpui_clippy1.cache.swf"; } return swfUrl; } private final FlowPanel content; private String text; private int visibleLen; private Label textLabel; private TextBox textBox; private Element swf; /** * Create a new label * * @param str initial content */ public CopyableLabel(final String str) { this(str, true); } /** * Create a new label * * @param str initial content * @param showLabel if true, the content is shown, if false it is hidden from * view and only the copy icon is displayed. */ public CopyableLabel(final String str, final boolean showLabel) { content = new FlowPanel(); initWidget(content); text = str; visibleLen = text.length(); if (showLabel) { textLabel = new InlineLabel(getText()); textLabel.setStyleName(ClippyResources.I.css().label()); textLabel.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { showTextBox(); } }); content.add(textLabel); } embedMovie(); } /** * Change the text which is displayed in the clickable label. * * @param text the new preview text, should be shorter than the original text * which would be copied to the clipboard. */ public void setPreviewText(final String text) { if (textLabel != null) { textLabel.setText(text); visibleLen = text.length(); } } private void embedMovie() { if (flashEnabled && UserAgent.hasFlash) { final String flashVars = "text=" + URL.encodeComponent(getText()); final SafeHtmlBuilder h = new SafeHtmlBuilder(); h.openElement("span"); h.setStyleName(ClippyResources.I.css().control()); h.openElement("object"); h.setWidth(SWF_WIDTH); h.setHeight(SWF_HEIGHT); h.setAttribute("classid", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"); h.paramElement("movie", swfUrl()); h.paramElement("FlashVars", flashVars); h.openElement("embed"); h.setWidth(SWF_WIDTH); h.setHeight(SWF_HEIGHT); h.setAttribute("type", "application/x-shockwave-flash"); h.setAttribute("src", swfUrl()); h.setAttribute("FlashVars", flashVars); h.closeSelf(); h.closeElement("object"); h.closeElement("span"); if (swf != null) { DOM.removeChild(getElement(), swf); } DOM.appendChild(getElement(), swf = SafeHtml.parse(h)); } } public String getText() { return text; } public void setText(final String newText) { text = newText; if (textLabel != null) { textLabel.setText(getText()); } if (textBox != null) { textBox.setText(getText()); textBox.selectAll(); } embedMovie(); } private void showTextBox() { if (textBox == null) { textBox = new TextBox(); textBox.setText(getText()); textBox.setVisibleLength(visibleLen); textBox.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(final KeyPressEvent event) { if (event.isControlKeyDown() || event.isMetaKeyDown()) { switch (event.getCharCode()) { case 'c': case 'x': DeferredCommand.addCommand(new Command() { public void execute() { hideTextBox(); } }); break; } } } }); textBox.addBlurHandler(new BlurHandler() { @Override public void onBlur(final BlurEvent event) { hideTextBox(); } }); content.insert(textBox, 1); } textLabel.setVisible(false); textBox.setVisible(true); - textBox.selectAll(); - textBox.setFocus(true); + DeferredCommand.addCommand(new Command() { + @Override + public void execute() { + textBox.selectAll(); + textBox.setFocus(true); + } + }); } private void hideTextBox() { if (textBox != null) { textBox.removeFromParent(); textBox = null; } textLabel.setVisible(true); } }
true
true
private void showTextBox() { if (textBox == null) { textBox = new TextBox(); textBox.setText(getText()); textBox.setVisibleLength(visibleLen); textBox.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(final KeyPressEvent event) { if (event.isControlKeyDown() || event.isMetaKeyDown()) { switch (event.getCharCode()) { case 'c': case 'x': DeferredCommand.addCommand(new Command() { public void execute() { hideTextBox(); } }); break; } } } }); textBox.addBlurHandler(new BlurHandler() { @Override public void onBlur(final BlurEvent event) { hideTextBox(); } }); content.insert(textBox, 1); } textLabel.setVisible(false); textBox.setVisible(true); textBox.selectAll(); textBox.setFocus(true); }
private void showTextBox() { if (textBox == null) { textBox = new TextBox(); textBox.setText(getText()); textBox.setVisibleLength(visibleLen); textBox.addKeyPressHandler(new KeyPressHandler() { @Override public void onKeyPress(final KeyPressEvent event) { if (event.isControlKeyDown() || event.isMetaKeyDown()) { switch (event.getCharCode()) { case 'c': case 'x': DeferredCommand.addCommand(new Command() { public void execute() { hideTextBox(); } }); break; } } } }); textBox.addBlurHandler(new BlurHandler() { @Override public void onBlur(final BlurEvent event) { hideTextBox(); } }); content.insert(textBox, 1); } textLabel.setVisible(false); textBox.setVisible(true); DeferredCommand.addCommand(new Command() { @Override public void execute() { textBox.selectAll(); textBox.setFocus(true); } }); }
diff --git a/podd-webapp-lib/src/main/java/com/github/podd/impl/purl/PoddPurlManagerImpl.java b/podd-webapp-lib/src/main/java/com/github/podd/impl/purl/PoddPurlManagerImpl.java index 9c7f3e6b..fb1c233b 100644 --- a/podd-webapp-lib/src/main/java/com/github/podd/impl/purl/PoddPurlManagerImpl.java +++ b/podd-webapp-lib/src/main/java/com/github/podd/impl/purl/PoddPurlManagerImpl.java @@ -1,171 +1,171 @@ /** * */ package com.github.podd.impl.purl; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.query.GraphQuery; import org.openrdf.query.GraphQueryResult; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.UpdateExecutionException; import org.openrdf.query.impl.DatasetImpl; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.podd.api.PoddProcessorStage; import com.github.podd.api.purl.PoddPurlManager; import com.github.podd.api.purl.PoddPurlProcessor; import com.github.podd.api.purl.PoddPurlProcessorFactory; import com.github.podd.api.purl.PoddPurlProcessorFactoryRegistry; import com.github.podd.api.purl.PoddPurlReference; import com.github.podd.exception.PoddRuntimeException; import com.github.podd.exception.PurlProcessorNotHandledException; import com.github.podd.utils.PoddRdfUtils; /** * Basic PURL Manager implementation for use in PODD. * * * @author kutila * */ public class PoddPurlManagerImpl implements PoddPurlManager { protected final Logger log = LoggerFactory.getLogger(this.getClass()); // This manager functions only during the RDF_PARSING processor stage. private final PoddProcessorStage processorStage = PoddProcessorStage.RDF_PARSING; private PoddPurlProcessorFactoryRegistry purlProcessorFactoryRegistry; @Override public void convertTemporaryUris(final Set<PoddPurlReference> purlResults, final RepositoryConnection repositoryConnection, final URI... contexts) throws RepositoryException, UpdateExecutionException { for(final PoddPurlReference purl : purlResults) { final String inputUri = purl.getTemporaryURI().stringValue(); final String outputUri = purl.getPurlURI().stringValue(); this.log.debug("Converting: {} to {}", inputUri, outputUri); try { URITranslator.doTranslation(repositoryConnection, inputUri, outputUri, contexts); } catch(final MalformedQueryException e) { final String message = "Error while translating temporary URIs to Purls"; this.log.error(message, e); throw new PoddRuntimeException(message, e); } } } @Override public Set<PoddPurlReference> extractPurlReferences(final RepositoryConnection repositoryConnection, final URI... contexts) throws PurlProcessorNotHandledException, RepositoryException { return this.extractPurlReferences(null, repositoryConnection, contexts); } @Override public Set<PoddPurlReference> extractPurlReferences(final URI parentUri, final RepositoryConnection repositoryConnection, final URI... contexts) throws PurlProcessorNotHandledException, RepositoryException { final Set<PoddPurlReference> internalPurlResults = Collections.newSetFromMap(new ConcurrentHashMap<PoddPurlReference, Boolean>()); // NOTE: We use a Set to avoid duplicate calls to any Purl processors for any // temporary URI final Set<URI> temporaryURIs = Collections.newSetFromMap(new ConcurrentHashMap<URI, Boolean>()); // NOTE: a Factory may handle only a particular temporary URI format, necessitating to // go through multiple factories to extract ALL temporary URIs in the Repository. for(final PoddPurlProcessorFactory nextProcessorFactory : this.getPurlProcessorFactoryRegistry().getByStage( this.processorStage)) { try { final String sparqlQuery = PoddRdfUtils.buildSparqlConstructQuery(nextProcessorFactory); final GraphQuery graphQuery = repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sparqlQuery); // Create a new dataset to specify contexts that the query will be allowed to access final DatasetImpl dataset = new DatasetImpl(); for(final URI artifactGraphUri : contexts) { dataset.addDefaultGraph(artifactGraphUri); dataset.addNamedGraph(artifactGraphUri); } // set the dataset for the query to be our artificially constructed dataset graphQuery.setDataset(dataset); final GraphQueryResult queryResult = graphQuery.evaluate(); // If the query matched anything, then for each of the temporary URIs in the - // resulting construct statements, we create a file reference and add it to the + // resulting construct statements, we create a Purl reference and add it to the // results while(queryResult.hasNext()) { final Statement next = queryResult.next(); // This processor factory matches the graph that we wish to use, so we create a // processor instance now to create the PURL // NOTE: This object cannot be shared as we do not specify that it needs to be - // threadsafe + // thread safe final PoddPurlProcessor processor = nextProcessorFactory.getProcessor(); // Subject rewriting if(next.getSubject() instanceof URI && !temporaryURIs.contains(next.getSubject()) && processor.canHandle((URI)next.getSubject())) { temporaryURIs.add((URI)next.getSubject()); internalPurlResults.add(processor.handleTranslation((URI)next.getSubject(), parentUri)); } // Predicate rewriting is not supported. Predicates in OWL Documents must // be URIs from recognized vocabularies, so cannot be auto generated PURLs // Object rewriting if(next.getObject() instanceof URI && !temporaryURIs.contains(next.getObject()) && processor.canHandle((URI)next.getObject())) { temporaryURIs.add((URI)next.getObject()); internalPurlResults.add(processor.handleTranslation((URI)next.getObject(), parentUri)); } } } catch(final MalformedQueryException | QueryEvaluationException e) { this.log.error("Unexpected query exception", e); // continue after logging an error, as another ProcessorFactory may generate a Purl // for this failed temporary URI } } return internalPurlResults; } @Override public PoddPurlProcessorFactoryRegistry getPurlProcessorFactoryRegistry() { return this.purlProcessorFactoryRegistry; } @Override public void setPurlProcessorFactoryRegistry(final PoddPurlProcessorFactoryRegistry purlProcessorFactoryRegistry) { this.purlProcessorFactoryRegistry = purlProcessorFactoryRegistry; } }
false
true
public Set<PoddPurlReference> extractPurlReferences(final URI parentUri, final RepositoryConnection repositoryConnection, final URI... contexts) throws PurlProcessorNotHandledException, RepositoryException { final Set<PoddPurlReference> internalPurlResults = Collections.newSetFromMap(new ConcurrentHashMap<PoddPurlReference, Boolean>()); // NOTE: We use a Set to avoid duplicate calls to any Purl processors for any // temporary URI final Set<URI> temporaryURIs = Collections.newSetFromMap(new ConcurrentHashMap<URI, Boolean>()); // NOTE: a Factory may handle only a particular temporary URI format, necessitating to // go through multiple factories to extract ALL temporary URIs in the Repository. for(final PoddPurlProcessorFactory nextProcessorFactory : this.getPurlProcessorFactoryRegistry().getByStage( this.processorStage)) { try { final String sparqlQuery = PoddRdfUtils.buildSparqlConstructQuery(nextProcessorFactory); final GraphQuery graphQuery = repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sparqlQuery); // Create a new dataset to specify contexts that the query will be allowed to access final DatasetImpl dataset = new DatasetImpl(); for(final URI artifactGraphUri : contexts) { dataset.addDefaultGraph(artifactGraphUri); dataset.addNamedGraph(artifactGraphUri); } // set the dataset for the query to be our artificially constructed dataset graphQuery.setDataset(dataset); final GraphQueryResult queryResult = graphQuery.evaluate(); // If the query matched anything, then for each of the temporary URIs in the // resulting construct statements, we create a file reference and add it to the // results while(queryResult.hasNext()) { final Statement next = queryResult.next(); // This processor factory matches the graph that we wish to use, so we create a // processor instance now to create the PURL // NOTE: This object cannot be shared as we do not specify that it needs to be // threadsafe final PoddPurlProcessor processor = nextProcessorFactory.getProcessor(); // Subject rewriting if(next.getSubject() instanceof URI && !temporaryURIs.contains(next.getSubject()) && processor.canHandle((URI)next.getSubject())) { temporaryURIs.add((URI)next.getSubject()); internalPurlResults.add(processor.handleTranslation((URI)next.getSubject(), parentUri)); } // Predicate rewriting is not supported. Predicates in OWL Documents must // be URIs from recognized vocabularies, so cannot be auto generated PURLs // Object rewriting if(next.getObject() instanceof URI && !temporaryURIs.contains(next.getObject()) && processor.canHandle((URI)next.getObject())) { temporaryURIs.add((URI)next.getObject()); internalPurlResults.add(processor.handleTranslation((URI)next.getObject(), parentUri)); } } } catch(final MalformedQueryException | QueryEvaluationException e) { this.log.error("Unexpected query exception", e); // continue after logging an error, as another ProcessorFactory may generate a Purl // for this failed temporary URI } } return internalPurlResults; }
public Set<PoddPurlReference> extractPurlReferences(final URI parentUri, final RepositoryConnection repositoryConnection, final URI... contexts) throws PurlProcessorNotHandledException, RepositoryException { final Set<PoddPurlReference> internalPurlResults = Collections.newSetFromMap(new ConcurrentHashMap<PoddPurlReference, Boolean>()); // NOTE: We use a Set to avoid duplicate calls to any Purl processors for any // temporary URI final Set<URI> temporaryURIs = Collections.newSetFromMap(new ConcurrentHashMap<URI, Boolean>()); // NOTE: a Factory may handle only a particular temporary URI format, necessitating to // go through multiple factories to extract ALL temporary URIs in the Repository. for(final PoddPurlProcessorFactory nextProcessorFactory : this.getPurlProcessorFactoryRegistry().getByStage( this.processorStage)) { try { final String sparqlQuery = PoddRdfUtils.buildSparqlConstructQuery(nextProcessorFactory); final GraphQuery graphQuery = repositoryConnection.prepareGraphQuery(QueryLanguage.SPARQL, sparqlQuery); // Create a new dataset to specify contexts that the query will be allowed to access final DatasetImpl dataset = new DatasetImpl(); for(final URI artifactGraphUri : contexts) { dataset.addDefaultGraph(artifactGraphUri); dataset.addNamedGraph(artifactGraphUri); } // set the dataset for the query to be our artificially constructed dataset graphQuery.setDataset(dataset); final GraphQueryResult queryResult = graphQuery.evaluate(); // If the query matched anything, then for each of the temporary URIs in the // resulting construct statements, we create a Purl reference and add it to the // results while(queryResult.hasNext()) { final Statement next = queryResult.next(); // This processor factory matches the graph that we wish to use, so we create a // processor instance now to create the PURL // NOTE: This object cannot be shared as we do not specify that it needs to be // thread safe final PoddPurlProcessor processor = nextProcessorFactory.getProcessor(); // Subject rewriting if(next.getSubject() instanceof URI && !temporaryURIs.contains(next.getSubject()) && processor.canHandle((URI)next.getSubject())) { temporaryURIs.add((URI)next.getSubject()); internalPurlResults.add(processor.handleTranslation((URI)next.getSubject(), parentUri)); } // Predicate rewriting is not supported. Predicates in OWL Documents must // be URIs from recognized vocabularies, so cannot be auto generated PURLs // Object rewriting if(next.getObject() instanceof URI && !temporaryURIs.contains(next.getObject()) && processor.canHandle((URI)next.getObject())) { temporaryURIs.add((URI)next.getObject()); internalPurlResults.add(processor.handleTranslation((URI)next.getObject(), parentUri)); } } } catch(final MalformedQueryException | QueryEvaluationException e) { this.log.error("Unexpected query exception", e); // continue after logging an error, as another ProcessorFactory may generate a Purl // for this failed temporary URI } } return internalPurlResults; }
diff --git a/osmdroid-third-party/src/main/java/org/osmdroid/google/wrapper/v2/OsmdroidMapWrapper.java b/osmdroid-third-party/src/main/java/org/osmdroid/google/wrapper/v2/OsmdroidMapWrapper.java index a5df285..9a12665 100644 --- a/osmdroid-third-party/src/main/java/org/osmdroid/google/wrapper/v2/OsmdroidMapWrapper.java +++ b/osmdroid-third-party/src/main/java/org/osmdroid/google/wrapper/v2/OsmdroidMapWrapper.java @@ -1,169 +1,170 @@ package org.osmdroid.google.wrapper.v2; import java.util.ArrayList; import org.osmdroid.api.IGeoPoint; import org.osmdroid.api.IMap; import org.osmdroid.api.IPosition; import org.osmdroid.api.IProjection; import org.osmdroid.api.Marker; import org.osmdroid.api.OnCameraChangeListener; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.ItemizedIconOverlay; import org.osmdroid.views.overlay.ItemizedOverlayWithFocus; import org.osmdroid.views.overlay.Overlay; import org.osmdroid.views.overlay.OverlayItem; import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay; import android.graphics.Canvas; import android.view.MotionEvent; class OsmdroidMapWrapper implements IMap { private final MapView mMapView; private MyLocationNewOverlay mMyLocationOverlay; private ItemizedOverlayWithFocus<OverlayItem> mItemizedOverlay; private OnCameraChangeListener mOnCameraChangeListener; OsmdroidMapWrapper(final MapView aMapView) { mMapView = aMapView; mMapView.getOverlays().add(new Overlay(mMapView.getContext()) { @Override protected void draw(final Canvas c, final MapView osmv, final boolean shadow) { // nothing to draw } @Override public boolean onTouchEvent(final MotionEvent aMotionEvent, final MapView aMapView) { if (aMotionEvent.getAction() == MotionEvent.ACTION_UP) { onCameraChange(); } return super.onTouchEvent(aMotionEvent, aMapView); } }); } @Override public float getZoomLevel() { return mMapView.getZoomLevel(); } @Override public void setZoom(final float aZoomLevel) { mMapView.getController().setZoom((int) aZoomLevel); } @Override public IGeoPoint getCenter() { return mMapView.getMapCenter(); } @Override public void setCenter(final double aLatitude, final double aLongitude) { mMapView.getController().setCenter(new GeoPoint(aLatitude, aLongitude)); onCameraChange(); } @Override public float getBearing() { return -mMapView.getMapOrientation(); } @Override public void setBearing(final float aBearing) { mMapView.setMapOrientation(-aBearing); } @Override public void setPosition(final IPosition aPosition) { if (aPosition.hasBearing()) { setBearing(aPosition.getBearing()); } if (aPosition.hasZoomLevel()) { setZoom(aPosition.getZoomLevel()); } setCenter(aPosition.getLatitude(), aPosition.getLongitude()); } @Override public boolean zoomIn() { return mMapView.getController().zoomIn(); } @Override public boolean zoomOut() { return mMapView.getController().zoomOut(); } @Override public void setMyLocationEnabled(final boolean aEnabled) { if (aEnabled) { if (mMyLocationOverlay == null) { mMyLocationOverlay = new MyLocationNewOverlay(mMapView.getContext(), mMapView); mMapView.getOverlays().add(mMyLocationOverlay); } mMyLocationOverlay.enableMyLocation(); } if (!aEnabled && mMyLocationOverlay != null) { mMyLocationOverlay.disableMyLocation(); } } @Override public boolean isMyLocationEnabled() { return mMyLocationOverlay != null && mMyLocationOverlay.isMyLocationEnabled(); } @Override public IProjection getProjection() { return mMapView.getProjection(); } @Override public void addMarker(final Marker aMarker) { if (mItemizedOverlay == null) { // XXX this is a bit cumbersome. Maybe we should just do a simple ItemizedIconOverlay with null listener mItemizedOverlay = new ItemizedOverlayWithFocus<OverlayItem>(new ArrayList<OverlayItem>(), new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() { @Override public boolean onItemSingleTapUp(final int index, final OverlayItem item) { return false; } @Override public boolean onItemLongPress(final int index, final OverlayItem item) { return false; } }, new ResourceProxyImpl(mMapView.getContext())); mItemizedOverlay.setFocusItemsOnTap(true); + mMapView.setUseSafeCanvas(false); mMapView.getOverlays().add(mItemizedOverlay); } final OverlayItem item = new OverlayItem(aMarker.title, aMarker.snippet, new GeoPoint(aMarker.latitude, aMarker.longitude)); if (aMarker.icon != 0) { item.setMarker(mMapView.getResources().getDrawable(aMarker.icon)); } if (aMarker.anchor == Marker.Anchor.CENTER) { item.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER); } mItemizedOverlay.addItem(item); } @Override public void clear() { if (mItemizedOverlay != null) { mItemizedOverlay.removeAllItems(); } // TODO clear everything else this is supposed to clear } @Override public void setOnCameraChangeListener(final OnCameraChangeListener aListener) { mOnCameraChangeListener = aListener; } private void onCameraChange() { if (mOnCameraChangeListener != null) { mOnCameraChangeListener.onCameraChange(null); // TODO set the parameter } } }
true
true
public void addMarker(final Marker aMarker) { if (mItemizedOverlay == null) { // XXX this is a bit cumbersome. Maybe we should just do a simple ItemizedIconOverlay with null listener mItemizedOverlay = new ItemizedOverlayWithFocus<OverlayItem>(new ArrayList<OverlayItem>(), new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() { @Override public boolean onItemSingleTapUp(final int index, final OverlayItem item) { return false; } @Override public boolean onItemLongPress(final int index, final OverlayItem item) { return false; } }, new ResourceProxyImpl(mMapView.getContext())); mItemizedOverlay.setFocusItemsOnTap(true); mMapView.getOverlays().add(mItemizedOverlay); } final OverlayItem item = new OverlayItem(aMarker.title, aMarker.snippet, new GeoPoint(aMarker.latitude, aMarker.longitude)); if (aMarker.icon != 0) { item.setMarker(mMapView.getResources().getDrawable(aMarker.icon)); } if (aMarker.anchor == Marker.Anchor.CENTER) { item.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER); } mItemizedOverlay.addItem(item); }
public void addMarker(final Marker aMarker) { if (mItemizedOverlay == null) { // XXX this is a bit cumbersome. Maybe we should just do a simple ItemizedIconOverlay with null listener mItemizedOverlay = new ItemizedOverlayWithFocus<OverlayItem>(new ArrayList<OverlayItem>(), new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() { @Override public boolean onItemSingleTapUp(final int index, final OverlayItem item) { return false; } @Override public boolean onItemLongPress(final int index, final OverlayItem item) { return false; } }, new ResourceProxyImpl(mMapView.getContext())); mItemizedOverlay.setFocusItemsOnTap(true); mMapView.setUseSafeCanvas(false); mMapView.getOverlays().add(mItemizedOverlay); } final OverlayItem item = new OverlayItem(aMarker.title, aMarker.snippet, new GeoPoint(aMarker.latitude, aMarker.longitude)); if (aMarker.icon != 0) { item.setMarker(mMapView.getResources().getDrawable(aMarker.icon)); } if (aMarker.anchor == Marker.Anchor.CENTER) { item.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER); } mItemizedOverlay.addItem(item); }
diff --git a/src/main/java/com/gimranov/zandy/app/task/APIRequest.java b/src/main/java/com/gimranov/zandy/app/task/APIRequest.java index 920c3c2..23aebb7 100644 --- a/src/main/java/com/gimranov/zandy/app/task/APIRequest.java +++ b/src/main/java/com/gimranov/zandy/app/task/APIRequest.java @@ -1,1239 +1,1239 @@ /******************************************************************************* * This file is part of Zandy. * * Zandy is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Zandy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Zandy. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.gimranov.zandy.app.task; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.UUID; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.os.Handler; import android.util.Log; import com.gimranov.zandy.app.ServerCredentials; import com.gimranov.zandy.app.XMLResponseParser; import com.gimranov.zandy.app.data.Attachment; import com.gimranov.zandy.app.data.Database; import com.gimranov.zandy.app.data.Item; import com.gimranov.zandy.app.data.ItemCollection; /** * Represents a request to the Zotero API. These can be consumed by * other things like ZoteroAPITask. These should be queued up for many purposes. * * The APIRequest should include the HttpPost / HttpGet / etc. that it needs * to be executed, and optionally a callback to be called when it completes. * * See http://www.zotero.org/support/dev/server_api for information. * * @author ajlyon * */ public class APIRequest { private static final String TAG = "com.gimranov.zandy.app.task.APIRequest"; /** * Statuses used for items and collections. They are currently strings, but * they should change to integers. These statuses may be stored in the database. */ // XXX i18n public static final String API_DIRTY = "Unsynced change"; public static final String API_NEW = "New item / collection"; public static final String API_MISSING ="Partial data"; public static final String API_STALE = "Stale data"; public static final String API_WIP = "Sync attempted"; public static final String API_CLEAN = "No unsynced change"; /** * These are constants represented by integers. * * The above should be moving down here some time. */ /** * HTTP response codes that we are used to */ public static final int HTTP_ERROR_CONFLICT = 412; public static final int HTTP_ERROR_UNSPECIFIED = 400; /** * The following are used when passing things back to the UI * from the API request service / thread. */ /** Used to indicate database data has changed. */ public static final int UPDATED_DATA = 1000; /** Current set of requests completed. */ public static final int BATCH_DONE = 2000; /** Used to indicate an error with no more details. */ public static final int ERROR_UNKNOWN = 4000; /** Queued more requests */ public static final int QUEUED_MORE = 3000; /** * Request types */ public static final int ITEMS_ALL = 10000; public static final int ITEMS_FOR_COLLECTION = 10001; public static final int ITEMS_CHILDREN = 10002; public static final int COLLECTIONS_ALL = 10003; public static final int ITEM_BY_KEY = 10004; // Requests that require write access public static final int ITEM_NEW = 20000; public static final int ITEM_UPDATE = 20001; public static final int ITEM_DELETE = 20002; public static final int ITEM_MEMBERSHIP_ADD = 20003; public static final int ITEM_MEMBERSHIP_REMOVE = 20004; public static final int ITEM_ATTACHMENT_NEW = 20005; public static final int ITEM_ATTACHMENT_UPDATE = 20006; public static final int ITEM_ATTACHMENT_DELETE = 20007; public static final int ITEM_FIELDS = 30000; public static final int CREATOR_TYPES = 30001; public static final int ITEM_FIELDS_L10N = 30002; public static final int CREATOR_TYPES_L10N = 30003; /** * Request status for use within the database */ public static final int REQ_NEW = 40000; public static final int REQ_FAILING = 41000; /** * We'll request the whole collection or library rather than * individual feeds when we have less than this proportion of * the items. Used when pre-fetching keys. */ public static double REREQUEST_CUTOFF = 0.7; /** * Type of request we're sending. This should be one of * the request types listed above. */ public int type; /** * Callback handler */ private APIEvent handler; /** * Base query to send. */ public String query; /** * API key used to make request. Can be omitted for requests that don't need one. */ public String key; /** * One of get, put, post, delete. * Lower-case preferred, but we coerce them anyway. */ public String method; /** * Response disposition: xml or raw. JSON also planned */ public String disposition; /** * Used when sending JSON in POST and PUT requests. */ public String contentType = "application/json"; /** * Optional token to avoid accidentally sending one request twice. The * server will decline to carry out a second request with the same writeToken * for a single API key in a several-hour period. */ public String writeToken; /** * The eTag received from the server when requesting an item. We can make changes * (delete, update) to an item only while the tag is valid; if the item changes * server-side, our request will be declined until we request the item anew and get * a new valid eTag. */ public String ifMatch; /** * Request body, generally JSON. */ public String body; /** * The temporary key (UUID) that the request is based on. */ public String updateKey; /** * Type of object we expect to get. This and the updateKey are used to update * the UUIDs / local keys of locally-created items. I know, it's a hack. */ public String updateType; /** * Status code for the request. Codes should be constants defined in APIRequest; * take the REQ_* code and add the response code if applicable. */ public int status; /** * UUID for this request. We use this for DB lookups and as the write token when * appropriate. Every request should have one. */ private String uuid; /** * Timestamp when this request was first created. */ private Date created; /** * Timestamp when this request was last attempted to be run. */ private Date lastAttempt; /** * Creates a basic APIRequest item. Augment the item using instance methods for more complex * requests, or pass it to ZoteroAPITask for simpler ones. The request can be run by * simply calling the instance method `issue(..)`, but not from the UI thread. * * The constructor is not to be used directly; use the static methods in this class, or create from * a cursor. The one exception is the Atom feed continuations produced by XMLResponseParser, but that * should be moved into this class as well. * * @param query Fragment being requested, like /items * @param method GET, POST, PUT, or DELETE (except that lowercase is preferred) * @param key Can be null, if you're planning on making requests that don't need a key. */ public APIRequest(String query, String method, String key) { this.query = query; this.method = method; this.key = key; // default to XML processing this.disposition = "xml"; // If this is processing-intensive, we can probably move it to the save method this.uuid = UUID.randomUUID().toString(); created = new Date(); } /** * Load an APIRequest from its serialized form in the database * public static final String[] REQUESTCOLS = {"_id", "uuid", "type", "query", "key", "method", "disposition", "if_match", "update_key", "update_type", "created", "last_attempt", "status"}; * @param uuid */ public APIRequest(Cursor cur) { // N.B.: getString and such use 0-based indexing this.uuid = cur.getString(1); this.type = cur.getInt(2); this.query = cur.getString(3); this.key = cur.getString(4); this.method = cur.getString(5); this.disposition = cur.getString(6); this.ifMatch = cur.getString(7); this.updateKey = cur.getString(8); this.updateType = cur.getString(9); this.created = new Date(); this.created.setTime(cur.getLong(10)); this.lastAttempt = new Date(); this.lastAttempt.setTime(cur.getLong(11)); this.status = cur.getInt(12); this.body = cur.getString(13); } /** * Saves the APIRequest's basic info to the database. Does not maintain handler information. * @param db */ public void save(Database db) { try { Log.d(TAG, "Saving APIRequest to database: "+uuid+" "+query); SQLiteStatement insert = db.compileStatement("insert or replace into apirequests " + "(uuid, type, query, key, method, disposition, if_match, update_key, update_type, " + "created, last_attempt, status, body)" + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)"); // Why, oh why does bind* use 1-based indexing? And cur.get* uses 0-based! insert.bindString(1, uuid); insert.bindLong(2, (long) type); String createdUnix = Long.toString(created.getTime()); String lastAttemptUnix; if (lastAttempt == null) lastAttemptUnix = null; else lastAttemptUnix = Long.toString(lastAttempt.getTime()); String status = Integer.toString(this.status); // Iterate through null-allowed strings and bind them String[] strings = {query, key, method, disposition, ifMatch, updateKey, updateType, createdUnix, lastAttemptUnix, status, body}; for (int i = 0; i < strings.length; i++) { Log.d(TAG, (3+i)+":"+strings[i]); if (strings[i] == null) insert.bindNull(3+i); else insert.bindString(3+i, strings[i]); } insert.executeInsert(); insert.clearBindings(); insert.close(); } catch (SQLiteException e) { Log.e(TAG, "Exception compiling or running insert statement", e); throw e; } } /** * Getter for the request's implementation of the APIEvent interface, * used for call-backs, usually tying into the UI. * * Returns a no-op, logging handler if none specified * * @return */ public APIEvent getHandler() { if (handler == null) { /* * We have to fall back on a no-op event handler to prevent null exceptions */ return new APIEvent() { @Override public void onComplete(APIRequest request) { Log.d(TAG, "onComplete called but no handler"); } @Override public void onUpdate(APIRequest request) { Log.d(TAG, "onUpdate called but no handler"); } @Override public void onError(APIRequest request, Exception exception) { Log.d(TAG, "onError called but no handler"); } @Override public void onError(APIRequest request, int error) { Log.d(TAG, "onError called but no handler"); } }; } return handler; } public void setHandler(APIEvent handler) { if (this.handler == null) { this.handler = handler; return; } Log.e(TAG, "APIEvent handler for request cannot be replaced"); } /** * Set an Android standard handler to be used for the APIEvents * @param handler */ public void setHandler(Handler handler) { final Handler mHandler = handler; if (this.handler == null) { this.handler = new APIEvent() { @Override public void onComplete(APIRequest request) { mHandler.sendEmptyMessage(BATCH_DONE); } @Override public void onUpdate(APIRequest request) { mHandler.sendEmptyMessage(UPDATED_DATA); } @Override public void onError(APIRequest request, Exception exception) { mHandler.sendEmptyMessage(ERROR_UNKNOWN); } @Override public void onError(APIRequest request, int error) { mHandler.sendEmptyMessage(ERROR_UNKNOWN); } }; return; } Log.e(TAG, "APIEvent handler for request cannot be replaced"); } /** * Populates the body with a JSON representation of * the specified item. * * Use this for updating items, i.e.: * PUT /users/1/items/ABCD2345 * @param item Item to put in the body. */ public void setBody(Item item) { try { body = item.getContent().toString(4); } catch (JSONException e) { Log.e(TAG, "Error setting body for item", e); } } /** * Populates the body with a JSON representation of the specified * items. * * Use this for creating new items, i.e.: * POST /users/1/items * @param items */ public void setBody(ArrayList<Item> items) { try { JSONArray array = new JSONArray(); for (Item i : items) { JSONObject jItem = i.getContent(); array.put(jItem); } JSONObject obj = new JSONObject(); obj.put("items", array); body = obj.toString(4); } catch (JSONException e) { Log.e(TAG, "Error setting body for items", e); } } /** * Populates the body with a JSON representation of specified * attachments; note that this is will not work with non-note * attachments until the server API supports them. * * @param attachments */ public void setBodyWithNotes(ArrayList<Attachment> attachments) { try { JSONArray array = new JSONArray(); for (Attachment a : attachments) { JSONObject jAtt = a.content; array.put(jAtt); } JSONObject obj = new JSONObject(); obj.put("items", array); body = obj.toString(4); } catch (JSONException e) { Log.e(TAG, "Error setting body for attachments", e); } } /** * Getter for the request's UUID * @return */ public String getUuid() { return uuid; } /** * Sets the HTTP response code portion of the request's status * * @param code * @return The new status */ public int setHttpStatus(int code) { status = (status - status % 1000) + code; return status; } /** * Gets the HTTP response code portion of the request's status; * returns 0 if there was no code set. */ public int getHttpStatus() { return status % 1000; } /** * Record a failed attempt to run the request. * * Saves the APIRequest in its current state. * * @param db Database object * @return Date object with new lastAttempt value */ public Date recordAttempt(Database db) { lastAttempt = new Date(); save(db); return lastAttempt; } /** * To be called when the request succeeds. Currently just * deletes the corresponding row from the database. * * @param db Database object */ public void succeeded(Database db) { getHandler().onComplete(this); String[] args = { uuid }; db.rawQuery("delete from apirequests where uuid=?", args); } /** * Returns HTML-formatted string of the request * * XXX i18n, once we settle on a format * * @return */ public String toHtmlString() { StringBuilder sb = new StringBuilder(); sb.append("<h1>"); sb.append(status); sb.append("</h1>"); sb.append("<p><i>"); sb.append(method + "</i> "+query); sb.append("</p>"); sb.append("<p>Body: "); sb.append(body); sb.append("</p>"); sb.append("<p>Created: "); sb.append(created.toString()); sb.append("</p>"); sb.append("<p>Attempted: "); if (lastAttempt.getTime() == 0) sb.append("Never"); else sb.append(lastAttempt.toString()); sb.append("</p>"); return sb.toString(); } /** * Issues the specified request, calling its specified handler as appropriate * * This should not be run from a UI thread * * @return * @throws APIException */ public void issue(Database db, ServerCredentials cred) throws APIException { URI uri; // Add the API key, if missing and we have it if (!query.contains("key=") && key != null) { String suffix = (query.contains("?")) ? "&key="+key : "?key="+key; query = query + suffix; } // Force lower-case method = method.toLowerCase(); Log.i(TAG, "Request "+ method +": " + query); try { uri = new URI(query); } catch (URISyntaxException e1) { throw new APIException(APIException.INVALID_URI, "Invalid URI: "+query, this); } HttpClient client = new DefaultHttpClient(); // The default implementation includes an Expect: header, which // confuses the Zotero servers. client.getParams().setParameter("http.protocol.expect-continue", false); // We also need to send our data nice and raw. client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpGet get = new HttpGet(uri); HttpPost post = new HttpPost(uri); HttpPut put = new HttpPut(uri); HttpDelete delete = new HttpDelete(uri); // There are several shared initialization routines for POST and PUT if ("post".equals(method) || "put".equals(method)) { if(ifMatch != null) { post.setHeader("If-Match", ifMatch); put.setHeader("If-Match", ifMatch); } if(contentType != null) { post.setHeader("Content-Type", contentType); put.setHeader("Content-Type", contentType); } if (body != null) { Log.d(TAG, "Request body: "+body); // Force the encoding to UTF-8 StringEntity entity; try { entity = new StringEntity(body,"UTF-8"); } catch (UnsupportedEncodingException e) { throw new APIException(APIException.INVALID_UUID, "UnsupportedEncodingException. This shouldn't " + "be possible-- UTF-8 is certainly supported", this); } post.setEntity(entity); put.setEntity(entity); } } if ("get".equals(method)) { if(contentType != null) { get.setHeader("Content-Type", contentType); } } /* For requests that return Atom feeds or entries (XML): * ITEMS_ALL ] * ITEMS_FOR_COLLECTION ]- Except format=keys * ITEMS_CHILDREN ] * * ITEM_BY_KEY * COLLECTIONS_ALL * ITEM_NEW * ITEM_UPDATE * ITEM_ATTACHMENT_NEW * ITEM_ATTACHMENT_UPDATE */ if ("xml".equals(disposition)) { XMLResponseParser parse = new XMLResponseParser(this); // These types will always have a temporary key that we've // been using locally, and which should be replaced by the // incoming item key. if (type == ITEM_NEW || type == ITEM_ATTACHMENT_NEW) { parse.update(updateType, updateKey); } try { HttpResponse hr; if ("post".equals(method)) { hr = client.execute(post); } else if ("put".equals(method)) { hr = client.execute(put); } else { // We fall back on GET here, but there really // shouldn't be anything else, so we throw in that case // for good measure if (!"get".equals(method)) { throw new APIException(APIException.INVALID_METHOD, "Unexpected method: "+method, this); } hr = client.execute(get); } // Record the response code status = hr.getStatusLine().getStatusCode(); Log.d(TAG, status + " : "+ hr.getStatusLine().getReasonPhrase()); if (status < 400) { HttpEntity he = hr.getEntity(); InputStream in = he.getContent(); parse.setInputStream(in); // Entry mode if the request is an update (PUT) or if it is a request // for a single item by key (ITEM_BY_KEY) int mode = ("put".equals(method) || type == APIRequest.ITEM_BY_KEY) ? XMLResponseParser.MODE_ENTRY : XMLResponseParser.MODE_FEED; try { parse.parse(mode, uri.toString(), db); } catch (RuntimeException e) { throw new RuntimeException("Parser threw exception on request: "+method+" "+query, e); } } else { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); hr.getEntity().writeTo(ostream); Log.e(TAG,"Error Body: "+ ostream.toString()); Log.e(TAG,"Request Body:"+ body); if (status == 412) { // This is: "Precondition Failed", meaning that we provided // the wrong etag to update the item. That should mean that // there is a conflict between what we're sending (PUT) and // the server. We mark that ourselves and save the request // to the database, and also notify our handler. getHandler().onError(this, APIRequest.HTTP_ERROR_CONFLICT); } else { Log.e(TAG, "Response status "+status+" : "+ostream.toString()); getHandler().onError(this, APIRequest.HTTP_ERROR_UNSPECIFIED); } status = getHttpStatus() + REQ_FAILING; recordAttempt(db); // I'm not sure whether we should throw here throw new APIException(APIException.HTTP_ERROR, ostream.toString(), this); } - } catch (IOException e) { + } catch (Exception e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement el : e.getStackTrace()) { sb.append(el.toString()+"\n"); } recordAttempt(db); throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(), this); } } // end if ("xml".equals(disposition)) {..} /* For requests that return non-XML data: * ITEMS_ALL ] * ITEMS_FOR_COLLECTION ]- For format=keys * ITEMS_CHILDREN ] * * No server response: * ITEM_DELETE * ITEM_MEMBERSHIP_ADD * ITEM_MEMBERSHIP_REMOVE * ITEM_ATTACHMENT_DELETE * * Currently not supported; return JSON: * ITEM_FIELDS * CREATOR_TYPES * ITEM_FIELDS_L10N * CREATOR_TYPES_L10N * * These ones use BasicResponseHandler, which gives us * the response as a basic string. This is only appropriate * for smaller responses, since it means we have to wait until * the entire response is received before parsing it, so we * don't use it for the XML responses. * * The disposition here is "none" or "raw". * * The JSON-returning requests, such as ITEM_FIELDS, are not currently * supported; they should have a disposition of their own. */ else { BasicResponseHandler brh = new BasicResponseHandler(); String resp; try { if ("post".equals(method)) { resp = client.execute(post, brh); } else if ("put".equals(method)) { resp = client.execute(put, brh); } else if ("delete".equals(method)) { resp = client.execute(delete, brh); } else { // We fall back on GET here, but there really // shouldn't be anything else, so we throw in that case // for good measure if (!"get".equals(method)) { throw new APIException(APIException.INVALID_METHOD, "Unexpected method: "+method, this); } resp = client.execute(get, brh); } } catch (IOException e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement el : e.getStackTrace()) { sb.append(el.toString()+"\n"); } recordAttempt(db); throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(), this); } if ("raw".equals(disposition)) { /* * The output should be a newline-delimited set of alphanumeric * keys. */ String[] keys = resp.split("\n"); ArrayList<String> missing = new ArrayList<String>(); if (type == ITEMS_ALL || type == ITEMS_FOR_COLLECTION) { // Try to get a parent collection // Our query looks like this: // /users/5770/collections/2AJUSIU9/items int colloc = query.indexOf("/collections/"); int itemloc = query.indexOf("/items"); // The string "/collections/" is thirteen characters long ItemCollection coll = ItemCollection.load( query.substring(colloc+13, itemloc), db); if (coll != null) { coll.loadChildren(db); // If this is a collection's key listing, we first look // for any synced keys we have that aren't in the list ArrayList<String> keyAL = new ArrayList<String>(Arrays.asList(keys)); ArrayList<Item> notThere = coll.notInKeys(keyAL); // We should then remove those memberships for (Item i : notThere) { coll.remove(i, true, db); } } ArrayList<Item> recd = new ArrayList<Item>(); for (int j = 0; j < keys.length; j++) { Item got = Item.load(keys[j], db); if (got == null) { missing.add(keys[j]); } else { // We can update the collection membership immediately if (coll != null) coll.add(got, true, db); recd.add(got); } } if (coll != null) { coll.saveChildren(db); coll.save(db); } Log.d(TAG, "Received "+keys.length+" keys, "+missing.size() + " missing ones"); Log.d(TAG, "Have "+(double) recd.size() / keys.length + " of list"); if (recd.size() == keys.length) { Log.d(TAG, "No new items"); succeeded(db); } else if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) { Log.d(TAG, "Requesting full list"); APIRequest mReq; if (type == ITEMS_FOR_COLLECTION) { mReq = fetchItems(coll, false, cred); } else { mReq = fetchItems(false, cred); } mReq.status = REQ_NEW; mReq.save(db); } else { Log.d(TAG, "Requesting "+missing.size()+" items one by one"); APIRequest mReq; for (String key : missing) { // Queue request for the missing key mReq = fetchItem(key, cred); mReq.status = REQ_NEW; mReq.save(db); } // Queue request for the collection again, by key // XXX This is not the best way to make sure these // items are put in the correct collection. if (type == ITEMS_FOR_COLLECTION) { fetchItems(coll, true, cred).save(db); } } } else if (type == ITEMS_CHILDREN) { // Try to get a parent item // Our query looks like this: // /users/5770/items/2AJUSIU9/children int itemloc = query.indexOf("/items/"); int childloc = query.indexOf("/children"); // The string "/items/" is seven characters long Item item = Item.load( query.substring(itemloc+7, childloc), db); ArrayList<Attachment> recd = new ArrayList<Attachment>(); for (int j = 0; j < keys.length; j++) { Attachment got = Attachment.load(keys[j], db); if (got == null) missing.add(keys[j]); else recd.add(got); } if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) { APIRequest mReq; mReq = cred.prep(children(item)); mReq.status = REQ_NEW; mReq.save(db); } else { APIRequest mReq; for (String key : missing) { // Queue request for the missing key mReq = fetchItem(key, cred); mReq.status = REQ_NEW; mReq.save(db); } } } } else if ("json".equals(disposition)) { // TODO } else { /* Here, disposition should be "none" */ // Nothing to be done. } getHandler().onComplete(this); } } /** NEXT SECTION: Static methods for generating APIRequests */ /** * Produces an API request for the specified item key * * @param key Item key * @param cred Credentials */ public static APIRequest fetchItem(String key, ServerCredentials cred) { APIRequest req = new APIRequest(ServerCredentials.APIBASE + cred.prep(ServerCredentials.ITEMS) +"/"+key, "get", null); req.query = req.query + "?content=json"; req.disposition = "xml"; req.type = ITEM_BY_KEY; req.key = cred.getKey(); return req; } /** * Produces an API request for the items in a specified collection. * * @param collection The collection to fetch * @param keysOnly Use format=keys rather than format=atom/content=json * @param cred Credentials */ public static APIRequest fetchItems(ItemCollection collection, boolean keysOnly, ServerCredentials cred) { return fetchItems(collection.getKey(), keysOnly, cred); } /** * Produces an API request for the items in a specified collection. * * @param collectionKey The collection to fetch * @param keysOnly Use format=keys rather than format=atom/content=json * @param cred Credentials */ public static APIRequest fetchItems(String collectionKey, boolean keysOnly, ServerCredentials cred) { APIRequest req = new APIRequest(ServerCredentials.APIBASE + cred.prep(ServerCredentials.COLLECTIONS) +"/"+collectionKey+"/items", "get", null); if (keysOnly) { req.query = req.query + "?format=keys"; req.disposition = "raw"; } else { req.query = req.query + "?content=json"; req.disposition = "xml"; } req.type = APIRequest.ITEMS_FOR_COLLECTION; req.key = cred.getKey(); return req; } /** * Produces an API request for all items * * @param keysOnly Use format=keys rather than format=atom/content=json * @param cred Credentials */ public static APIRequest fetchItems(boolean keysOnly, ServerCredentials cred) { APIRequest req = new APIRequest(ServerCredentials.APIBASE + cred.prep(ServerCredentials.ITEMS) +"/top", "get", null); if (keysOnly) { req.query = req.query + "?format=keys"; req.disposition = "raw"; } else { req.query = req.query + "?content=json"; req.disposition = "xml"; } req.type = APIRequest.ITEMS_ALL; req.key = cred.getKey(); return req; } /** * Produces an API request for all collections * * @param c Context */ public static APIRequest fetchCollections(ServerCredentials cred) { APIRequest req = new APIRequest(ServerCredentials.APIBASE + cred.prep(ServerCredentials.COLLECTIONS) + "?content=json", "get", null); req.disposition = "xml"; req.type = APIRequest.COLLECTIONS_ALL; req.key = cred.getKey(); return req; } /** * Produces an API request to remove the specified item from the collection. * This request always needs a key, but it isn't set automatically and should * be set by whatever consumes this request. * * From the API docs: * DELETE /users/1/collections/QRST9876/items/ABCD2345 * * @param item * @param collection * @return */ public static APIRequest remove(Item item, ItemCollection collection) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.COLLECTIONS + "/" + collection.getKey() + "/items/" + item.getKey(), "DELETE", null); templ.disposition = "none"; return templ; } /** * Produces an API request to add the specified items to the collection. * This request always needs a key, but it isn't set automatically and should * be set by whatever consumes this request. * * From the API docs: * POST /users/1/collections/QRST9876/items * * ABCD2345 FBCD2335 * * @param items * @param collection * @return */ public static APIRequest add(ArrayList<Item> items, ItemCollection collection) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.COLLECTIONS + "/" + collection.getKey() + "/items", "POST", null); templ.body = ""; for (Item i : items) { templ.body += i.getKey() + " "; } templ.disposition = "none"; return templ; } /** * Craft a request to add a single item to the server * * @param item * @param collection * @return */ public static APIRequest add(Item item, ItemCollection collection) { ArrayList<Item> items = new ArrayList<Item>(); items.add(item); return add(items, collection); } /** * Craft a request to add items to the server * This does not attempt to update them, just add them. * * @param items * @return */ public static APIRequest add(ArrayList<Item> items) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS + "?content=json", "POST", null); templ.setBody(items); templ.disposition = "xml"; templ.updateType = "item"; // TODO this needs to be reworked to send all the keys. Or the whole system // needs to be reworked. Log.d(TAG, "Using the templ key of the first new item for now..."); templ.updateKey = items.get(0).getKey(); return templ; } /** * Craft a request to add child items (notes, attachments) to the server * This does not attempt to update them, just add them. * * @param item The parent item of the attachments * @param attachments * @return */ public static APIRequest add(Item item, ArrayList<Attachment> attachments) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS + "/" + item.getKey() + "/children?content=json", "POST", null); templ.setBodyWithNotes(attachments); templ.disposition = "xml"; templ.updateType = "attachment"; // TODO this needs to be reworked to send all the keys. Or the whole system // needs to be reworked. Log.d(TAG, "Using the templ key of the first new attachment for now..."); templ.updateKey = attachments.get(0).key; return templ; } /** * Craft a request for the children of the specified item * @param item * @return */ public static APIRequest children(Item item) { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS+"/"+item.getKey()+"/children?content=json", "GET", null); templ.disposition = "xml"; templ.type = ITEMS_CHILDREN; return templ; } /** * Craft a request to update an attachment on the server * Does not refresh eTag * * @param attachment * @return */ public static APIRequest update(Attachment attachment, Database db) { Log.d(TAG, "Attachment key pre-update: "+attachment.key); // If we have an attachment marked as new, update it if (attachment.key.length() > 10) { Item item = Item.load(attachment.parentKey, db); ArrayList<Attachment> aL = new ArrayList<Attachment>(); aL.add(attachment); if (item == null) { Log.e(TAG, "Orphaned attachment with key: "+attachment.key); attachment.delete(db); // send something, so we don't get errors elsewhere return new APIRequest(ServerCredentials.APIBASE, "GET", null); } return add(item, aL); } APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS+"/" + attachment.key, "PUT", null); try { templ.body = attachment.content.toString(4); } catch (JSONException e) { Log.e(TAG, "JSON exception setting body for attachment update: "+attachment.key,e); } templ.ifMatch = '"' + attachment.etag + '"'; templ.disposition = "xml"; return templ; } /** * Craft a request to update an attachment on the server * Does not refresh eTag * * @param item * @return */ public static APIRequest update(Item item) { // If we have an item markes as new, update it if (item.getKey().length() > 10) { ArrayList<Item> mAL = new ArrayList<Item>(); mAL.add(item); return add(mAL); } APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS+"/"+item.getKey(), "PUT", null); templ.setBody(item); templ.ifMatch = '"' + item.getEtag() + '"'; Log.d(TAG,"etag: "+item.getEtag()); templ.disposition = "xml"; return templ; } /** * Produces API requests to delete queued items from the server. * This request always needs a key. * * From the API docs: * DELETE /users/1/items/ABCD2345 * If-Match: "8e984e9b2a8fb560b0085b40f6c2c2b7" * * @param c * @return */ public static ArrayList<APIRequest> delete(Context c) { ArrayList<APIRequest> list = new ArrayList<APIRequest>(); Database db = new Database(c); String[] args = {}; Cursor cur = db.rawQuery("select item_key, etag from deleteditems", args); if (cur == null) { db.close(); Log.d(TAG, "No deleted items found in database"); return list; } do { APIRequest templ = new APIRequest(ServerCredentials.APIBASE + ServerCredentials.ITEMS + "/" + cur.getString(0), "DELETE", null); templ.disposition = "none"; templ.ifMatch = cur.getString(1); Log.d(TAG, "Adding deleted item: "+cur.getString(0) + " : " + templ.ifMatch); // Save the request to the database to be dispatched later templ.save(db); list.add(templ); } while (cur.moveToNext() != false); cur.close(); db.rawQuery("delete from deleteditems", args); db.close(); return list; } /** * Returns APIRequest objects from the database * @return */ public static ArrayList<APIRequest> queue(Database db) { ArrayList<APIRequest> list = new ArrayList<APIRequest>(); String[] cols = Database.REQUESTCOLS; String[] args = { }; Cursor cur = db.query("apirequests", cols, "", args, null, null, null, null); if (cur == null) return list; do { APIRequest req = new APIRequest(cur); list.add(req); Log.d(TAG, "Queueing request: "+req.query); } while (cur.moveToNext() != false); cur.close(); return list; } }
true
true
public void issue(Database db, ServerCredentials cred) throws APIException { URI uri; // Add the API key, if missing and we have it if (!query.contains("key=") && key != null) { String suffix = (query.contains("?")) ? "&key="+key : "?key="+key; query = query + suffix; } // Force lower-case method = method.toLowerCase(); Log.i(TAG, "Request "+ method +": " + query); try { uri = new URI(query); } catch (URISyntaxException e1) { throw new APIException(APIException.INVALID_URI, "Invalid URI: "+query, this); } HttpClient client = new DefaultHttpClient(); // The default implementation includes an Expect: header, which // confuses the Zotero servers. client.getParams().setParameter("http.protocol.expect-continue", false); // We also need to send our data nice and raw. client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpGet get = new HttpGet(uri); HttpPost post = new HttpPost(uri); HttpPut put = new HttpPut(uri); HttpDelete delete = new HttpDelete(uri); // There are several shared initialization routines for POST and PUT if ("post".equals(method) || "put".equals(method)) { if(ifMatch != null) { post.setHeader("If-Match", ifMatch); put.setHeader("If-Match", ifMatch); } if(contentType != null) { post.setHeader("Content-Type", contentType); put.setHeader("Content-Type", contentType); } if (body != null) { Log.d(TAG, "Request body: "+body); // Force the encoding to UTF-8 StringEntity entity; try { entity = new StringEntity(body,"UTF-8"); } catch (UnsupportedEncodingException e) { throw new APIException(APIException.INVALID_UUID, "UnsupportedEncodingException. This shouldn't " + "be possible-- UTF-8 is certainly supported", this); } post.setEntity(entity); put.setEntity(entity); } } if ("get".equals(method)) { if(contentType != null) { get.setHeader("Content-Type", contentType); } } /* For requests that return Atom feeds or entries (XML): * ITEMS_ALL ] * ITEMS_FOR_COLLECTION ]- Except format=keys * ITEMS_CHILDREN ] * * ITEM_BY_KEY * COLLECTIONS_ALL * ITEM_NEW * ITEM_UPDATE * ITEM_ATTACHMENT_NEW * ITEM_ATTACHMENT_UPDATE */ if ("xml".equals(disposition)) { XMLResponseParser parse = new XMLResponseParser(this); // These types will always have a temporary key that we've // been using locally, and which should be replaced by the // incoming item key. if (type == ITEM_NEW || type == ITEM_ATTACHMENT_NEW) { parse.update(updateType, updateKey); } try { HttpResponse hr; if ("post".equals(method)) { hr = client.execute(post); } else if ("put".equals(method)) { hr = client.execute(put); } else { // We fall back on GET here, but there really // shouldn't be anything else, so we throw in that case // for good measure if (!"get".equals(method)) { throw new APIException(APIException.INVALID_METHOD, "Unexpected method: "+method, this); } hr = client.execute(get); } // Record the response code status = hr.getStatusLine().getStatusCode(); Log.d(TAG, status + " : "+ hr.getStatusLine().getReasonPhrase()); if (status < 400) { HttpEntity he = hr.getEntity(); InputStream in = he.getContent(); parse.setInputStream(in); // Entry mode if the request is an update (PUT) or if it is a request // for a single item by key (ITEM_BY_KEY) int mode = ("put".equals(method) || type == APIRequest.ITEM_BY_KEY) ? XMLResponseParser.MODE_ENTRY : XMLResponseParser.MODE_FEED; try { parse.parse(mode, uri.toString(), db); } catch (RuntimeException e) { throw new RuntimeException("Parser threw exception on request: "+method+" "+query, e); } } else { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); hr.getEntity().writeTo(ostream); Log.e(TAG,"Error Body: "+ ostream.toString()); Log.e(TAG,"Request Body:"+ body); if (status == 412) { // This is: "Precondition Failed", meaning that we provided // the wrong etag to update the item. That should mean that // there is a conflict between what we're sending (PUT) and // the server. We mark that ourselves and save the request // to the database, and also notify our handler. getHandler().onError(this, APIRequest.HTTP_ERROR_CONFLICT); } else { Log.e(TAG, "Response status "+status+" : "+ostream.toString()); getHandler().onError(this, APIRequest.HTTP_ERROR_UNSPECIFIED); } status = getHttpStatus() + REQ_FAILING; recordAttempt(db); // I'm not sure whether we should throw here throw new APIException(APIException.HTTP_ERROR, ostream.toString(), this); } } catch (IOException e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement el : e.getStackTrace()) { sb.append(el.toString()+"\n"); } recordAttempt(db); throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(), this); } } // end if ("xml".equals(disposition)) {..} /* For requests that return non-XML data: * ITEMS_ALL ] * ITEMS_FOR_COLLECTION ]- For format=keys * ITEMS_CHILDREN ] * * No server response: * ITEM_DELETE * ITEM_MEMBERSHIP_ADD * ITEM_MEMBERSHIP_REMOVE * ITEM_ATTACHMENT_DELETE * * Currently not supported; return JSON: * ITEM_FIELDS * CREATOR_TYPES * ITEM_FIELDS_L10N * CREATOR_TYPES_L10N * * These ones use BasicResponseHandler, which gives us * the response as a basic string. This is only appropriate * for smaller responses, since it means we have to wait until * the entire response is received before parsing it, so we * don't use it for the XML responses. * * The disposition here is "none" or "raw". * * The JSON-returning requests, such as ITEM_FIELDS, are not currently * supported; they should have a disposition of their own. */ else { BasicResponseHandler brh = new BasicResponseHandler(); String resp; try { if ("post".equals(method)) { resp = client.execute(post, brh); } else if ("put".equals(method)) { resp = client.execute(put, brh); } else if ("delete".equals(method)) { resp = client.execute(delete, brh); } else { // We fall back on GET here, but there really // shouldn't be anything else, so we throw in that case // for good measure if (!"get".equals(method)) { throw new APIException(APIException.INVALID_METHOD, "Unexpected method: "+method, this); } resp = client.execute(get, brh); } } catch (IOException e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement el : e.getStackTrace()) { sb.append(el.toString()+"\n"); } recordAttempt(db); throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(), this); } if ("raw".equals(disposition)) { /* * The output should be a newline-delimited set of alphanumeric * keys. */ String[] keys = resp.split("\n"); ArrayList<String> missing = new ArrayList<String>(); if (type == ITEMS_ALL || type == ITEMS_FOR_COLLECTION) { // Try to get a parent collection // Our query looks like this: // /users/5770/collections/2AJUSIU9/items int colloc = query.indexOf("/collections/"); int itemloc = query.indexOf("/items"); // The string "/collections/" is thirteen characters long ItemCollection coll = ItemCollection.load( query.substring(colloc+13, itemloc), db); if (coll != null) { coll.loadChildren(db); // If this is a collection's key listing, we first look // for any synced keys we have that aren't in the list ArrayList<String> keyAL = new ArrayList<String>(Arrays.asList(keys)); ArrayList<Item> notThere = coll.notInKeys(keyAL); // We should then remove those memberships for (Item i : notThere) { coll.remove(i, true, db); } } ArrayList<Item> recd = new ArrayList<Item>(); for (int j = 0; j < keys.length; j++) { Item got = Item.load(keys[j], db); if (got == null) { missing.add(keys[j]); } else { // We can update the collection membership immediately if (coll != null) coll.add(got, true, db); recd.add(got); } } if (coll != null) { coll.saveChildren(db); coll.save(db); } Log.d(TAG, "Received "+keys.length+" keys, "+missing.size() + " missing ones"); Log.d(TAG, "Have "+(double) recd.size() / keys.length + " of list"); if (recd.size() == keys.length) { Log.d(TAG, "No new items"); succeeded(db); } else if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) { Log.d(TAG, "Requesting full list"); APIRequest mReq; if (type == ITEMS_FOR_COLLECTION) { mReq = fetchItems(coll, false, cred); } else { mReq = fetchItems(false, cred); } mReq.status = REQ_NEW; mReq.save(db); } else { Log.d(TAG, "Requesting "+missing.size()+" items one by one"); APIRequest mReq; for (String key : missing) { // Queue request for the missing key mReq = fetchItem(key, cred); mReq.status = REQ_NEW; mReq.save(db); } // Queue request for the collection again, by key // XXX This is not the best way to make sure these // items are put in the correct collection. if (type == ITEMS_FOR_COLLECTION) { fetchItems(coll, true, cred).save(db); } } } else if (type == ITEMS_CHILDREN) { // Try to get a parent item // Our query looks like this: // /users/5770/items/2AJUSIU9/children int itemloc = query.indexOf("/items/"); int childloc = query.indexOf("/children"); // The string "/items/" is seven characters long Item item = Item.load( query.substring(itemloc+7, childloc), db); ArrayList<Attachment> recd = new ArrayList<Attachment>(); for (int j = 0; j < keys.length; j++) { Attachment got = Attachment.load(keys[j], db); if (got == null) missing.add(keys[j]); else recd.add(got); } if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) { APIRequest mReq; mReq = cred.prep(children(item)); mReq.status = REQ_NEW; mReq.save(db); } else { APIRequest mReq; for (String key : missing) { // Queue request for the missing key mReq = fetchItem(key, cred); mReq.status = REQ_NEW; mReq.save(db); } } } } else if ("json".equals(disposition)) { // TODO } else { /* Here, disposition should be "none" */ // Nothing to be done. } getHandler().onComplete(this); } }
public void issue(Database db, ServerCredentials cred) throws APIException { URI uri; // Add the API key, if missing and we have it if (!query.contains("key=") && key != null) { String suffix = (query.contains("?")) ? "&key="+key : "?key="+key; query = query + suffix; } // Force lower-case method = method.toLowerCase(); Log.i(TAG, "Request "+ method +": " + query); try { uri = new URI(query); } catch (URISyntaxException e1) { throw new APIException(APIException.INVALID_URI, "Invalid URI: "+query, this); } HttpClient client = new DefaultHttpClient(); // The default implementation includes an Expect: header, which // confuses the Zotero servers. client.getParams().setParameter("http.protocol.expect-continue", false); // We also need to send our data nice and raw. client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); HttpGet get = new HttpGet(uri); HttpPost post = new HttpPost(uri); HttpPut put = new HttpPut(uri); HttpDelete delete = new HttpDelete(uri); // There are several shared initialization routines for POST and PUT if ("post".equals(method) || "put".equals(method)) { if(ifMatch != null) { post.setHeader("If-Match", ifMatch); put.setHeader("If-Match", ifMatch); } if(contentType != null) { post.setHeader("Content-Type", contentType); put.setHeader("Content-Type", contentType); } if (body != null) { Log.d(TAG, "Request body: "+body); // Force the encoding to UTF-8 StringEntity entity; try { entity = new StringEntity(body,"UTF-8"); } catch (UnsupportedEncodingException e) { throw new APIException(APIException.INVALID_UUID, "UnsupportedEncodingException. This shouldn't " + "be possible-- UTF-8 is certainly supported", this); } post.setEntity(entity); put.setEntity(entity); } } if ("get".equals(method)) { if(contentType != null) { get.setHeader("Content-Type", contentType); } } /* For requests that return Atom feeds or entries (XML): * ITEMS_ALL ] * ITEMS_FOR_COLLECTION ]- Except format=keys * ITEMS_CHILDREN ] * * ITEM_BY_KEY * COLLECTIONS_ALL * ITEM_NEW * ITEM_UPDATE * ITEM_ATTACHMENT_NEW * ITEM_ATTACHMENT_UPDATE */ if ("xml".equals(disposition)) { XMLResponseParser parse = new XMLResponseParser(this); // These types will always have a temporary key that we've // been using locally, and which should be replaced by the // incoming item key. if (type == ITEM_NEW || type == ITEM_ATTACHMENT_NEW) { parse.update(updateType, updateKey); } try { HttpResponse hr; if ("post".equals(method)) { hr = client.execute(post); } else if ("put".equals(method)) { hr = client.execute(put); } else { // We fall back on GET here, but there really // shouldn't be anything else, so we throw in that case // for good measure if (!"get".equals(method)) { throw new APIException(APIException.INVALID_METHOD, "Unexpected method: "+method, this); } hr = client.execute(get); } // Record the response code status = hr.getStatusLine().getStatusCode(); Log.d(TAG, status + " : "+ hr.getStatusLine().getReasonPhrase()); if (status < 400) { HttpEntity he = hr.getEntity(); InputStream in = he.getContent(); parse.setInputStream(in); // Entry mode if the request is an update (PUT) or if it is a request // for a single item by key (ITEM_BY_KEY) int mode = ("put".equals(method) || type == APIRequest.ITEM_BY_KEY) ? XMLResponseParser.MODE_ENTRY : XMLResponseParser.MODE_FEED; try { parse.parse(mode, uri.toString(), db); } catch (RuntimeException e) { throw new RuntimeException("Parser threw exception on request: "+method+" "+query, e); } } else { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); hr.getEntity().writeTo(ostream); Log.e(TAG,"Error Body: "+ ostream.toString()); Log.e(TAG,"Request Body:"+ body); if (status == 412) { // This is: "Precondition Failed", meaning that we provided // the wrong etag to update the item. That should mean that // there is a conflict between what we're sending (PUT) and // the server. We mark that ourselves and save the request // to the database, and also notify our handler. getHandler().onError(this, APIRequest.HTTP_ERROR_CONFLICT); } else { Log.e(TAG, "Response status "+status+" : "+ostream.toString()); getHandler().onError(this, APIRequest.HTTP_ERROR_UNSPECIFIED); } status = getHttpStatus() + REQ_FAILING; recordAttempt(db); // I'm not sure whether we should throw here throw new APIException(APIException.HTTP_ERROR, ostream.toString(), this); } } catch (Exception e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement el : e.getStackTrace()) { sb.append(el.toString()+"\n"); } recordAttempt(db); throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(), this); } } // end if ("xml".equals(disposition)) {..} /* For requests that return non-XML data: * ITEMS_ALL ] * ITEMS_FOR_COLLECTION ]- For format=keys * ITEMS_CHILDREN ] * * No server response: * ITEM_DELETE * ITEM_MEMBERSHIP_ADD * ITEM_MEMBERSHIP_REMOVE * ITEM_ATTACHMENT_DELETE * * Currently not supported; return JSON: * ITEM_FIELDS * CREATOR_TYPES * ITEM_FIELDS_L10N * CREATOR_TYPES_L10N * * These ones use BasicResponseHandler, which gives us * the response as a basic string. This is only appropriate * for smaller responses, since it means we have to wait until * the entire response is received before parsing it, so we * don't use it for the XML responses. * * The disposition here is "none" or "raw". * * The JSON-returning requests, such as ITEM_FIELDS, are not currently * supported; they should have a disposition of their own. */ else { BasicResponseHandler brh = new BasicResponseHandler(); String resp; try { if ("post".equals(method)) { resp = client.execute(post, brh); } else if ("put".equals(method)) { resp = client.execute(put, brh); } else if ("delete".equals(method)) { resp = client.execute(delete, brh); } else { // We fall back on GET here, but there really // shouldn't be anything else, so we throw in that case // for good measure if (!"get".equals(method)) { throw new APIException(APIException.INVALID_METHOD, "Unexpected method: "+method, this); } resp = client.execute(get, brh); } } catch (IOException e) { StringBuilder sb = new StringBuilder(); for (StackTraceElement el : e.getStackTrace()) { sb.append(el.toString()+"\n"); } recordAttempt(db); throw new APIException(APIException.HTTP_ERROR, "An IOException was thrown: " + sb.toString(), this); } if ("raw".equals(disposition)) { /* * The output should be a newline-delimited set of alphanumeric * keys. */ String[] keys = resp.split("\n"); ArrayList<String> missing = new ArrayList<String>(); if (type == ITEMS_ALL || type == ITEMS_FOR_COLLECTION) { // Try to get a parent collection // Our query looks like this: // /users/5770/collections/2AJUSIU9/items int colloc = query.indexOf("/collections/"); int itemloc = query.indexOf("/items"); // The string "/collections/" is thirteen characters long ItemCollection coll = ItemCollection.load( query.substring(colloc+13, itemloc), db); if (coll != null) { coll.loadChildren(db); // If this is a collection's key listing, we first look // for any synced keys we have that aren't in the list ArrayList<String> keyAL = new ArrayList<String>(Arrays.asList(keys)); ArrayList<Item> notThere = coll.notInKeys(keyAL); // We should then remove those memberships for (Item i : notThere) { coll.remove(i, true, db); } } ArrayList<Item> recd = new ArrayList<Item>(); for (int j = 0; j < keys.length; j++) { Item got = Item.load(keys[j], db); if (got == null) { missing.add(keys[j]); } else { // We can update the collection membership immediately if (coll != null) coll.add(got, true, db); recd.add(got); } } if (coll != null) { coll.saveChildren(db); coll.save(db); } Log.d(TAG, "Received "+keys.length+" keys, "+missing.size() + " missing ones"); Log.d(TAG, "Have "+(double) recd.size() / keys.length + " of list"); if (recd.size() == keys.length) { Log.d(TAG, "No new items"); succeeded(db); } else if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) { Log.d(TAG, "Requesting full list"); APIRequest mReq; if (type == ITEMS_FOR_COLLECTION) { mReq = fetchItems(coll, false, cred); } else { mReq = fetchItems(false, cred); } mReq.status = REQ_NEW; mReq.save(db); } else { Log.d(TAG, "Requesting "+missing.size()+" items one by one"); APIRequest mReq; for (String key : missing) { // Queue request for the missing key mReq = fetchItem(key, cred); mReq.status = REQ_NEW; mReq.save(db); } // Queue request for the collection again, by key // XXX This is not the best way to make sure these // items are put in the correct collection. if (type == ITEMS_FOR_COLLECTION) { fetchItems(coll, true, cred).save(db); } } } else if (type == ITEMS_CHILDREN) { // Try to get a parent item // Our query looks like this: // /users/5770/items/2AJUSIU9/children int itemloc = query.indexOf("/items/"); int childloc = query.indexOf("/children"); // The string "/items/" is seven characters long Item item = Item.load( query.substring(itemloc+7, childloc), db); ArrayList<Attachment> recd = new ArrayList<Attachment>(); for (int j = 0; j < keys.length; j++) { Attachment got = Attachment.load(keys[j], db); if (got == null) missing.add(keys[j]); else recd.add(got); } if ((double) recd.size() / keys.length < REREQUEST_CUTOFF) { APIRequest mReq; mReq = cred.prep(children(item)); mReq.status = REQ_NEW; mReq.save(db); } else { APIRequest mReq; for (String key : missing) { // Queue request for the missing key mReq = fetchItem(key, cred); mReq.status = REQ_NEW; mReq.save(db); } } } } else if ("json".equals(disposition)) { // TODO } else { /* Here, disposition should be "none" */ // Nothing to be done. } getHandler().onComplete(this); } }
diff --git a/Player.java b/Player.java index 27672bf..78b06b4 100644 --- a/Player.java +++ b/Player.java @@ -1,388 +1,388 @@ import java.awt.*; import java.awt.event.KeyEvent; import java.util.*; public class Player extends Shape { static final int WIDTH = 30; static final int HEIGHT = 30; int x = Volfied.BOARD_WIDTH; int y = Volfied.BOARD_HEIGHT; int pase = 5; boolean isAttacking = false; boolean first_time = true; ArrayList<Point> trail = new ArrayList<Point>(); public void draw(Graphics g_main){ this.paint(g_main); } public void changeLineThickness(Graphics g_main) {} public void scale() {} public void paint(Graphics g) { g.setColor(Color.black); g.drawRect(Volfied.OFFSET_GRID + x, Volfied.OFFSET_GRID + y, WIDTH, HEIGHT); g.setColor(Color.blue); int trail_size = this.trail.size(); for (int i = 0; i < trail_size-1; i++) g.drawLine(Volfied.OFFSET_GRID + WIDTH/2 + trail.get(i).x, Volfied.OFFSET_GRID + trail.get(i).y + HEIGHT/2, Volfied.OFFSET_GRID + trail.get(i+1).x +WIDTH/2, Volfied.OFFSET_GRID + trail.get(i+1).y+HEIGHT/2); } public ArrayList<Point> onWhatLine() { ArrayList<Point> ret = new ArrayList<Point>(); int n = Volfied.terain.poli.size(); for (int i = 0; i < n; i++) { Point curr_point = Volfied.terain.poli.get(i); Point next_point = Volfied.terain.poli.get((i == n - 1) ? 0 : i + 1); if (this.y == curr_point.y && this.x == curr_point.x) { Point prev_point = Volfied.terain.poli.get(i == 0 ? n - 1 : i - 1); ret.add(prev_point); ret.add(curr_point); ret.add(next_point); return ret; } if ((this.y == curr_point.y) && (this.y == next_point.y)) if (((this.x > curr_point.x) && (this.x < next_point.x)) || ((this.x < curr_point.x) && (this.x > next_point.x))) { ret.add(curr_point); ret.add(next_point); return ret; } if ((this.x == curr_point.x) && (this.x == next_point.x)) if (((this.y > curr_point.y) && (this.y < next_point.y)) || ((this.y < curr_point.y) && (this.y > next_point.y))) { ret.add(curr_point); ret.add(next_point); return ret; } } return ret; } public boolean isPointonTrail(Point lookup) { int n = this.trail.size(); for (int i = 0; i < n; i++) { Point curr_point = trail.get(i); Point next_point = trail.get((i == n - 1) ? 0 : i + 1); if (lookup.y == curr_point.y && lookup.x == curr_point.x) { return true; } if ((lookup.y == curr_point.y) && (lookup.y == next_point.y)) if (((lookup.x > curr_point.x) && (lookup.x < next_point.x)) || ((lookup.x < curr_point.x) && (lookup.x > next_point.x))) { return true; } if ((lookup.x == curr_point.x) && (lookup.x == next_point.x)) if (((lookup.y > curr_point.y) && (lookup.y < next_point.y)) || ((lookup.y < curr_point.y) && (lookup.y > next_point.y))) { return true; } } return false; } public boolean isPointonMyTerrain(Point lookup) { int n = Volfied.terain.poli.size(); for (int i = 0; i < n; i++) { Point curr_point = Volfied.terain.poli.get(i); Point next_point = Volfied.terain.poli.get((i == n - 1) ? 0 : i + 1); if (lookup.y == curr_point.y && lookup.x == curr_point.x) { return true; } if ((lookup.y == curr_point.y) && (lookup.y == next_point.y)) if (((lookup.x > curr_point.x) && (lookup.x < next_point.x)) || ((lookup.x < curr_point.x) && (lookup.x > next_point.x))) { return true; } if ((lookup.x == curr_point.x) && (lookup.x == next_point.x)) if (((lookup.y > curr_point.y) && (lookup.y < next_point.y)) || ((lookup.y < curr_point.y) && (lookup.y > next_point.y))) { return true; } } return false; } public boolean canMoveNotAttack(int keyCode) { ArrayList<Point> position = onWhatLine(); int nr_elem = position.size(); if (nr_elem == 0) return false; System.out.println(nr_elem); switch (keyCode) { case KeyEvent.VK_UP: if (nr_elem == 2) { if (position.get(0).x == position.get(1).x) return true; } else if ((position.get(0).x == position.get(1).x) || (position.get(1).x == position.get(2).x)) return true; break; case KeyEvent.VK_DOWN: if (nr_elem == 2) { if (position.get(0).x == position.get(1).x) return true; } else if ((position.get(0).x == position.get(1).x) || (position.get(1).x == position.get(2).x)) return true; break; case KeyEvent.VK_LEFT: if (nr_elem == 2) { if (position.get(0).y == position.get(1).y) return true; } else if ((position.get(0).y == position.get(1).y) || (position.get(1).y == position.get(2).y)) return true; break; case KeyEvent.VK_RIGHT: if (nr_elem == 2) { if (position.get(0).y == position.get(1).y) return true; } else if ((position.get(0).y == position.get(1).y) || (position.get(1).y == position.get(2).y)) return true; break; } return false; } public boolean isValidAttack(int keyCode) { Point next_point; switch(keyCode) { case KeyEvent.VK_UP: next_point = new Point(this.x, this.y - this.pase); if (isPointonTrail(next_point)) return false; break; case KeyEvent.VK_DOWN: next_point = new Point(this.x, this.y + this.pase); if (isPointonTrail(next_point)) return false; break; case KeyEvent.VK_LEFT: next_point = new Point(this.x - this.pase, this.y); if (isPointonTrail(next_point)) return false; break; case KeyEvent.VK_RIGHT: next_point = new Point(this.x + this.pase, this.y); if (isPointonTrail(next_point)) return false; break; } return true; } public void cutTerrain() { } public void attack(int keyCode) { switch (keyCode) { case KeyEvent.VK_UP: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.y - this.pase < 0) this.y = 0; else this.y -= this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() -1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.x == pre_prev.x) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; case KeyEvent.VK_DOWN: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.y + this.pase > Volfied.BOARD_HEIGHT) this.y = Volfied.BOARD_HEIGHT; else this.y += this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() - 1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.x == pre_prev.x) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; case KeyEvent.VK_LEFT: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.x - this.pase < 0) this.x = 0; else this.x -= this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() - 1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); - if (prev.x == pre_prev.x) + if (prev.y == pre_prev.y) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; case KeyEvent.VK_RIGHT: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.x + this.pase > Volfied.BOARD_WIDTH) this.x = Volfied.BOARD_WIDTH; else this.x += this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() -1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); - if (prev.x == pre_prev.x) + if (prev.y == pre_prev.y) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; } } public void key_decide(int keyCode){ switch (keyCode) { case KeyEvent.VK_UP: if (canMoveNotAttack(keyCode)) { if (this.y - this.pase < 0) this.y = 0; else this.y -= this.pase; } else { isAttacking = true; attack(keyCode); } break; case KeyEvent.VK_DOWN: if (canMoveNotAttack(keyCode)) { if (this.y + this.pase > Volfied.BOARD_HEIGHT) this.y = Volfied.BOARD_HEIGHT; else this.y += this.pase; } else{ isAttacking = true; attack(keyCode); } break; case KeyEvent.VK_LEFT: if (canMoveNotAttack(keyCode)) { if (this.x - this.pase < 0) this.x = 0; else this.x -= this.pase; } else { isAttacking = true; attack(keyCode); } break; case KeyEvent.VK_RIGHT: if (canMoveNotAttack(keyCode)) { if (this.x + this.pase > Volfied.BOARD_WIDTH) this.x = Volfied.BOARD_WIDTH; else this.x += this.pase; } else { isAttacking = true; attack(keyCode); } break; } } }
false
true
public void attack(int keyCode) { switch (keyCode) { case KeyEvent.VK_UP: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.y - this.pase < 0) this.y = 0; else this.y -= this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() -1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.x == pre_prev.x) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; case KeyEvent.VK_DOWN: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.y + this.pase > Volfied.BOARD_HEIGHT) this.y = Volfied.BOARD_HEIGHT; else this.y += this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() - 1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.x == pre_prev.x) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; case KeyEvent.VK_LEFT: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.x - this.pase < 0) this.x = 0; else this.x -= this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() - 1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.x == pre_prev.x) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; case KeyEvent.VK_RIGHT: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.x + this.pase > Volfied.BOARD_WIDTH) this.x = Volfied.BOARD_WIDTH; else this.x += this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() -1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.x == pre_prev.x) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; } }
public void attack(int keyCode) { switch (keyCode) { case KeyEvent.VK_UP: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.y - this.pase < 0) this.y = 0; else this.y -= this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() -1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.x == pre_prev.x) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; case KeyEvent.VK_DOWN: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.y + this.pase > Volfied.BOARD_HEIGHT) this.y = Volfied.BOARD_HEIGHT; else this.y += this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() - 1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.x == pre_prev.x) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; case KeyEvent.VK_LEFT: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.x - this.pase < 0) this.x = 0; else this.x -= this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() - 1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.y == pre_prev.y) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; case KeyEvent.VK_RIGHT: if (isValidAttack(keyCode) && isAttacking) { if (first_time) { this.trail.add(new Point(this.x, this.y)); first_time = false; } if (this.x + this.pase > Volfied.BOARD_WIDTH) this.x = Volfied.BOARD_WIDTH; else this.x += this.pase; if (isPointonMyTerrain(new Point(this.x, this.y))){ //finalize attack isAttacking = false; } int prev_pos = trail.size() -1 ; int pre_prev_pos = trail.size() - 2; if (pre_prev_pos >= 0) { Point prev = trail.get(prev_pos); Point pre_prev = trail.get(pre_prev_pos); if (prev.y == pre_prev.y) this.trail.set(prev_pos, new Point(this.x, this.y)); else this.trail.add(new Point(this.x, this.y)); } else this.trail.add(new Point(this.x, this.y)); } break; } }
diff --git a/TheatreProjectWeb/src/theatreProject/client/AdminInventory.java b/TheatreProjectWeb/src/theatreProject/client/AdminInventory.java index 89a5a5d..0b542b1 100644 --- a/TheatreProjectWeb/src/theatreProject/client/AdminInventory.java +++ b/TheatreProjectWeb/src/theatreProject/client/AdminInventory.java @@ -1,256 +1,256 @@ package theatreProject.client; import theatreProject.shared.PersistenceAsync; import theatreProject.shared.InventoryObject; import theatreProject.shared.Persistence; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Hidden; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; //import com.google.apphosting.api.ApiProxy; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Image; public class AdminInventory { private static final int RETRY_MS = 1000; public final static PersistenceAsync persistence = GWT.create(Persistence.class); public static InventoryObject thisObject; /** * @wbp.parser.entryPoint */ public static void adminOnlyInventory(final String ID){ final TextArea txtDescription = new TextArea(); final TextArea txtDisclaimers = new TextArea(); final TextBox txtShowDate = new TextBox(); final TextBox txtLocation = new TextBox(); final TextBox lblStatus = new TextBox(); final TextBox txtbxEmailAddress = new TextBox(); final TextBox nameOfObject = new TextBox(); final Hidden hiddenID = new Hidden(); final TextBox txtStroageArea = new TextBox(); Timer loadFields = new Timer(){ @Override public void run() { persistence.getInventoryObject(ID, new AsyncCallback<InventoryObject>() { @Override public void onFailure(Throwable caught) { thisObject = null; } @Override public void onSuccess(InventoryObject object) { thisObject = object; if(thisObject == null){ schedule(RETRY_MS); } else { txtDescription.setText(thisObject.getDescription()); txtDisclaimers.setText(thisObject.getDisclaimers()); txtShowDate.setText(thisObject.getStatus().getShowDay()); txtLocation.setText(thisObject.getStatus().getLocation()); if (thisObject.getStatus().getLocation() == "warehouse") lblStatus.setText("IN"); else lblStatus.setText("OUT"); txtbxEmailAddress.setText(thisObject.getStatus().getRenter()); nameOfObject.setText(thisObject.getName()); hiddenID.setValue(thisObject.getID()); txtStroageArea.setText(thisObject.getStorageArea()); } } }); } }; loadFields.run(); final RootPanel rootPanel = RootPanel.get(); rootPanel.setStyleName("gwt-Root"); final VerticalPanel manguageUserPanel = new VerticalPanel(); rootPanel.add(manguageUserPanel, 10 ,10 ); manguageUserPanel.setSize("498px", "627px"); final Label title = new Label("Admin Inventory Page"); title.setStyleName("gwt-Header"); manguageUserPanel.add(title); title.setSize("338px","25px"); AbsolutePanel absolutePanel = new AbsolutePanel(); manguageUserPanel.add(absolutePanel); absolutePanel.setSize("472px", "582px"); //Error Label final Label lblCouldNotFind = new Label("COULD NOT SAVE OBJECT. PLEASE CONTACT SITE ADMINISTRATOR."); lblCouldNotFind.setVisible(false); absolutePanel.add(lblCouldNotFind, 24, 75); lblCouldNotFind.setSize("158px", "82px"); HorizontalPanel horizontalPanel_4 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_4, 10, 291); horizontalPanel_4.setSize("434px", "98px"); //Description Box Label lblNewLabel = new Label("Description: "); horizontalPanel_4.add(lblNewLabel); horizontalPanel_4.add(txtDescription); txtDescription.setSize("342px", "96px"); HorizontalPanel horizontalPanel_5 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_5, 10, 418); horizontalPanel_5.setSize("433px", "110px"); Label lblDisclaimers = new Label("Disclaimers: "); horizontalPanel_5.add(lblDisclaimers); horizontalPanel_5.add(txtDisclaimers); txtDisclaimers.setSize("339px", "96px"); HorizontalPanel horizontalPanel_1 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_1, 232, 119); horizontalPanel_1.setSize("211px", "34px"); Label lblLocation = new Label("Location: "); horizontalPanel_1.add(lblLocation); horizontalPanel_1.add(txtLocation); txtLocation.setWidth("136px"); HorizontalPanel horizontalPanel_7 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_7, 232, 179); horizontalPanel_7.setSize("211px", "34px"); Label lblShowEndDate = new Label("Show End Date: "); horizontalPanel_7.add(lblShowEndDate); horizontalPanel_7.add(txtShowDate); txtShowDate.setWidth("130px"); HorizontalPanel horizontalPanel_2 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_2, 233, 47); horizontalPanel_2.setSize("211px", "49px"); Label lblCheckInoutStatus = new Label("Check in/out Status: "); horizontalPanel_2.add(lblCheckInoutStatus); lblCheckInoutStatus.setWidth("92px"); horizontalPanel_2.add(lblStatus); lblStatus.setSize("97px", "22px"); HorizontalPanel horizontalPanel_6 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_6, 232, 237); horizontalPanel_6.setSize("211px", "34px"); Label lblEmailOfRenter = new Label("Location in Warehouse: "); horizontalPanel_6.add(lblEmailOfRenter); horizontalPanel_6.add(txtStroageArea); txtbxEmailAddress.setWidth("111px"); HorizontalPanel horizontalPanel_8 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_8, 10, 219); horizontalPanel_8.setSize("196px", "34px"); final Label lblNameOfRenter = new Label("Name of Renter: "); horizontalPanel_8.add(lblNameOfRenter); lblNameOfRenter.setWidth("55px"); horizontalPanel_8.add(txtbxEmailAddress); txtbxEmailAddress.setWidth("133px"); nameOfObject.setStyleName("gwt-Heading2"); absolutePanel.add(nameOfObject, 10, 10); nameOfObject.setSize("419px", "18px"); Button btnUploadImage = new Button("Upload Image"); absolutePanel.add(btnUploadImage, 10, 179); - Image image = new Image((String) null); - image.setAltText("Image of Item"); - absolutePanel.add(image, 10, 47); - image.setSize("198px", "126px"); +// Image image = new Image((String) null); +// image.setAltText("Image of Item"); +// absolutePanel.add(image, 10, 47); +// image.setSize("198px", "126px"); //Main Menu Button Button btnMainMenu_1 = new Button("Main Menu"); btnMainMenu_1.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { rootPanel.clear(); TheatreProjectWeb.mainPage(); } }); absolutePanel.add(btnMainMenu_1, 364, 545); //save buttons Button btnNewButton = new Button("New button"); btnNewButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { //start by setting thisObject parameters to current txtbxs thisObject.setName(nameOfObject.getText()); thisObject.setDescription(txtDescription.getText()); thisObject.setDisclaimers(txtDisclaimers.getText()); //TODO //thisObject.setImage(newImageURL); //thisObject.setStorageArea(newStorageArea); thisObject.getStatus().setLocation(txtLocation.getText()); thisObject.getStatus().setRenter(lblNameOfRenter.getText()); thisObject.getStatus().setShowDay(txtShowDate.getText()); //then save out the changes persistence.saveObject(thisObject, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { lblCouldNotFind.setVisible(true); } @Override public void onSuccess(Void result) { lblCouldNotFind.setVisible(false); //when saved, it returns to the main page rootPanel.clear(); TheatreProjectWeb.mainPage(); } }); } }); btnNewButton.setText("Save"); absolutePanel.add(btnNewButton, 10, 545); //Delete button Button btnDeleteItem = new Button("Delete Item"); btnDeleteItem.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { persistence.deleteObject(thisObject, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { lblCouldNotFind.setVisible(true); } @Override public void onSuccess(Void result) { lblCouldNotFind.setVisible(false); //when saved, it returns to the main page rootPanel.clear(); TheatreProjectWeb.mainPage(); } }); } }); absolutePanel.add(btnDeleteItem, 73, 545); } }
true
true
public static void adminOnlyInventory(final String ID){ final TextArea txtDescription = new TextArea(); final TextArea txtDisclaimers = new TextArea(); final TextBox txtShowDate = new TextBox(); final TextBox txtLocation = new TextBox(); final TextBox lblStatus = new TextBox(); final TextBox txtbxEmailAddress = new TextBox(); final TextBox nameOfObject = new TextBox(); final Hidden hiddenID = new Hidden(); final TextBox txtStroageArea = new TextBox(); Timer loadFields = new Timer(){ @Override public void run() { persistence.getInventoryObject(ID, new AsyncCallback<InventoryObject>() { @Override public void onFailure(Throwable caught) { thisObject = null; } @Override public void onSuccess(InventoryObject object) { thisObject = object; if(thisObject == null){ schedule(RETRY_MS); } else { txtDescription.setText(thisObject.getDescription()); txtDisclaimers.setText(thisObject.getDisclaimers()); txtShowDate.setText(thisObject.getStatus().getShowDay()); txtLocation.setText(thisObject.getStatus().getLocation()); if (thisObject.getStatus().getLocation() == "warehouse") lblStatus.setText("IN"); else lblStatus.setText("OUT"); txtbxEmailAddress.setText(thisObject.getStatus().getRenter()); nameOfObject.setText(thisObject.getName()); hiddenID.setValue(thisObject.getID()); txtStroageArea.setText(thisObject.getStorageArea()); } } }); } }; loadFields.run(); final RootPanel rootPanel = RootPanel.get(); rootPanel.setStyleName("gwt-Root"); final VerticalPanel manguageUserPanel = new VerticalPanel(); rootPanel.add(manguageUserPanel, 10 ,10 ); manguageUserPanel.setSize("498px", "627px"); final Label title = new Label("Admin Inventory Page"); title.setStyleName("gwt-Header"); manguageUserPanel.add(title); title.setSize("338px","25px"); AbsolutePanel absolutePanel = new AbsolutePanel(); manguageUserPanel.add(absolutePanel); absolutePanel.setSize("472px", "582px"); //Error Label final Label lblCouldNotFind = new Label("COULD NOT SAVE OBJECT. PLEASE CONTACT SITE ADMINISTRATOR."); lblCouldNotFind.setVisible(false); absolutePanel.add(lblCouldNotFind, 24, 75); lblCouldNotFind.setSize("158px", "82px"); HorizontalPanel horizontalPanel_4 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_4, 10, 291); horizontalPanel_4.setSize("434px", "98px"); //Description Box Label lblNewLabel = new Label("Description: "); horizontalPanel_4.add(lblNewLabel); horizontalPanel_4.add(txtDescription); txtDescription.setSize("342px", "96px"); HorizontalPanel horizontalPanel_5 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_5, 10, 418); horizontalPanel_5.setSize("433px", "110px"); Label lblDisclaimers = new Label("Disclaimers: "); horizontalPanel_5.add(lblDisclaimers); horizontalPanel_5.add(txtDisclaimers); txtDisclaimers.setSize("339px", "96px"); HorizontalPanel horizontalPanel_1 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_1, 232, 119); horizontalPanel_1.setSize("211px", "34px"); Label lblLocation = new Label("Location: "); horizontalPanel_1.add(lblLocation); horizontalPanel_1.add(txtLocation); txtLocation.setWidth("136px"); HorizontalPanel horizontalPanel_7 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_7, 232, 179); horizontalPanel_7.setSize("211px", "34px"); Label lblShowEndDate = new Label("Show End Date: "); horizontalPanel_7.add(lblShowEndDate); horizontalPanel_7.add(txtShowDate); txtShowDate.setWidth("130px"); HorizontalPanel horizontalPanel_2 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_2, 233, 47); horizontalPanel_2.setSize("211px", "49px"); Label lblCheckInoutStatus = new Label("Check in/out Status: "); horizontalPanel_2.add(lblCheckInoutStatus); lblCheckInoutStatus.setWidth("92px"); horizontalPanel_2.add(lblStatus); lblStatus.setSize("97px", "22px"); HorizontalPanel horizontalPanel_6 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_6, 232, 237); horizontalPanel_6.setSize("211px", "34px"); Label lblEmailOfRenter = new Label("Location in Warehouse: "); horizontalPanel_6.add(lblEmailOfRenter); horizontalPanel_6.add(txtStroageArea); txtbxEmailAddress.setWidth("111px"); HorizontalPanel horizontalPanel_8 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_8, 10, 219); horizontalPanel_8.setSize("196px", "34px"); final Label lblNameOfRenter = new Label("Name of Renter: "); horizontalPanel_8.add(lblNameOfRenter); lblNameOfRenter.setWidth("55px"); horizontalPanel_8.add(txtbxEmailAddress); txtbxEmailAddress.setWidth("133px"); nameOfObject.setStyleName("gwt-Heading2"); absolutePanel.add(nameOfObject, 10, 10); nameOfObject.setSize("419px", "18px"); Button btnUploadImage = new Button("Upload Image"); absolutePanel.add(btnUploadImage, 10, 179); Image image = new Image((String) null); image.setAltText("Image of Item"); absolutePanel.add(image, 10, 47); image.setSize("198px", "126px"); //Main Menu Button Button btnMainMenu_1 = new Button("Main Menu"); btnMainMenu_1.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { rootPanel.clear(); TheatreProjectWeb.mainPage(); } }); absolutePanel.add(btnMainMenu_1, 364, 545); //save buttons Button btnNewButton = new Button("New button"); btnNewButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { //start by setting thisObject parameters to current txtbxs thisObject.setName(nameOfObject.getText()); thisObject.setDescription(txtDescription.getText()); thisObject.setDisclaimers(txtDisclaimers.getText()); //TODO //thisObject.setImage(newImageURL); //thisObject.setStorageArea(newStorageArea); thisObject.getStatus().setLocation(txtLocation.getText()); thisObject.getStatus().setRenter(lblNameOfRenter.getText()); thisObject.getStatus().setShowDay(txtShowDate.getText()); //then save out the changes persistence.saveObject(thisObject, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { lblCouldNotFind.setVisible(true); } @Override public void onSuccess(Void result) { lblCouldNotFind.setVisible(false); //when saved, it returns to the main page rootPanel.clear(); TheatreProjectWeb.mainPage(); } }); } }); btnNewButton.setText("Save"); absolutePanel.add(btnNewButton, 10, 545); //Delete button Button btnDeleteItem = new Button("Delete Item"); btnDeleteItem.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { persistence.deleteObject(thisObject, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { lblCouldNotFind.setVisible(true); } @Override public void onSuccess(Void result) { lblCouldNotFind.setVisible(false); //when saved, it returns to the main page rootPanel.clear(); TheatreProjectWeb.mainPage(); } }); } }); absolutePanel.add(btnDeleteItem, 73, 545); }
public static void adminOnlyInventory(final String ID){ final TextArea txtDescription = new TextArea(); final TextArea txtDisclaimers = new TextArea(); final TextBox txtShowDate = new TextBox(); final TextBox txtLocation = new TextBox(); final TextBox lblStatus = new TextBox(); final TextBox txtbxEmailAddress = new TextBox(); final TextBox nameOfObject = new TextBox(); final Hidden hiddenID = new Hidden(); final TextBox txtStroageArea = new TextBox(); Timer loadFields = new Timer(){ @Override public void run() { persistence.getInventoryObject(ID, new AsyncCallback<InventoryObject>() { @Override public void onFailure(Throwable caught) { thisObject = null; } @Override public void onSuccess(InventoryObject object) { thisObject = object; if(thisObject == null){ schedule(RETRY_MS); } else { txtDescription.setText(thisObject.getDescription()); txtDisclaimers.setText(thisObject.getDisclaimers()); txtShowDate.setText(thisObject.getStatus().getShowDay()); txtLocation.setText(thisObject.getStatus().getLocation()); if (thisObject.getStatus().getLocation() == "warehouse") lblStatus.setText("IN"); else lblStatus.setText("OUT"); txtbxEmailAddress.setText(thisObject.getStatus().getRenter()); nameOfObject.setText(thisObject.getName()); hiddenID.setValue(thisObject.getID()); txtStroageArea.setText(thisObject.getStorageArea()); } } }); } }; loadFields.run(); final RootPanel rootPanel = RootPanel.get(); rootPanel.setStyleName("gwt-Root"); final VerticalPanel manguageUserPanel = new VerticalPanel(); rootPanel.add(manguageUserPanel, 10 ,10 ); manguageUserPanel.setSize("498px", "627px"); final Label title = new Label("Admin Inventory Page"); title.setStyleName("gwt-Header"); manguageUserPanel.add(title); title.setSize("338px","25px"); AbsolutePanel absolutePanel = new AbsolutePanel(); manguageUserPanel.add(absolutePanel); absolutePanel.setSize("472px", "582px"); //Error Label final Label lblCouldNotFind = new Label("COULD NOT SAVE OBJECT. PLEASE CONTACT SITE ADMINISTRATOR."); lblCouldNotFind.setVisible(false); absolutePanel.add(lblCouldNotFind, 24, 75); lblCouldNotFind.setSize("158px", "82px"); HorizontalPanel horizontalPanel_4 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_4, 10, 291); horizontalPanel_4.setSize("434px", "98px"); //Description Box Label lblNewLabel = new Label("Description: "); horizontalPanel_4.add(lblNewLabel); horizontalPanel_4.add(txtDescription); txtDescription.setSize("342px", "96px"); HorizontalPanel horizontalPanel_5 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_5, 10, 418); horizontalPanel_5.setSize("433px", "110px"); Label lblDisclaimers = new Label("Disclaimers: "); horizontalPanel_5.add(lblDisclaimers); horizontalPanel_5.add(txtDisclaimers); txtDisclaimers.setSize("339px", "96px"); HorizontalPanel horizontalPanel_1 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_1, 232, 119); horizontalPanel_1.setSize("211px", "34px"); Label lblLocation = new Label("Location: "); horizontalPanel_1.add(lblLocation); horizontalPanel_1.add(txtLocation); txtLocation.setWidth("136px"); HorizontalPanel horizontalPanel_7 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_7, 232, 179); horizontalPanel_7.setSize("211px", "34px"); Label lblShowEndDate = new Label("Show End Date: "); horizontalPanel_7.add(lblShowEndDate); horizontalPanel_7.add(txtShowDate); txtShowDate.setWidth("130px"); HorizontalPanel horizontalPanel_2 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_2, 233, 47); horizontalPanel_2.setSize("211px", "49px"); Label lblCheckInoutStatus = new Label("Check in/out Status: "); horizontalPanel_2.add(lblCheckInoutStatus); lblCheckInoutStatus.setWidth("92px"); horizontalPanel_2.add(lblStatus); lblStatus.setSize("97px", "22px"); HorizontalPanel horizontalPanel_6 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_6, 232, 237); horizontalPanel_6.setSize("211px", "34px"); Label lblEmailOfRenter = new Label("Location in Warehouse: "); horizontalPanel_6.add(lblEmailOfRenter); horizontalPanel_6.add(txtStroageArea); txtbxEmailAddress.setWidth("111px"); HorizontalPanel horizontalPanel_8 = new HorizontalPanel(); absolutePanel.add(horizontalPanel_8, 10, 219); horizontalPanel_8.setSize("196px", "34px"); final Label lblNameOfRenter = new Label("Name of Renter: "); horizontalPanel_8.add(lblNameOfRenter); lblNameOfRenter.setWidth("55px"); horizontalPanel_8.add(txtbxEmailAddress); txtbxEmailAddress.setWidth("133px"); nameOfObject.setStyleName("gwt-Heading2"); absolutePanel.add(nameOfObject, 10, 10); nameOfObject.setSize("419px", "18px"); Button btnUploadImage = new Button("Upload Image"); absolutePanel.add(btnUploadImage, 10, 179); // Image image = new Image((String) null); // image.setAltText("Image of Item"); // absolutePanel.add(image, 10, 47); // image.setSize("198px", "126px"); //Main Menu Button Button btnMainMenu_1 = new Button("Main Menu"); btnMainMenu_1.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { rootPanel.clear(); TheatreProjectWeb.mainPage(); } }); absolutePanel.add(btnMainMenu_1, 364, 545); //save buttons Button btnNewButton = new Button("New button"); btnNewButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { //start by setting thisObject parameters to current txtbxs thisObject.setName(nameOfObject.getText()); thisObject.setDescription(txtDescription.getText()); thisObject.setDisclaimers(txtDisclaimers.getText()); //TODO //thisObject.setImage(newImageURL); //thisObject.setStorageArea(newStorageArea); thisObject.getStatus().setLocation(txtLocation.getText()); thisObject.getStatus().setRenter(lblNameOfRenter.getText()); thisObject.getStatus().setShowDay(txtShowDate.getText()); //then save out the changes persistence.saveObject(thisObject, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { lblCouldNotFind.setVisible(true); } @Override public void onSuccess(Void result) { lblCouldNotFind.setVisible(false); //when saved, it returns to the main page rootPanel.clear(); TheatreProjectWeb.mainPage(); } }); } }); btnNewButton.setText("Save"); absolutePanel.add(btnNewButton, 10, 545); //Delete button Button btnDeleteItem = new Button("Delete Item"); btnDeleteItem.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { persistence.deleteObject(thisObject, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { lblCouldNotFind.setVisible(true); } @Override public void onSuccess(Void result) { lblCouldNotFind.setVisible(false); //when saved, it returns to the main page rootPanel.clear(); TheatreProjectWeb.mainPage(); } }); } }); absolutePanel.add(btnDeleteItem, 73, 545); }
diff --git a/src/org/mozilla/javascript/DToA.java b/src/org/mozilla/javascript/DToA.java index 732898c4..b4ae3fdb 100644 --- a/src/org/mozilla/javascript/DToA.java +++ b/src/org/mozilla/javascript/DToA.java @@ -1,1260 +1,1262 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Waldemar Horwat * Roger Lawrence * Attila Szegedi * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ /**************************************************************** * * The author of this software is David M. Gay. * * Copyright (c) 1991, 2000, 2001 by Lucent Technologies. * * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. * * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. * ***************************************************************/ package org.mozilla.javascript; import java.math.BigInteger; class DToA { private static char BASEDIGIT(int digit) { return (char)((digit >= 10) ? 'a' - 10 + digit : '0' + digit); } static final int DTOSTR_STANDARD = 0, /* Either fixed or exponential format; round-trip */ DTOSTR_STANDARD_EXPONENTIAL = 1, /* Always exponential format; round-trip */ DTOSTR_FIXED = 2, /* Round to <precision> digits after the decimal point; exponential if number is large */ DTOSTR_EXPONENTIAL = 3, /* Always exponential format; <precision> significant digits */ DTOSTR_PRECISION = 4; /* Either fixed or exponential format; <precision> significant digits */ private static final int Frac_mask = 0xfffff; private static final int Exp_shift = 20; private static final int Exp_msk1 = 0x100000; private static final long Frac_maskL = 0xfffffffffffffL; private static final int Exp_shiftL = 52; private static final long Exp_msk1L = 0x10000000000000L; private static final int Bias = 1023; private static final int P = 53; private static final int Exp_shift1 = 20; private static final int Exp_mask = 0x7ff00000; private static final int Exp_mask_shifted = 0x7ff; private static final int Bndry_mask = 0xfffff; private static final int Log2P = 1; private static final int Sign_bit = 0x80000000; private static final int Exp_11 = 0x3ff00000; private static final int Ten_pmax = 22; private static final int Quick_max = 14; private static final int Bletch = 0x10; private static final int Frac_mask1 = 0xfffff; private static final int Int_max = 14; private static final int n_bigtens = 5; private static final double tens[] = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22 }; private static final double bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 }; private static int lo0bits(int y) { int k; int x = y; if ((x & 7) != 0) { if ((x & 1) != 0) return 0; if ((x & 2) != 0) { return 1; } return 2; } k = 0; if ((x & 0xffff) == 0) { k = 16; x >>>= 16; } if ((x & 0xff) == 0) { k += 8; x >>>= 8; } if ((x & 0xf) == 0) { k += 4; x >>>= 4; } if ((x & 0x3) == 0) { k += 2; x >>>= 2; } if ((x & 1) == 0) { k++; x >>>= 1; if ((x & 1) == 0) return 32; } return k; } /* Return the number (0 through 32) of most significant zero bits in x. */ private static int hi0bits(int x) { int k = 0; if ((x & 0xffff0000) == 0) { k = 16; x <<= 16; } if ((x & 0xff000000) == 0) { k += 8; x <<= 8; } if ((x & 0xf0000000) == 0) { k += 4; x <<= 4; } if ((x & 0xc0000000) == 0) { k += 2; x <<= 2; } if ((x & 0x80000000) == 0) { k++; if ((x & 0x40000000) == 0) return 32; } return k; } private static void stuffBits(byte bits[], int offset, int val) { bits[offset] = (byte)(val >> 24); bits[offset + 1] = (byte)(val >> 16); bits[offset + 2] = (byte)(val >> 8); bits[offset + 3] = (byte)(val); } /* Convert d into the form b*2^e, where b is an odd integer. b is the returned * Bigint and e is the returned binary exponent. Return the number of significant * bits in b in bits. d must be finite and nonzero. */ private static BigInteger d2b(double d, int[] e, int[] bits) { byte dbl_bits[]; int i, k, y, z, de; long dBits = Double.doubleToLongBits(d); int d0 = (int)(dBits >>> 32); int d1 = (int)(dBits); z = d0 & Frac_mask; d0 &= 0x7fffffff; /* clear sign bit, which we ignore */ if ((de = (d0 >>> Exp_shift)) != 0) z |= Exp_msk1; if ((y = d1) != 0) { dbl_bits = new byte[8]; k = lo0bits(y); y >>>= k; if (k != 0) { stuffBits(dbl_bits, 4, y | z << (32 - k)); z >>= k; } else stuffBits(dbl_bits, 4, y); stuffBits(dbl_bits, 0, z); i = (z != 0) ? 2 : 1; } else { // JS_ASSERT(z); dbl_bits = new byte[4]; k = lo0bits(z); z >>>= k; stuffBits(dbl_bits, 0, z); k += 32; i = 1; } if (de != 0) { e[0] = de - Bias - (P-1) + k; bits[0] = P - k; } else { e[0] = de - Bias - (P-1) + 1 + k; bits[0] = 32*i - hi0bits(z); } return new BigInteger(dbl_bits); } static String JS_dtobasestr(int base, double d) { if (!(2 <= base && base <= 36)) throw new IllegalArgumentException("Bad base: "+base); /* Check for Infinity and NaN */ if (Double.isNaN(d)) { return "NaN"; } else if (Double.isInfinite(d)) { return (d > 0.0) ? "Infinity" : "-Infinity"; } else if (d == 0) { // ALERT: should it distinguish -0.0 from +0.0 ? return "0"; } boolean negative; if (d >= 0.0) { negative = false; } else { negative = true; d = -d; } /* Get the integer part of d including '-' sign. */ String intDigits; double dfloor = Math.floor(d); long lfloor = (long)dfloor; if (lfloor == dfloor) { // int part fits long intDigits = Long.toString((negative) ? -lfloor : lfloor, base); } else { // BigInteger should be used long floorBits = Double.doubleToLongBits(dfloor); int exp = (int)(floorBits >> Exp_shiftL) & Exp_mask_shifted; long mantissa; if (exp == 0) { mantissa = (floorBits & Frac_maskL) << 1; } else { mantissa = (floorBits & Frac_maskL) | Exp_msk1L; } if (negative) { mantissa = -mantissa; } exp -= 1075; BigInteger x = BigInteger.valueOf(mantissa); if (exp > 0) { x = x.shiftLeft(exp); } else if (exp < 0) { x = x.shiftRight(-exp); } intDigits = x.toString(base); } if (d == dfloor) { // No fraction part return intDigits; } else { /* We have a fraction. */ StringBuilder buffer; /* The output string */ int digit; double df; /* The fractional part of d */ BigInteger b; buffer = new StringBuilder(); buffer.append(intDigits).append('.'); df = d - dfloor; long dBits = Double.doubleToLongBits(d); int word0 = (int)(dBits >> 32); int word1 = (int)(dBits); int[] e = new int[1]; int[] bbits = new int[1]; b = d2b(df, e, bbits); // JS_ASSERT(e < 0); /* At this point df = b * 2^e. e must be less than zero because 0 < df < 1. */ int s2 = -(word0 >>> Exp_shift1 & Exp_mask >> Exp_shift1); if (s2 == 0) s2 = -1; s2 += Bias + P; /* 1/2^s2 = (nextDouble(d) - d)/2 */ // JS_ASSERT(-s2 < e); BigInteger mlo = BigInteger.valueOf(1); BigInteger mhi = mlo; if ((word1 == 0) && ((word0 & Bndry_mask) == 0) && ((word0 & (Exp_mask & Exp_mask << 1)) != 0)) { /* The special case. Here we want to be within a quarter of the last input significant digit instead of one half of it when the output string's value is less than d. */ s2 += Log2P; mhi = BigInteger.valueOf(1<<Log2P); } b = b.shiftLeft(e[0] + s2); BigInteger s = BigInteger.valueOf(1); s = s.shiftLeft(s2); /* At this point we have the following: * s = 2^s2; * 1 > df = b/2^s2 > 0; * (d - prevDouble(d))/2 = mlo/2^s2; * (nextDouble(d) - d)/2 = mhi/2^s2. */ BigInteger bigBase = BigInteger.valueOf(base); boolean done = false; do { b = b.multiply(bigBase); BigInteger[] divResult = b.divideAndRemainder(s); b = divResult[1]; digit = (char)(divResult[0].intValue()); if (mlo == mhi) mlo = mhi = mlo.multiply(bigBase); else { mlo = mlo.multiply(bigBase); mhi = mhi.multiply(bigBase); } /* Do we yet have the shortest string that will round to d? */ int j = b.compareTo(mlo); /* j is b/2^s2 compared with mlo/2^s2. */ BigInteger delta = s.subtract(mhi); int j1 = (delta.signum() <= 0) ? 1 : b.compareTo(delta); /* j1 is b/2^s2 compared with 1 - mhi/2^s2. */ if (j1 == 0 && ((word1 & 1) == 0)) { if (j > 0) digit++; done = true; } else if (j < 0 || (j == 0 && ((word1 & 1) == 0))) { if (j1 > 0) { /* Either dig or dig+1 would work here as the least significant digit. Use whichever would produce an output value closer to d. */ b = b.shiftLeft(1); j1 = b.compareTo(s); if (j1 > 0) /* The even test (|| (j1 == 0 && (digit & 1))) is not here because it messes up odd base output * such as 3.5 in base 3. */ digit++; } done = true; } else if (j1 > 0) { digit++; done = true; } // JS_ASSERT(digit < (uint32)base); buffer.append(BASEDIGIT(digit)); } while (!done); return buffer.toString(); } } /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string. * * Inspired by "How to Print Floating-Point Numbers Accurately" by * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 92-101]. * * Modifications: * 1. Rather than iterating, we use a simple numeric overestimate * to determine k = floor(log10(d)). We scale relevant * quantities using O(log2(k)) rather than O(k) multiplications. * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't * try to generate digits strictly left to right. Instead, we * compute with fewer bits and propagate the carry if necessary * when rounding the final digit up. This is often faster. * 3. Under the assumption that input will be rounded nearest, * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22. * That is, we allow equality in stopping tests when the * round-nearest rule will give the same floating-point value * as would satisfaction of the stopping test with strict * inequality. * 4. We remove common factors of powers of 2 from relevant * quantities. * 5. When converting floating-point integers less than 1e16, * we use floating-point arithmetic rather than resorting * to multiple-precision integers. * 6. When asked to produce fewer than 15 digits, we first try * to get by with floating-point arithmetic; we resort to * multiple-precision integer arithmetic only if we cannot * guarantee that the floating-point calculation has given * the correctly rounded result. For k requested digits and * "uniformly" distributed input, the probability is * something like 10^(k-15) that we must resort to the Long * calculation. */ static int word0(double d) { long dBits = Double.doubleToLongBits(d); return (int)(dBits >> 32); } static double setWord0(double d, int i) { long dBits = Double.doubleToLongBits(d); dBits = ((long)i << 32) | (dBits & 0x0FFFFFFFFL); return Double.longBitsToDouble(dBits); } static int word1(double d) { long dBits = Double.doubleToLongBits(d); return (int)(dBits); } /* Return b * 5^k. k must be nonnegative. */ // XXXX the C version built a cache of these static BigInteger pow5mult(BigInteger b, int k) { return b.multiply(BigInteger.valueOf(5).pow(k)); } static boolean roundOff(StringBuilder buf) { int i = buf.length(); while (i != 0) { --i; char c = buf.charAt(i); if (c != '9') { buf.setCharAt(i, (char)(c + 1)); buf.setLength(i + 1); return false; } } buf.setLength(0); return true; } /* Always emits at least one digit. */ /* If biasUp is set, then rounding in modes 2 and 3 will round away from zero * when the number is exactly halfway between two representable values. For example, * rounding 2.5 to zero digits after the decimal point will return 3 and not 2. * 2.49 will still round to 2, and 2.51 will still round to 3. */ /* bufsize should be at least 20 for modes 0 and 1. For the other modes, * bufsize should be two greater than the maximum number of output characters expected. */ static int JS_dtoa(double d, int mode, boolean biasUp, int ndigits, boolean[] sign, StringBuilder buf) { /* Arguments ndigits, decpt, sign are similar to those of ecvt and fcvt; trailing zeros are suppressed from the returned string. If not null, *rve is set to point to the end of the return value. If d is +-Infinity or NaN, then *decpt is set to 9999. mode: 0 ==> shortest string that yields d when read in and rounded to nearest. 1 ==> like 0, but with Steele & White stopping rule; e.g. with IEEE P754 arithmetic , mode 0 gives 1e23 whereas mode 1 gives 9.999999999999999e22. 2 ==> max(1,ndigits) significant digits. This gives a return value similar to that of ecvt, except that trailing zeros are suppressed. 3 ==> through ndigits past the decimal point. This gives a return value similar to that from fcvt, except that trailing zeros are suppressed, and ndigits can be negative. 4-9 should give the same return values as 2-3, i.e., 4 <= mode <= 9 ==> same return as mode 2 + (mode & 1). These modes are mainly for debugging; often they run slower but sometimes faster than modes 2-3. 4,5,8,9 ==> left-to-right digit generation. 6-9 ==> don't try fast floating-point estimate (if applicable). Values of mode other than 0-9 are treated as mode 0. Sufficient space is allocated to the return value to hold the suppressed trailing zeros. */ int b2, b5, i, ieps, ilim, ilim0, ilim1, j, j1, k, k0, m2, m5, s2, s5; char dig; long L; long x; BigInteger b, b1, delta, mlo, mhi, S; int[] be = new int[1]; int[] bbits = new int[1]; double d2, ds, eps; boolean spec_case, denorm, k_check, try_quick, leftright; if ((word0(d) & Sign_bit) != 0) { /* set sign for everything, including 0's and NaNs */ sign[0] = true; // word0(d) &= ~Sign_bit; /* clear sign bit */ d = setWord0(d, word0(d) & ~Sign_bit); } else sign[0] = false; if ((word0(d) & Exp_mask) == Exp_mask) { /* Infinity or NaN */ buf.append(((word1(d) == 0) && ((word0(d) & Frac_mask) == 0)) ? "Infinity" : "NaN"); return 9999; } if (d == 0) { // no_digits: buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; } b = d2b(d, be, bbits); if ((i = (word0(d) >>> Exp_shift1 & (Exp_mask>>Exp_shift1))) != 0) { d2 = setWord0(d, (word0(d) & Frac_mask1) | Exp_11); /* log(x) ~=~ log(1.5) + (x-1.5)/1.5 * log10(x) = log(x) / log(10) * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10)) * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2) * * This suggests computing an approximation k to log10(d) by * * k = (i - Bias)*0.301029995663981 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 ); * * We want k to be too large rather than too small. * The error in the first-order Taylor series approximation * is in our favor, so we just round up the constant enough * to compensate for any error in the multiplication of * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077, * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14, * adding 1e-13 to the constant term more than suffices. * Hence we adjust the constant term to 0.1760912590558. * (We could get a more accurate k by invoking log10, * but this is probably not worthwhile.) */ i -= Bias; denorm = false; } else { /* d is denormalized */ i = bbits[0] + be[0] + (Bias + (P-1) - 1); - x = (i > 32) ? word0(d) << (64 - i) | word1(d) >>> (i - 32) : word1(d) << (32 - i); + x = (i > 32) + ? ((long) word0(d)) << (64 - i) | word1(d) >>> (i - 32) + : ((long) word1(d)) << (32 - i); // d2 = x; // word0(d2) -= 31*Exp_msk1; /* adjust exponent */ d2 = setWord0(x, word0(x) - 31*Exp_msk1); i -= (Bias + (P-1) - 1) + 1; denorm = true; } /* At this point d = f*2^i, where 1 <= f < 2. d2 is an approximation of f. */ ds = (d2-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981; k = (int)ds; if (ds < 0.0 && ds != k) k--; /* want k = floor(ds) */ k_check = true; if (k >= 0 && k <= Ten_pmax) { if (d < tens[k]) k--; k_check = false; } /* At this point floor(log10(d)) <= k <= floor(log10(d))+1. If k_check is zero, we're guaranteed that k = floor(log10(d)). */ j = bbits[0] - i - 1; /* At this point d = b/2^j, where b is an odd integer. */ if (j >= 0) { b2 = 0; s2 = j; } else { b2 = -j; s2 = 0; } if (k >= 0) { b5 = 0; s5 = k; s2 += k; } else { b2 -= k; b5 = -k; s5 = 0; } /* At this point d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5), where b is an odd integer, b2 >= 0, b5 >= 0, s2 >= 0, and s5 >= 0. */ if (mode < 0 || mode > 9) mode = 0; try_quick = true; if (mode > 5) { mode -= 4; try_quick = false; } leftright = true; ilim = ilim1 = 0; switch(mode) { case 0: case 1: ilim = ilim1 = -1; i = 18; ndigits = 0; break; case 2: leftright = false; /* no break */ case 4: if (ndigits <= 0) ndigits = 1; ilim = ilim1 = i = ndigits; break; case 3: leftright = false; /* no break */ case 5: i = ndigits + k + 1; ilim = i; ilim1 = i - 1; if (i <= 0) i = 1; } /* ilim is the maximum number of significant digits we want, based on k and ndigits. */ /* ilim1 is the maximum number of significant digits we want, based on k and ndigits, when it turns out that k was computed too high by one. */ boolean fast_failed = false; if (ilim >= 0 && ilim <= Quick_max && try_quick) { /* Try to get by with floating-point arithmetic. */ i = 0; d2 = d; k0 = k; ilim0 = ilim; ieps = 2; /* conservative */ /* Divide d by 10^k, keeping track of the roundoff error and avoiding overflows. */ if (k > 0) { ds = tens[k&0xf]; j = k >> 4; if ((j & Bletch) != 0) { /* prevent overflows */ j &= Bletch - 1; d /= bigtens[n_bigtens-1]; ieps++; } for(; (j != 0); j >>= 1, i++) if ((j & 1) != 0) { ieps++; ds *= bigtens[i]; } d /= ds; } else if ((j1 = -k) != 0) { d *= tens[j1 & 0xf]; for(j = j1 >> 4; (j != 0); j >>= 1, i++) if ((j & 1) != 0) { ieps++; d *= bigtens[i]; } } /* Check that k was computed correctly. */ if (k_check && d < 1.0 && ilim > 0) { if (ilim1 <= 0) fast_failed = true; else { ilim = ilim1; k--; d *= 10.; ieps++; } } /* eps bounds the cumulative error. */ // eps = ieps*d + 7.0; // word0(eps) -= (P-1)*Exp_msk1; eps = ieps*d + 7.0; eps = setWord0(eps, word0(eps) - (P-1)*Exp_msk1); if (ilim == 0) { S = mhi = null; d -= 5.0; if (d > eps) { buf.append('1'); k++; return k + 1; } if (d < -eps) { buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; } fast_failed = true; } if (!fast_failed) { fast_failed = true; if (leftright) { /* Use Steele & White method of only * generating digits needed. */ eps = 0.5/tens[ilim-1] - eps; for(i = 0;;) { L = (long)d; d -= L; buf.append((char)('0' + L)); if (d < eps) { return k + 1; } if (1.0 - d < eps) { // goto bump_up; char lastCh; while (true) { lastCh = buf.charAt(buf.length() - 1); buf.setLength(buf.length() - 1); if (lastCh != '9') break; if (buf.length() == 0) { k++; lastCh = '0'; break; } } buf.append((char)(lastCh + 1)); return k + 1; } if (++i >= ilim) break; eps *= 10.0; d *= 10.0; } } else { /* Generate ilim digits, then fix them up. */ eps *= tens[ilim-1]; for(i = 1;; i++, d *= 10.0) { L = (long)d; d -= L; buf.append((char)('0' + L)); if (i == ilim) { if (d > 0.5 + eps) { // goto bump_up; char lastCh; while (true) { lastCh = buf.charAt(buf.length() - 1); buf.setLength(buf.length() - 1); if (lastCh != '9') break; if (buf.length() == 0) { k++; lastCh = '0'; break; } } buf.append((char)(lastCh + 1)); return k + 1; } else if (d < 0.5 - eps) { stripTrailingZeroes(buf); // while(*--s == '0') ; // s++; return k + 1; } break; } } } } if (fast_failed) { buf.setLength(0); d = d2; k = k0; ilim = ilim0; } } /* Do we have a "small" integer? */ if (be[0] >= 0 && k <= Int_max) { /* Yes. */ ds = tens[k]; if (ndigits < 0 && ilim <= 0) { S = mhi = null; if (ilim < 0 || d < 5*ds || (!biasUp && d == 5*ds)) { buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; } buf.append('1'); k++; return k + 1; } for(i = 1;; i++) { L = (long) (d / ds); d -= L*ds; buf.append((char)('0' + L)); if (i == ilim) { d += d; if ((d > ds) || (d == ds && (((L & 1) != 0) || biasUp))) { // bump_up: // while(*--s == '9') // if (s == buf) { // k++; // *s = '0'; // break; // } // ++*s++; char lastCh; while (true) { lastCh = buf.charAt(buf.length() - 1); buf.setLength(buf.length() - 1); if (lastCh != '9') break; if (buf.length() == 0) { k++; lastCh = '0'; break; } } buf.append((char)(lastCh + 1)); } break; } d *= 10.0; if (d == 0) break; } return k + 1; } m2 = b2; m5 = b5; mhi = mlo = null; if (leftright) { if (mode < 2) { i = (denorm) ? be[0] + (Bias + (P-1) - 1 + 1) : 1 + P - bbits[0]; /* i is 1 plus the number of trailing zero bits in d's significand. Thus, (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 lsb of d)/10^k. */ } else { j = ilim - 1; if (m5 >= j) m5 -= j; else { s5 += j -= m5; b5 += j; m5 = 0; } if ((i = ilim) < 0) { m2 -= i; i = 0; } /* (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 * 10^(1-ilim))/10^k. */ } b2 += i; s2 += i; mhi = BigInteger.valueOf(1); /* (mhi * 2^m2 * 5^m5) / (2^s2 * 5^s5) = one-half of last printed (when mode >= 2) or input (when mode < 2) significant digit, divided by 10^k. */ } /* We still have d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5). Reduce common factors in b2, m2, and s2 without changing the equalities. */ if (m2 > 0 && s2 > 0) { i = (m2 < s2) ? m2 : s2; b2 -= i; m2 -= i; s2 -= i; } /* Fold b5 into b and m5 into mhi. */ if (b5 > 0) { if (leftright) { if (m5 > 0) { mhi = pow5mult(mhi, m5); b1 = mhi.multiply(b); b = b1; } if ((j = b5 - m5) != 0) b = pow5mult(b, j); } else b = pow5mult(b, b5); } /* Now we have d/10^k = (b * 2^b2) / (2^s2 * 5^s5) and (mhi * 2^m2) / (2^s2 * 5^s5) = one-half of last printed or input significant digit, divided by 10^k. */ S = BigInteger.valueOf(1); if (s5 > 0) S = pow5mult(S, s5); /* Now we have d/10^k = (b * 2^b2) / (S * 2^s2) and (mhi * 2^m2) / (S * 2^s2) = one-half of last printed or input significant digit, divided by 10^k. */ /* Check for special case that d is a normalized power of 2. */ spec_case = false; if (mode < 2) { if ( (word1(d) == 0) && ((word0(d) & Bndry_mask) == 0) && ((word0(d) & (Exp_mask & Exp_mask << 1)) != 0) ) { /* The special case. Here we want to be within a quarter of the last input significant digit instead of one half of it when the decimal output string's value is less than d. */ b2 += Log2P; s2 += Log2P; spec_case = true; } } /* Arrange for convenient computation of quotients: * shift left if necessary so divisor has 4 leading 0 bits. * * Perhaps we should just compute leading 28 bits of S once * and for all and pass them and a shift to quorem, so it * can do shifts and ors to compute the numerator for q. */ byte [] S_bytes = S.toByteArray(); int S_hiWord = 0; for (int idx = 0; idx < 4; idx++) { S_hiWord = (S_hiWord << 8); if (idx < S_bytes.length) S_hiWord |= (S_bytes[idx] & 0xFF); } if ((i = (((s5 != 0) ? 32 - hi0bits(S_hiWord) : 1) + s2) & 0x1f) != 0) i = 32 - i; /* i is the number of leading zero bits in the most significant word of S*2^s2. */ if (i > 4) { i -= 4; b2 += i; m2 += i; s2 += i; } else if (i < 4) { i += 28; b2 += i; m2 += i; s2 += i; } /* Now S*2^s2 has exactly four leading zero bits in its most significant word. */ if (b2 > 0) b = b.shiftLeft(b2); if (s2 > 0) S = S.shiftLeft(s2); /* Now we have d/10^k = b/S and (mhi * 2^m2) / S = maximum acceptable error, divided by 10^k. */ if (k_check) { if (b.compareTo(S) < 0) { k--; b = b.multiply(BigInteger.valueOf(10)); /* we botched the k estimate */ if (leftright) mhi = mhi.multiply(BigInteger.valueOf(10)); ilim = ilim1; } } /* At this point 1 <= d/10^k = b/S < 10. */ if (ilim <= 0 && mode > 2) { /* We're doing fixed-mode output and d is less than the minimum nonzero output in this mode. Output either zero or the minimum nonzero output depending on which is closer to d. */ if ((ilim < 0 ) || ((i = b.compareTo(S = S.multiply(BigInteger.valueOf(5)))) < 0) || ((i == 0 && !biasUp))) { /* Always emit at least one digit. If the number appears to be zero using the current mode, then emit one '0' digit and set decpt to 1. */ /*no_digits: k = -1 - ndigits; goto ret; */ buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; // goto no_digits; } // one_digit: buf.append('1'); k++; return k + 1; } if (leftright) { if (m2 > 0) mhi = mhi.shiftLeft(m2); /* Compute mlo -- check for special case * that d is a normalized power of 2. */ mlo = mhi; if (spec_case) { mhi = mlo; mhi = mhi.shiftLeft(Log2P); } /* mlo/S = maximum acceptable error, divided by 10^k, if the output is less than d. */ /* mhi/S = maximum acceptable error, divided by 10^k, if the output is greater than d. */ for(i = 1;;i++) { BigInteger[] divResult = b.divideAndRemainder(S); b = divResult[1]; dig = (char)(divResult[0].intValue() + '0'); /* Do we yet have the shortest decimal string * that will round to d? */ j = b.compareTo(mlo); /* j is b/S compared with mlo/S. */ delta = S.subtract(mhi); j1 = (delta.signum() <= 0) ? 1 : b.compareTo(delta); /* j1 is b/S compared with 1 - mhi/S. */ if ((j1 == 0) && (mode == 0) && ((word1(d) & 1) == 0)) { if (dig == '9') { buf.append('9'); if (roundOff(buf)) { k++; buf.append('1'); } return k + 1; // goto round_9_up; } if (j > 0) dig++; buf.append(dig); return k + 1; } if ((j < 0) || ((j == 0) && (mode == 0) && ((word1(d) & 1) == 0) )) { if (j1 > 0) { /* Either dig or dig+1 would work here as the least significant decimal digit. Use whichever would produce a decimal value closer to d. */ b = b.shiftLeft(1); j1 = b.compareTo(S); if (((j1 > 0) || (j1 == 0 && (((dig & 1) == 1) || biasUp))) && (dig++ == '9')) { buf.append('9'); if (roundOff(buf)) { k++; buf.append('1'); } return k + 1; // goto round_9_up; } } buf.append(dig); return k + 1; } if (j1 > 0) { if (dig == '9') { /* possible if i == 1 */ // round_9_up: // *s++ = '9'; // goto roundoff; buf.append('9'); if (roundOff(buf)) { k++; buf.append('1'); } return k + 1; } buf.append((char)(dig + 1)); return k + 1; } buf.append(dig); if (i == ilim) break; b = b.multiply(BigInteger.valueOf(10)); if (mlo == mhi) mlo = mhi = mhi.multiply(BigInteger.valueOf(10)); else { mlo = mlo.multiply(BigInteger.valueOf(10)); mhi = mhi.multiply(BigInteger.valueOf(10)); } } } else for(i = 1;; i++) { // (char)(dig = quorem(b,S) + '0'); BigInteger[] divResult = b.divideAndRemainder(S); b = divResult[1]; dig = (char)(divResult[0].intValue() + '0'); buf.append(dig); if (i >= ilim) break; b = b.multiply(BigInteger.valueOf(10)); } /* Round off last digit */ b = b.shiftLeft(1); j = b.compareTo(S); if ((j > 0) || (j == 0 && (((dig & 1) == 1) || biasUp))) { // roundoff: // while(*--s == '9') // if (s == buf) { // k++; // *s++ = '1'; // goto ret; // } // ++*s++; if (roundOff(buf)) { k++; buf.append('1'); return k + 1; } } else { stripTrailingZeroes(buf); // while(*--s == '0') ; // s++; } // ret: // Bfree(S); // if (mhi) { // if (mlo && mlo != mhi) // Bfree(mlo); // Bfree(mhi); // } // ret1: // Bfree(b); // JS_ASSERT(s < buf + bufsize); return k + 1; } private static void stripTrailingZeroes(StringBuilder buf) { // while(*--s == '0') ; // s++; int bl = buf.length(); while(bl-->0 && buf.charAt(bl) == '0') { // empty } buf.setLength(bl + 1); } /* Mapping of JSDToStrMode -> JS_dtoa mode */ private static final int dtoaModes[] = { 0, /* DTOSTR_STANDARD */ 0, /* DTOSTR_STANDARD_EXPONENTIAL, */ 3, /* DTOSTR_FIXED, */ 2, /* DTOSTR_EXPONENTIAL, */ 2}; /* DTOSTR_PRECISION */ static void JS_dtostr(StringBuilder buffer, int mode, int precision, double d) { int decPt; /* Position of decimal point relative to first digit returned by JS_dtoa */ boolean[] sign = new boolean[1]; /* true if the sign bit was set in d */ int nDigits; /* Number of significand digits returned by JS_dtoa */ // JS_ASSERT(bufferSize >= (size_t)(mode <= DTOSTR_STANDARD_EXPONENTIAL ? DTOSTR_STANDARD_BUFFER_SIZE : // DTOSTR_VARIABLE_BUFFER_SIZE(precision))); if (mode == DTOSTR_FIXED && (d >= 1e21 || d <= -1e21)) mode = DTOSTR_STANDARD; /* Change mode here rather than below because the buffer may not be large enough to hold a large integer. */ decPt = JS_dtoa(d, dtoaModes[mode], mode >= DTOSTR_FIXED, precision, sign, buffer); nDigits = buffer.length(); /* If Infinity, -Infinity, or NaN, return the string regardless of the mode. */ if (decPt != 9999) { boolean exponentialNotation = false; int minNDigits = 0; /* Minimum number of significand digits required by mode and precision */ int p; switch (mode) { case DTOSTR_STANDARD: if (decPt < -5 || decPt > 21) exponentialNotation = true; else minNDigits = decPt; break; case DTOSTR_FIXED: if (precision >= 0) minNDigits = decPt + precision; else minNDigits = decPt; break; case DTOSTR_EXPONENTIAL: // JS_ASSERT(precision > 0); minNDigits = precision; /* Fall through */ case DTOSTR_STANDARD_EXPONENTIAL: exponentialNotation = true; break; case DTOSTR_PRECISION: // JS_ASSERT(precision > 0); minNDigits = precision; if (decPt < -5 || decPt > precision) exponentialNotation = true; break; } /* If the number has fewer than minNDigits, pad it with zeros at the end */ if (nDigits < minNDigits) { p = minNDigits; nDigits = minNDigits; do { buffer.append('0'); } while (buffer.length() != p); } if (exponentialNotation) { /* Insert a decimal point if more than one significand digit */ if (nDigits != 1) { buffer.insert(1, '.'); } buffer.append('e'); if ((decPt - 1) >= 0) buffer.append('+'); buffer.append(decPt - 1); // JS_snprintf(numEnd, bufferSize - (numEnd - buffer), "e%+d", decPt-1); } else if (decPt != nDigits) { /* Some kind of a fraction in fixed notation */ // JS_ASSERT(decPt <= nDigits); if (decPt > 0) { /* dd...dd . dd...dd */ buffer.insert(decPt, '.'); } else { /* 0 . 00...00dd...dd */ for (int i = 0; i < 1 - decPt; i++) buffer.insert(0, '0'); buffer.insert(1, '.'); } } } /* If negative and neither -0.0 nor NaN, output a leading '-'. */ if (sign[0] && !(word0(d) == Sign_bit && word1(d) == 0) && !((word0(d) & Exp_mask) == Exp_mask && ((word1(d) != 0) || ((word0(d) & Frac_mask) != 0)))) { buffer.insert(0, '-'); } } }
true
true
static int JS_dtoa(double d, int mode, boolean biasUp, int ndigits, boolean[] sign, StringBuilder buf) { /* Arguments ndigits, decpt, sign are similar to those of ecvt and fcvt; trailing zeros are suppressed from the returned string. If not null, *rve is set to point to the end of the return value. If d is +-Infinity or NaN, then *decpt is set to 9999. mode: 0 ==> shortest string that yields d when read in and rounded to nearest. 1 ==> like 0, but with Steele & White stopping rule; e.g. with IEEE P754 arithmetic , mode 0 gives 1e23 whereas mode 1 gives 9.999999999999999e22. 2 ==> max(1,ndigits) significant digits. This gives a return value similar to that of ecvt, except that trailing zeros are suppressed. 3 ==> through ndigits past the decimal point. This gives a return value similar to that from fcvt, except that trailing zeros are suppressed, and ndigits can be negative. 4-9 should give the same return values as 2-3, i.e., 4 <= mode <= 9 ==> same return as mode 2 + (mode & 1). These modes are mainly for debugging; often they run slower but sometimes faster than modes 2-3. 4,5,8,9 ==> left-to-right digit generation. 6-9 ==> don't try fast floating-point estimate (if applicable). Values of mode other than 0-9 are treated as mode 0. Sufficient space is allocated to the return value to hold the suppressed trailing zeros. */ int b2, b5, i, ieps, ilim, ilim0, ilim1, j, j1, k, k0, m2, m5, s2, s5; char dig; long L; long x; BigInteger b, b1, delta, mlo, mhi, S; int[] be = new int[1]; int[] bbits = new int[1]; double d2, ds, eps; boolean spec_case, denorm, k_check, try_quick, leftright; if ((word0(d) & Sign_bit) != 0) { /* set sign for everything, including 0's and NaNs */ sign[0] = true; // word0(d) &= ~Sign_bit; /* clear sign bit */ d = setWord0(d, word0(d) & ~Sign_bit); } else sign[0] = false; if ((word0(d) & Exp_mask) == Exp_mask) { /* Infinity or NaN */ buf.append(((word1(d) == 0) && ((word0(d) & Frac_mask) == 0)) ? "Infinity" : "NaN"); return 9999; } if (d == 0) { // no_digits: buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; } b = d2b(d, be, bbits); if ((i = (word0(d) >>> Exp_shift1 & (Exp_mask>>Exp_shift1))) != 0) { d2 = setWord0(d, (word0(d) & Frac_mask1) | Exp_11); /* log(x) ~=~ log(1.5) + (x-1.5)/1.5 * log10(x) = log(x) / log(10) * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10)) * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2) * * This suggests computing an approximation k to log10(d) by * * k = (i - Bias)*0.301029995663981 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 ); * * We want k to be too large rather than too small. * The error in the first-order Taylor series approximation * is in our favor, so we just round up the constant enough * to compensate for any error in the multiplication of * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077, * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14, * adding 1e-13 to the constant term more than suffices. * Hence we adjust the constant term to 0.1760912590558. * (We could get a more accurate k by invoking log10, * but this is probably not worthwhile.) */ i -= Bias; denorm = false; } else { /* d is denormalized */ i = bbits[0] + be[0] + (Bias + (P-1) - 1); x = (i > 32) ? word0(d) << (64 - i) | word1(d) >>> (i - 32) : word1(d) << (32 - i); // d2 = x; // word0(d2) -= 31*Exp_msk1; /* adjust exponent */ d2 = setWord0(x, word0(x) - 31*Exp_msk1); i -= (Bias + (P-1) - 1) + 1; denorm = true; } /* At this point d = f*2^i, where 1 <= f < 2. d2 is an approximation of f. */ ds = (d2-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981; k = (int)ds; if (ds < 0.0 && ds != k) k--; /* want k = floor(ds) */ k_check = true; if (k >= 0 && k <= Ten_pmax) { if (d < tens[k]) k--; k_check = false; } /* At this point floor(log10(d)) <= k <= floor(log10(d))+1. If k_check is zero, we're guaranteed that k = floor(log10(d)). */ j = bbits[0] - i - 1; /* At this point d = b/2^j, where b is an odd integer. */ if (j >= 0) { b2 = 0; s2 = j; } else { b2 = -j; s2 = 0; } if (k >= 0) { b5 = 0; s5 = k; s2 += k; } else { b2 -= k; b5 = -k; s5 = 0; } /* At this point d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5), where b is an odd integer, b2 >= 0, b5 >= 0, s2 >= 0, and s5 >= 0. */ if (mode < 0 || mode > 9) mode = 0; try_quick = true; if (mode > 5) { mode -= 4; try_quick = false; } leftright = true; ilim = ilim1 = 0; switch(mode) { case 0: case 1: ilim = ilim1 = -1; i = 18; ndigits = 0; break; case 2: leftright = false; /* no break */ case 4: if (ndigits <= 0) ndigits = 1; ilim = ilim1 = i = ndigits; break; case 3: leftright = false; /* no break */ case 5: i = ndigits + k + 1; ilim = i; ilim1 = i - 1; if (i <= 0) i = 1; } /* ilim is the maximum number of significant digits we want, based on k and ndigits. */ /* ilim1 is the maximum number of significant digits we want, based on k and ndigits, when it turns out that k was computed too high by one. */ boolean fast_failed = false; if (ilim >= 0 && ilim <= Quick_max && try_quick) { /* Try to get by with floating-point arithmetic. */ i = 0; d2 = d; k0 = k; ilim0 = ilim; ieps = 2; /* conservative */ /* Divide d by 10^k, keeping track of the roundoff error and avoiding overflows. */ if (k > 0) { ds = tens[k&0xf]; j = k >> 4; if ((j & Bletch) != 0) { /* prevent overflows */ j &= Bletch - 1; d /= bigtens[n_bigtens-1]; ieps++; } for(; (j != 0); j >>= 1, i++) if ((j & 1) != 0) { ieps++; ds *= bigtens[i]; } d /= ds; } else if ((j1 = -k) != 0) { d *= tens[j1 & 0xf]; for(j = j1 >> 4; (j != 0); j >>= 1, i++) if ((j & 1) != 0) { ieps++; d *= bigtens[i]; } } /* Check that k was computed correctly. */ if (k_check && d < 1.0 && ilim > 0) { if (ilim1 <= 0) fast_failed = true; else { ilim = ilim1; k--; d *= 10.; ieps++; } } /* eps bounds the cumulative error. */ // eps = ieps*d + 7.0; // word0(eps) -= (P-1)*Exp_msk1; eps = ieps*d + 7.0; eps = setWord0(eps, word0(eps) - (P-1)*Exp_msk1); if (ilim == 0) { S = mhi = null; d -= 5.0; if (d > eps) { buf.append('1'); k++; return k + 1; } if (d < -eps) { buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; } fast_failed = true; } if (!fast_failed) { fast_failed = true; if (leftright) { /* Use Steele & White method of only * generating digits needed. */ eps = 0.5/tens[ilim-1] - eps; for(i = 0;;) { L = (long)d; d -= L; buf.append((char)('0' + L)); if (d < eps) { return k + 1; } if (1.0 - d < eps) { // goto bump_up; char lastCh; while (true) { lastCh = buf.charAt(buf.length() - 1); buf.setLength(buf.length() - 1); if (lastCh != '9') break; if (buf.length() == 0) { k++; lastCh = '0'; break; } } buf.append((char)(lastCh + 1)); return k + 1; } if (++i >= ilim) break; eps *= 10.0; d *= 10.0; } } else { /* Generate ilim digits, then fix them up. */ eps *= tens[ilim-1]; for(i = 1;; i++, d *= 10.0) { L = (long)d; d -= L; buf.append((char)('0' + L)); if (i == ilim) { if (d > 0.5 + eps) { // goto bump_up; char lastCh; while (true) { lastCh = buf.charAt(buf.length() - 1); buf.setLength(buf.length() - 1); if (lastCh != '9') break; if (buf.length() == 0) { k++; lastCh = '0'; break; } } buf.append((char)(lastCh + 1)); return k + 1; } else if (d < 0.5 - eps) { stripTrailingZeroes(buf); // while(*--s == '0') ; // s++; return k + 1; } break; } } } } if (fast_failed) { buf.setLength(0); d = d2; k = k0; ilim = ilim0; } } /* Do we have a "small" integer? */ if (be[0] >= 0 && k <= Int_max) { /* Yes. */ ds = tens[k]; if (ndigits < 0 && ilim <= 0) { S = mhi = null; if (ilim < 0 || d < 5*ds || (!biasUp && d == 5*ds)) { buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; } buf.append('1'); k++; return k + 1; } for(i = 1;; i++) { L = (long) (d / ds); d -= L*ds; buf.append((char)('0' + L)); if (i == ilim) { d += d; if ((d > ds) || (d == ds && (((L & 1) != 0) || biasUp))) { // bump_up: // while(*--s == '9') // if (s == buf) { // k++; // *s = '0'; // break; // } // ++*s++; char lastCh; while (true) { lastCh = buf.charAt(buf.length() - 1); buf.setLength(buf.length() - 1); if (lastCh != '9') break; if (buf.length() == 0) { k++; lastCh = '0'; break; } } buf.append((char)(lastCh + 1)); } break; } d *= 10.0; if (d == 0) break; } return k + 1; } m2 = b2; m5 = b5; mhi = mlo = null; if (leftright) { if (mode < 2) { i = (denorm) ? be[0] + (Bias + (P-1) - 1 + 1) : 1 + P - bbits[0]; /* i is 1 plus the number of trailing zero bits in d's significand. Thus, (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 lsb of d)/10^k. */ } else { j = ilim - 1; if (m5 >= j) m5 -= j; else { s5 += j -= m5; b5 += j; m5 = 0; } if ((i = ilim) < 0) { m2 -= i; i = 0; } /* (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 * 10^(1-ilim))/10^k. */ } b2 += i; s2 += i; mhi = BigInteger.valueOf(1); /* (mhi * 2^m2 * 5^m5) / (2^s2 * 5^s5) = one-half of last printed (when mode >= 2) or input (when mode < 2) significant digit, divided by 10^k. */ } /* We still have d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5). Reduce common factors in b2, m2, and s2 without changing the equalities. */ if (m2 > 0 && s2 > 0) { i = (m2 < s2) ? m2 : s2; b2 -= i; m2 -= i; s2 -= i; } /* Fold b5 into b and m5 into mhi. */ if (b5 > 0) { if (leftright) { if (m5 > 0) { mhi = pow5mult(mhi, m5); b1 = mhi.multiply(b); b = b1; } if ((j = b5 - m5) != 0) b = pow5mult(b, j); } else b = pow5mult(b, b5); } /* Now we have d/10^k = (b * 2^b2) / (2^s2 * 5^s5) and (mhi * 2^m2) / (2^s2 * 5^s5) = one-half of last printed or input significant digit, divided by 10^k. */ S = BigInteger.valueOf(1); if (s5 > 0) S = pow5mult(S, s5); /* Now we have d/10^k = (b * 2^b2) / (S * 2^s2) and (mhi * 2^m2) / (S * 2^s2) = one-half of last printed or input significant digit, divided by 10^k. */ /* Check for special case that d is a normalized power of 2. */ spec_case = false; if (mode < 2) { if ( (word1(d) == 0) && ((word0(d) & Bndry_mask) == 0) && ((word0(d) & (Exp_mask & Exp_mask << 1)) != 0) ) { /* The special case. Here we want to be within a quarter of the last input significant digit instead of one half of it when the decimal output string's value is less than d. */ b2 += Log2P; s2 += Log2P; spec_case = true; } } /* Arrange for convenient computation of quotients: * shift left if necessary so divisor has 4 leading 0 bits. * * Perhaps we should just compute leading 28 bits of S once * and for all and pass them and a shift to quorem, so it * can do shifts and ors to compute the numerator for q. */ byte [] S_bytes = S.toByteArray(); int S_hiWord = 0; for (int idx = 0; idx < 4; idx++) { S_hiWord = (S_hiWord << 8); if (idx < S_bytes.length) S_hiWord |= (S_bytes[idx] & 0xFF); } if ((i = (((s5 != 0) ? 32 - hi0bits(S_hiWord) : 1) + s2) & 0x1f) != 0) i = 32 - i; /* i is the number of leading zero bits in the most significant word of S*2^s2. */ if (i > 4) { i -= 4; b2 += i; m2 += i; s2 += i; } else if (i < 4) { i += 28; b2 += i; m2 += i; s2 += i; } /* Now S*2^s2 has exactly four leading zero bits in its most significant word. */ if (b2 > 0) b = b.shiftLeft(b2); if (s2 > 0) S = S.shiftLeft(s2); /* Now we have d/10^k = b/S and (mhi * 2^m2) / S = maximum acceptable error, divided by 10^k. */ if (k_check) { if (b.compareTo(S) < 0) { k--; b = b.multiply(BigInteger.valueOf(10)); /* we botched the k estimate */ if (leftright) mhi = mhi.multiply(BigInteger.valueOf(10)); ilim = ilim1; } } /* At this point 1 <= d/10^k = b/S < 10. */ if (ilim <= 0 && mode > 2) { /* We're doing fixed-mode output and d is less than the minimum nonzero output in this mode. Output either zero or the minimum nonzero output depending on which is closer to d. */ if ((ilim < 0 ) || ((i = b.compareTo(S = S.multiply(BigInteger.valueOf(5)))) < 0) || ((i == 0 && !biasUp))) { /* Always emit at least one digit. If the number appears to be zero using the current mode, then emit one '0' digit and set decpt to 1. */ /*no_digits: k = -1 - ndigits; goto ret; */ buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; // goto no_digits; } // one_digit: buf.append('1'); k++; return k + 1; } if (leftright) { if (m2 > 0) mhi = mhi.shiftLeft(m2); /* Compute mlo -- check for special case * that d is a normalized power of 2. */ mlo = mhi; if (spec_case) { mhi = mlo; mhi = mhi.shiftLeft(Log2P); } /* mlo/S = maximum acceptable error, divided by 10^k, if the output is less than d. */ /* mhi/S = maximum acceptable error, divided by 10^k, if the output is greater than d. */ for(i = 1;;i++) { BigInteger[] divResult = b.divideAndRemainder(S); b = divResult[1]; dig = (char)(divResult[0].intValue() + '0'); /* Do we yet have the shortest decimal string * that will round to d? */ j = b.compareTo(mlo); /* j is b/S compared with mlo/S. */ delta = S.subtract(mhi); j1 = (delta.signum() <= 0) ? 1 : b.compareTo(delta); /* j1 is b/S compared with 1 - mhi/S. */ if ((j1 == 0) && (mode == 0) && ((word1(d) & 1) == 0)) { if (dig == '9') { buf.append('9'); if (roundOff(buf)) { k++; buf.append('1'); } return k + 1; // goto round_9_up; } if (j > 0) dig++; buf.append(dig); return k + 1; } if ((j < 0) || ((j == 0) && (mode == 0) && ((word1(d) & 1) == 0) )) { if (j1 > 0) { /* Either dig or dig+1 would work here as the least significant decimal digit. Use whichever would produce a decimal value closer to d. */ b = b.shiftLeft(1); j1 = b.compareTo(S); if (((j1 > 0) || (j1 == 0 && (((dig & 1) == 1) || biasUp))) && (dig++ == '9')) { buf.append('9'); if (roundOff(buf)) { k++; buf.append('1'); } return k + 1; // goto round_9_up; } } buf.append(dig); return k + 1; } if (j1 > 0) { if (dig == '9') { /* possible if i == 1 */ // round_9_up: // *s++ = '9'; // goto roundoff; buf.append('9'); if (roundOff(buf)) { k++; buf.append('1'); } return k + 1; } buf.append((char)(dig + 1)); return k + 1; } buf.append(dig); if (i == ilim) break; b = b.multiply(BigInteger.valueOf(10)); if (mlo == mhi) mlo = mhi = mhi.multiply(BigInteger.valueOf(10)); else { mlo = mlo.multiply(BigInteger.valueOf(10)); mhi = mhi.multiply(BigInteger.valueOf(10)); } } } else for(i = 1;; i++) { // (char)(dig = quorem(b,S) + '0'); BigInteger[] divResult = b.divideAndRemainder(S); b = divResult[1]; dig = (char)(divResult[0].intValue() + '0'); buf.append(dig); if (i >= ilim) break; b = b.multiply(BigInteger.valueOf(10)); } /* Round off last digit */ b = b.shiftLeft(1); j = b.compareTo(S); if ((j > 0) || (j == 0 && (((dig & 1) == 1) || biasUp))) { // roundoff: // while(*--s == '9') // if (s == buf) { // k++; // *s++ = '1'; // goto ret; // } // ++*s++; if (roundOff(buf)) { k++; buf.append('1'); return k + 1; } } else { stripTrailingZeroes(buf); // while(*--s == '0') ; // s++; } // ret: // Bfree(S); // if (mhi) { // if (mlo && mlo != mhi) // Bfree(mlo); // Bfree(mhi); // } // ret1: // Bfree(b); // JS_ASSERT(s < buf + bufsize); return k + 1; }
static int JS_dtoa(double d, int mode, boolean biasUp, int ndigits, boolean[] sign, StringBuilder buf) { /* Arguments ndigits, decpt, sign are similar to those of ecvt and fcvt; trailing zeros are suppressed from the returned string. If not null, *rve is set to point to the end of the return value. If d is +-Infinity or NaN, then *decpt is set to 9999. mode: 0 ==> shortest string that yields d when read in and rounded to nearest. 1 ==> like 0, but with Steele & White stopping rule; e.g. with IEEE P754 arithmetic , mode 0 gives 1e23 whereas mode 1 gives 9.999999999999999e22. 2 ==> max(1,ndigits) significant digits. This gives a return value similar to that of ecvt, except that trailing zeros are suppressed. 3 ==> through ndigits past the decimal point. This gives a return value similar to that from fcvt, except that trailing zeros are suppressed, and ndigits can be negative. 4-9 should give the same return values as 2-3, i.e., 4 <= mode <= 9 ==> same return as mode 2 + (mode & 1). These modes are mainly for debugging; often they run slower but sometimes faster than modes 2-3. 4,5,8,9 ==> left-to-right digit generation. 6-9 ==> don't try fast floating-point estimate (if applicable). Values of mode other than 0-9 are treated as mode 0. Sufficient space is allocated to the return value to hold the suppressed trailing zeros. */ int b2, b5, i, ieps, ilim, ilim0, ilim1, j, j1, k, k0, m2, m5, s2, s5; char dig; long L; long x; BigInteger b, b1, delta, mlo, mhi, S; int[] be = new int[1]; int[] bbits = new int[1]; double d2, ds, eps; boolean spec_case, denorm, k_check, try_quick, leftright; if ((word0(d) & Sign_bit) != 0) { /* set sign for everything, including 0's and NaNs */ sign[0] = true; // word0(d) &= ~Sign_bit; /* clear sign bit */ d = setWord0(d, word0(d) & ~Sign_bit); } else sign[0] = false; if ((word0(d) & Exp_mask) == Exp_mask) { /* Infinity or NaN */ buf.append(((word1(d) == 0) && ((word0(d) & Frac_mask) == 0)) ? "Infinity" : "NaN"); return 9999; } if (d == 0) { // no_digits: buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; } b = d2b(d, be, bbits); if ((i = (word0(d) >>> Exp_shift1 & (Exp_mask>>Exp_shift1))) != 0) { d2 = setWord0(d, (word0(d) & Frac_mask1) | Exp_11); /* log(x) ~=~ log(1.5) + (x-1.5)/1.5 * log10(x) = log(x) / log(10) * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10)) * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2) * * This suggests computing an approximation k to log10(d) by * * k = (i - Bias)*0.301029995663981 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 ); * * We want k to be too large rather than too small. * The error in the first-order Taylor series approximation * is in our favor, so we just round up the constant enough * to compensate for any error in the multiplication of * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077, * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14, * adding 1e-13 to the constant term more than suffices. * Hence we adjust the constant term to 0.1760912590558. * (We could get a more accurate k by invoking log10, * but this is probably not worthwhile.) */ i -= Bias; denorm = false; } else { /* d is denormalized */ i = bbits[0] + be[0] + (Bias + (P-1) - 1); x = (i > 32) ? ((long) word0(d)) << (64 - i) | word1(d) >>> (i - 32) : ((long) word1(d)) << (32 - i); // d2 = x; // word0(d2) -= 31*Exp_msk1; /* adjust exponent */ d2 = setWord0(x, word0(x) - 31*Exp_msk1); i -= (Bias + (P-1) - 1) + 1; denorm = true; } /* At this point d = f*2^i, where 1 <= f < 2. d2 is an approximation of f. */ ds = (d2-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981; k = (int)ds; if (ds < 0.0 && ds != k) k--; /* want k = floor(ds) */ k_check = true; if (k >= 0 && k <= Ten_pmax) { if (d < tens[k]) k--; k_check = false; } /* At this point floor(log10(d)) <= k <= floor(log10(d))+1. If k_check is zero, we're guaranteed that k = floor(log10(d)). */ j = bbits[0] - i - 1; /* At this point d = b/2^j, where b is an odd integer. */ if (j >= 0) { b2 = 0; s2 = j; } else { b2 = -j; s2 = 0; } if (k >= 0) { b5 = 0; s5 = k; s2 += k; } else { b2 -= k; b5 = -k; s5 = 0; } /* At this point d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5), where b is an odd integer, b2 >= 0, b5 >= 0, s2 >= 0, and s5 >= 0. */ if (mode < 0 || mode > 9) mode = 0; try_quick = true; if (mode > 5) { mode -= 4; try_quick = false; } leftright = true; ilim = ilim1 = 0; switch(mode) { case 0: case 1: ilim = ilim1 = -1; i = 18; ndigits = 0; break; case 2: leftright = false; /* no break */ case 4: if (ndigits <= 0) ndigits = 1; ilim = ilim1 = i = ndigits; break; case 3: leftright = false; /* no break */ case 5: i = ndigits + k + 1; ilim = i; ilim1 = i - 1; if (i <= 0) i = 1; } /* ilim is the maximum number of significant digits we want, based on k and ndigits. */ /* ilim1 is the maximum number of significant digits we want, based on k and ndigits, when it turns out that k was computed too high by one. */ boolean fast_failed = false; if (ilim >= 0 && ilim <= Quick_max && try_quick) { /* Try to get by with floating-point arithmetic. */ i = 0; d2 = d; k0 = k; ilim0 = ilim; ieps = 2; /* conservative */ /* Divide d by 10^k, keeping track of the roundoff error and avoiding overflows. */ if (k > 0) { ds = tens[k&0xf]; j = k >> 4; if ((j & Bletch) != 0) { /* prevent overflows */ j &= Bletch - 1; d /= bigtens[n_bigtens-1]; ieps++; } for(; (j != 0); j >>= 1, i++) if ((j & 1) != 0) { ieps++; ds *= bigtens[i]; } d /= ds; } else if ((j1 = -k) != 0) { d *= tens[j1 & 0xf]; for(j = j1 >> 4; (j != 0); j >>= 1, i++) if ((j & 1) != 0) { ieps++; d *= bigtens[i]; } } /* Check that k was computed correctly. */ if (k_check && d < 1.0 && ilim > 0) { if (ilim1 <= 0) fast_failed = true; else { ilim = ilim1; k--; d *= 10.; ieps++; } } /* eps bounds the cumulative error. */ // eps = ieps*d + 7.0; // word0(eps) -= (P-1)*Exp_msk1; eps = ieps*d + 7.0; eps = setWord0(eps, word0(eps) - (P-1)*Exp_msk1); if (ilim == 0) { S = mhi = null; d -= 5.0; if (d > eps) { buf.append('1'); k++; return k + 1; } if (d < -eps) { buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; } fast_failed = true; } if (!fast_failed) { fast_failed = true; if (leftright) { /* Use Steele & White method of only * generating digits needed. */ eps = 0.5/tens[ilim-1] - eps; for(i = 0;;) { L = (long)d; d -= L; buf.append((char)('0' + L)); if (d < eps) { return k + 1; } if (1.0 - d < eps) { // goto bump_up; char lastCh; while (true) { lastCh = buf.charAt(buf.length() - 1); buf.setLength(buf.length() - 1); if (lastCh != '9') break; if (buf.length() == 0) { k++; lastCh = '0'; break; } } buf.append((char)(lastCh + 1)); return k + 1; } if (++i >= ilim) break; eps *= 10.0; d *= 10.0; } } else { /* Generate ilim digits, then fix them up. */ eps *= tens[ilim-1]; for(i = 1;; i++, d *= 10.0) { L = (long)d; d -= L; buf.append((char)('0' + L)); if (i == ilim) { if (d > 0.5 + eps) { // goto bump_up; char lastCh; while (true) { lastCh = buf.charAt(buf.length() - 1); buf.setLength(buf.length() - 1); if (lastCh != '9') break; if (buf.length() == 0) { k++; lastCh = '0'; break; } } buf.append((char)(lastCh + 1)); return k + 1; } else if (d < 0.5 - eps) { stripTrailingZeroes(buf); // while(*--s == '0') ; // s++; return k + 1; } break; } } } } if (fast_failed) { buf.setLength(0); d = d2; k = k0; ilim = ilim0; } } /* Do we have a "small" integer? */ if (be[0] >= 0 && k <= Int_max) { /* Yes. */ ds = tens[k]; if (ndigits < 0 && ilim <= 0) { S = mhi = null; if (ilim < 0 || d < 5*ds || (!biasUp && d == 5*ds)) { buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; } buf.append('1'); k++; return k + 1; } for(i = 1;; i++) { L = (long) (d / ds); d -= L*ds; buf.append((char)('0' + L)); if (i == ilim) { d += d; if ((d > ds) || (d == ds && (((L & 1) != 0) || biasUp))) { // bump_up: // while(*--s == '9') // if (s == buf) { // k++; // *s = '0'; // break; // } // ++*s++; char lastCh; while (true) { lastCh = buf.charAt(buf.length() - 1); buf.setLength(buf.length() - 1); if (lastCh != '9') break; if (buf.length() == 0) { k++; lastCh = '0'; break; } } buf.append((char)(lastCh + 1)); } break; } d *= 10.0; if (d == 0) break; } return k + 1; } m2 = b2; m5 = b5; mhi = mlo = null; if (leftright) { if (mode < 2) { i = (denorm) ? be[0] + (Bias + (P-1) - 1 + 1) : 1 + P - bbits[0]; /* i is 1 plus the number of trailing zero bits in d's significand. Thus, (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 lsb of d)/10^k. */ } else { j = ilim - 1; if (m5 >= j) m5 -= j; else { s5 += j -= m5; b5 += j; m5 = 0; } if ((i = ilim) < 0) { m2 -= i; i = 0; } /* (2^m2 * 5^m5) / (2^(s2+i) * 5^s5) = (1/2 * 10^(1-ilim))/10^k. */ } b2 += i; s2 += i; mhi = BigInteger.valueOf(1); /* (mhi * 2^m2 * 5^m5) / (2^s2 * 5^s5) = one-half of last printed (when mode >= 2) or input (when mode < 2) significant digit, divided by 10^k. */ } /* We still have d/10^k = (b * 2^b2 * 5^b5) / (2^s2 * 5^s5). Reduce common factors in b2, m2, and s2 without changing the equalities. */ if (m2 > 0 && s2 > 0) { i = (m2 < s2) ? m2 : s2; b2 -= i; m2 -= i; s2 -= i; } /* Fold b5 into b and m5 into mhi. */ if (b5 > 0) { if (leftright) { if (m5 > 0) { mhi = pow5mult(mhi, m5); b1 = mhi.multiply(b); b = b1; } if ((j = b5 - m5) != 0) b = pow5mult(b, j); } else b = pow5mult(b, b5); } /* Now we have d/10^k = (b * 2^b2) / (2^s2 * 5^s5) and (mhi * 2^m2) / (2^s2 * 5^s5) = one-half of last printed or input significant digit, divided by 10^k. */ S = BigInteger.valueOf(1); if (s5 > 0) S = pow5mult(S, s5); /* Now we have d/10^k = (b * 2^b2) / (S * 2^s2) and (mhi * 2^m2) / (S * 2^s2) = one-half of last printed or input significant digit, divided by 10^k. */ /* Check for special case that d is a normalized power of 2. */ spec_case = false; if (mode < 2) { if ( (word1(d) == 0) && ((word0(d) & Bndry_mask) == 0) && ((word0(d) & (Exp_mask & Exp_mask << 1)) != 0) ) { /* The special case. Here we want to be within a quarter of the last input significant digit instead of one half of it when the decimal output string's value is less than d. */ b2 += Log2P; s2 += Log2P; spec_case = true; } } /* Arrange for convenient computation of quotients: * shift left if necessary so divisor has 4 leading 0 bits. * * Perhaps we should just compute leading 28 bits of S once * and for all and pass them and a shift to quorem, so it * can do shifts and ors to compute the numerator for q. */ byte [] S_bytes = S.toByteArray(); int S_hiWord = 0; for (int idx = 0; idx < 4; idx++) { S_hiWord = (S_hiWord << 8); if (idx < S_bytes.length) S_hiWord |= (S_bytes[idx] & 0xFF); } if ((i = (((s5 != 0) ? 32 - hi0bits(S_hiWord) : 1) + s2) & 0x1f) != 0) i = 32 - i; /* i is the number of leading zero bits in the most significant word of S*2^s2. */ if (i > 4) { i -= 4; b2 += i; m2 += i; s2 += i; } else if (i < 4) { i += 28; b2 += i; m2 += i; s2 += i; } /* Now S*2^s2 has exactly four leading zero bits in its most significant word. */ if (b2 > 0) b = b.shiftLeft(b2); if (s2 > 0) S = S.shiftLeft(s2); /* Now we have d/10^k = b/S and (mhi * 2^m2) / S = maximum acceptable error, divided by 10^k. */ if (k_check) { if (b.compareTo(S) < 0) { k--; b = b.multiply(BigInteger.valueOf(10)); /* we botched the k estimate */ if (leftright) mhi = mhi.multiply(BigInteger.valueOf(10)); ilim = ilim1; } } /* At this point 1 <= d/10^k = b/S < 10. */ if (ilim <= 0 && mode > 2) { /* We're doing fixed-mode output and d is less than the minimum nonzero output in this mode. Output either zero or the minimum nonzero output depending on which is closer to d. */ if ((ilim < 0 ) || ((i = b.compareTo(S = S.multiply(BigInteger.valueOf(5)))) < 0) || ((i == 0 && !biasUp))) { /* Always emit at least one digit. If the number appears to be zero using the current mode, then emit one '0' digit and set decpt to 1. */ /*no_digits: k = -1 - ndigits; goto ret; */ buf.setLength(0); buf.append('0'); /* copy "0" to buffer */ return 1; // goto no_digits; } // one_digit: buf.append('1'); k++; return k + 1; } if (leftright) { if (m2 > 0) mhi = mhi.shiftLeft(m2); /* Compute mlo -- check for special case * that d is a normalized power of 2. */ mlo = mhi; if (spec_case) { mhi = mlo; mhi = mhi.shiftLeft(Log2P); } /* mlo/S = maximum acceptable error, divided by 10^k, if the output is less than d. */ /* mhi/S = maximum acceptable error, divided by 10^k, if the output is greater than d. */ for(i = 1;;i++) { BigInteger[] divResult = b.divideAndRemainder(S); b = divResult[1]; dig = (char)(divResult[0].intValue() + '0'); /* Do we yet have the shortest decimal string * that will round to d? */ j = b.compareTo(mlo); /* j is b/S compared with mlo/S. */ delta = S.subtract(mhi); j1 = (delta.signum() <= 0) ? 1 : b.compareTo(delta); /* j1 is b/S compared with 1 - mhi/S. */ if ((j1 == 0) && (mode == 0) && ((word1(d) & 1) == 0)) { if (dig == '9') { buf.append('9'); if (roundOff(buf)) { k++; buf.append('1'); } return k + 1; // goto round_9_up; } if (j > 0) dig++; buf.append(dig); return k + 1; } if ((j < 0) || ((j == 0) && (mode == 0) && ((word1(d) & 1) == 0) )) { if (j1 > 0) { /* Either dig or dig+1 would work here as the least significant decimal digit. Use whichever would produce a decimal value closer to d. */ b = b.shiftLeft(1); j1 = b.compareTo(S); if (((j1 > 0) || (j1 == 0 && (((dig & 1) == 1) || biasUp))) && (dig++ == '9')) { buf.append('9'); if (roundOff(buf)) { k++; buf.append('1'); } return k + 1; // goto round_9_up; } } buf.append(dig); return k + 1; } if (j1 > 0) { if (dig == '9') { /* possible if i == 1 */ // round_9_up: // *s++ = '9'; // goto roundoff; buf.append('9'); if (roundOff(buf)) { k++; buf.append('1'); } return k + 1; } buf.append((char)(dig + 1)); return k + 1; } buf.append(dig); if (i == ilim) break; b = b.multiply(BigInteger.valueOf(10)); if (mlo == mhi) mlo = mhi = mhi.multiply(BigInteger.valueOf(10)); else { mlo = mlo.multiply(BigInteger.valueOf(10)); mhi = mhi.multiply(BigInteger.valueOf(10)); } } } else for(i = 1;; i++) { // (char)(dig = quorem(b,S) + '0'); BigInteger[] divResult = b.divideAndRemainder(S); b = divResult[1]; dig = (char)(divResult[0].intValue() + '0'); buf.append(dig); if (i >= ilim) break; b = b.multiply(BigInteger.valueOf(10)); } /* Round off last digit */ b = b.shiftLeft(1); j = b.compareTo(S); if ((j > 0) || (j == 0 && (((dig & 1) == 1) || biasUp))) { // roundoff: // while(*--s == '9') // if (s == buf) { // k++; // *s++ = '1'; // goto ret; // } // ++*s++; if (roundOff(buf)) { k++; buf.append('1'); return k + 1; } } else { stripTrailingZeroes(buf); // while(*--s == '0') ; // s++; } // ret: // Bfree(S); // if (mhi) { // if (mlo && mlo != mhi) // Bfree(mlo); // Bfree(mhi); // } // ret1: // Bfree(b); // JS_ASSERT(s < buf + bufsize); return k + 1; }
diff --git a/demos/pax-britannica/pax-britannica/src/de/swagner/paxbritannica/Ship.java b/demos/pax-britannica/pax-britannica/src/de/swagner/paxbritannica/Ship.java index 6afec21eb..d7ce097dd 100644 --- a/demos/pax-britannica/pax-britannica/src/de/swagner/paxbritannica/Ship.java +++ b/demos/pax-britannica/pax-britannica/src/de/swagner/paxbritannica/Ship.java @@ -1,182 +1,182 @@ package de.swagner.paxbritannica; import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import de.swagner.paxbritannica.factory.FactoryProduction; public class Ship extends Sprite { protected float amount = 1.0f; protected float turnSpeed = 1.0f; protected float accel = 0.0f; protected float hitPoints = 0; protected float maxHitPoints = 0; private float delta = 0.0f; public float aliveTime = 0.0f; public Vector2 position = new Vector2(); public Vector2 velocity = new Vector2(); public Vector2 facing = new Vector2(); public Vector2 collisionCenter = new Vector2(); public Array<Vector2> collisionPoints = new Array<Vector2>(); public boolean alive = true; private float deathCounter = 50f; private float nextExplosion = 10f; private float opacity = 5.0f; public int id = 0; public Ship(int id, Vector2 position, Vector2 facing) { super(); this.id = id; this.position.set(position); this.facing.set(facing); collisionPoints.clear(); collisionPoints.add(new Vector2()); collisionPoints.add(new Vector2()); collisionPoints.add(new Vector2()); collisionPoints.add(new Vector2()); this.setOrigin(this.getWidth() / 2.f, this.getHeight() / 2.f); } @Override public void draw(Batch batch) { delta = Math.min(0.06f, Gdx.graphics.getDeltaTime()); aliveTime += delta; collisionPoints.get(0).set( this.getVertices()[0], this.getVertices()[1]); collisionPoints.get(1).set( this.getVertices()[5], this.getVertices()[6]); collisionPoints.get(2).set( this.getVertices()[10], this.getVertices()[11]); collisionPoints.get(3).set( this.getVertices()[15], this.getVertices()[16]); - collisionCenter.set(collisionPoints.get(2)).scl(0.5f).add(collisionPoints.get(0)); + collisionCenter.set(collisionPoints.get(0)).add(collisionPoints.get(2)).scl(0.5f); velocity.scl( (float) Math.pow(0.97f, delta * 30.f)); position.add(velocity.x * delta, velocity.y * delta); this.setRotation(facing.angle()); this.setPosition(position.x, position.y); if (!(this instanceof Bullet) && hitPoints <= 0) destruct(); if (MathUtils.random() < velocity.len() / 900.f) { GameInstance.getInstance().bubbleParticles.addParticle(randomPointOnShip()); } super.draw(batch); } public void turn(float direction) { delta = Math.min(0.06f, Gdx.graphics.getDeltaTime()); facing.rotate(direction * turnSpeed * delta).nor(); } public void thrust() { delta = Math.min(0.06f, Gdx.graphics.getDeltaTime()); velocity.add(facing.x * accel * delta, facing.y * accel * delta); } public void thrust(float amount) { delta = Math.min(0.06f, Gdx.graphics.getDeltaTime()); velocity.add(facing.x * accel * delta, facing.y * accel * amount * delta); } public Vector2 randomPointOnShip() { return new Vector2(collisionCenter.x + MathUtils.random(-this.getWidth() / 2, this.getWidth() / 2), collisionCenter.y + MathUtils.random(-this.getHeight() / 2, this.getHeight() / 2)); } /* * Scratch space for computing a target's direction. This is safe (as a static) because * its only used in goTowardsOrAway which is only called on the render thread (via update). */ private static final Vector2 target_direction = new Vector2(); public void goTowardsOrAway(Vector2 targetPos, boolean forceThrust, boolean isAway) { target_direction.set(targetPos).sub(collisionCenter); if (isAway) { target_direction.scl(-1); } if (facing.crs(target_direction) > 0) { turn(1); } else { turn(-1); } if (forceThrust || facing.dot(target_direction) > 0) { thrust(); } } public float healthPercentage() { return Math.max(hitPoints / maxHitPoints, 0); } public void damage(float amount) { hitPoints = Math.max(hitPoints - amount, 0); } public void destruct() { if (this instanceof FactoryProduction) { factoryDestruct(); } else { GameInstance.getInstance().explode(this); alive = false; for (Ship factory : GameInstance.getInstance().factorys) { if(factory instanceof FactoryProduction && factory.id == this.id) ((FactoryProduction) factory).ownShips--; } } } public void factoryDestruct() { delta = Math.min(0.06f, Gdx.graphics.getDeltaTime()); if (deathCounter > 0) { ((FactoryProduction) this).production.halt_production = true; this.setColor(1, 1, 1, Math.min(1, opacity)); opacity -= 1 * delta; if (Math.floor(deathCounter) % nextExplosion == 0) { GameInstance.getInstance().explode(this, randomPointOnShip()); nextExplosion = MathUtils.random(2, 6); } deathCounter -= 10 * delta; } else { for (int i = 1; i <= 10; ++i) { GameInstance.getInstance().explode(this, randomPointOnShip()); } alive = false; } } // automatically thrusts and turns according to the target public void goTowards(Vector2 targetPos, boolean forceThrust) { goTowardsOrAway(targetPos, forceThrust, false); } public void goAway(Vector2 targetPos, boolean forceThrust) { goTowardsOrAway(targetPos, forceThrust, true); } }
true
true
public void draw(Batch batch) { delta = Math.min(0.06f, Gdx.graphics.getDeltaTime()); aliveTime += delta; collisionPoints.get(0).set( this.getVertices()[0], this.getVertices()[1]); collisionPoints.get(1).set( this.getVertices()[5], this.getVertices()[6]); collisionPoints.get(2).set( this.getVertices()[10], this.getVertices()[11]); collisionPoints.get(3).set( this.getVertices()[15], this.getVertices()[16]); collisionCenter.set(collisionPoints.get(2)).scl(0.5f).add(collisionPoints.get(0)); velocity.scl( (float) Math.pow(0.97f, delta * 30.f)); position.add(velocity.x * delta, velocity.y * delta); this.setRotation(facing.angle()); this.setPosition(position.x, position.y); if (!(this instanceof Bullet) && hitPoints <= 0) destruct(); if (MathUtils.random() < velocity.len() / 900.f) { GameInstance.getInstance().bubbleParticles.addParticle(randomPointOnShip()); } super.draw(batch); }
public void draw(Batch batch) { delta = Math.min(0.06f, Gdx.graphics.getDeltaTime()); aliveTime += delta; collisionPoints.get(0).set( this.getVertices()[0], this.getVertices()[1]); collisionPoints.get(1).set( this.getVertices()[5], this.getVertices()[6]); collisionPoints.get(2).set( this.getVertices()[10], this.getVertices()[11]); collisionPoints.get(3).set( this.getVertices()[15], this.getVertices()[16]); collisionCenter.set(collisionPoints.get(0)).add(collisionPoints.get(2)).scl(0.5f); velocity.scl( (float) Math.pow(0.97f, delta * 30.f)); position.add(velocity.x * delta, velocity.y * delta); this.setRotation(facing.angle()); this.setPosition(position.x, position.y); if (!(this instanceof Bullet) && hitPoints <= 0) destruct(); if (MathUtils.random() < velocity.len() / 900.f) { GameInstance.getInstance().bubbleParticles.addParticle(randomPointOnShip()); } super.draw(batch); }
diff --git a/gwt-client/src/main/java/org/mule/galaxy/web/client/SessionKilledDialog.java b/gwt-client/src/main/java/org/mule/galaxy/web/client/SessionKilledDialog.java index 88eb0bab..17812d7f 100644 --- a/gwt-client/src/main/java/org/mule/galaxy/web/client/SessionKilledDialog.java +++ b/gwt-client/src/main/java/org/mule/galaxy/web/client/SessionKilledDialog.java @@ -1,139 +1,139 @@ /* * $Id$ * -------------------------------------------------------------------------------------- * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.mule.galaxy.web.client; import org.mule.galaxy.web.client.util.InlineFlowPanel; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; public class SessionKilledDialog extends DialogBox { protected Galaxy galaxy; // used for UI updates only private Timer reconnectTimerUI; protected Label timerLabel; protected HTML trailingText; protected Button loginNowBtn; private HeartbeatTimer heartbeatTimer; public SessionKilledDialog(final Galaxy galaxy, final HeartbeatTimer timer) { heartbeatTimer = timer; setText("Connection Terminated by Server"); setStyleName("sessionKilledDialogBox"); loginNowBtn = new Button("Login Now"); //loginNowBtn.setTitle("Ignore and try to login now (will not work if the server is down)"); loginNowBtn.setEnabled(heartbeatTimer.isServerUp()); loginNowBtn.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { close(); // just pointing to root doesn't always work, use the logout trick Window.open(GWT.getHostPageBaseURL() + "j_logout", "_self", null); } }); final Button closeBtn = new Button("Close"); closeBtn.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { close(); } }); DockPanel main = new DockPanel(); InlineFlowPanel buttonRow = new InlineFlowPanel(); buttonRow.addStyleName("buttonRow"); buttonRow.add(loginNowBtn); buttonRow.add(closeBtn); main.add(buttonRow, DockPanel.SOUTH); final InlineFlowPanel mainMessage = new InlineFlowPanel(); mainMessage.addStyleName("padding"); - final HTML text = new HTML("This client connection has been terminated by the server. This could happen due to either:" + + final HTML text = new HTML("This sdf client connection has been terminated by the server. This could happen due to either:" + "<ul><li>Server having crashed</li><li>Client session forcefully killed on the server</li></ul>" + "This error is <strong>unrecoverable</strong> and you'll need to re-login. Next " + "connection attempt will be made in "); text.addStyleName("dialog-connectionLost"); timerLabel = new Label("" + heartbeatTimer.getIntervalSeconds()); trailingText = new HTML("&nbsp;seconds."); mainMessage.add(text); mainMessage.add(timerLabel); mainMessage.add(trailingText); main.add(mainMessage, DockPanel.CENTER); setWidget(main); reconnectTimerUI = new Timer() { public void run() { final int update = Integer.parseInt(timerLabel.getText()) - 1; // some language formatting switch (update) { case 1: trailingText.setHTML("&nbsp;second."); timerLabel.setText("" + update); break; case 0: trailingText.setHTML("&nbsp;seconds."); timerLabel.setText("" + update); break; case -1: // time to ping // start heartbeat timer again heartbeatTimer.scheduleRepeating(heartbeatTimer.getIntervalSeconds() * 1000); timerLabel.setText("" + heartbeatTimer.getIntervalSeconds()); break; default: timerLabel.setText("" + update); break; } } }; reconnectTimerUI.scheduleRepeating(1000); // every second } /** * Close, cleanup and send all signals. */ protected void close() { reconnectTimerUI.cancel(); heartbeatTimer.onDialogDismissed(); hide(); } public void onServerUp() { loginNowBtn.setEnabled(true); } public void onServerDown() { loginNowBtn.setEnabled(false); } }
true
true
public SessionKilledDialog(final Galaxy galaxy, final HeartbeatTimer timer) { heartbeatTimer = timer; setText("Connection Terminated by Server"); setStyleName("sessionKilledDialogBox"); loginNowBtn = new Button("Login Now"); //loginNowBtn.setTitle("Ignore and try to login now (will not work if the server is down)"); loginNowBtn.setEnabled(heartbeatTimer.isServerUp()); loginNowBtn.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { close(); // just pointing to root doesn't always work, use the logout trick Window.open(GWT.getHostPageBaseURL() + "j_logout", "_self", null); } }); final Button closeBtn = new Button("Close"); closeBtn.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { close(); } }); DockPanel main = new DockPanel(); InlineFlowPanel buttonRow = new InlineFlowPanel(); buttonRow.addStyleName("buttonRow"); buttonRow.add(loginNowBtn); buttonRow.add(closeBtn); main.add(buttonRow, DockPanel.SOUTH); final InlineFlowPanel mainMessage = new InlineFlowPanel(); mainMessage.addStyleName("padding"); final HTML text = new HTML("This client connection has been terminated by the server. This could happen due to either:" + "<ul><li>Server having crashed</li><li>Client session forcefully killed on the server</li></ul>" + "This error is <strong>unrecoverable</strong> and you'll need to re-login. Next " + "connection attempt will be made in "); text.addStyleName("dialog-connectionLost"); timerLabel = new Label("" + heartbeatTimer.getIntervalSeconds()); trailingText = new HTML("&nbsp;seconds."); mainMessage.add(text); mainMessage.add(timerLabel); mainMessage.add(trailingText); main.add(mainMessage, DockPanel.CENTER); setWidget(main); reconnectTimerUI = new Timer() { public void run() { final int update = Integer.parseInt(timerLabel.getText()) - 1; // some language formatting switch (update) { case 1: trailingText.setHTML("&nbsp;second."); timerLabel.setText("" + update); break; case 0: trailingText.setHTML("&nbsp;seconds."); timerLabel.setText("" + update); break; case -1: // time to ping // start heartbeat timer again heartbeatTimer.scheduleRepeating(heartbeatTimer.getIntervalSeconds() * 1000); timerLabel.setText("" + heartbeatTimer.getIntervalSeconds()); break; default: timerLabel.setText("" + update); break; } } }; reconnectTimerUI.scheduleRepeating(1000); // every second }
public SessionKilledDialog(final Galaxy galaxy, final HeartbeatTimer timer) { heartbeatTimer = timer; setText("Connection Terminated by Server"); setStyleName("sessionKilledDialogBox"); loginNowBtn = new Button("Login Now"); //loginNowBtn.setTitle("Ignore and try to login now (will not work if the server is down)"); loginNowBtn.setEnabled(heartbeatTimer.isServerUp()); loginNowBtn.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { close(); // just pointing to root doesn't always work, use the logout trick Window.open(GWT.getHostPageBaseURL() + "j_logout", "_self", null); } }); final Button closeBtn = new Button("Close"); closeBtn.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { close(); } }); DockPanel main = new DockPanel(); InlineFlowPanel buttonRow = new InlineFlowPanel(); buttonRow.addStyleName("buttonRow"); buttonRow.add(loginNowBtn); buttonRow.add(closeBtn); main.add(buttonRow, DockPanel.SOUTH); final InlineFlowPanel mainMessage = new InlineFlowPanel(); mainMessage.addStyleName("padding"); final HTML text = new HTML("This sdf client connection has been terminated by the server. This could happen due to either:" + "<ul><li>Server having crashed</li><li>Client session forcefully killed on the server</li></ul>" + "This error is <strong>unrecoverable</strong> and you'll need to re-login. Next " + "connection attempt will be made in "); text.addStyleName("dialog-connectionLost"); timerLabel = new Label("" + heartbeatTimer.getIntervalSeconds()); trailingText = new HTML("&nbsp;seconds."); mainMessage.add(text); mainMessage.add(timerLabel); mainMessage.add(trailingText); main.add(mainMessage, DockPanel.CENTER); setWidget(main); reconnectTimerUI = new Timer() { public void run() { final int update = Integer.parseInt(timerLabel.getText()) - 1; // some language formatting switch (update) { case 1: trailingText.setHTML("&nbsp;second."); timerLabel.setText("" + update); break; case 0: trailingText.setHTML("&nbsp;seconds."); timerLabel.setText("" + update); break; case -1: // time to ping // start heartbeat timer again heartbeatTimer.scheduleRepeating(heartbeatTimer.getIntervalSeconds() * 1000); timerLabel.setText("" + heartbeatTimer.getIntervalSeconds()); break; default: timerLabel.setText("" + update); break; } } }; reconnectTimerUI.scheduleRepeating(1000); // every second }
diff --git a/src/org/proofpad/Acl2Parser.java b/src/org/proofpad/Acl2Parser.java index 5c0b384..1dc032c 100644 --- a/src/org/proofpad/Acl2Parser.java +++ b/src/org/proofpad/Acl2Parser.java @@ -1,684 +1,686 @@ package org.proofpad; import java.awt.Color; import java.io.File; import java.io.FileNotFoundException; import java.io.Serializable; import java.util.*; import java.util.logging.Logger; import javax.swing.text.BadLocationException; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.parser.*; public class Acl2Parser extends AbstractParser { private static Logger logger = Logger.getLogger(Acl2Parser.class.toString()); public static class CacheKey implements Serializable { private static final long serialVersionUID = -4201796432147755450L; private File book; private long mtime; public CacheKey(File book, long mtime) { this.book = book; this.mtime = mtime; } @Override public int hashCode() { return book.hashCode() ^ Long.valueOf(mtime).hashCode(); } @Override public boolean equals(Object other) { return (other instanceof CacheKey && ((CacheKey) other).book.equals(this.book) && ((CacheKey) other).mtime == this.mtime); } } private static class Range implements Serializable { private static final long serialVersionUID = 3510110011135344206L; public final int lower; public final int upper; private Range(int both) { upper = lower = both; } private Range(int lower, int upper) { this.lower = lower; this.upper = upper; } } static class CacheSets implements Serializable { private static final long serialVersionUID = -2233827686979689741L; public Set<String> functions; public Set<String> macros; public Set<String> constants; } public Set<String> functions; public Set<String> macros; public Set<String> constants; public File workingDir; private Map<CacheKey, CacheSets> cache = Main.cache.getBookCache(); private File acl2Dir; public Acl2Parser(File workingDir, File acl2Dir) { this(null, workingDir, acl2Dir); } public Acl2Parser(CodePane codePane, File workingDir, File acl2Dir) { this.workingDir = workingDir; this.acl2Dir = acl2Dir; } private static Map<String, Range> paramCounts = new HashMap<String, Range>(); static { paramCounts.put("-", new Range(1, 2)); paramCounts.put("/", new Range(1, 2)); paramCounts.put("/=", new Range(2, 2)); paramCounts.put("1+", new Range(1, 1)); paramCounts.put("1-", new Range(1, 1)); paramCounts.put("<=", new Range(2, 2)); paramCounts.put(">", new Range(2, 2)); paramCounts.put(">=", new Range(2, 2)); paramCounts.put("abs", new Range(1, 1)); paramCounts.put("acl2-numberp", new Range(1, 1)); paramCounts.put("acons", new Range(3, 3)); paramCounts.put("add-to-set-eq", new Range(2, 2)); paramCounts.put("add-to-set-eql", new Range(2, 2)); paramCounts.put("add-to-set-equal", new Range(2, 2)); paramCounts.put("alistp", new Range(1, 1)); paramCounts.put("alpha-char-p", new Range(1, 1)); paramCounts.put("alphorder", new Range(2, 2)); paramCounts.put("ash", new Range(2, 2)); paramCounts.put("assert$", new Range(2, 2)); paramCounts.put("assoc-eq", new Range(2, 2)); paramCounts.put("assoc-equal", new Range(2, 2)); paramCounts.put("assoc-keyword", new Range(2, 2)); paramCounts.put("atom", new Range(1, 1)); paramCounts.put("atom-listp", new Range(1, 1)); paramCounts.put("binary-*", new Range(2, 2)); paramCounts.put("binary-+", new Range(2, 2)); paramCounts.put("binary-append", new Range(2, 2)); paramCounts.put("boole$", new Range(3, 3)); paramCounts.put("booleanp", new Range(1, 1)); paramCounts.put("butlast", new Range(2, 2)); paramCounts.put("caaaar", new Range(1, 1)); paramCounts.put("caaadr", new Range(1, 1)); paramCounts.put("caaar", new Range(1, 1)); paramCounts.put("caadar", new Range(1, 1)); paramCounts.put("caaddr", new Range(1, 1)); paramCounts.put("caadr", new Range(1, 1)); paramCounts.put("caar", new Range(1, 1)); paramCounts.put("cadaar", new Range(1, 1)); paramCounts.put("cadadr", new Range(1, 1)); paramCounts.put("cadar", new Range(1, 1)); paramCounts.put("caddar", new Range(1, 1)); paramCounts.put("cadddr", new Range(1, 1)); paramCounts.put("caddr", new Range(1, 1)); paramCounts.put("cadr", new Range(1, 1)); paramCounts.put("car", new Range(1, 1)); paramCounts.put("cdaaar", new Range(1, 1)); paramCounts.put("cdaadr", new Range(1, 1)); paramCounts.put("cdaar", new Range(1, 1)); paramCounts.put("cdadar", new Range(1, 1)); paramCounts.put("cdaddr", new Range(1, 1)); paramCounts.put("cdadr", new Range(1, 1)); paramCounts.put("cdar", new Range(1, 1)); paramCounts.put("cddaar", new Range(1, 1)); paramCounts.put("cddadr", new Range(1, 1)); paramCounts.put("cddar", new Range(1, 1)); paramCounts.put("cdddar", new Range(1, 1)); paramCounts.put("cddddr", new Range(1, 1)); paramCounts.put("cdddr", new Range(1, 1)); paramCounts.put("cddr", new Range(1, 1)); paramCounts.put("cdr", new Range(1, 1)); paramCounts.put("ceiling", new Range(2, 2)); paramCounts.put("char", new Range(2, 2)); paramCounts.put("char-code", new Range(1, 1)); paramCounts.put("char-downcase", new Range(1, 1)); paramCounts.put("char-equal", new Range(2, 2)); paramCounts.put("char-upcase", new Range(1, 1)); paramCounts.put("char<", new Range(2, 2)); paramCounts.put("char<=", new Range(2, 2)); paramCounts.put("char>", new Range(2, 2)); paramCounts.put("char>=", new Range(2, 2)); paramCounts.put("character-alistp", new Range(1, 1)); paramCounts.put("character-listp", new Range(1, 1)); paramCounts.put("characterp", new Range(1, 1)); paramCounts.put("code-char", new Range(1, 1)); paramCounts.put("coerce", new Range(2, 2)); paramCounts.put("comp", new Range(1, 1)); paramCounts.put("comp-gcl", new Range(1, 1)); paramCounts.put("complex", new Range(2, 2)); paramCounts.put("complex-rationalp", new Range(1, 1)); paramCounts.put("complex/complex-rationalp", new Range(1, 1)); paramCounts.put("conjugate", new Range(1, 1)); paramCounts.put("cons", new Range(2, 2)); paramCounts.put("consp", new Range(1, 1)); paramCounts.put("cpu-core-count", new Range(1, 1)); paramCounts.put("delete-assoc-eq", new Range(2, 2)); paramCounts.put("denominator", new Range(1, 1)); paramCounts.put("digit-char-p", new Range(1, 2)); paramCounts.put("digit-to-char", new Range(1, 1)); paramCounts.put("ec-call", new Range(1, 1)); paramCounts.put("eighth", new Range(1, 1)); paramCounts.put("endp", new Range(1, 1)); paramCounts.put("eq", new Range(2, 2)); paramCounts.put("eql", new Range(2, 2)); paramCounts.put("eqlable-alistp", new Range(1, 1)); paramCounts.put("eqlable-listp", new Range(1, 1)); paramCounts.put("eqlablep", new Range(1, 1)); paramCounts.put("equal", new Range(2, 2)); paramCounts.put("error1", new Range(4, 4)); paramCounts.put("evenp", new Range(1, 1)); paramCounts.put("explode-nonnegative-integer", new Range(3, 5)); paramCounts.put("expt", new Range(2, 2)); paramCounts.put("fifth", new Range(1, 1)); paramCounts.put("first", new Range(1, 1)); paramCounts.put("fix", new Range(1, 1)); paramCounts.put("fix-true-list", new Range(1, 1)); paramCounts.put("floor", new Range(2, 2)); paramCounts.put("fms", new Range(5, 5)); paramCounts.put("fms!", new Range(5, 5)); paramCounts.put("fmt", new Range(5, 5)); paramCounts.put("fmt!", new Range(5, 5)); paramCounts.put("fmt1", new Range(6, 6)); paramCounts.put("fmt1!", new Range(6, 6)); paramCounts.put("fourth", new Range(1, 1)); paramCounts.put("get-output-stream-string$", new Range(2, 4)); paramCounts.put("getenv$", new Range(2, 2)); paramCounts.put("getprop", new Range(5, 5)); paramCounts.put("good-atom-listp", new Range(1, 1)); paramCounts.put("hard-error", new Range(3, 3)); paramCounts.put("identity", new Range(1, 1)); paramCounts.put("if", new Range(3, 3)); paramCounts.put("iff", new Range(2, 2)); paramCounts.put("ifix", new Range(1, 1)); paramCounts.put("illegal", new Range(3, 3)); paramCounts.put("imagpart", new Range(1, 1)); paramCounts.put("implies", new Range(2, 2)); paramCounts.put("improper-consp", new Range(1, 1)); paramCounts.put("int=", new Range(2, 2)); paramCounts.put("integer-length", new Range(1, 1)); paramCounts.put("integer-listp", new Range(1, 1)); paramCounts.put("integerp", new Range(1, 1)); paramCounts.put("intern", new Range(2, 2)); paramCounts.put("intern$", new Range(2, 2)); paramCounts.put("intern-in-package-of-symbol", new Range(2, 5)); paramCounts.put("intersectp-eq", new Range(2, 2)); paramCounts.put("intersectp-equal", new Range(2, 2)); paramCounts.put("keywordp", new Range(1, 1)); paramCounts.put("kwote", new Range(1, 1)); paramCounts.put("kwote-lst", new Range(1, 1)); paramCounts.put("last", new Range(1, 1)); paramCounts.put("len", new Range(1, 1)); paramCounts.put("length", new Range(1, 1)); paramCounts.put("lexorder", new Range(2, 2)); paramCounts.put("listp", new Range(1, 1)); paramCounts.put("logandc1", new Range(2, 2)); paramCounts.put("logandc2", new Range(2, 2)); paramCounts.put("logbitp", new Range(2, 2)); paramCounts.put("logcount", new Range(1, 1)); paramCounts.put("lognand", new Range(2, 2)); paramCounts.put("lognor", new Range(2, 2)); paramCounts.put("lognot", new Range(1, 1)); paramCounts.put("logorc1", new Range(2, 2)); paramCounts.put("logorc2", new Range(2, 2)); paramCounts.put("logtest", new Range(2, 2)); paramCounts.put("lower-case-p", new Range(1, 1)); paramCounts.put("make-ord", new Range(3, 3)); paramCounts.put("max", new Range(2, 2)); paramCounts.put("mbe1", new Range(2, 2)); paramCounts.put("mbt", new Range(1, 1)); paramCounts.put("member-eq", new Range(2, 2)); paramCounts.put("member-equal", new Range(2, 2)); paramCounts.put("min", new Range(2, 2)); paramCounts.put("minusp", new Range(1, 1)); paramCounts.put("mod", new Range(2, 2)); paramCounts.put("mod-expt", new Range(3, 3)); paramCounts.put("must-be-equal", new Range(2, 2)); paramCounts.put("mv-list", new Range(2, 2)); paramCounts.put("mv-nth", new Range(2, 2)); paramCounts.put("natp", new Range(1, 1)); paramCounts.put("nfix", new Range(1, 1)); paramCounts.put("ninth", new Range(1, 1)); paramCounts.put("no-duplicatesp-eq", new Range(1, 1)); paramCounts.put("nonnegative-integer-quotient", new Range(2, 4)); paramCounts.put("not", new Range(1, 1)); paramCounts.put("nth", new Range(2, 2)); paramCounts.put("nthcdr", new Range(2, 2)); paramCounts.put("null", new Range(1, 1)); paramCounts.put("numerator", new Range(1, 1)); paramCounts.put("o-finp", new Range(1, 1)); paramCounts.put("o-first-coeff", new Range(1, 1)); paramCounts.put("o-first-expt", new Range(1, 1)); paramCounts.put("o-infp", new Range(1, 1)); paramCounts.put("o-p", new Range(1, 1)); paramCounts.put("o-rst", new Range(1, 1)); paramCounts.put("o<", new Range(2, 2)); paramCounts.put("o<=", new Range(2, 2)); paramCounts.put("o>", new Range(2, 2)); paramCounts.put("o>=", new Range(2, 2)); paramCounts.put("oddp", new Range(1, 1)); paramCounts.put("pairlis$", new Range(2, 2)); paramCounts.put("peek-char$", new Range(2, 2)); paramCounts.put("pkg-imports", new Range(1, 1)); paramCounts.put("pkg-witness", new Range(1, 1)); paramCounts.put("plusp", new Range(1, 1)); paramCounts.put("position-eq", new Range(2, 2)); paramCounts.put("position-equal", new Range(2, 2)); paramCounts.put("posp", new Range(1, 1)); paramCounts.put("print-object$", new Range(3, 3)); paramCounts.put("prog2$", new Range(2, 2)); paramCounts.put("proofs-co", new Range(1, 1)); paramCounts.put("proper-consp", new Range(1, 1)); paramCounts.put("put-assoc-eq", new Range(3, 3)); paramCounts.put("put-assoc-eql", new Range(3, 3)); paramCounts.put("put-assoc-equal", new Range(3, 3)); paramCounts.put("putprop", new Range(4, 4)); paramCounts.put("r-eqlable-alistp", new Range(1, 1)); paramCounts.put("r-symbol-alistp", new Range(1, 1)); paramCounts.put("random$", new Range(2, 2)); paramCounts.put("rassoc-eq", new Range(2, 2)); paramCounts.put("rassoc-equal", new Range(2, 2)); paramCounts.put("rational-listp", new Range(1, 1)); paramCounts.put("rationalp", new Range(1, 1)); paramCounts.put("read-byte$", new Range(2, 2)); paramCounts.put("read-char$", new Range(2, 2)); paramCounts.put("read-object", new Range(2, 2)); paramCounts.put("real/rationalp", new Range(1, 1)); paramCounts.put("realfix", new Range(1, 1)); paramCounts.put("realpart", new Range(1, 1)); paramCounts.put("rem", new Range(2, 2)); paramCounts.put("remove-duplicates-eq", new Range(1, 1)); paramCounts.put("remove-duplicates-equal", new Range(1, 6)); paramCounts.put("remove-eq", new Range(2, 2)); paramCounts.put("remove-equal", new Range(2, 2)); paramCounts.put("remove1-eq", new Range(2, 2)); paramCounts.put("remove1-equal", new Range(2, 2)); paramCounts.put("rest", new Range(1, 1)); paramCounts.put("return-last", new Range(3, 3)); paramCounts.put("revappend", new Range(2, 2)); paramCounts.put("reverse", new Range(1, 1)); paramCounts.put("rfix", new Range(1, 1)); paramCounts.put("round", new Range(2, 2)); paramCounts.put("second", new Range(1, 1)); paramCounts.put("set-difference-eq", new Range(2, 2)); paramCounts.put("setenv$", new Range(2, 2)); paramCounts.put("seventh", new Range(1, 1)); paramCounts.put("signum", new Range(1, 1)); paramCounts.put("sixth", new Range(1, 1)); paramCounts.put("standard-char-p", new Range(1, 1)); paramCounts.put("string", new Range(1, 1)); paramCounts.put("string-append", new Range(2, 2)); paramCounts.put("string-downcase", new Range(1, 1)); paramCounts.put("string-equal", new Range(2, 2)); paramCounts.put("string-listp", new Range(1, 1)); paramCounts.put("string-upcase", new Range(1, 1)); paramCounts.put("string<", new Range(2, 2)); paramCounts.put("string<=", new Range(2, 2)); paramCounts.put("string>", new Range(2, 2)); paramCounts.put("string>=", new Range(2, 2)); paramCounts.put("stringp", new Range(1, 1)); paramCounts.put("strip-cars", new Range(1, 1)); paramCounts.put("strip-cdrs", new Range(1, 1)); paramCounts.put("sublis", new Range(2, 2)); paramCounts.put("subseq", new Range(3, 3)); paramCounts.put("subsetp-eq", new Range(2, 2)); paramCounts.put("subsetp-equal", new Range(2, 2)); paramCounts.put("subst", new Range(3, 3)); paramCounts.put("substitute", new Range(3, 3)); paramCounts.put("symbol-<", new Range(2, 2)); paramCounts.put("symbol-alistp", new Range(1, 1)); paramCounts.put("symbol-listp", new Range(1, 1)); paramCounts.put("symbol-name", new Range(1, 1)); paramCounts.put("symbolp", new Range(1, 1)); paramCounts.put("sys-call-status", new Range(1, 1)); paramCounts.put("take", new Range(2, 2)); paramCounts.put("tenth", new Range(1, 1)); paramCounts.put("the", new Range(2, 2)); paramCounts.put("third", new Range(1, 1)); paramCounts.put("true-list-listp", new Range(1, 1)); paramCounts.put("true-listp", new Range(1, 1)); paramCounts.put("truncate", new Range(2, 2)); paramCounts.put("unary--", new Range(1, 1)); paramCounts.put("unary-/", new Range(1, 1)); paramCounts.put("union-equal", new Range(2, 2)); paramCounts.put("update-nth", new Range(3, 3)); paramCounts.put("upper-case-p", new Range(1, 1)); paramCounts.put("with-live-state", new Range(1, 1)); paramCounts.put("write-byte$", new Range(3, 3)); paramCounts.put("xor", new Range(2, 2)); paramCounts.put("zerop", new Range(1, 1)); paramCounts.put("zip", new Range(1, 1)); paramCounts.put("zp", new Range(1, 1)); paramCounts.put("zpf", new Range(1, 1)); paramCounts.put("comp", new Range(1, 1)); paramCounts.put("defconst", new Range(2, 3)); paramCounts.put("defdoc", new Range(2, 2)); paramCounts.put("defpkg", new Range(2, 5)); paramCounts.put("defproxy", new Range(4, 4)); paramCounts.put("local", new Range(1, 1)); paramCounts.put("remove-custom-keyword-hint", new Range(1, 1)); paramCounts.put("set-body", new Range(2, 2)); paramCounts.put("show-custom-keyword-hint-expansion", new Range(1, 1)); paramCounts.put("table", new Range(1, 5)); paramCounts.put("unmemoize", new Range(1, 1)); paramCounts.put("add-binop", new Range(2, 2)); paramCounts.put("add-dive-into-macro", new Range(2, 2)); paramCounts.put("add-include-book-dir", new Range(2, 2)); paramCounts.put("add-macro-alias", new Range(2, 2)); paramCounts.put("add-nth-alias", new Range(2, 2)); paramCounts.put("binop-table", new Range(1, 1)); paramCounts.put("delete-include-book-dir", new Range(1, 1)); paramCounts.put("remove-binop", new Range(1, 1)); paramCounts.put("remove-default-hints", new Range(1, 1)); paramCounts.put("remove-default-hints!", new Range(1, 1)); paramCounts.put("remove-dive-into-macro", new Range(1, 1)); paramCounts.put("remove-macro-alias", new Range(1, 1)); paramCounts.put("remove-nth-alias", new Range(1, 1)); paramCounts.put("remove-override-hints", new Range(1, 1)); paramCounts.put("remove-override-hints!", new Range(1, 1)); paramCounts.put("set-backchain-limit", new Range(1, 1)); paramCounts.put("set-bogus-defun-hints-ok", new Range(1, 1)); paramCounts.put("set-bogus-mutual-recursion-ok", new Range(1, 1)); paramCounts.put("set-case-split-limitations", new Range(1, 1)); paramCounts.put("set-checkpoint-summary-limit", new Range(1, 1)); paramCounts.put("set-compile-fns", new Range(1, 1)); paramCounts.put("set-debugger-enable", new Range(1, 1)); paramCounts.put("set-default-backchain-limit", new Range(1, 1)); paramCounts.put("set-default-hints", new Range(1, 1)); paramCounts.put("set-default-hints!", new Range(1, 1)); paramCounts.put("set-deferred-ttag-notes", new Range(2, 6)); paramCounts.put("set-enforce-redundancy", new Range(1, 1)); paramCounts.put("set-gag-mode", new Range(1, 1)); paramCounts.put("set-guard-checking", new Range(1, 1)); paramCounts.put("set-ignore-doc-string-error", new Range(1, 1)); paramCounts.put("set-ignore-ok", new Range(1, 1)); paramCounts.put("set-inhibit-output-lst", new Range(1, 1)); paramCounts.put("set-inhibited-summary-types", new Range(1, 1)); paramCounts.put("set-invisible-fns-table", new Range(1, 1)); paramCounts.put("set-irrelevant-formals-ok", new Range(1, 1)); paramCounts.put("set-ld-keyword-aliases", new Range(2, 6)); paramCounts.put("set-ld-redefinition-action", new Range(2, 5)); paramCounts.put("set-ld-skip-proofs", new Range(2, 2)); paramCounts.put("set-let*-abstraction", new Range(1, 1)); paramCounts.put("set-let*-abstractionp", new Range(1, 1)); paramCounts.put("set-match-free-default", new Range(1, 1)); paramCounts.put("set-match-free-error", new Range(1, 1)); paramCounts.put("set-measure-function", new Range(1, 1)); paramCounts.put("set-non-linear", new Range(1, 1)); paramCounts.put("set-non-linearp", new Range(1, 1)); paramCounts.put("set-nu-rewriter-mode", new Range(1, 1)); paramCounts.put("set-override-hints", new Range(1, 1)); paramCounts.put("set-override-hints!", new Range(1, 1)); paramCounts.put("set-print-clause-ids", new Range(1, 1)); paramCounts.put("set-prover-step-limit", new Range(1, 1)); paramCounts.put("set-raw-mode", new Range(1, 1)); paramCounts.put("set-raw-proof-format", new Range(1, 1)); paramCounts.put("set-rewrite-stack-limit", new Range(1, 1)); paramCounts.put("set-ruler-extenders", new Range(1, 1)); paramCounts.put("set-rw-cache-state", new Range(1, 1)); paramCounts.put("set-rw-cache-state!", new Range(1, 1)); paramCounts.put("set-saved-output", new Range(2, 2)); paramCounts.put("set-state-ok", new Range(1, 1)); paramCounts.put("set-tainted-ok", new Range(1, 1)); paramCounts.put("set-tainted-okp", new Range(1, 1)); paramCounts.put("set-verify-guards-eagerness", new Range(1, 1)); paramCounts.put("set-waterfall-parallelism", new Range(1, 2)); paramCounts.put("set-waterfall-printing", new Range(1, 1)); paramCounts.put("set-well-founded-relation", new Range(1, 1)); paramCounts.put("set-write-acl2x", new Range(2, 2)); paramCounts.put("with-guard-checking", new Range(2, 2)); } public class ParseToken { public int offset; public int line; public String name; public List<String> params = new ArrayList<String>(); public Set<String> vars = new HashSet<String>(); } public class Acl2ParserNotice extends DefaultParserNotice { public Acl2ParserNotice(Acl2Parser parser, String msg, int line, int offs, int len, int level) { super(parser, msg, line, offs, len); //System.out.println("ERROR on line " + line + ": " + msg); setLevel(level); } public Acl2ParserNotice(Acl2Parser parser, String msg, ParseToken top, int end) { this(parser, msg, top.line, top.offset, end - top.offset, ERROR); } public Acl2ParserNotice(Acl2Parser parser, String msg, int line, Token token, int level) { this(parser, msg, line, token.offset, token.textCount, level); } public Color getColor() { if (getLevel() == ERROR) { return Color.RED; } else if (getLevel() == INFO) { return null; } else { return null; } } @Override public boolean getShowInEditor() { return getLevel() != INFO; } } @Override public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) { DefaultParseResult result = new DefaultParseResult(this); int lines = doc.getDefaultRootElement().getElementCount(); result.setParsedLines(0, lines); functions = new HashSet<String>(); macros = new HashSet<String>(Arrays.asList(new String [] { "declare", "include-book", "defproperty", "defttag" })); constants = new HashSet<String>(); constants.add("state"); Stack<ParseToken> s = new Stack<ParseToken>(); Token token; for (int line = 0; line < lines; line++) { token = doc.getTokenListForLine(line); while (token != null && token.isPaintable()) { ParseToken top = (s.empty() ? null : s.peek()); if (!s.empty() && top.name != null && !token.isWhitespace() && !token.isComment() && !token.isSingleChar(')')) { // In a parameter position. top.params.add(token.getLexeme()); if (top.name.equals("defun") && top.params.size() == 1) { functions.add(token.getLexeme().toLowerCase()); } else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) && top.params.size() == 1) { macros.add(token.getLexeme()); } else if (top.name.equals("defconst") && top.params.size() == 1) { constants.add(token.getLexeme()); String constName = token.getLexeme(); if (!constName.startsWith("*") || !constName.endsWith("*")) { result.addNotice(new Acl2ParserNotice(this, "Constant names must begin and end with *.", line, token, ParserNotice.ERROR)); } } } ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2); ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3); boolean isVariableOfParent = (parent != null && parent.name != null && (parent.name.equals("defun") && parent.params.size() == 2 || parent.name.equals("mv-let") && parent.params.size() == 1)); boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null && ((grandparent.name.equals("let") || grandparent.name.equals("let*")) && grandparent.params.size() == 1 && top.params.size() == 0)); if (isVariableOfParent || isVariableOfGrandparent) { if (token.type == Token.IDENTIFIER) { if (isVariableOfParent) { parent.vars.add(token.getLexeme()); } else if (isVariableOfGrandparent) { grandparent.vars.add(token.getLexeme()); } } else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) { result.addNotice(new Acl2ParserNotice(this, "Expected a variable name", line, token, ParserNotice.ERROR)); } } boolean isIgnoredBecauseMacro = false; boolean isThm = false; Set<String> vars = new HashSet<String>(); for (ParseToken ancestor : s) { isIgnoredBecauseMacro |= macros.contains(ancestor.name); vars.addAll(ancestor.vars); isThm |= ancestor.name != null && (ancestor.name.equals("thm") || ancestor.name.equals("defthm")); } boolean isIgnoredBecauseParent = parent != null && parent.name != null && (parent.name.equals("defun") && parent.params.size() == 2 || parent.name.equals("defmacro") && parent.params.size() == 2 || parent.name.equals("mv-let") && parent.params.size() == 1 || parent.name.equals("cond") /* any parameter */ || parent.name.equals("case") /* any parameter */); boolean isIgnoredBecauseCurrent = top != null && top.name != null && (top.name.equals("defun") && top.params.size() == 1 || - top.name.equals("defmacro") && top.params.size() == 1); + top.name.equals("defmacro") && top.params.size() == 1 || + top.name.equals("assign") && top.params.size() == 1 || + top.name.equals("@") && top.params.size() == 1); boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent || (grandparent != null && grandparent.name != null && (grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 || grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0)); if (token.isSingleChar('(')) { if (top != null && top.name == null) top.name = ""; s.push(new ParseToken()); s.peek().line = line; s.peek().offset = token.offset; } else if (token.isSingleChar(')')) { if (s.empty()) { result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1, ParserNotice.ERROR)); } else { Range range = paramCounts.get(top.name); if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) { String msg; if (range.lower == range.upper) { msg = "<html><b>" + htmlEncode(top.name) + "</b> expects " + range.lower + " parameter" + (range.lower == 1 ? "" : "s") + ".</html>"; } else { msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between " + range.lower + " and " + range.upper + " parameters.</html>"; } result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1)); } s.pop(); if (top != null && top.name != null && top.name.equals("include-book")) { String bookName = top.params.get(0); int dirLoc = top.params.indexOf(":dir") + 1; File dir; String dirKey = ""; if (dirLoc == 0) { dir = workingDir; } else { dirKey = top.params.get(dirLoc); if (dirKey.equals(":system")) { dir = new File(acl2Dir, "books"); } else if (dirKey.equals(":teachpacks")) { dir = new File(acl2Dir, "dracula"); } else { result.addNotice(new Acl2ParserNotice(this, "Unrecognized book location: " + dirKey, top, token.offset + 1)); dir = null; } } File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp"); CacheSets bookCache = null; long mtime = book.lastModified(); if (dirKey.equals(":system")) { mtime = Long.MAX_VALUE; } CacheKey key = new CacheKey(book, mtime); if (cache.containsKey(key)) { bookCache = cache.get(key); } else { try { // TODO: Progress indicator. bookCache = parseBook(book, acl2Dir, cache); cache.put(key, bookCache); } catch (FileNotFoundException e) { result.addNotice(new Acl2ParserNotice(this, "File could not be found", top, token.offset + 1)); } catch (BadLocationException e) { } } if (bookCache != null) { functions.addAll(bookCache.functions); macros.addAll(bookCache.macros); constants.addAll(bookCache.constants); } } } } else if (!s.empty() && top.name == null && !token.isComment() && !token.isWhitespace()) { // This token is at the beginning of an s expression top.name = token.getLexeme().toLowerCase(); if (token.type != Token.RESERVED_WORD && token.type != Token.RESERVED_WORD_2 && !functions.contains(top.name) && !macros.contains(top.name) && !isIgnored) { result.addNotice(new Acl2ParserNotice(this, "<html><b>" + htmlEncode(top.name) + "</b> is undefined.</html>", line, token, ParserNotice.ERROR)); } if (token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2) { // TODO: Make these more noticeable? Map<String, String> docs = Main.cache.getDocs(); String upperToken = token.getLexeme().toUpperCase(); if (docs.containsKey(upperToken)) { String msg = "<html>" + docs.get(upperToken) + "<br><font " + "color=\"gray\" size=\"2\">Cmd+? for more.</font></html>"; result.addNotice(new Acl2ParserNotice(this, msg, line, token, ParserNotice.INFO)); } } } else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER || token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2) && !constants.contains(token.getLexeme()) && !vars.contains(token.getLexeme())) { result.addNotice(new Acl2ParserNotice(this, token.getLexeme() + " is undeclared.", line, token, ParserNotice.ERROR)); } token = token.getNextToken(); } } return result; } public static CacheSets parseBook(File book, File acl2Dir, Map<CacheKey, CacheSets> cache) throws FileNotFoundException, BadLocationException { CacheSets bookCache; Scanner bookScanner = new Scanner(book); bookScanner.useDelimiter("\\Z"); String bookContents = bookScanner.next(); logger.info("PARSING: " + book); book.lastModified(); Acl2Parser bookParser = new Acl2Parser(book.getParentFile(), acl2Dir); bookParser.cache = cache; RSyntaxDocument bookDoc = new IdeDocument(null); bookDoc.insertString(0, bookContents, null); bookParser.parse(bookDoc, null); bookCache = new CacheSets(); bookCache.functions = bookParser.functions; bookCache.constants = bookParser.constants; bookCache.macros = bookParser.macros; return bookCache; } private String htmlEncode(String name) { return name.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"); } }
true
true
public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) { DefaultParseResult result = new DefaultParseResult(this); int lines = doc.getDefaultRootElement().getElementCount(); result.setParsedLines(0, lines); functions = new HashSet<String>(); macros = new HashSet<String>(Arrays.asList(new String [] { "declare", "include-book", "defproperty", "defttag" })); constants = new HashSet<String>(); constants.add("state"); Stack<ParseToken> s = new Stack<ParseToken>(); Token token; for (int line = 0; line < lines; line++) { token = doc.getTokenListForLine(line); while (token != null && token.isPaintable()) { ParseToken top = (s.empty() ? null : s.peek()); if (!s.empty() && top.name != null && !token.isWhitespace() && !token.isComment() && !token.isSingleChar(')')) { // In a parameter position. top.params.add(token.getLexeme()); if (top.name.equals("defun") && top.params.size() == 1) { functions.add(token.getLexeme().toLowerCase()); } else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) && top.params.size() == 1) { macros.add(token.getLexeme()); } else if (top.name.equals("defconst") && top.params.size() == 1) { constants.add(token.getLexeme()); String constName = token.getLexeme(); if (!constName.startsWith("*") || !constName.endsWith("*")) { result.addNotice(new Acl2ParserNotice(this, "Constant names must begin and end with *.", line, token, ParserNotice.ERROR)); } } } ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2); ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3); boolean isVariableOfParent = (parent != null && parent.name != null && (parent.name.equals("defun") && parent.params.size() == 2 || parent.name.equals("mv-let") && parent.params.size() == 1)); boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null && ((grandparent.name.equals("let") || grandparent.name.equals("let*")) && grandparent.params.size() == 1 && top.params.size() == 0)); if (isVariableOfParent || isVariableOfGrandparent) { if (token.type == Token.IDENTIFIER) { if (isVariableOfParent) { parent.vars.add(token.getLexeme()); } else if (isVariableOfGrandparent) { grandparent.vars.add(token.getLexeme()); } } else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) { result.addNotice(new Acl2ParserNotice(this, "Expected a variable name", line, token, ParserNotice.ERROR)); } } boolean isIgnoredBecauseMacro = false; boolean isThm = false; Set<String> vars = new HashSet<String>(); for (ParseToken ancestor : s) { isIgnoredBecauseMacro |= macros.contains(ancestor.name); vars.addAll(ancestor.vars); isThm |= ancestor.name != null && (ancestor.name.equals("thm") || ancestor.name.equals("defthm")); } boolean isIgnoredBecauseParent = parent != null && parent.name != null && (parent.name.equals("defun") && parent.params.size() == 2 || parent.name.equals("defmacro") && parent.params.size() == 2 || parent.name.equals("mv-let") && parent.params.size() == 1 || parent.name.equals("cond") /* any parameter */ || parent.name.equals("case") /* any parameter */); boolean isIgnoredBecauseCurrent = top != null && top.name != null && (top.name.equals("defun") && top.params.size() == 1 || top.name.equals("defmacro") && top.params.size() == 1); boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent || (grandparent != null && grandparent.name != null && (grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 || grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0)); if (token.isSingleChar('(')) { if (top != null && top.name == null) top.name = ""; s.push(new ParseToken()); s.peek().line = line; s.peek().offset = token.offset; } else if (token.isSingleChar(')')) { if (s.empty()) { result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1, ParserNotice.ERROR)); } else { Range range = paramCounts.get(top.name); if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) { String msg; if (range.lower == range.upper) { msg = "<html><b>" + htmlEncode(top.name) + "</b> expects " + range.lower + " parameter" + (range.lower == 1 ? "" : "s") + ".</html>"; } else { msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between " + range.lower + " and " + range.upper + " parameters.</html>"; } result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1)); } s.pop(); if (top != null && top.name != null && top.name.equals("include-book")) { String bookName = top.params.get(0); int dirLoc = top.params.indexOf(":dir") + 1; File dir; String dirKey = ""; if (dirLoc == 0) { dir = workingDir; } else { dirKey = top.params.get(dirLoc); if (dirKey.equals(":system")) { dir = new File(acl2Dir, "books"); } else if (dirKey.equals(":teachpacks")) { dir = new File(acl2Dir, "dracula"); } else { result.addNotice(new Acl2ParserNotice(this, "Unrecognized book location: " + dirKey, top, token.offset + 1)); dir = null; } } File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp"); CacheSets bookCache = null; long mtime = book.lastModified(); if (dirKey.equals(":system")) { mtime = Long.MAX_VALUE; } CacheKey key = new CacheKey(book, mtime); if (cache.containsKey(key)) { bookCache = cache.get(key); } else { try { // TODO: Progress indicator. bookCache = parseBook(book, acl2Dir, cache); cache.put(key, bookCache); } catch (FileNotFoundException e) { result.addNotice(new Acl2ParserNotice(this, "File could not be found", top, token.offset + 1)); } catch (BadLocationException e) { } } if (bookCache != null) { functions.addAll(bookCache.functions); macros.addAll(bookCache.macros); constants.addAll(bookCache.constants); } } } } else if (!s.empty() && top.name == null && !token.isComment() && !token.isWhitespace()) { // This token is at the beginning of an s expression top.name = token.getLexeme().toLowerCase(); if (token.type != Token.RESERVED_WORD && token.type != Token.RESERVED_WORD_2 && !functions.contains(top.name) && !macros.contains(top.name) && !isIgnored) { result.addNotice(new Acl2ParserNotice(this, "<html><b>" + htmlEncode(top.name) + "</b> is undefined.</html>", line, token, ParserNotice.ERROR)); } if (token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2) { // TODO: Make these more noticeable? Map<String, String> docs = Main.cache.getDocs(); String upperToken = token.getLexeme().toUpperCase(); if (docs.containsKey(upperToken)) { String msg = "<html>" + docs.get(upperToken) + "<br><font " + "color=\"gray\" size=\"2\">Cmd+? for more.</font></html>"; result.addNotice(new Acl2ParserNotice(this, msg, line, token, ParserNotice.INFO)); } } } else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER || token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2) && !constants.contains(token.getLexeme()) && !vars.contains(token.getLexeme())) { result.addNotice(new Acl2ParserNotice(this, token.getLexeme() + " is undeclared.", line, token, ParserNotice.ERROR)); } token = token.getNextToken(); } } return result; }
public ParseResult parse(RSyntaxDocument doc, String style /* ignored */) { DefaultParseResult result = new DefaultParseResult(this); int lines = doc.getDefaultRootElement().getElementCount(); result.setParsedLines(0, lines); functions = new HashSet<String>(); macros = new HashSet<String>(Arrays.asList(new String [] { "declare", "include-book", "defproperty", "defttag" })); constants = new HashSet<String>(); constants.add("state"); Stack<ParseToken> s = new Stack<ParseToken>(); Token token; for (int line = 0; line < lines; line++) { token = doc.getTokenListForLine(line); while (token != null && token.isPaintable()) { ParseToken top = (s.empty() ? null : s.peek()); if (!s.empty() && top.name != null && !token.isWhitespace() && !token.isComment() && !token.isSingleChar(')')) { // In a parameter position. top.params.add(token.getLexeme()); if (top.name.equals("defun") && top.params.size() == 1) { functions.add(token.getLexeme().toLowerCase()); } else if ((top.name.equals("defmacro") || top.name.equals("defabbrev")) && top.params.size() == 1) { macros.add(token.getLexeme()); } else if (top.name.equals("defconst") && top.params.size() == 1) { constants.add(token.getLexeme()); String constName = token.getLexeme(); if (!constName.startsWith("*") || !constName.endsWith("*")) { result.addNotice(new Acl2ParserNotice(this, "Constant names must begin and end with *.", line, token, ParserNotice.ERROR)); } } } ParseToken parent = s.size() <= 1 ? null : s.get(s.size() - 2); ParseToken grandparent = s.size() <= 2 ? null : s.get(s.size() - 3); boolean isVariableOfParent = (parent != null && parent.name != null && (parent.name.equals("defun") && parent.params.size() == 2 || parent.name.equals("mv-let") && parent.params.size() == 1)); boolean isVariableOfGrandparent = (grandparent != null && grandparent.name != null && ((grandparent.name.equals("let") || grandparent.name.equals("let*")) && grandparent.params.size() == 1 && top.params.size() == 0)); if (isVariableOfParent || isVariableOfGrandparent) { if (token.type == Token.IDENTIFIER) { if (isVariableOfParent) { parent.vars.add(token.getLexeme()); } else if (isVariableOfGrandparent) { grandparent.vars.add(token.getLexeme()); } } else if (token.type != Token.WHITESPACE && !token.isSingleChar(')')) { result.addNotice(new Acl2ParserNotice(this, "Expected a variable name", line, token, ParserNotice.ERROR)); } } boolean isIgnoredBecauseMacro = false; boolean isThm = false; Set<String> vars = new HashSet<String>(); for (ParseToken ancestor : s) { isIgnoredBecauseMacro |= macros.contains(ancestor.name); vars.addAll(ancestor.vars); isThm |= ancestor.name != null && (ancestor.name.equals("thm") || ancestor.name.equals("defthm")); } boolean isIgnoredBecauseParent = parent != null && parent.name != null && (parent.name.equals("defun") && parent.params.size() == 2 || parent.name.equals("defmacro") && parent.params.size() == 2 || parent.name.equals("mv-let") && parent.params.size() == 1 || parent.name.equals("cond") /* any parameter */ || parent.name.equals("case") /* any parameter */); boolean isIgnoredBecauseCurrent = top != null && top.name != null && (top.name.equals("defun") && top.params.size() == 1 || top.name.equals("defmacro") && top.params.size() == 1 || top.name.equals("assign") && top.params.size() == 1 || top.name.equals("@") && top.params.size() == 1); boolean isIgnored = isIgnoredBecauseMacro || isIgnoredBecauseParent || isIgnoredBecauseCurrent || (grandparent != null && grandparent.name != null && (grandparent.name.equals("let") && grandparent.params.size() == 1 && top.params.size() == 0 || grandparent.name.equals("let*") && grandparent.params.size() == 1 && top.params.size() == 0)); if (token.isSingleChar('(')) { if (top != null && top.name == null) top.name = ""; s.push(new ParseToken()); s.peek().line = line; s.peek().offset = token.offset; } else if (token.isSingleChar(')')) { if (s.empty()) { result.addNotice(new Acl2ParserNotice(this, "Unmatched )", line, token.offset, 1, ParserNotice.ERROR)); } else { Range range = paramCounts.get(top.name); if (range != null && (top.params.size() < range.lower || top.params.size() > range.upper)) { String msg; if (range.lower == range.upper) { msg = "<html><b>" + htmlEncode(top.name) + "</b> expects " + range.lower + " parameter" + (range.lower == 1 ? "" : "s") + ".</html>"; } else { msg = "<html><b>" + htmlEncode(top.name) + "</b> expects between " + range.lower + " and " + range.upper + " parameters.</html>"; } result.addNotice(new Acl2ParserNotice(this, msg, top, token.offset + 1)); } s.pop(); if (top != null && top.name != null && top.name.equals("include-book")) { String bookName = top.params.get(0); int dirLoc = top.params.indexOf(":dir") + 1; File dir; String dirKey = ""; if (dirLoc == 0) { dir = workingDir; } else { dirKey = top.params.get(dirLoc); if (dirKey.equals(":system")) { dir = new File(acl2Dir, "books"); } else if (dirKey.equals(":teachpacks")) { dir = new File(acl2Dir, "dracula"); } else { result.addNotice(new Acl2ParserNotice(this, "Unrecognized book location: " + dirKey, top, token.offset + 1)); dir = null; } } File book = new File(dir, bookName.substring(1, bookName.length() - 1) + ".lisp"); CacheSets bookCache = null; long mtime = book.lastModified(); if (dirKey.equals(":system")) { mtime = Long.MAX_VALUE; } CacheKey key = new CacheKey(book, mtime); if (cache.containsKey(key)) { bookCache = cache.get(key); } else { try { // TODO: Progress indicator. bookCache = parseBook(book, acl2Dir, cache); cache.put(key, bookCache); } catch (FileNotFoundException e) { result.addNotice(new Acl2ParserNotice(this, "File could not be found", top, token.offset + 1)); } catch (BadLocationException e) { } } if (bookCache != null) { functions.addAll(bookCache.functions); macros.addAll(bookCache.macros); constants.addAll(bookCache.constants); } } } } else if (!s.empty() && top.name == null && !token.isComment() && !token.isWhitespace()) { // This token is at the beginning of an s expression top.name = token.getLexeme().toLowerCase(); if (token.type != Token.RESERVED_WORD && token.type != Token.RESERVED_WORD_2 && !functions.contains(top.name) && !macros.contains(top.name) && !isIgnored) { result.addNotice(new Acl2ParserNotice(this, "<html><b>" + htmlEncode(top.name) + "</b> is undefined.</html>", line, token, ParserNotice.ERROR)); } if (token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2) { // TODO: Make these more noticeable? Map<String, String> docs = Main.cache.getDocs(); String upperToken = token.getLexeme().toUpperCase(); if (docs.containsKey(upperToken)) { String msg = "<html>" + docs.get(upperToken) + "<br><font " + "color=\"gray\" size=\"2\">Cmd+? for more.</font></html>"; result.addNotice(new Acl2ParserNotice(this, msg, line, token, ParserNotice.INFO)); } } } else if (!isThm && !isIgnored && (token.type == Token.IDENTIFIER || token.type == Token.RESERVED_WORD || token.type == Token.RESERVED_WORD_2) && !constants.contains(token.getLexeme()) && !vars.contains(token.getLexeme())) { result.addNotice(new Acl2ParserNotice(this, token.getLexeme() + " is undeclared.", line, token, ParserNotice.ERROR)); } token = token.getNextToken(); } } return result; }
diff --git a/EventManagmentSystem/src/GUI/CommitteePanel.java b/EventManagmentSystem/src/GUI/CommitteePanel.java index 0fe997c..495c701 100644 --- a/EventManagmentSystem/src/GUI/CommitteePanel.java +++ b/EventManagmentSystem/src/GUI/CommitteePanel.java @@ -1,839 +1,839 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GUI; import GUI.Dialog.TaskDialog; import javax.swing.*; import BackEnd.EventSystem.Committee; import BackEnd.EventSystem.Event; import BackEnd.EventSystem.Task; import BackEnd.EventSystem.TimeSchedule; import BackEnd.ManagerSystem.MainManager; import BackEnd.UserSystem.User; import GUI.Dialog.BudgetDialog; import GUI.Dialog.FindMemberDialog; import GUI.Dialog.NewTaskDialog; import java.awt.Color; import java.awt.Component; import java.util.Calendar; /** * * @author Sid */ public class CommitteePanel extends javax.swing.JPanel { /** * Creates new form CommitteePanel */ private MainManager manager; public CommitteePanel() { initComponents(); manager = MainManager.getInstance(); MembersCellRenderer memberRenderer = new MembersCellRenderer(); TasksCellRenderer taskRenderer = new TasksCellRenderer(); memberList.setCellRenderer(memberRenderer); taskList.setCellRenderer(taskRenderer); } public void setChairView() { committeeChangeButton.setVisible(false); } public void setCommitteeMemberView() { setChairView(); budgetButton.setVisible(false); addToBudgetButton.setVisible(false); removeMemberFromBudgetButton.setVisible(false); addMemberButton.setVisible(false); removeMemberButton.setVisible(false); addTaskButton.setVisible(false); removeTaskButton.setVisible(false); } public void setBudgetAccessMemberView() { setCommitteeMemberView(); budgetButton.setVisible(true); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { committeeChangeButton = new javax.swing.JButton(); removeTaskButton = new javax.swing.JButton(); addTaskButton = new javax.swing.JButton(); removeMemberButton = new javax.swing.JButton(); addMemberButton = new javax.swing.JButton(); addToBudgetButton = new javax.swing.JButton(); removeMemberFromBudgetButton = new javax.swing.JButton(); headerLabel = new javax.swing.JLabel(); memberScrollPane = new javax.swing.JScrollPane(); memberList = new javax.swing.JList(); membersLabel = new javax.swing.JLabel(); headLabel = new javax.swing.JLabel(); headNameLabel = new javax.swing.JLabel(); taskScrollPane = new javax.swing.JScrollPane(); taskList = new javax.swing.JList(); tasksLabel = new javax.swing.JLabel(); taskProgressBar = new javax.swing.JProgressBar(); budgetButton = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); addMemberLabel = new javax.swing.JLabel(); removeMemberLabel = new javax.swing.JLabel(); addTaskLabel = new javax.swing.JLabel(); removeTaskLabel = new javax.swing.JLabel(); removeBudgetAccessLabel = new javax.swing.JLabel(); addBudgetAccessLabel = new javax.swing.JLabel(); committeeChangeButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N committeeChangeButton.setText("change"); committeeChangeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { committeeChangeButtonActionPerformed(evt); } }); removeTaskButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N removeTaskButton.setText("-"); removeTaskButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeTaskButtonActionPerformed(evt); } }); addTaskButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N addTaskButton.setText("+"); addTaskButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addTaskButtonActionPerformed(evt); } }); removeMemberButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N removeMemberButton.setText("-"); removeMemberButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeMemberButtonActionPerformed(evt); } }); addMemberButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N addMemberButton.setText("+"); addMemberButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addMemberButtonActionPerformed(evt); } }); addToBudgetButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N addToBudgetButton.setText("+"); addToBudgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addToBudgetButtonActionPerformed(evt); } }); removeMemberFromBudgetButton.setText("-"); removeMemberFromBudgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeMemberFromBudgetButtonActionPerformed(evt); } }); setBackground(new java.awt.Color(153, 204, 255)); setMinimumSize(new java.awt.Dimension(387, 327)); headerLabel.setFont(new java.awt.Font("Candara", 1, 24)); // NOI18N headerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); headerLabel.setText("Committee Name"); headerLabel.setPreferredSize(new java.awt.Dimension(200, 25)); memberList.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N memberList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); memberList.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { memberListValueChanged(evt); } }); memberScrollPane.setViewportView(memberList); membersLabel.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N membersLabel.setText("Members"); headLabel.setFont(new java.awt.Font("Candara", 1, 18)); // NOI18N headLabel.setText("Head: "); headNameLabel.setFont(new java.awt.Font("Candara", 1, 16)); // NOI18N headNameLabel.setText("committee head"); taskList.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N taskList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); taskList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { taskListMouseClicked(evt); } }); taskScrollPane.setViewportView(taskList); tasksLabel.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N tasksLabel.setText("Tasks"); taskProgressBar.setOrientation(1); budgetButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N budgetButton.setText("View Budget"); budgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { budgetButtonActionPerformed(evt); } }); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); - jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/edit1.png"))); // NOI18N + jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\edit1.png")); // NOI18N jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); - addMemberLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/add1.png"))); // NOI18N + addMemberLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\add1.png")); // NOI18N addMemberLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addMemberLabelMouseClicked(evt); } }); - removeMemberLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/remove1.png"))); // NOI18N + removeMemberLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\remove1.png")); // NOI18N removeMemberLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { removeMemberLabelMouseClicked(evt); } }); - addTaskLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/add1.png"))); // NOI18N + addTaskLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\add1.png")); // NOI18N addTaskLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addTaskLabelMouseClicked(evt); } }); - removeTaskLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/remove1.png"))); // NOI18N + removeTaskLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\remove1.png")); // NOI18N removeTaskLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { removeTaskLabelMouseClicked(evt); } }); - removeBudgetAccessLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/remove1.png"))); // NOI18N + removeBudgetAccessLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\remove1.png")); // NOI18N removeBudgetAccessLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { removeBudgetAccessLabelMouseClicked(evt); } }); - addBudgetAccessLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/add1.png"))); // NOI18N + addBudgetAccessLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\add1.png")); // NOI18N addBudgetAccessLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addBudgetAccessLabelMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(headerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(membersLabel) .addGap(227, 227, 227) .addComponent(tasksLabel)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(memberScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(addMemberLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeMemberLabel))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(addBudgetAccessLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeBudgetAccessLabel)) .addComponent(budgetButton, javax.swing.GroupLayout.Alignment.LEADING))) .addGap(70, 70, 70) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(headLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(headNameLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(taskScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(addTaskLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeTaskLabel))) .addGap(10, 10, 10) .addComponent(taskProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(headerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(headLabel) .addComponent(headNameLabel) .addComponent(budgetButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(addBudgetAccessLabel)) .addComponent(removeBudgetAccessLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(membersLabel) .addComponent(tasksLabel)) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(memberScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(removeMemberLabel) .addComponent(addMemberLabel))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(taskProgressBar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(taskScrollPane, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(removeTaskLabel) .addComponent(addTaskLabel))))) ); }// </editor-fold>//GEN-END:initComponents public void setCommittee(Committee c) { manager.getCommitteeManager().setSelectedCommittee(c); updateInfo(); } public void updateInfo() { Committee c = manager.getCommitteeManager().getSelectedCommittee(); if(c.getTitle() != null) { headerLabel.setText(c.getTitle()); } headNameLabel.setText(c.getChair().getFirstName() + " " + c.getChair().getLastName()); DefaultListModel tModel = new DefaultListModel(); DefaultListModel mModel = new DefaultListModel(); for(User m : c.getMemberListWithChair()){ mModel.addElement(m); } for(Task t : c.getTaskList()){ tModel.addElement(t); } taskList.setModel(tModel); memberList.setModel(mModel); taskProgressBar.setValue(manager.getCommitteeManager().getSelectedCommittee().getCompletePercent()); } private void budgetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_budgetButtonActionPerformed // TODO add your handling code here: manager.getBudgetManager().setSelectedBudget(manager.getCommitteeManager().getSelectedCommittee().getBudget()); BudgetDialog bd = new BudgetDialog((JFrame)SwingUtilities.windowForComponent(this), true); bd.setVisible(true); }//GEN-LAST:event_budgetButtonActionPerformed private void taskListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_taskListMouseClicked // TODO add your handling code here: if(evt.getClickCount() == 2) { manager.getTaskManager().setSelectedTask(manager.getCommitteeManager().getSelectedCommittee().getTaskList().get(taskList.getMaxSelectionIndex())); TaskDialog td = new TaskDialog((JFrame)SwingUtilities.windowForComponent(this), true); td.setVisible(true); if(td.getConfirm()) { //UPDATE ALL TASK INFO Task t = td.createTask(); User u = manager.getLogInManager().getLoggedInUser(); Event e = manager.getEventManager().getSelectedEvent(); Committee c = manager.getCommitteeManager().getSelectedCommittee(); try { manager.getTaskManager().editCompleted(t.getCompleted(), u, e, c); manager.getTaskManager().editTitle(t.getTitle(), u, e, c); manager.getTaskManager().editDescription(t.getDescription(), u, e, c); // for(User us : t.getResponsibleList()) // { // manager.getTaskManager().addResponsible(us, u, e, c); // } TimeSchedule ts = t.getTimeSchedule(); int year = ts.getStartDateTimeCalendar().get(Calendar.YEAR); int month = ts.getStartDateTimeCalendar().get(Calendar.MONTH)+1; int day = ts.getStartDateTimeCalendar().get(Calendar.DAY_OF_MONTH); int hour = ts.getStartDateTimeCalendar().get(Calendar.HOUR); int minute = ts.getStartDateTimeCalendar().get(Calendar.MINUTE); manager.getTaskManager().editStartDateTime(year, month, day, hour, minute, u, e, c); year = ts.getEndDateTimeCalendar().get(Calendar.YEAR); month = ts.getEndDateTimeCalendar().get(Calendar.MONTH)+1; day = ts.getEndDateTimeCalendar().get(Calendar.DAY_OF_MONTH); hour = ts.getEndDateTimeCalendar().get(Calendar.HOUR); minute = ts.getEndDateTimeCalendar().get(Calendar.MINUTE); manager.getTaskManager().editEndDateTime(year, month, day, hour, minute, u, e, c); } catch (Exception ex) { ex.printStackTrace(); } } updateInfo(); } }//GEN-LAST:event_taskListMouseClicked private void removeMemberButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeMemberButtonActionPerformed // TODO add your handling code here: try { manager.getCommitteeManager().removeMember(manager.getCommitteeManager().getSelectedCommittee().getMemberList().get(memberList.getSelectedIndex()), manager.getUserManager().getSelectedUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { System.out.println(e); } updateInfo(); }//GEN-LAST:event_removeMemberButtonActionPerformed private void removeTaskButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeTaskButtonActionPerformed // TODO add your handling code here: try { manager.getCommitteeManager().getSelectedCommittee().getTaskList().remove(taskList.getSelectedIndex()); } catch (Exception e) { e.printStackTrace(); } updateInfo(); if(taskList.getModel().getSize() >= 0) { taskList.setSelectedIndex(0); } }//GEN-LAST:event_removeTaskButtonActionPerformed private void addMemberButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addMemberButtonActionPerformed // TODO add your handling code here: FindMemberDialog fmd = new FindMemberDialog((JFrame)SwingUtilities.windowForComponent(this), true); fmd.setVisible(true); if(fmd.getConfirm()) { User u = fmd.createUser(); if(manager.getCommitteeManager().getSelectedCommittee().getMemberListWithChair().contains(u)) { JOptionPane.showMessageDialog(null, "User already exists in member list."); } else { try { manager.getCommitteeManager().addMember(u, manager.getUserManager().getSelectedUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { e.printStackTrace(); } } } updateInfo(); }//GEN-LAST:event_addMemberButtonActionPerformed private void addTaskButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addTaskButtonActionPerformed // TODO add your handling code here: NewTaskDialog ntd = new NewTaskDialog((JFrame)SwingUtilities.windowForComponent(this), true); ntd.setVisible(true); if(ntd.getConfirm()) { try { Task t = ntd.createTask(); User u = manager.getLogInManager().getLoggedInUser(); Event e = manager.getEventManager().getSelectedEvent(); Committee c = manager.getCommitteeManager().getSelectedCommittee(); manager.getTaskManager().setSelectedTask(manager.getCommitteeManager().createTask(t, u, e)); manager.getTaskManager().editTitle(t.getTitle(), u, e, c); manager.getTaskManager().editCompleted(t.getCompleted(), u, e, c); manager.getTaskManager().editDescription(t.getDescription(), u, e, c); manager.getTaskManager().addResponsible(u, u, e, c); TimeSchedule ts = t.getTimeSchedule(); int year = ts.getStartDateTimeCalendar().get(Calendar.YEAR); int month = ts.getStartDateTimeCalendar().get(Calendar.MONTH)+1; int day = ts.getStartDateTimeCalendar().get(Calendar.DAY_OF_MONTH); int hour = ts.getStartDateTimeCalendar().get(Calendar.HOUR); int minute = ts.getStartDateTimeCalendar().get(Calendar.MINUTE); manager.getTaskManager().editStartDateTime(year, month, day, hour, minute, u, e, c); year = ts.getEndDateTimeCalendar().get(Calendar.YEAR); month = ts.getEndDateTimeCalendar().get(Calendar.MONTH)+1; day = ts.getEndDateTimeCalendar().get(Calendar.DAY_OF_MONTH); hour = ts.getEndDateTimeCalendar().get(Calendar.HOUR); minute = ts.getEndDateTimeCalendar().get(Calendar.MINUTE); manager.getTaskManager().editEndDateTime(year, month, day, hour, minute, u, e, c); } catch (Exception e) { System.out.println("Error in adding task to committee."); e.printStackTrace(); } } updateInfo(); }//GEN-LAST:event_addTaskButtonActionPerformed private void committeeChangeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_committeeChangeButtonActionPerformed // TODO add your handling code here: FindMemberDialog fmd = new FindMemberDialog((JFrame)SwingUtilities.windowForComponent(this), true); fmd.setVisible(true); if(fmd.getConfirm()) { try { manager.getCommitteeManager().editChair(fmd.createUser(), manager.getLogInManager().getLoggedInUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { e.printStackTrace(); } } updateInfo(); }//GEN-LAST:event_committeeChangeButtonActionPerformed private void addToBudgetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addToBudgetButtonActionPerformed // TODO add your handling code here: try { manager.getCommitteeManager().addBudgetAccess( manager.getUserManager().getSelectedUser(), manager.getLogInManager().getLoggedInUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { e.printStackTrace(); } updateInfo(); }//GEN-LAST:event_addToBudgetButtonActionPerformed private void memberListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_memberListValueChanged // TODO add your handling code here: if(memberList.getSelectedValue() instanceof User) { User u = (User)memberList.getSelectedValue(); manager.getUserManager().setSelectedUser(u); } }//GEN-LAST:event_memberListValueChanged private void removeMemberFromBudgetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeMemberFromBudgetButtonActionPerformed // TODO add your handling code here: try { manager.getCommitteeManager().removeBudgetAccess( manager.getUserManager().getSelectedUser(), manager.getLogInManager().getLoggedInUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { e.printStackTrace(); } updateInfo(); }//GEN-LAST:event_removeMemberFromBudgetButtonActionPerformed private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked // TODO add your handling code here: FindMemberDialog fmd = new FindMemberDialog((JFrame)SwingUtilities.windowForComponent(this), true); fmd.setVisible(true); if(fmd.getConfirm()) { try { manager.getCommitteeManager().editChair(fmd.createUser(), manager.getLogInManager().getLoggedInUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { e.printStackTrace(); } } updateInfo(); }//GEN-LAST:event_jLabel1MouseClicked private void addMemberLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addMemberLabelMouseClicked // TODO add your handling code here: FindMemberDialog fmd = new FindMemberDialog((JFrame)SwingUtilities.windowForComponent(this), true); fmd.setVisible(true); if(fmd.getConfirm()) { User u = fmd.createUser(); if(manager.getCommitteeManager().getSelectedCommittee().getMemberListWithChair().contains(u)) { JOptionPane.showMessageDialog(null, "User already exists in member list."); } else { try { manager.getCommitteeManager().addMember(u, manager.getUserManager().getSelectedUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { e.printStackTrace(); } } } updateInfo(); }//GEN-LAST:event_addMemberLabelMouseClicked private void removeMemberLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeMemberLabelMouseClicked // TODO add your handling code here: if(manager.getCommitteeManager().getSelectedCommittee().getChair().equals((User)memberList.getSelectedValue())) { JOptionPane.showMessageDialog(null, "Can not remove chair. Change chair first and then remove.", "Remove Chair Error", JOptionPane.ERROR_MESSAGE); } else { try { manager.getCommitteeManager().removeMember( manager.getCommitteeManager().getSelectedCommittee().getMemberList().get( memberList.getSelectedIndex()), manager.getUserManager().getSelectedUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { System.out.println(e); } } updateInfo(); }//GEN-LAST:event_removeMemberLabelMouseClicked private void addTaskLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addTaskLabelMouseClicked // TODO add your handling code here: NewTaskDialog ntd = new NewTaskDialog((JFrame)SwingUtilities.windowForComponent(this), true); ntd.setVisible(true); if(ntd.getConfirm()) { try { Task t = ntd.createTask(); User u = manager.getLogInManager().getLoggedInUser(); Event e = manager.getEventManager().getSelectedEvent(); Committee c = manager.getCommitteeManager().getSelectedCommittee(); manager.getTaskManager().setSelectedTask(manager.getCommitteeManager().createTask(t, u, e)); manager.getTaskManager().editTitle(t.getTitle(), u, e, c); manager.getTaskManager().editCompleted(t.getCompleted(), u, e, c); manager.getTaskManager().editDescription(t.getDescription(), u, e, c); manager.getTaskManager().addResponsible(u, u, e, c); TimeSchedule ts = t.getTimeSchedule(); int year = ts.getStartDateTimeCalendar().get(Calendar.YEAR); int month = ts.getStartDateTimeCalendar().get(Calendar.MONTH)+1; int day = ts.getStartDateTimeCalendar().get(Calendar.DAY_OF_MONTH); int hour = ts.getStartDateTimeCalendar().get(Calendar.HOUR); int minute = ts.getStartDateTimeCalendar().get(Calendar.MINUTE); manager.getTaskManager().editStartDateTime(year, month, day, hour, minute, u, e, c); year = ts.getEndDateTimeCalendar().get(Calendar.YEAR); month = ts.getEndDateTimeCalendar().get(Calendar.MONTH)+1; day = ts.getEndDateTimeCalendar().get(Calendar.DAY_OF_MONTH); hour = ts.getEndDateTimeCalendar().get(Calendar.HOUR); minute = ts.getEndDateTimeCalendar().get(Calendar.MINUTE); manager.getTaskManager().editEndDateTime(year, month, day, hour, minute, u, e, c); } catch (Exception e) { System.out.println("Error in adding task to committee."); e.printStackTrace(); } } updateInfo(); }//GEN-LAST:event_addTaskLabelMouseClicked private void removeTaskLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeTaskLabelMouseClicked // TODO add your handling code here: try { manager.getCommitteeManager().getSelectedCommittee().getTaskList().remove(taskList.getSelectedIndex()); } catch (Exception e) { e.printStackTrace(); } updateInfo(); if(taskList.getModel().getSize() >= 0) { taskList.setSelectedIndex(0); } }//GEN-LAST:event_removeTaskLabelMouseClicked private void removeBudgetAccessLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeBudgetAccessLabelMouseClicked // TODO add your handling code here: try { manager.getCommitteeManager().removeBudgetAccess( manager.getUserManager().getSelectedUser(), manager.getLogInManager().getLoggedInUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { e.printStackTrace(); } updateInfo(); }//GEN-LAST:event_removeBudgetAccessLabelMouseClicked private void addBudgetAccessLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addBudgetAccessLabelMouseClicked // TODO add your handling code here: try { manager.getCommitteeManager().addBudgetAccess( manager.getUserManager().getSelectedUser(), manager.getLogInManager().getLoggedInUser(), manager.getEventManager().getSelectedEvent()); } catch (Exception e) { e.printStackTrace(); } updateInfo(); }//GEN-LAST:event_addBudgetAccessLabelMouseClicked // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel addBudgetAccessLabel; private javax.swing.JButton addMemberButton; private javax.swing.JLabel addMemberLabel; private javax.swing.JButton addTaskButton; private javax.swing.JLabel addTaskLabel; private javax.swing.JButton addToBudgetButton; private javax.swing.JButton budgetButton; private javax.swing.JButton committeeChangeButton; private javax.swing.JLabel headLabel; private javax.swing.JLabel headNameLabel; private javax.swing.JLabel headerLabel; private javax.swing.JLabel jLabel1; private javax.swing.JSeparator jSeparator1; private javax.swing.JList memberList; private javax.swing.JScrollPane memberScrollPane; private javax.swing.JLabel membersLabel; private javax.swing.JLabel removeBudgetAccessLabel; private javax.swing.JButton removeMemberButton; private javax.swing.JButton removeMemberFromBudgetButton; private javax.swing.JLabel removeMemberLabel; private javax.swing.JButton removeTaskButton; private javax.swing.JLabel removeTaskLabel; private javax.swing.JList taskList; private javax.swing.JProgressBar taskProgressBar; private javax.swing.JScrollPane taskScrollPane; private javax.swing.JLabel tasksLabel; // End of variables declaration//GEN-END:variables class MembersCellRenderer extends JLabel implements ListCellRenderer { public MembersCellRenderer() { setOpaque(true); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if(value instanceof User) { User u = (User)value; if(manager.getCommitteeManager().getSelectedCommittee().getChair().equals(u)) { setText(u.toString()+"(C)"); setBackground(Color.GREEN); } else if(manager.getCommitteeManager().getSelectedCommittee().getBudgetAccessList().contains(u)) { setText(u.toString()+"*"); setBackground(Color.ORANGE); } else { setText(u.toString()); setBackground(Color.WHITE); } if(isSelected) { setBackground(Color.LIGHT_GRAY); } } return this; } } class TasksCellRenderer extends JLabel implements ListCellRenderer { public TasksCellRenderer() { setOpaque(true); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if(value instanceof Task) { Task t = (Task)value; if(t.getCompleted()) { setText(t.toString()); setBackground(new Color(128,255,128)); } else { setText(t.toString()); setBackground(new Color(255,128,128)); } if(isSelected) { setBackground(Color.LIGHT_GRAY); } } return this; } } }
false
true
private void initComponents() { committeeChangeButton = new javax.swing.JButton(); removeTaskButton = new javax.swing.JButton(); addTaskButton = new javax.swing.JButton(); removeMemberButton = new javax.swing.JButton(); addMemberButton = new javax.swing.JButton(); addToBudgetButton = new javax.swing.JButton(); removeMemberFromBudgetButton = new javax.swing.JButton(); headerLabel = new javax.swing.JLabel(); memberScrollPane = new javax.swing.JScrollPane(); memberList = new javax.swing.JList(); membersLabel = new javax.swing.JLabel(); headLabel = new javax.swing.JLabel(); headNameLabel = new javax.swing.JLabel(); taskScrollPane = new javax.swing.JScrollPane(); taskList = new javax.swing.JList(); tasksLabel = new javax.swing.JLabel(); taskProgressBar = new javax.swing.JProgressBar(); budgetButton = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); addMemberLabel = new javax.swing.JLabel(); removeMemberLabel = new javax.swing.JLabel(); addTaskLabel = new javax.swing.JLabel(); removeTaskLabel = new javax.swing.JLabel(); removeBudgetAccessLabel = new javax.swing.JLabel(); addBudgetAccessLabel = new javax.swing.JLabel(); committeeChangeButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N committeeChangeButton.setText("change"); committeeChangeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { committeeChangeButtonActionPerformed(evt); } }); removeTaskButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N removeTaskButton.setText("-"); removeTaskButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeTaskButtonActionPerformed(evt); } }); addTaskButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N addTaskButton.setText("+"); addTaskButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addTaskButtonActionPerformed(evt); } }); removeMemberButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N removeMemberButton.setText("-"); removeMemberButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeMemberButtonActionPerformed(evt); } }); addMemberButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N addMemberButton.setText("+"); addMemberButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addMemberButtonActionPerformed(evt); } }); addToBudgetButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N addToBudgetButton.setText("+"); addToBudgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addToBudgetButtonActionPerformed(evt); } }); removeMemberFromBudgetButton.setText("-"); removeMemberFromBudgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeMemberFromBudgetButtonActionPerformed(evt); } }); setBackground(new java.awt.Color(153, 204, 255)); setMinimumSize(new java.awt.Dimension(387, 327)); headerLabel.setFont(new java.awt.Font("Candara", 1, 24)); // NOI18N headerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); headerLabel.setText("Committee Name"); headerLabel.setPreferredSize(new java.awt.Dimension(200, 25)); memberList.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N memberList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); memberList.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { memberListValueChanged(evt); } }); memberScrollPane.setViewportView(memberList); membersLabel.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N membersLabel.setText("Members"); headLabel.setFont(new java.awt.Font("Candara", 1, 18)); // NOI18N headLabel.setText("Head: "); headNameLabel.setFont(new java.awt.Font("Candara", 1, 16)); // NOI18N headNameLabel.setText("committee head"); taskList.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N taskList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); taskList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { taskListMouseClicked(evt); } }); taskScrollPane.setViewportView(taskList); tasksLabel.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N tasksLabel.setText("Tasks"); taskProgressBar.setOrientation(1); budgetButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N budgetButton.setText("View Budget"); budgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { budgetButtonActionPerformed(evt); } }); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/edit1.png"))); // NOI18N jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); addMemberLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/add1.png"))); // NOI18N addMemberLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addMemberLabelMouseClicked(evt); } }); removeMemberLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/remove1.png"))); // NOI18N removeMemberLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { removeMemberLabelMouseClicked(evt); } }); addTaskLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/add1.png"))); // NOI18N addTaskLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addTaskLabelMouseClicked(evt); } }); removeTaskLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/remove1.png"))); // NOI18N removeTaskLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { removeTaskLabelMouseClicked(evt); } }); removeBudgetAccessLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/remove1.png"))); // NOI18N removeBudgetAccessLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { removeBudgetAccessLabelMouseClicked(evt); } }); addBudgetAccessLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Images/add1.png"))); // NOI18N addBudgetAccessLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addBudgetAccessLabelMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(headerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(membersLabel) .addGap(227, 227, 227) .addComponent(tasksLabel)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(memberScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(addMemberLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeMemberLabel))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(addBudgetAccessLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeBudgetAccessLabel)) .addComponent(budgetButton, javax.swing.GroupLayout.Alignment.LEADING))) .addGap(70, 70, 70) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(headLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(headNameLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(taskScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(addTaskLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeTaskLabel))) .addGap(10, 10, 10) .addComponent(taskProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(headerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(headLabel) .addComponent(headNameLabel) .addComponent(budgetButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(addBudgetAccessLabel)) .addComponent(removeBudgetAccessLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(membersLabel) .addComponent(tasksLabel)) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(memberScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(removeMemberLabel) .addComponent(addMemberLabel))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(taskProgressBar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(taskScrollPane, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(removeTaskLabel) .addComponent(addTaskLabel))))) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { committeeChangeButton = new javax.swing.JButton(); removeTaskButton = new javax.swing.JButton(); addTaskButton = new javax.swing.JButton(); removeMemberButton = new javax.swing.JButton(); addMemberButton = new javax.swing.JButton(); addToBudgetButton = new javax.swing.JButton(); removeMemberFromBudgetButton = new javax.swing.JButton(); headerLabel = new javax.swing.JLabel(); memberScrollPane = new javax.swing.JScrollPane(); memberList = new javax.swing.JList(); membersLabel = new javax.swing.JLabel(); headLabel = new javax.swing.JLabel(); headNameLabel = new javax.swing.JLabel(); taskScrollPane = new javax.swing.JScrollPane(); taskList = new javax.swing.JList(); tasksLabel = new javax.swing.JLabel(); taskProgressBar = new javax.swing.JProgressBar(); budgetButton = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); addMemberLabel = new javax.swing.JLabel(); removeMemberLabel = new javax.swing.JLabel(); addTaskLabel = new javax.swing.JLabel(); removeTaskLabel = new javax.swing.JLabel(); removeBudgetAccessLabel = new javax.swing.JLabel(); addBudgetAccessLabel = new javax.swing.JLabel(); committeeChangeButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N committeeChangeButton.setText("change"); committeeChangeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { committeeChangeButtonActionPerformed(evt); } }); removeTaskButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N removeTaskButton.setText("-"); removeTaskButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeTaskButtonActionPerformed(evt); } }); addTaskButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N addTaskButton.setText("+"); addTaskButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addTaskButtonActionPerformed(evt); } }); removeMemberButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N removeMemberButton.setText("-"); removeMemberButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeMemberButtonActionPerformed(evt); } }); addMemberButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N addMemberButton.setText("+"); addMemberButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addMemberButtonActionPerformed(evt); } }); addToBudgetButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N addToBudgetButton.setText("+"); addToBudgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addToBudgetButtonActionPerformed(evt); } }); removeMemberFromBudgetButton.setText("-"); removeMemberFromBudgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeMemberFromBudgetButtonActionPerformed(evt); } }); setBackground(new java.awt.Color(153, 204, 255)); setMinimumSize(new java.awt.Dimension(387, 327)); headerLabel.setFont(new java.awt.Font("Candara", 1, 24)); // NOI18N headerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); headerLabel.setText("Committee Name"); headerLabel.setPreferredSize(new java.awt.Dimension(200, 25)); memberList.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N memberList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); memberList.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { memberListValueChanged(evt); } }); memberScrollPane.setViewportView(memberList); membersLabel.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N membersLabel.setText("Members"); headLabel.setFont(new java.awt.Font("Candara", 1, 18)); // NOI18N headLabel.setText("Head: "); headNameLabel.setFont(new java.awt.Font("Candara", 1, 16)); // NOI18N headNameLabel.setText("committee head"); taskList.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N taskList.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); taskList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { taskListMouseClicked(evt); } }); taskScrollPane.setViewportView(taskList); tasksLabel.setFont(new java.awt.Font("Candara", 0, 12)); // NOI18N tasksLabel.setText("Tasks"); taskProgressBar.setOrientation(1); budgetButton.setFont(new java.awt.Font("Candara", 0, 11)); // NOI18N budgetButton.setText("View Budget"); budgetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { budgetButtonActionPerformed(evt); } }); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\edit1.png")); // NOI18N jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); addMemberLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\add1.png")); // NOI18N addMemberLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addMemberLabelMouseClicked(evt); } }); removeMemberLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\remove1.png")); // NOI18N removeMemberLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { removeMemberLabelMouseClicked(evt); } }); addTaskLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\add1.png")); // NOI18N addTaskLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addTaskLabelMouseClicked(evt); } }); removeTaskLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\remove1.png")); // NOI18N removeTaskLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { removeTaskLabelMouseClicked(evt); } }); removeBudgetAccessLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\remove1.png")); // NOI18N removeBudgetAccessLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { removeBudgetAccessLabelMouseClicked(evt); } }); addBudgetAccessLabel.setIcon(new javax.swing.ImageIcon("C:\\Users\\Sid\\Documents\\GitHub\\EMS\\EventManagmentSystem\\add1.png")); // NOI18N addBudgetAccessLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { addBudgetAccessLabelMouseClicked(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(headerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(membersLabel) .addGap(227, 227, 227) .addComponent(tasksLabel)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(memberScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(addMemberLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeMemberLabel))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(addBudgetAccessLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeBudgetAccessLabel)) .addComponent(budgetButton, javax.swing.GroupLayout.Alignment.LEADING))) .addGap(70, 70, 70) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(headLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(headNameLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(taskScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(addTaskLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeTaskLabel))) .addGap(10, 10, 10) .addComponent(taskProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(headerLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(headLabel) .addComponent(headNameLabel) .addComponent(budgetButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(addBudgetAccessLabel)) .addComponent(removeBudgetAccessLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(membersLabel) .addComponent(tasksLabel)) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(memberScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(removeMemberLabel) .addComponent(addMemberLabel))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(taskProgressBar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(taskScrollPane, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(removeTaskLabel) .addComponent(addTaskLabel))))) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/Compiler/JoosPrograms/SyntacticallyValidPrograms/ArithmeticOperations.java b/Compiler/JoosPrograms/SyntacticallyValidPrograms/ArithmeticOperations.java index dc2184a4..731d3667 100644 --- a/Compiler/JoosPrograms/SyntacticallyValidPrograms/ArithmeticOperations.java +++ b/Compiler/JoosPrograms/SyntacticallyValidPrograms/ArithmeticOperations.java @@ -1,7 +1,6 @@ public class ArithmeticOperations { public ArithmeticOperations() {} public int m(int x) { - int x = +1; return -2*x+87%x-(x/7); } }
true
true
public int m(int x) { int x = +1; return -2*x+87%x-(x/7); }
public int m(int x) { return -2*x+87%x-(x/7); }
diff --git a/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/config/TestConfiguration.java b/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/config/TestConfiguration.java index 9b1018976..1d8387f3b 100644 --- a/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/config/TestConfiguration.java +++ b/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/config/TestConfiguration.java @@ -1,135 +1,135 @@ package org.jboss.tools.ui.bot.ext.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import org.apache.log4j.Logger; import org.jboss.tools.ui.bot.ext.Activator; import org.jboss.tools.ui.bot.ext.SWTTestExt; import org.jboss.tools.ui.bot.ext.config.TestConfigurator.Keys; import org.jboss.tools.ui.bot.ext.config.TestConfigurator.Values; public class TestConfiguration { private static final Logger log = Logger.getLogger(TestConfiguration.class); private Properties swtTestProperties = new Properties(); public String getProperty(String key) { return swtTestProperties.getProperty(key); } private final String propName; private final String propFile; private ServerBean server; private SeamBean seam; private ESBBean esb; private JavaBean java; public TestConfiguration(String propName, String propFile) throws Exception { this.propName = propName; this.propFile = propFile; if (!"".equals(propFile)) { if (new File(propFile).exists()) { log.info("Loading configuration file '" + propFile + "'"); swtTestProperties.load(new FileInputStream(propFile)); } else { throw new IOException(propName + " " + propFile + " does not exist!"); } } else { log.info("Loading default configuration"); swtTestProperties.load(new FileInputStream(SWTTestExt.util .getResourceFile(Activator.PLUGIN_ID, "/SWTBotTest-default.properties"))); } // properties got loaded java = JavaBean.fromString(getProperty(Keys.JAVA)); printConfig(Keys.JAVA, java); server = ServerBean.fromString(getProperty(Keys.SERVER)); printConfig(Keys.SERVER, server); seam = SeamBean.fromString(getProperty(Keys.SEAM)); printConfig(Keys.SEAM, seam); esb = ESBBean.fromString(getProperty(Keys.ESB)); printConfig(Keys.ESB, esb); checkConfig(); } private static void printConfig(String propName, Object bean) { if (bean == null) { log.info("Property " + propName + " not found, " + propName + " not configured"); } else { log.info("Configured " + bean.toString()); } } private boolean checkConfig() throws Exception { if (java != null) checkDirExists(java.javaHome); if (seam != null) checkDirExists(seam.seamHome); if (server != null) checkDirExists(server.runtimeHome); if (esb != null) checkDirExists(esb.esbHome); // special checks capturing dependency of server on java if (java == null && server != null && !server.withJavaVersion .equals(Values.SERVER_WITH_DEFAULT_JAVA)) { throw new Exception( "Server is configured to run with java version=" + server.withJavaVersion + " but no JAVA is configured"); } - if (java != null) { + if (java != null && server!=null) { if (!java.version.equals(server.withJavaVersion) && !Values.SERVER_WITH_DEFAULT_JAVA .equals(server.withJavaVersion)) { throw new Exception( "Server is configured to run with java version=" + server.withJavaVersion + " but JAVA is configured with " + java.version); } } return true; } private static void checkDirExists(String dir) throws FileNotFoundException { if (!new File(dir).exists() || !new File(dir).isDirectory()) { throw new FileNotFoundException("File '" + dir + "' does not exist or is not directory"); } } public ESBBean getEsb() { return esb; } public SeamBean getSeam() { return seam; } public ServerBean getServer() { return server; } public JavaBean getJava() { return java; } public String getPropFile() { return propFile; } public String getPropName() { return propName; } }
true
true
private boolean checkConfig() throws Exception { if (java != null) checkDirExists(java.javaHome); if (seam != null) checkDirExists(seam.seamHome); if (server != null) checkDirExists(server.runtimeHome); if (esb != null) checkDirExists(esb.esbHome); // special checks capturing dependency of server on java if (java == null && server != null && !server.withJavaVersion .equals(Values.SERVER_WITH_DEFAULT_JAVA)) { throw new Exception( "Server is configured to run with java version=" + server.withJavaVersion + " but no JAVA is configured"); } if (java != null) { if (!java.version.equals(server.withJavaVersion) && !Values.SERVER_WITH_DEFAULT_JAVA .equals(server.withJavaVersion)) { throw new Exception( "Server is configured to run with java version=" + server.withJavaVersion + " but JAVA is configured with " + java.version); } } return true; }
private boolean checkConfig() throws Exception { if (java != null) checkDirExists(java.javaHome); if (seam != null) checkDirExists(seam.seamHome); if (server != null) checkDirExists(server.runtimeHome); if (esb != null) checkDirExists(esb.esbHome); // special checks capturing dependency of server on java if (java == null && server != null && !server.withJavaVersion .equals(Values.SERVER_WITH_DEFAULT_JAVA)) { throw new Exception( "Server is configured to run with java version=" + server.withJavaVersion + " but no JAVA is configured"); } if (java != null && server!=null) { if (!java.version.equals(server.withJavaVersion) && !Values.SERVER_WITH_DEFAULT_JAVA .equals(server.withJavaVersion)) { throw new Exception( "Server is configured to run with java version=" + server.withJavaVersion + " but JAVA is configured with " + java.version); } } return true; }
diff --git a/bundles/org.eclipse.orion.server.search/src/org/eclipse/orion/internal/server/search/SearchServlet.java b/bundles/org.eclipse.orion.server.search/src/org/eclipse/orion/internal/server/search/SearchServlet.java index 609abad2..12f8f25f 100644 --- a/bundles/org.eclipse.orion.server.search/src/org/eclipse/orion/internal/server/search/SearchServlet.java +++ b/bundles/org.eclipse.orion.server.search/src/org/eclipse/orion/internal/server/search/SearchServlet.java @@ -1,150 +1,156 @@ /******************************************************************************* * Copyright (c) 2011, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.orion.internal.server.search; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.core.SolrCore; import org.apache.solr.request.*; import org.eclipse.orion.internal.server.servlets.ProtocolConstants; import org.eclipse.orion.server.core.LogHelper; import org.eclipse.orion.server.servlets.OrionServlet; /** * Servlet for performing searches against files in the workspace. */ public class SearchServlet extends OrionServlet { private static final long serialVersionUID = 1L; private static final String FIELD_NAMES = "Id,Name,NameLower,Length,Directory,LastModified,Location,Path"; //$NON-NLS-1$ private static final List<String> FIELD_LIST = Arrays.asList(FIELD_NAMES.split(",")); //$NON-NLS-1$ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { traceRequest(req); SolrQuery query = buildSolrQuery(req); try { QueryResponse solrResponse = SearchActivator.getInstance().getSolrServer().query(query); writeResponse(query, req, resp, solrResponse); } catch (SolrServerException e) { LogHelper.log(e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } private SolrQuery buildSolrQuery(HttpServletRequest req) { SolrQuery query = new SolrQuery(); query.setParam(CommonParams.WT, "json"); //$NON-NLS-1$ query.setParam(CommonParams.FL, FIELD_NAMES); String queryString = req.getParameter(CommonParams.Q).trim(); if (queryString.length() > 0) { String processedQuery = ""; //$NON-NLS-1$ //divide into search terms delimited by space character String[] terms = queryString.split("\\s+"); //$NON-NLS-1$ for (String term : terms) { if (term.length() == 0) continue; if (isSearchField(term)) { - //field searches are always case sensitive - processedQuery += term; + //solr does not lowercase queries containing wildcards + //https://issues.apache.org/jira/browse/SOLR-219 + if (term.startsWith("NameLower:")) { + processedQuery += "NameLower:" + term.substring(10).toLowerCase(); + } else { + //all other field searches are case sensitive + processedQuery += term; + } } else { //solr does not lowercase queries containing wildcards //see https://bugs.eclipse.org/bugs/show_bug.cgi?id=359766 String processedTerm = term.toLowerCase(); //add leading and trailing wildcards to match word segments if (processedTerm.charAt(0) != '*') processedTerm = '*' + processedTerm; if (processedTerm.charAt(processedTerm.length() - 1) != '*') processedTerm += '*'; processedQuery += processedTerm; } processedQuery += " AND "; //$NON-NLS-1$ } queryString = processedQuery; } queryString += ProtocolConstants.KEY_USER_NAME + ':' + ClientUtils.escapeQueryChars(req.getRemoteUser()); query.setQuery(queryString); //other common fields setField(req, query, CommonParams.ROWS); setField(req, query, CommonParams.START); setField(req, query, CommonParams.SORT); return query; } /** * Returns whether the search term is against a particular field rather than the default field * (search on name, location, etc). */ private boolean isSearchField(String term) { for (String field : FIELD_LIST) { if (term.startsWith(field + ":")) //$NON-NLS-1$ return true; } return false; } private void setField(HttpServletRequest req, SolrQuery query, String parameter) { String value = req.getParameter(parameter); if (value != null) query.set(parameter, value); } /** * Writes the response to the search query to the HTTP response's output stream. */ private void writeResponse(SolrQuery query, HttpServletRequest httpRequest, HttpServletResponse httpResponse, QueryResponse queryResponse) throws IOException { SolrCore core = SearchActivator.getInstance().getSolrCore(); //this seems to be the only way to obtain the JSON response representation SolrQueryRequest solrRequest = new LocalSolrQueryRequest(core, query.toNamedList()); SolrQueryResponse solrResponse = new SolrQueryResponse(); //bash the query in the response to remove user info NamedList<Object> params = (NamedList<Object>) queryResponse.getHeader().get("params"); //$NON-NLS-1$ params.remove(CommonParams.Q); params.add(CommonParams.Q, httpRequest.getParameter(CommonParams.Q)); NamedList<Object> values = queryResponse.getResponse(); String contextPath = httpRequest.getContextPath(); if (contextPath.length() > 0) setSearchResultContext(values, contextPath); solrResponse.setAllValues(values); QueryResponseWriter writer = core.getQueryResponseWriter("json"); //$NON-NLS-1$ writer.write(httpResponse.getWriter(), solrRequest, solrResponse); } /** * Prepend the server context path to the location of search result documents. */ private void setSearchResultContext(NamedList<Object> values, String contextPath) { //find the search result documents in the search response SolrDocumentList documents = (SolrDocumentList) values.get("response"); //$NON-NLS-1$ if (documents == null) return; for (SolrDocument doc : documents) { String location = (String) doc.getFieldValue(ProtocolConstants.KEY_LOCATION); if (location != null) { //prepend the context path and update the document location = contextPath + location; doc.setField(ProtocolConstants.KEY_LOCATION, location); } } } }
true
true
private SolrQuery buildSolrQuery(HttpServletRequest req) { SolrQuery query = new SolrQuery(); query.setParam(CommonParams.WT, "json"); //$NON-NLS-1$ query.setParam(CommonParams.FL, FIELD_NAMES); String queryString = req.getParameter(CommonParams.Q).trim(); if (queryString.length() > 0) { String processedQuery = ""; //$NON-NLS-1$ //divide into search terms delimited by space character String[] terms = queryString.split("\\s+"); //$NON-NLS-1$ for (String term : terms) { if (term.length() == 0) continue; if (isSearchField(term)) { //field searches are always case sensitive processedQuery += term; } else { //solr does not lowercase queries containing wildcards //see https://bugs.eclipse.org/bugs/show_bug.cgi?id=359766 String processedTerm = term.toLowerCase(); //add leading and trailing wildcards to match word segments if (processedTerm.charAt(0) != '*') processedTerm = '*' + processedTerm; if (processedTerm.charAt(processedTerm.length() - 1) != '*') processedTerm += '*'; processedQuery += processedTerm; } processedQuery += " AND "; //$NON-NLS-1$ } queryString = processedQuery; } queryString += ProtocolConstants.KEY_USER_NAME + ':' + ClientUtils.escapeQueryChars(req.getRemoteUser()); query.setQuery(queryString); //other common fields setField(req, query, CommonParams.ROWS); setField(req, query, CommonParams.START); setField(req, query, CommonParams.SORT); return query; }
private SolrQuery buildSolrQuery(HttpServletRequest req) { SolrQuery query = new SolrQuery(); query.setParam(CommonParams.WT, "json"); //$NON-NLS-1$ query.setParam(CommonParams.FL, FIELD_NAMES); String queryString = req.getParameter(CommonParams.Q).trim(); if (queryString.length() > 0) { String processedQuery = ""; //$NON-NLS-1$ //divide into search terms delimited by space character String[] terms = queryString.split("\\s+"); //$NON-NLS-1$ for (String term : terms) { if (term.length() == 0) continue; if (isSearchField(term)) { //solr does not lowercase queries containing wildcards //https://issues.apache.org/jira/browse/SOLR-219 if (term.startsWith("NameLower:")) { processedQuery += "NameLower:" + term.substring(10).toLowerCase(); } else { //all other field searches are case sensitive processedQuery += term; } } else { //solr does not lowercase queries containing wildcards //see https://bugs.eclipse.org/bugs/show_bug.cgi?id=359766 String processedTerm = term.toLowerCase(); //add leading and trailing wildcards to match word segments if (processedTerm.charAt(0) != '*') processedTerm = '*' + processedTerm; if (processedTerm.charAt(processedTerm.length() - 1) != '*') processedTerm += '*'; processedQuery += processedTerm; } processedQuery += " AND "; //$NON-NLS-1$ } queryString = processedQuery; } queryString += ProtocolConstants.KEY_USER_NAME + ':' + ClientUtils.escapeQueryChars(req.getRemoteUser()); query.setQuery(queryString); //other common fields setField(req, query, CommonParams.ROWS); setField(req, query, CommonParams.START); setField(req, query, CommonParams.SORT); return query; }
diff --git a/src/main/java/org/Barteks2x/b173gen/generator/ChunkProviderGenerate.java b/src/main/java/org/Barteks2x/b173gen/generator/ChunkProviderGenerate.java index 10bf311..fc73a3d 100644 --- a/src/main/java/org/Barteks2x/b173gen/generator/ChunkProviderGenerate.java +++ b/src/main/java/org/Barteks2x/b173gen/generator/ChunkProviderGenerate.java @@ -1,816 +1,829 @@ package org.Barteks2x.b173gen.generator; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.logging.Level; import net.minecraft.server.v1_5_R3.*; import org.Barteks2x.b173gen.generator.beta173.*; import org.Barteks2x.b173gen.plugin.Generator; import org.Barteks2x.b173gen.config.WorldConfig; import org.bukkit.generator.ChunkGenerator; import static net.minecraft.server.v1_5_R3.Block.*; public class ChunkProviderGenerate extends ChunkGenerator implements IChunkProvider { private Random rand; private NoiseGeneratorOctavesOld noiseOctaves1; private NoiseGeneratorOctavesOld noiseOctaves2; private NoiseGeneratorOctavesOld noiseOctaves3; private NoiseGeneratorOctavesOld noiseOctaves4; private NoiseGeneratorOctavesOld noiseOctaves5; private NoiseGeneratorOctavesOld noiseOctaves6; private NoiseGeneratorOctavesOld noiseOctaves7; private NoiseGeneratorOctavesOld mobSpawnerNoise; private double noise[]; private double sandNoise[] = new double[256]; private double gravelNoise[] = new double[256]; private double stoneNoise[] = new double[256]; private WorldGenBase caves; private BiomeBase[] biomes; private double d[]; private double e[]; private double f[]; private double g[]; private double h[]; private int i[][] = new int[32][32]; private float[] temperatures; private WorldChunkManagerOld wcm; private List<org.bukkit.generator.BlockPopulator> populatorList; private World world; private WorldConfig config; private Generator plugin; private WorldGenerator dungeonGen, dirtGen, gravelGen, coalGen, ironGen, goldGen, redstoneGen, diamondGen, emeraldGen, lapisGen, yellowFlowerGen, longGrassGen1, longGrassGen2, deadBushGen, redFlowerGen, brownMushroomGen, redMushroomGen, reedGen, pumpkinGen, cactusGen, liquidWaterGen, liquidLavaGen, clayGen, waterLakeGen, lavaLakeGen; private WorldGenCanyon canyonGen; private WorldGenStronghold strongholdGen; private WorldGenMineshaft mineshaftGen; private WorldGenVillage villageGen; //desert temples private WorldGenLargeFeature largeFeatureGen; private boolean isInit = false; @Override public List<org.bukkit.generator.BlockPopulator> getDefaultPopulators(org.bukkit.World w) { plugin.initWorld(w); return populatorList; } public void init(World workWorld, WorldChunkManagerOld wcm, long seed) { isInit = true; world = workWorld; this.wcm = wcm; rand = new Random(seed); noiseOctaves1 = new NoiseGeneratorOctavesOld(rand, 16); noiseOctaves2 = new NoiseGeneratorOctavesOld(rand, 16); noiseOctaves3 = new NoiseGeneratorOctavesOld(rand, 8); noiseOctaves4 = new NoiseGeneratorOctavesOld(rand, 4); noiseOctaves5 = new NoiseGeneratorOctavesOld(rand, 4); noiseOctaves6 = new NoiseGeneratorOctavesOld(rand, 10); noiseOctaves7 = new NoiseGeneratorOctavesOld(rand, 16); mobSpawnerNoise = new NoiseGeneratorOctavesOld(rand, 8); i = new int[32][32]; clayGen = config.newClayGen ? new WorldGenClay(32) : new WorldGenClayOld(32); waterLakeGen = config.newLakeGen ? new WorldGenLakes(WATER.id) : new WorldGenLakesOld(WATER.id); lavaLakeGen = config.newLakeGen ? new WorldGenLakes(LAVA.id) : new WorldGenLakesOld(LAVA.id); caves = config.newCaveGen ? new WorldGenCaves() : new WorldGenCavesOld(); dungeonGen = new WorldGenDungeons(); dirtGen = new WorldGenMinable(DIRT.id, 32); gravelGen = new WorldGenMinable(GRAVEL.id, 32); coalGen = new WorldGenMinable(COAL_ORE.id, 16); ironGen = new WorldGenMinable(IRON_ORE.id, 8); goldGen = new WorldGenMinable(GOLD_ORE.id, 8); redstoneGen = new WorldGenMinable(REDSTONE_ORE.id, 7); diamondGen = new WorldGenMinable(DIAMOND_ORE.id, 7); lapisGen = new WorldGenMinable(LAPIS_ORE.id, 6); yellowFlowerGen = new WorldGenFlowers(YELLOW_FLOWER.id); longGrassGen1 = new WorldGenGrass(LONG_GRASS.id, 1); longGrassGen2 = new WorldGenGrass(LONG_GRASS.id, 2); deadBushGen = new WorldGenDeadBush(DEAD_BUSH.id); redFlowerGen = new WorldGenFlowers(RED_ROSE.id); brownMushroomGen = new WorldGenFlowers(BROWN_MUSHROOM.id); redMushroomGen = new WorldGenFlowers(RED_MUSHROOM.id); reedGen = new WorldGenReed(); pumpkinGen = new WorldGenPumpkin(); cactusGen = new WorldGenCactus(); liquidWaterGen = new WorldGenLiquids(WATER.id); liquidLavaGen = new WorldGenLiquids(LAVA.id); workWorld.worldData.setType(WorldType.FLAT); canyonGen = config.generateCanyons ? new WorldGenCanyon() : null; strongholdGen = config.generateStrongholds ? new WorldGenStronghold() : null; mineshaftGen = config.generateMineshafts ? new WorldGenMineshaft() : null; villageGen = config.generateVillages ? new WorldGenVillage() : null; largeFeatureGen = config.generateTemples ? new WorldGenLargeFeature() : null; emeraldGen = config.generateEmerald ? new WorldGenMinable(EMERALD_ORE.id, 2) : null; } @SuppressWarnings({"unchecked", "rawtypes"}) public ChunkProviderGenerate(WorldConfig config, Generator plugin) { this.plugin = plugin; this.config = config; this.populatorList = new ArrayList(); this.populatorList.add(new BlockPopulator(this)); } public void generateTerrain(int i, int j, byte terrain[], double ad[]) { //plugin.getLogger().log(Level.INFO, "genChunkAt "+i+", "+j); byte byte0 = 4; byte byte1 = 64; int k = byte0 + 1; byte b2 = 17; int l = byte0 + 1; noise = initNoiseField(noise, i * byte0, 0, j * byte0, k, b2, l); for (int i1 = 0; i1 < byte0; i1++) { for (int j1 = 0; j1 < byte0; j1++) { for (int k1 = 0; k1 < 16; k1++) { double d = 0.125D; double d1 = noise[((i1 + 0) * l + (j1 + 0)) * b2 + (k1 + 0)]; double d2 = noise[((i1 + 0) * l + (j1 + 1)) * b2 + (k1 + 0)]; double d3 = noise[((i1 + 1) * l + (j1 + 0)) * b2 + (k1 + 0)]; double d4 = noise[((i1 + 1) * l + (j1 + 1)) * b2 + (k1 + 0)]; double d5 = (noise[((i1 + 0) * l + (j1 + 0)) * b2 + (k1 + 1)] - d1) * d; double d6 = (noise[((i1 + 0) * l + (j1 + 1)) * b2 + (k1 + 1)] - d2) * d; double d7 = (noise[((i1 + 1) * l + (j1 + 0)) * b2 + (k1 + 1)] - d3) * d; double d8 = (noise[((i1 + 1) * l + (j1 + 1)) * b2 + (k1 + 1)] - d4) * d; for (int l1 = 0; l1 < 8; l1++) { double d9 = 0.25D; double d10 = d1; double d11 = d2; double d12 = (d3 - d1) * d9; double d13 = (d4 - d2) * d9; for (int i2 = 0; i2 < 4; i2++) { int blockLoc = i2 + i1 * 4 << 11 | 0 + j1 * 4 << 7 | k1 * 8 + l1; char c = '\200'; double d14 = 0.25D; double d15 = d10; double d16 = (d11 - d10) * d14; for (int k2 = 0; k2 < 4; k2++) { double d17 = ad[(i1 * 4 + i2) * 16 + (j1 * 4 + k2)]; int block = 0; if (k1 * 8 + l1 < byte1) { if (d17 < 0.5D && k1 * 8 + l1 >= byte1 - 1) { block = ICE.id; } else { block = STATIONARY_WATER.id; } } if (d15 > 0.0D) { block = STONE.id; } terrain[blockLoc] = (byte)block; blockLoc += c; d15 += d16; } d10 += d12; d11 += d13; } d1 += d5; d2 += d6; d3 += d7; d4 += d8; } } } } } @Override public byte[] generate(org.bukkit.World w, Random random, int x, int z) { this.rand.setSeed(x * 341873128712L + z * 132897987541L); byte terrain[] = new byte[32768]; biomes = wcm.getBiomeBlock(biomes, x * 16, z * 16, 16, 16); double ad[] = this.wcm.temperature; generateTerrain(x, z, terrain, ad); replaceBlocksForBiome(x, z, terrain, biomes); caves.a(this, world, x, z, terrain); if (canyonGen != null) { canyonGen.a(this, world, x, z, terrain); } if (strongholdGen != null) { strongholdGen.a(this, world, x, z, terrain); } if (mineshaftGen != null) { mineshaftGen.a(this, world, x, z, terrain); } if (villageGen != null) { villageGen.a(this, world, x, z, terrain); } if (largeFeatureGen != null) { largeFeatureGen.a(this, world, x, z, terrain); } return terrain; } public void replaceBlocksForBiome(int i, int j, byte terrainBlockArray[], BiomeBase abiomebase[]) { byte byte0 = 64; double d = 0.03125D; sandNoise = noiseOctaves4. gen(sandNoise, i * 16, j * 16, 0.0D, 16, 16, 1, d, d, 1.0D); gravelNoise = noiseOctaves4. gen(gravelNoise, i * 16, 109.0134D, j * 16, 16, 1, 16, d, 1.0D, d); stoneNoise = noiseOctaves5.gen(stoneNoise, i * 16, j * 16, 0.0D, 16, 16, 1, d * 2D, d * 2D, d * 2D); for (int k = 0; k < 16; k++) { for (int l = 0; l < 16; l++) { BiomeBase biomegenbase = abiomebase[k + l * 16]; boolean randomSand = sandNoise[k + l * 16] + rand.nextDouble() * 0.20000000000000001D > 0.0D; boolean randomGravel = gravelNoise[k + l * 16] + rand.nextDouble() * 0.20000000000000001D > 3D; int i1 = (int)(stoneNoise[k + l * 16] / 3D + 3D + rand.nextDouble() * 0.25D); int j1 = -1; byte topBlock = biomegenbase.A; byte fillerBlock = biomegenbase.B; for (int k1 = 127; k1 >= 0; k1--) { int currentBlockInArrayNum = (l * 16 + k) * 128 + k1; if (k1 <= 0 + rand.nextInt(5)) { terrainBlockArray[currentBlockInArrayNum] = (byte)BEDROCK.id; continue; } byte currentBlock = terrainBlockArray[currentBlockInArrayNum]; if (currentBlock == 0) { j1 = -1; continue; } if (currentBlock != STONE.id) { continue; } if (j1 == -1) { if (i1 <= 0) { topBlock = 0; fillerBlock = (byte)STONE.id; } else if (k1 >= byte0 - 4 && k1 <= byte0 + 1) { topBlock = biomegenbase.A; fillerBlock = biomegenbase.B; if (randomGravel) { topBlock = 0; } if (randomGravel) { fillerBlock = (byte)GRAVEL.id; } if (randomSand) { topBlock = (byte)SAND.id; } if (randomSand) { fillerBlock = (byte)SAND.id; } } if (k1 < byte0 && topBlock == 0) { topBlock = (byte)STATIONARY_WATER.id; } j1 = i1; if (k1 >= byte0 - 1) { terrainBlockArray[currentBlockInArrayNum] = topBlock; } else { terrainBlockArray[currentBlockInArrayNum] = fillerBlock; } continue; } if (j1 <= 0) { continue; } j1--; terrainBlockArray[currentBlockInArrayNum] = fillerBlock; if (j1 == 0 && fillerBlock == SAND.id) { j1 = rand.nextInt(4); fillerBlock = (byte)SANDSTONE.id; } } } } } public Chunk getChunkAt(int i, int j) { return getOrCreateChunk(i, j); } @SuppressWarnings("cast") public Chunk getOrCreateChunk(int i, int i1) { rand.setSeed((long)i * 0x4f9939f508L + (long)i1 * 0x1ef1565bd5L); byte terrain[] = new byte[32768]; Chunk chunk = new Chunk(world, terrain, i, i1); biomes = this.wcm.getBiomeBlock(biomes, i * 16, i1 * 16, 16, 16); double temp[] = this.wcm.temperature; generateTerrain(i, i1, terrain, temp); replaceBlocksForBiome(i, i1, terrain, biomes); caves.a(this, world, i, i1, terrain); if (canyonGen != null) { canyonGen.a(this, world, i, i1, terrain); } if (strongholdGen != null) { strongholdGen.a(this, world, i, i1, terrain); } if (mineshaftGen != null) { mineshaftGen.a(this, world, i, i1, terrain); } if (villageGen != null) { villageGen.a(this, world, i, i1, terrain); } if (largeFeatureGen != null) { largeFeatureGen.a(this, world, i, i1, terrain); } chunk.initLighting(); return chunk; } public void b() { //TODO ??? } @SuppressWarnings("cast") private double[] initNoiseField(double ad[], int i, int j, int k, int l, int i1, int j1) { if (ad == null) { ad = new double[l * i1 * j1]; } double d = 684.41200000000003D; double d1 = 684.41200000000003D; double ad1[] = this.wcm.temperature; double ad2[] = this.wcm.rain; g = noiseOctaves6.func_4109_a(g, i, k, l, j1, 1.121D, 1.121D, 0.5D); h = noiseOctaves7.func_4109_a(h, i, k, l, j1, 200D, 200D, 0.5D); this.d = noiseOctaves3.gen(this.d, i, j, k, l, i1, j1, d / 80D, d1 / 160D, d / 80D); e = noiseOctaves1.gen(e, i, j, k, l, i1, j1, d, d1, d); f = noiseOctaves2.gen(f, i, j, k, l, i1, j1, d, d1, d); int k1 = 0; int l1 = 0; int i2 = 16 / l; for (int j2 = 0; j2 < l; j2++) { int k2 = j2 * i2 + i2 / 2; for (int l2 = 0; l2 < j1; l2++) { int i3 = l2 * i2 + i2 / 2; double d2 = ad1[k2 * 16 + i3]; double d3 = ad2[k2 * 16 + i3] * d2; double d4 = 1.0D - d3; d4 *= d4; d4 *= d4; d4 = 1.0D - d4; double d5 = (g[l1] + 256D) / 512D; d5 *= d4; if (d5 > 1.0D) { d5 = 1.0D; } double d6 = h[l1] / 8000D; if (d6 < 0.0D) { d6 = -d6 * 0.29999999999999999D; } d6 = d6 * 3D - 2D; if (d6 < 0.0D) { d6 /= 2D; if (d6 < -1D) { d6 = -1D; } d6 /= 1.3999999999999999D; d6 /= 2D; d5 = 0.0D; } else { if (d6 > 1.0D) { d6 = 1.0D; } d6 /= 8D; } if (d5 < 0.0D) { d5 = 0.0D; } d5 += 0.5D; d6 = (d6 * (double)i1) / 16D; double d7 = (double)i1 / 2D + d6 * 4D; l1++; for (int j3 = 0; j3 < i1; j3++) { double d8 = 0.0D; double d9 = (((double)j3 - d7) * 12D) / d5; if (d9 < 0.0D) { d9 *= 4D; } double d10 = e[k1] / 512D; double d11 = f[k1] / 512D; double d12 = (this.d[k1] / 10D + 1.0D) / 2D; if (d12 < 0.0D) { d8 = d10; } else if (d12 > 1.0D) { d8 = d11; } else { d8 = d10 + (d11 - d10) * d12; } d8 -= d9; if (j3 > i1 - 4) { double d13 = (float)(j3 - (i1 - 4)) / 3F; d8 = d8 * (1.0D - d13) + -10D * d13; } ad[k1] = d8; k1++; } } } return ad; } @SuppressWarnings("cast") public void getChunkAt(IChunkProvider chunkprovider, int i, int j) { BlockSand.instaFall = true; int k = i * 16; int l = j * 16; BiomeGenBase biome = this.wcm.getBiome(k + 16, l + 16); rand.setSeed(world.getSeed()); long l1 = (rand.nextLong() / 2L) * 2L + 1L; long l2 = (rand.nextLong() / 2L) * 2L + 1L; rand.setSeed((long)i * l1 + (long)j * l2 ^ world.getSeed()); double d = 0.25D; - if (rand.nextInt(4) == 0) { + boolean villageFlag = false; + if(this.mineshaftGen!=null){ + this.mineshaftGen.a(world, rand, i, j); + } + if(this.villageGen!=null){ + villageFlag = this.villageGen.a(world, rand, i, j); + } + if(this.strongholdGen!=null){ + this.strongholdGen.a(world, rand, i, j); + } + if(this.largeFeatureGen!=null){ + this.largeFeatureGen.a(world, rand, i, j); + } + if (!villageFlag && rand.nextInt(4) == 0) { int i1 = k + rand.nextInt(16) + 8; int l4 = rand.nextInt(128); int i8 = l + rand.nextInt(16) + 8; waterLakeGen.a(world, rand, i1, l4, i8); } - if (rand.nextInt(8) == 0) { + if (!villageFlag && rand.nextInt(8) == 0) { int j1 = k + rand.nextInt(16) + 8; int i5 = rand.nextInt(rand.nextInt(120) + 8); int j8 = l + rand.nextInt(16) + 8; if (i5 < 64 || rand.nextInt(10) == 0) { lavaLakeGen.a(world, rand, j1, i5, j8); } } for (int k1 = 0; k1 < 8; k1++) { int j5 = k + rand.nextInt(16) + 8; int k8 = rand.nextInt(128); int j11 = l + rand.nextInt(16) + 8; dungeonGen.a(world, rand, j5, k8, j11); } for (int i2 = 0; i2 < 10; i2++) { int k5 = k + rand.nextInt(16); int l8 = rand.nextInt(128); int k11 = l + rand.nextInt(16); clayGen.a(world, rand, k5, l8, k11); } for (int j2 = 0; j2 < 20; j2++) { int l5 = k + rand.nextInt(16); int i9 = rand.nextInt(128); int l11 = l + rand.nextInt(16); dirtGen.a(world, rand, l5, i9, l11); } for (int k2 = 0; k2 < 10; k2++) { int i6 = k + rand.nextInt(16); int j9 = rand.nextInt(128); int i12 = l + rand.nextInt(16); gravelGen.a(world, rand, i6, j9, i12); } for (int i3 = 0; i3 < 20; i3++) { int j6 = k + rand.nextInt(16); int k9 = rand.nextInt(128); int j12 = l + rand.nextInt(16); coalGen.a(world, rand, j6, k9, j12); } for (int j3 = 0; j3 < 20; j3++) { int k6 = k + rand.nextInt(16); int l9 = rand.nextInt(64); int k12 = l + rand.nextInt(16); ironGen.a(world, rand, k6, l9, k12); } for (int k3 = 0; k3 < 2; k3++) { int l6 = k + rand.nextInt(16); int i10 = rand.nextInt(32); int l12 = l + rand.nextInt(16); goldGen.a(world, rand, l6, i10, l12); } for (int l3 = 0; l3 < 8; l3++) { int i7 = k + rand.nextInt(16); int j10 = rand.nextInt(16); int i13 = l + rand.nextInt(16); redstoneGen.a(world, rand, i7, j10, i13); } for (int i4 = 0; i4 < 1; i4++) { int j7 = k + rand.nextInt(16); int k10 = rand.nextInt(16); int j13 = l + rand.nextInt(16); diamondGen.a(world, rand, j7, k10, j13); } for (int j4 = 0; j4 < 1; j4++) { int k7 = k + rand.nextInt(16); int l10 = rand.nextInt(16) + rand.nextInt(16); int k13 = l + rand.nextInt(16); lapisGen.a(world, rand, k7, l10, k13); } d = 0.5D; int k4 = (int)((mobSpawnerNoise.a((double)k * d, (double)l * d) / 8D + rand.nextDouble() * 4D + 4D) / 3D); int l7 = 0; if (rand.nextInt(10) == 0) { l7++; } if (biome == BiomeGenBase.forest) { l7 += k4 + 5; } if (biome == BiomeGenBase.rainforest) { l7 += k4 + 5; } if (biome == BiomeGenBase.seasonalForest) { l7 += k4 + 2; } if (biome == BiomeGenBase.taiga) { l7 += k4 + 5; } if (biome == BiomeGenBase.desert) { l7 -= 20; } if (biome == BiomeGenBase.tundra) { l7 -= 20; } if (biome == BiomeGenBase.plains) { l7 -= 20; } for (int i11 = 0; i11 < l7; i11++) { int l13 = k + rand.nextInt(16) + 8; int j14 = l + rand.nextInt(16) + 8; WorldGenerator worldgenerator = biome.a(rand); worldgenerator.a(1.0D, 1.0D, 1.0D); worldgenerator.a(world, rand, l13, world.getHighestBlockYAt(l13, j14), j14); } byte byte0 = 0; if (biome == BiomeGenBase.forest) { byte0 = 2; } if (biome == BiomeGenBase.seasonalForest) { byte0 = 4; } if (biome == BiomeGenBase.taiga) { byte0 = 2; } if (biome == BiomeGenBase.plains) { byte0 = 3; } for (int i14 = 0; i14 < byte0; i14++) { int k14 = k + rand.nextInt(16) + 8; int l16 = rand.nextInt(128); int k19 = l + rand.nextInt(16) + 8; yellowFlowerGen.a(world, rand, k14, l16, k19); } byte byte1 = 0; if (biome == BiomeGenBase.forest) { byte1 = 2; } if (biome == BiomeGenBase.rainforest) { byte1 = 10; } if (biome == BiomeGenBase.seasonalForest) { byte1 = 2; } if (biome == BiomeGenBase.taiga) { byte1 = 1; } if (biome == BiomeGenBase.plains) { byte1 = 10; } for (int l14 = 0; l14 < byte1; l14++) { boolean flag = (biome == BiomeGenBase.rainforest && rand.nextInt(3) != 0); int l19 = k + rand.nextInt(16) + 8; int k22 = rand.nextInt(128); int j24 = l + rand.nextInt(16) + 8; if (flag) { longGrassGen2.a(world, rand, l19, k22, j24); } else { longGrassGen1.a(world, rand, l19, k22, j24); } } byte1 = 0; if (biome == BiomeGenBase.desert) { byte1 = 2; } for (int i15 = 0; i15 < byte1; i15++) { int i17 = k + rand.nextInt(16) + 8; int i20 = rand.nextInt(128); int l22 = l + rand.nextInt(16) + 8; deadBushGen.a(world, rand, i17, i20, l22); } if (rand.nextInt(2) == 0) { int j15 = k + rand.nextInt(16) + 8; int j17 = rand.nextInt(128); int j20 = l + rand.nextInt(16) + 8; redFlowerGen.a(world, rand, j15, j17, j20); } if (rand.nextInt(4) == 0) { int k15 = k + rand.nextInt(16) + 8; int k17 = rand.nextInt(128); int k20 = l + rand.nextInt(16) + 8; brownMushroomGen.a(world, rand, k15, k17, k20); } if (rand.nextInt(8) == 0) { int l15 = k + rand.nextInt(16) + 8; int l17 = rand.nextInt(128); int l20 = l + rand.nextInt(16) + 8; redMushroomGen.a(world, rand, l15, l17, l20); } for (int i16 = 0; i16 < 10; i16++) { int i18 = k + rand.nextInt(16) + 8; int i21 = rand.nextInt(128); int i23 = l + rand.nextInt(16) + 8; reedGen.a(world, rand, i18, i21, i23); } if (rand.nextInt(32) == 0) { int j16 = k + rand.nextInt(16) + 8; int j18 = rand.nextInt(128); int j21 = l + rand.nextInt(16) + 8; pumpkinGen.a(world, rand, j16, j18, j21); } int k16 = 0; if (biome == BiomeGenBase.desert) { k16 += 10; } for (int k18 = 0; k18 < k16; k18++) { int k21 = k + rand.nextInt(16) + 8; int j23 = rand.nextInt(128); int k24 = l + rand.nextInt(16) + 8; cactusGen.a(world, rand, k21, j23, k24); } for (int l18 = 0; l18 < 50; l18++) { int l21 = k + rand.nextInt(16) + 8; int k23 = rand.nextInt(rand.nextInt(120) + 8); int l24 = l + rand.nextInt(16) + 8; liquidWaterGen.a(world, rand, l21, k23, l24); } for (int i19 = 0; i19 < 20; i19++) { int i22 = k + rand.nextInt(16) + 8; int l23 = rand.nextInt(rand.nextInt(rand.nextInt(112) + 8) + 8); int i25 = l + rand.nextInt(16) + 8; liquidLavaGen.a(world, rand, i22, l23, i25); } temperatures = this.wcm.getTemperatures(temperatures, k + 8, l + 8, 16, 16); for (int j19 = k + 8; j19 < k + 8 + 16; j19++) { for (int j22 = l + 8; j22 < l + 8 + 16; j22++) { int i24 = j19 - (k + 8); int j25 = j22 - (l + 8); int k25 = world.getHighestBlockYAt(j19, j22); double d1 = temperatures[i24 * 16 + j25] - ((double)(k25 - 64) / 64D) * 0.29999999999999999D; Material m = world.getMaterial(j19, k25 - 1, j22); if (d1 < 0.5D && k25 > 0 && k25 < 128 && world. isEmpty(j19, k25, j22) && m.isSolid() && m != Material.ICE) { world.setTypeIdAndData(j19, k25, j22, SNOW.id, 0, 2); } } } if (emeraldGen != null) { for (int j4 = 0; j4 < 5; j4++) { int k7 = k + rand.nextInt(16); int l10 = rand.nextInt(16) + rand.nextInt(16); int k13 = l + rand.nextInt(16); emeraldGen.a(world, rand, k7, l10, k13); } } BlockSand.instaFall = false; } public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) { return true; } public boolean canSave() { return true; } public String makeString() { return this.toString(); } @SuppressWarnings("rawtypes") public List getMobsFor(EnumCreatureType type, int x, int y, int z) { BiomeBase biome = this.wcm.getBiome(x, z); return biome.getMobs(type); } public boolean unloadChunks() { return false; } public boolean isChunkLoaded(int x, int z) { return true; } public ChunkPosition findNearestMapFeature(World world, String type, int x, int y, int z) { return ((("Stronghold".equals(type)) && (this.strongholdGen != null)) ? this.strongholdGen.getNearestGeneratedFeature(world, x, y, z) : null); } public int getLoadedChunks() { return 0; } public String getName() { return plugin.getDescription().getName(); } public void recreateStructures(int arg0, int arg1) { if (strongholdGen != null) { strongholdGen.a(this, world, arg0, arg1, (byte[])null); } if (largeFeatureGen != null) { largeFeatureGen.a(this, world, arg0, arg1, (byte[])null); } } @Override public boolean canSpawn(org.bukkit.World w, int x, int z) { this.plugin.initWorld(w); if (w != null) { int id = w.getHighestBlockAt(x, z).getTypeId(); Material mat; if (id != 0 && (mat = byId[id].material) != null) { return byId[id].material.isSolid(); } else { return false; } } else { return false; } } @Override public String toString(){ return new StringBuilder(plugin.getDescription().getName()).append(" ").append(plugin.getDescription().getVersion()).toString(); } }
false
true
public void getChunkAt(IChunkProvider chunkprovider, int i, int j) { BlockSand.instaFall = true; int k = i * 16; int l = j * 16; BiomeGenBase biome = this.wcm.getBiome(k + 16, l + 16); rand.setSeed(world.getSeed()); long l1 = (rand.nextLong() / 2L) * 2L + 1L; long l2 = (rand.nextLong() / 2L) * 2L + 1L; rand.setSeed((long)i * l1 + (long)j * l2 ^ world.getSeed()); double d = 0.25D; if (rand.nextInt(4) == 0) { int i1 = k + rand.nextInt(16) + 8; int l4 = rand.nextInt(128); int i8 = l + rand.nextInt(16) + 8; waterLakeGen.a(world, rand, i1, l4, i8); } if (rand.nextInt(8) == 0) { int j1 = k + rand.nextInt(16) + 8; int i5 = rand.nextInt(rand.nextInt(120) + 8); int j8 = l + rand.nextInt(16) + 8; if (i5 < 64 || rand.nextInt(10) == 0) { lavaLakeGen.a(world, rand, j1, i5, j8); } } for (int k1 = 0; k1 < 8; k1++) { int j5 = k + rand.nextInt(16) + 8; int k8 = rand.nextInt(128); int j11 = l + rand.nextInt(16) + 8; dungeonGen.a(world, rand, j5, k8, j11); } for (int i2 = 0; i2 < 10; i2++) { int k5 = k + rand.nextInt(16); int l8 = rand.nextInt(128); int k11 = l + rand.nextInt(16); clayGen.a(world, rand, k5, l8, k11); } for (int j2 = 0; j2 < 20; j2++) { int l5 = k + rand.nextInt(16); int i9 = rand.nextInt(128); int l11 = l + rand.nextInt(16); dirtGen.a(world, rand, l5, i9, l11); } for (int k2 = 0; k2 < 10; k2++) { int i6 = k + rand.nextInt(16); int j9 = rand.nextInt(128); int i12 = l + rand.nextInt(16); gravelGen.a(world, rand, i6, j9, i12); } for (int i3 = 0; i3 < 20; i3++) { int j6 = k + rand.nextInt(16); int k9 = rand.nextInt(128); int j12 = l + rand.nextInt(16); coalGen.a(world, rand, j6, k9, j12); } for (int j3 = 0; j3 < 20; j3++) { int k6 = k + rand.nextInt(16); int l9 = rand.nextInt(64); int k12 = l + rand.nextInt(16); ironGen.a(world, rand, k6, l9, k12); } for (int k3 = 0; k3 < 2; k3++) { int l6 = k + rand.nextInt(16); int i10 = rand.nextInt(32); int l12 = l + rand.nextInt(16); goldGen.a(world, rand, l6, i10, l12); } for (int l3 = 0; l3 < 8; l3++) { int i7 = k + rand.nextInt(16); int j10 = rand.nextInt(16); int i13 = l + rand.nextInt(16); redstoneGen.a(world, rand, i7, j10, i13); } for (int i4 = 0; i4 < 1; i4++) { int j7 = k + rand.nextInt(16); int k10 = rand.nextInt(16); int j13 = l + rand.nextInt(16); diamondGen.a(world, rand, j7, k10, j13); } for (int j4 = 0; j4 < 1; j4++) { int k7 = k + rand.nextInt(16); int l10 = rand.nextInt(16) + rand.nextInt(16); int k13 = l + rand.nextInt(16); lapisGen.a(world, rand, k7, l10, k13); } d = 0.5D; int k4 = (int)((mobSpawnerNoise.a((double)k * d, (double)l * d) / 8D + rand.nextDouble() * 4D + 4D) / 3D); int l7 = 0; if (rand.nextInt(10) == 0) { l7++; } if (biome == BiomeGenBase.forest) { l7 += k4 + 5; } if (biome == BiomeGenBase.rainforest) { l7 += k4 + 5; } if (biome == BiomeGenBase.seasonalForest) { l7 += k4 + 2; } if (biome == BiomeGenBase.taiga) { l7 += k4 + 5; } if (biome == BiomeGenBase.desert) { l7 -= 20; } if (biome == BiomeGenBase.tundra) { l7 -= 20; } if (biome == BiomeGenBase.plains) { l7 -= 20; } for (int i11 = 0; i11 < l7; i11++) { int l13 = k + rand.nextInt(16) + 8; int j14 = l + rand.nextInt(16) + 8; WorldGenerator worldgenerator = biome.a(rand); worldgenerator.a(1.0D, 1.0D, 1.0D); worldgenerator.a(world, rand, l13, world.getHighestBlockYAt(l13, j14), j14); } byte byte0 = 0; if (biome == BiomeGenBase.forest) { byte0 = 2; } if (biome == BiomeGenBase.seasonalForest) { byte0 = 4; } if (biome == BiomeGenBase.taiga) { byte0 = 2; } if (biome == BiomeGenBase.plains) { byte0 = 3; } for (int i14 = 0; i14 < byte0; i14++) { int k14 = k + rand.nextInt(16) + 8; int l16 = rand.nextInt(128); int k19 = l + rand.nextInt(16) + 8; yellowFlowerGen.a(world, rand, k14, l16, k19); } byte byte1 = 0; if (biome == BiomeGenBase.forest) { byte1 = 2; } if (biome == BiomeGenBase.rainforest) { byte1 = 10; } if (biome == BiomeGenBase.seasonalForest) { byte1 = 2; } if (biome == BiomeGenBase.taiga) { byte1 = 1; } if (biome == BiomeGenBase.plains) { byte1 = 10; } for (int l14 = 0; l14 < byte1; l14++) { boolean flag = (biome == BiomeGenBase.rainforest && rand.nextInt(3) != 0); int l19 = k + rand.nextInt(16) + 8; int k22 = rand.nextInt(128); int j24 = l + rand.nextInt(16) + 8; if (flag) { longGrassGen2.a(world, rand, l19, k22, j24); } else { longGrassGen1.a(world, rand, l19, k22, j24); } } byte1 = 0; if (biome == BiomeGenBase.desert) { byte1 = 2; } for (int i15 = 0; i15 < byte1; i15++) { int i17 = k + rand.nextInt(16) + 8; int i20 = rand.nextInt(128); int l22 = l + rand.nextInt(16) + 8; deadBushGen.a(world, rand, i17, i20, l22); } if (rand.nextInt(2) == 0) { int j15 = k + rand.nextInt(16) + 8; int j17 = rand.nextInt(128); int j20 = l + rand.nextInt(16) + 8; redFlowerGen.a(world, rand, j15, j17, j20); } if (rand.nextInt(4) == 0) { int k15 = k + rand.nextInt(16) + 8; int k17 = rand.nextInt(128); int k20 = l + rand.nextInt(16) + 8; brownMushroomGen.a(world, rand, k15, k17, k20); } if (rand.nextInt(8) == 0) { int l15 = k + rand.nextInt(16) + 8; int l17 = rand.nextInt(128); int l20 = l + rand.nextInt(16) + 8; redMushroomGen.a(world, rand, l15, l17, l20); } for (int i16 = 0; i16 < 10; i16++) { int i18 = k + rand.nextInt(16) + 8; int i21 = rand.nextInt(128); int i23 = l + rand.nextInt(16) + 8; reedGen.a(world, rand, i18, i21, i23); } if (rand.nextInt(32) == 0) { int j16 = k + rand.nextInt(16) + 8; int j18 = rand.nextInt(128); int j21 = l + rand.nextInt(16) + 8; pumpkinGen.a(world, rand, j16, j18, j21); } int k16 = 0; if (biome == BiomeGenBase.desert) { k16 += 10; } for (int k18 = 0; k18 < k16; k18++) { int k21 = k + rand.nextInt(16) + 8; int j23 = rand.nextInt(128); int k24 = l + rand.nextInt(16) + 8; cactusGen.a(world, rand, k21, j23, k24); } for (int l18 = 0; l18 < 50; l18++) { int l21 = k + rand.nextInt(16) + 8; int k23 = rand.nextInt(rand.nextInt(120) + 8); int l24 = l + rand.nextInt(16) + 8; liquidWaterGen.a(world, rand, l21, k23, l24); } for (int i19 = 0; i19 < 20; i19++) { int i22 = k + rand.nextInt(16) + 8; int l23 = rand.nextInt(rand.nextInt(rand.nextInt(112) + 8) + 8); int i25 = l + rand.nextInt(16) + 8; liquidLavaGen.a(world, rand, i22, l23, i25); } temperatures = this.wcm.getTemperatures(temperatures, k + 8, l + 8, 16, 16); for (int j19 = k + 8; j19 < k + 8 + 16; j19++) { for (int j22 = l + 8; j22 < l + 8 + 16; j22++) { int i24 = j19 - (k + 8); int j25 = j22 - (l + 8); int k25 = world.getHighestBlockYAt(j19, j22); double d1 = temperatures[i24 * 16 + j25] - ((double)(k25 - 64) / 64D) * 0.29999999999999999D; Material m = world.getMaterial(j19, k25 - 1, j22); if (d1 < 0.5D && k25 > 0 && k25 < 128 && world. isEmpty(j19, k25, j22) && m.isSolid() && m != Material.ICE) { world.setTypeIdAndData(j19, k25, j22, SNOW.id, 0, 2); } } } if (emeraldGen != null) { for (int j4 = 0; j4 < 5; j4++) { int k7 = k + rand.nextInt(16); int l10 = rand.nextInt(16) + rand.nextInt(16); int k13 = l + rand.nextInt(16); emeraldGen.a(world, rand, k7, l10, k13); } } BlockSand.instaFall = false; }
public void getChunkAt(IChunkProvider chunkprovider, int i, int j) { BlockSand.instaFall = true; int k = i * 16; int l = j * 16; BiomeGenBase biome = this.wcm.getBiome(k + 16, l + 16); rand.setSeed(world.getSeed()); long l1 = (rand.nextLong() / 2L) * 2L + 1L; long l2 = (rand.nextLong() / 2L) * 2L + 1L; rand.setSeed((long)i * l1 + (long)j * l2 ^ world.getSeed()); double d = 0.25D; boolean villageFlag = false; if(this.mineshaftGen!=null){ this.mineshaftGen.a(world, rand, i, j); } if(this.villageGen!=null){ villageFlag = this.villageGen.a(world, rand, i, j); } if(this.strongholdGen!=null){ this.strongholdGen.a(world, rand, i, j); } if(this.largeFeatureGen!=null){ this.largeFeatureGen.a(world, rand, i, j); } if (!villageFlag && rand.nextInt(4) == 0) { int i1 = k + rand.nextInt(16) + 8; int l4 = rand.nextInt(128); int i8 = l + rand.nextInt(16) + 8; waterLakeGen.a(world, rand, i1, l4, i8); } if (!villageFlag && rand.nextInt(8) == 0) { int j1 = k + rand.nextInt(16) + 8; int i5 = rand.nextInt(rand.nextInt(120) + 8); int j8 = l + rand.nextInt(16) + 8; if (i5 < 64 || rand.nextInt(10) == 0) { lavaLakeGen.a(world, rand, j1, i5, j8); } } for (int k1 = 0; k1 < 8; k1++) { int j5 = k + rand.nextInt(16) + 8; int k8 = rand.nextInt(128); int j11 = l + rand.nextInt(16) + 8; dungeonGen.a(world, rand, j5, k8, j11); } for (int i2 = 0; i2 < 10; i2++) { int k5 = k + rand.nextInt(16); int l8 = rand.nextInt(128); int k11 = l + rand.nextInt(16); clayGen.a(world, rand, k5, l8, k11); } for (int j2 = 0; j2 < 20; j2++) { int l5 = k + rand.nextInt(16); int i9 = rand.nextInt(128); int l11 = l + rand.nextInt(16); dirtGen.a(world, rand, l5, i9, l11); } for (int k2 = 0; k2 < 10; k2++) { int i6 = k + rand.nextInt(16); int j9 = rand.nextInt(128); int i12 = l + rand.nextInt(16); gravelGen.a(world, rand, i6, j9, i12); } for (int i3 = 0; i3 < 20; i3++) { int j6 = k + rand.nextInt(16); int k9 = rand.nextInt(128); int j12 = l + rand.nextInt(16); coalGen.a(world, rand, j6, k9, j12); } for (int j3 = 0; j3 < 20; j3++) { int k6 = k + rand.nextInt(16); int l9 = rand.nextInt(64); int k12 = l + rand.nextInt(16); ironGen.a(world, rand, k6, l9, k12); } for (int k3 = 0; k3 < 2; k3++) { int l6 = k + rand.nextInt(16); int i10 = rand.nextInt(32); int l12 = l + rand.nextInt(16); goldGen.a(world, rand, l6, i10, l12); } for (int l3 = 0; l3 < 8; l3++) { int i7 = k + rand.nextInt(16); int j10 = rand.nextInt(16); int i13 = l + rand.nextInt(16); redstoneGen.a(world, rand, i7, j10, i13); } for (int i4 = 0; i4 < 1; i4++) { int j7 = k + rand.nextInt(16); int k10 = rand.nextInt(16); int j13 = l + rand.nextInt(16); diamondGen.a(world, rand, j7, k10, j13); } for (int j4 = 0; j4 < 1; j4++) { int k7 = k + rand.nextInt(16); int l10 = rand.nextInt(16) + rand.nextInt(16); int k13 = l + rand.nextInt(16); lapisGen.a(world, rand, k7, l10, k13); } d = 0.5D; int k4 = (int)((mobSpawnerNoise.a((double)k * d, (double)l * d) / 8D + rand.nextDouble() * 4D + 4D) / 3D); int l7 = 0; if (rand.nextInt(10) == 0) { l7++; } if (biome == BiomeGenBase.forest) { l7 += k4 + 5; } if (biome == BiomeGenBase.rainforest) { l7 += k4 + 5; } if (biome == BiomeGenBase.seasonalForest) { l7 += k4 + 2; } if (biome == BiomeGenBase.taiga) { l7 += k4 + 5; } if (biome == BiomeGenBase.desert) { l7 -= 20; } if (biome == BiomeGenBase.tundra) { l7 -= 20; } if (biome == BiomeGenBase.plains) { l7 -= 20; } for (int i11 = 0; i11 < l7; i11++) { int l13 = k + rand.nextInt(16) + 8; int j14 = l + rand.nextInt(16) + 8; WorldGenerator worldgenerator = biome.a(rand); worldgenerator.a(1.0D, 1.0D, 1.0D); worldgenerator.a(world, rand, l13, world.getHighestBlockYAt(l13, j14), j14); } byte byte0 = 0; if (biome == BiomeGenBase.forest) { byte0 = 2; } if (biome == BiomeGenBase.seasonalForest) { byte0 = 4; } if (biome == BiomeGenBase.taiga) { byte0 = 2; } if (biome == BiomeGenBase.plains) { byte0 = 3; } for (int i14 = 0; i14 < byte0; i14++) { int k14 = k + rand.nextInt(16) + 8; int l16 = rand.nextInt(128); int k19 = l + rand.nextInt(16) + 8; yellowFlowerGen.a(world, rand, k14, l16, k19); } byte byte1 = 0; if (biome == BiomeGenBase.forest) { byte1 = 2; } if (biome == BiomeGenBase.rainforest) { byte1 = 10; } if (biome == BiomeGenBase.seasonalForest) { byte1 = 2; } if (biome == BiomeGenBase.taiga) { byte1 = 1; } if (biome == BiomeGenBase.plains) { byte1 = 10; } for (int l14 = 0; l14 < byte1; l14++) { boolean flag = (biome == BiomeGenBase.rainforest && rand.nextInt(3) != 0); int l19 = k + rand.nextInt(16) + 8; int k22 = rand.nextInt(128); int j24 = l + rand.nextInt(16) + 8; if (flag) { longGrassGen2.a(world, rand, l19, k22, j24); } else { longGrassGen1.a(world, rand, l19, k22, j24); } } byte1 = 0; if (biome == BiomeGenBase.desert) { byte1 = 2; } for (int i15 = 0; i15 < byte1; i15++) { int i17 = k + rand.nextInt(16) + 8; int i20 = rand.nextInt(128); int l22 = l + rand.nextInt(16) + 8; deadBushGen.a(world, rand, i17, i20, l22); } if (rand.nextInt(2) == 0) { int j15 = k + rand.nextInt(16) + 8; int j17 = rand.nextInt(128); int j20 = l + rand.nextInt(16) + 8; redFlowerGen.a(world, rand, j15, j17, j20); } if (rand.nextInt(4) == 0) { int k15 = k + rand.nextInt(16) + 8; int k17 = rand.nextInt(128); int k20 = l + rand.nextInt(16) + 8; brownMushroomGen.a(world, rand, k15, k17, k20); } if (rand.nextInt(8) == 0) { int l15 = k + rand.nextInt(16) + 8; int l17 = rand.nextInt(128); int l20 = l + rand.nextInt(16) + 8; redMushroomGen.a(world, rand, l15, l17, l20); } for (int i16 = 0; i16 < 10; i16++) { int i18 = k + rand.nextInt(16) + 8; int i21 = rand.nextInt(128); int i23 = l + rand.nextInt(16) + 8; reedGen.a(world, rand, i18, i21, i23); } if (rand.nextInt(32) == 0) { int j16 = k + rand.nextInt(16) + 8; int j18 = rand.nextInt(128); int j21 = l + rand.nextInt(16) + 8; pumpkinGen.a(world, rand, j16, j18, j21); } int k16 = 0; if (biome == BiomeGenBase.desert) { k16 += 10; } for (int k18 = 0; k18 < k16; k18++) { int k21 = k + rand.nextInt(16) + 8; int j23 = rand.nextInt(128); int k24 = l + rand.nextInt(16) + 8; cactusGen.a(world, rand, k21, j23, k24); } for (int l18 = 0; l18 < 50; l18++) { int l21 = k + rand.nextInt(16) + 8; int k23 = rand.nextInt(rand.nextInt(120) + 8); int l24 = l + rand.nextInt(16) + 8; liquidWaterGen.a(world, rand, l21, k23, l24); } for (int i19 = 0; i19 < 20; i19++) { int i22 = k + rand.nextInt(16) + 8; int l23 = rand.nextInt(rand.nextInt(rand.nextInt(112) + 8) + 8); int i25 = l + rand.nextInt(16) + 8; liquidLavaGen.a(world, rand, i22, l23, i25); } temperatures = this.wcm.getTemperatures(temperatures, k + 8, l + 8, 16, 16); for (int j19 = k + 8; j19 < k + 8 + 16; j19++) { for (int j22 = l + 8; j22 < l + 8 + 16; j22++) { int i24 = j19 - (k + 8); int j25 = j22 - (l + 8); int k25 = world.getHighestBlockYAt(j19, j22); double d1 = temperatures[i24 * 16 + j25] - ((double)(k25 - 64) / 64D) * 0.29999999999999999D; Material m = world.getMaterial(j19, k25 - 1, j22); if (d1 < 0.5D && k25 > 0 && k25 < 128 && world. isEmpty(j19, k25, j22) && m.isSolid() && m != Material.ICE) { world.setTypeIdAndData(j19, k25, j22, SNOW.id, 0, 2); } } } if (emeraldGen != null) { for (int j4 = 0; j4 < 5; j4++) { int k7 = k + rand.nextInt(16); int l10 = rand.nextInt(16) + rand.nextInt(16); int k13 = l + rand.nextInt(16); emeraldGen.a(world, rand, k7, l10, k13); } } BlockSand.instaFall = false; }
diff --git a/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/TrackableComputationExt.java b/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/TrackableComputationExt.java index 582f7d8a5..e6a8e9808 100644 --- a/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/TrackableComputationExt.java +++ b/bundles/org.eclipse.e4.core.contexts/src/org/eclipse/e4/core/internal/contexts/TrackableComputationExt.java @@ -1,117 +1,117 @@ /******************************************************************************* * Copyright (c) 2009, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.e4.core.internal.contexts; import java.util.List; import org.eclipse.e4.core.contexts.RunAndTrack; import org.eclipse.e4.core.internal.contexts.EclipseContext.Scheduled; public class TrackableComputationExt extends Computation implements IContextRecorder { private RunAndTrack runnable; private ContextChangeEvent cachedEvent; public TrackableComputationExt(RunAndTrack runnable) { this.runnable = runnable; } public int hashCode() { return 31 + ((runnable == null) ? 0 : runnable.hashCode()); } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TrackableComputationExt other = (TrackableComputationExt) obj; if (runnable == null) { if (other.runnable != null) return false; } else if (!runnable.equals(other.runnable)) return false; return true; } protected void doHandleInvalid(ContextChangeEvent event, List<Scheduled> scheduledList) { int eventType = event.getEventType(); if (eventType == ContextChangeEvent.INITIAL || eventType == ContextChangeEvent.DISPOSE) { // process right away update(event); } else { // schedule processing scheduledList.add(new Scheduled(this, event)); } } public boolean update(ContextChangeEvent event) { // is this a structural event? // structural changes: INITIAL, DISPOSE, UNINJECTED are always processed right away int eventType = event.getEventType(); if ((runnable instanceof RunAndTrackExt) && ((RunAndTrackExt) runnable).batchProcess()) { if ((eventType == ContextChangeEvent.ADDED) || (eventType == ContextChangeEvent.REMOVED)) { cachedEvent = event; EclipseContext eventsContext = (EclipseContext) event.getContext(); eventsContext.addWaiting(this); return true; } } Computation oldComputation = EclipseContext.localComputation().get(); EclipseContext.localComputation().set(this); boolean result = true; try { if (cachedEvent != null) { if (runnable instanceof RunAndTrackExt) result = ((RunAndTrackExt) runnable).update(event.getContext(), event.getEventType(), event.getArguments(), this); else { if (eventType == ContextChangeEvent.DISPOSE) runnable.disposed(cachedEvent.getContext()); - else + else if (eventType != ContextChangeEvent.UNINJECTED) result = runnable.changed(cachedEvent.getContext()); } cachedEvent = null; } if (eventType != ContextChangeEvent.UPDATE) { if (runnable instanceof RunAndTrackExt) result = ((RunAndTrackExt) runnable).update(event.getContext(), event.getEventType(), event.getArguments(), this); else { if (eventType == ContextChangeEvent.DISPOSE) runnable.disposed(event.getContext()); - else + else if (eventType != ContextChangeEvent.UNINJECTED) result = runnable.changed(event.getContext()); } } } finally { EclipseContext.localComputation().set(oldComputation); } EclipseContext eventsContext = (EclipseContext) event.getContext(); if (result && eventType != ContextChangeEvent.DISPOSE) startListening(eventsContext); else removeAll(eventsContext); return result; } public String toString() { return "TrackableComputationExt(" + runnable + ')'; //$NON-NLS-1$ } public void startAcessRecording() { EclipseContext.localComputation().set(this); } public void stopAccessRecording() { EclipseContext.localComputation().set(null); } }
false
true
public boolean update(ContextChangeEvent event) { // is this a structural event? // structural changes: INITIAL, DISPOSE, UNINJECTED are always processed right away int eventType = event.getEventType(); if ((runnable instanceof RunAndTrackExt) && ((RunAndTrackExt) runnable).batchProcess()) { if ((eventType == ContextChangeEvent.ADDED) || (eventType == ContextChangeEvent.REMOVED)) { cachedEvent = event; EclipseContext eventsContext = (EclipseContext) event.getContext(); eventsContext.addWaiting(this); return true; } } Computation oldComputation = EclipseContext.localComputation().get(); EclipseContext.localComputation().set(this); boolean result = true; try { if (cachedEvent != null) { if (runnable instanceof RunAndTrackExt) result = ((RunAndTrackExt) runnable).update(event.getContext(), event.getEventType(), event.getArguments(), this); else { if (eventType == ContextChangeEvent.DISPOSE) runnable.disposed(cachedEvent.getContext()); else result = runnable.changed(cachedEvent.getContext()); } cachedEvent = null; } if (eventType != ContextChangeEvent.UPDATE) { if (runnable instanceof RunAndTrackExt) result = ((RunAndTrackExt) runnable).update(event.getContext(), event.getEventType(), event.getArguments(), this); else { if (eventType == ContextChangeEvent.DISPOSE) runnable.disposed(event.getContext()); else result = runnable.changed(event.getContext()); } } } finally { EclipseContext.localComputation().set(oldComputation); } EclipseContext eventsContext = (EclipseContext) event.getContext(); if (result && eventType != ContextChangeEvent.DISPOSE) startListening(eventsContext); else removeAll(eventsContext); return result; }
public boolean update(ContextChangeEvent event) { // is this a structural event? // structural changes: INITIAL, DISPOSE, UNINJECTED are always processed right away int eventType = event.getEventType(); if ((runnable instanceof RunAndTrackExt) && ((RunAndTrackExt) runnable).batchProcess()) { if ((eventType == ContextChangeEvent.ADDED) || (eventType == ContextChangeEvent.REMOVED)) { cachedEvent = event; EclipseContext eventsContext = (EclipseContext) event.getContext(); eventsContext.addWaiting(this); return true; } } Computation oldComputation = EclipseContext.localComputation().get(); EclipseContext.localComputation().set(this); boolean result = true; try { if (cachedEvent != null) { if (runnable instanceof RunAndTrackExt) result = ((RunAndTrackExt) runnable).update(event.getContext(), event.getEventType(), event.getArguments(), this); else { if (eventType == ContextChangeEvent.DISPOSE) runnable.disposed(cachedEvent.getContext()); else if (eventType != ContextChangeEvent.UNINJECTED) result = runnable.changed(cachedEvent.getContext()); } cachedEvent = null; } if (eventType != ContextChangeEvent.UPDATE) { if (runnable instanceof RunAndTrackExt) result = ((RunAndTrackExt) runnable).update(event.getContext(), event.getEventType(), event.getArguments(), this); else { if (eventType == ContextChangeEvent.DISPOSE) runnable.disposed(event.getContext()); else if (eventType != ContextChangeEvent.UNINJECTED) result = runnable.changed(event.getContext()); } } } finally { EclipseContext.localComputation().set(oldComputation); } EclipseContext eventsContext = (EclipseContext) event.getContext(); if (result && eventType != ContextChangeEvent.DISPOSE) startListening(eventsContext); else removeAll(eventsContext); return result; }
diff --git a/JavaSource/org/aitools/programd/processor/aiml/RandomProcessor.java b/JavaSource/org/aitools/programd/processor/aiml/RandomProcessor.java index d710031..e8afb5f 100644 --- a/JavaSource/org/aitools/programd/processor/aiml/RandomProcessor.java +++ b/JavaSource/org/aitools/programd/processor/aiml/RandomProcessor.java @@ -1,199 +1,199 @@ /* * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.aitools.programd.processor.aiml; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.w3c.dom.Element; import org.aitools.programd.Core; import org.aitools.programd.CoreSettings; import org.aitools.programd.parser.TemplateParser; import org.aitools.programd.processor.ProcessorException; import org.aitools.util.math.MersenneTwisterFast; import org.aitools.util.xml.XML; import org.apache.commons.collections.map.LRUMap; /** * <p> * Handles a <code><a href="http://aitools.org/aiml/TR/2001/WD-aiml/#section-random">random</a></code> element. * </p> * <p> * To achieve the kind of randomness expected by * users and AIML authors, the following requirements exist: * </p> * <ul> * <li>Each <code>random</code> element should have its own &quot;space&quot;. This means that, for example, * if <code>random</code> element <code>A</code> contains five <code>li</code> children, and * <code>random</code> element <code>B</code> contains seven <code>li</code> children, the probability that * any given <code>li</code> of <code>A</code> will be chosen when <code>A</code> is activated should con- * sistently be 1:5, and the probability that any given <code>li</code> of <code>B</code> will be chosen when * <code>B</code> is chosen should consistently be 1:7. Essentially, each <code>random</code> must have its * own unique series of random numbers.</li> * <li>A &quot;unique space&quot; requirement exists as well on a per-user basis: each user should have an * equivalent experience of randomness for each <code>random</code> element, independent of any other users.</li> * <li>The individual bot also has a uniqueness requirement, multiplying the previous two. In effect, if there * are <code>m</code> bots, <code>n</code> users, and <code>p</code> random elements, there are (potentially) * <code>m * n * n</code> independent random number series.</li> * </ul> * <p> * As an alternative to the first point, it is possible (since 4.7) to set Program D to process <code>random</code> * elements in a kind of stack-based fashion, so no list item will be repeated (within the same per-user, per-bot * space) until all others have been chosen. * </p> * * @author <a href="mailto:[email protected]">Noel Bush</a> * @author Jon Baer * @author Thomas Ringate, Pedro Colla * @author Jay Myers */ public class RandomProcessor extends AIMLProcessor { /** The label (as required by the registration scheme). */ public static final String label = "random"; /** The tag name for a listitem element. */ public static final String LI = "li"; /** * The map in which MersenneTwisterFast random number generators will be stored for each unique botid + userid + * random element. */ private LRUMap generators = new LRUMap(100); /** * The map in which indices not-yet-used listitems will be stored if * non-repeating random choosing is enabled. (We store indices rather * than references to the listitems themselves, because the DOM Element doesn't * appear to implement equals() in a way that makes List operations like remove() * work. */ private Map<String, List<Integer>> availableIndices = new HashMap<String, List<Integer>>(); /** * Creates a new RandomProcessor using the given Core. * * @param core the Core object to use */ @SuppressWarnings("unchecked") public RandomProcessor(Core core) { super(core); this.availableIndices = core.getStoredObject(RandomProcessor.class.getName(), "availableIndices", this.availableIndices); this.generators = core.getStoredObject(RandomProcessor.class.getName(), "generators", this.generators); } /** * @see AIMLProcessor#process(Element, TemplateParser) */ @SuppressWarnings("boxing") @Override public String process(Element element, TemplateParser parser) throws ProcessorException { // Construct the identifying string (botid + userid + element // contents). String userid = parser.getUserID(); - String identifier = parser.getBotID() + userid + element.toString(); + String identifier = parser.getBotID() + userid + element.hashCode(); // Does the generators map already contain this one? MersenneTwisterFast generator = (MersenneTwisterFast)this.generators.get(identifier); if (generator == null) { generator = new MersenneTwisterFast(System.currentTimeMillis()); this.generators.put(identifier, generator); } List<Element> listitems = XML.getElementChildrenOf(element); int nodeCount = listitems.size(); // Only one <li></li> child means we don't have to pick anything. if (nodeCount == 1) { return parser.evaluate(listitems.get(0).getChildNodes()); } // Otherwise, select a random element of the listitem (if strategy is pure-random). if (this._core.getSettings().getRandomStrategy() == CoreSettings.RandomStrategy.PURE_RANDOM) { return parser.evaluate(listitems.get(generator.nextInt(nodeCount)).getChildNodes()); } // If we get here, then the no-repeat strategy is wanted. List<Integer> indices; Integer choice = null; // Check whether this random + userid + botid has been selected before. if (this.availableIndices.containsKey(identifier)) { // If it has, get the remaining available sets. indices = this.availableIndices.get(identifier); // Note that, because of the logic below, this set will never get to size 0. assert indices.size() > 0 : "Random strategy logic failed."; /* * If it is complete, then we've been through all before, and * the last index in the list was the last one chosen (see below), * so make sure this first choice does not repeat the last one. */ if (indices.size() == nodeCount) { choice = indices.get(generator.nextInt(indices.size() - 1)); } else { // Otherwise just make a random choice from the indices. choice = indices.get(generator.nextInt(indices.size())); } } else { // If it has not (been selected before), create a new set containing an index for each listitem. indices = makeIncrementingList(nodeCount); this.availableIndices.put(identifier, indices); // Make a random choice from the indices. choice = indices.get(generator.nextInt(indices.size())); } // Remove the chosen index. indices.remove(choice); // If this has reduced the size to zero, if (indices.size() == 0) { // Reconstitute the list, indices.addAll(makeIncrementingList(nodeCount)); // but remove the last choice, indices.remove(choice); // and place it last, so we can avoid repeating it next go-round (see above). indices.add(choice); } // Evaluate the node corresponding to the chosen index. return parser.evaluate(listitems.get(choice).getChildNodes()); } @SuppressWarnings("boxing") private static List<Integer> makeIncrementingList(int size) { List<Integer> result = new ArrayList<Integer>(); for (int index = 0; index < size; index++) { result.add(index); } return result; } }
true
true
public String process(Element element, TemplateParser parser) throws ProcessorException { // Construct the identifying string (botid + userid + element // contents). String userid = parser.getUserID(); String identifier = parser.getBotID() + userid + element.toString(); // Does the generators map already contain this one? MersenneTwisterFast generator = (MersenneTwisterFast)this.generators.get(identifier); if (generator == null) { generator = new MersenneTwisterFast(System.currentTimeMillis()); this.generators.put(identifier, generator); } List<Element> listitems = XML.getElementChildrenOf(element); int nodeCount = listitems.size(); // Only one <li></li> child means we don't have to pick anything. if (nodeCount == 1) { return parser.evaluate(listitems.get(0).getChildNodes()); } // Otherwise, select a random element of the listitem (if strategy is pure-random). if (this._core.getSettings().getRandomStrategy() == CoreSettings.RandomStrategy.PURE_RANDOM) { return parser.evaluate(listitems.get(generator.nextInt(nodeCount)).getChildNodes()); } // If we get here, then the no-repeat strategy is wanted. List<Integer> indices; Integer choice = null; // Check whether this random + userid + botid has been selected before. if (this.availableIndices.containsKey(identifier)) { // If it has, get the remaining available sets. indices = this.availableIndices.get(identifier); // Note that, because of the logic below, this set will never get to size 0. assert indices.size() > 0 : "Random strategy logic failed."; /* * If it is complete, then we've been through all before, and * the last index in the list was the last one chosen (see below), * so make sure this first choice does not repeat the last one. */ if (indices.size() == nodeCount) { choice = indices.get(generator.nextInt(indices.size() - 1)); } else { // Otherwise just make a random choice from the indices. choice = indices.get(generator.nextInt(indices.size())); } } else { // If it has not (been selected before), create a new set containing an index for each listitem. indices = makeIncrementingList(nodeCount); this.availableIndices.put(identifier, indices); // Make a random choice from the indices. choice = indices.get(generator.nextInt(indices.size())); } // Remove the chosen index. indices.remove(choice); // If this has reduced the size to zero, if (indices.size() == 0) { // Reconstitute the list, indices.addAll(makeIncrementingList(nodeCount)); // but remove the last choice, indices.remove(choice); // and place it last, so we can avoid repeating it next go-round (see above). indices.add(choice); } // Evaluate the node corresponding to the chosen index. return parser.evaluate(listitems.get(choice).getChildNodes()); }
public String process(Element element, TemplateParser parser) throws ProcessorException { // Construct the identifying string (botid + userid + element // contents). String userid = parser.getUserID(); String identifier = parser.getBotID() + userid + element.hashCode(); // Does the generators map already contain this one? MersenneTwisterFast generator = (MersenneTwisterFast)this.generators.get(identifier); if (generator == null) { generator = new MersenneTwisterFast(System.currentTimeMillis()); this.generators.put(identifier, generator); } List<Element> listitems = XML.getElementChildrenOf(element); int nodeCount = listitems.size(); // Only one <li></li> child means we don't have to pick anything. if (nodeCount == 1) { return parser.evaluate(listitems.get(0).getChildNodes()); } // Otherwise, select a random element of the listitem (if strategy is pure-random). if (this._core.getSettings().getRandomStrategy() == CoreSettings.RandomStrategy.PURE_RANDOM) { return parser.evaluate(listitems.get(generator.nextInt(nodeCount)).getChildNodes()); } // If we get here, then the no-repeat strategy is wanted. List<Integer> indices; Integer choice = null; // Check whether this random + userid + botid has been selected before. if (this.availableIndices.containsKey(identifier)) { // If it has, get the remaining available sets. indices = this.availableIndices.get(identifier); // Note that, because of the logic below, this set will never get to size 0. assert indices.size() > 0 : "Random strategy logic failed."; /* * If it is complete, then we've been through all before, and * the last index in the list was the last one chosen (see below), * so make sure this first choice does not repeat the last one. */ if (indices.size() == nodeCount) { choice = indices.get(generator.nextInt(indices.size() - 1)); } else { // Otherwise just make a random choice from the indices. choice = indices.get(generator.nextInt(indices.size())); } } else { // If it has not (been selected before), create a new set containing an index for each listitem. indices = makeIncrementingList(nodeCount); this.availableIndices.put(identifier, indices); // Make a random choice from the indices. choice = indices.get(generator.nextInt(indices.size())); } // Remove the chosen index. indices.remove(choice); // If this has reduced the size to zero, if (indices.size() == 0) { // Reconstitute the list, indices.addAll(makeIncrementingList(nodeCount)); // but remove the last choice, indices.remove(choice); // and place it last, so we can avoid repeating it next go-round (see above). indices.add(choice); } // Evaluate the node corresponding to the chosen index. return parser.evaluate(listitems.get(choice).getChildNodes()); }
diff --git a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/basic/table/columns/AbstractColumn.java b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/basic/table/columns/AbstractColumn.java index 6570f2ecbd..25c111e2d6 100644 --- a/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/basic/table/columns/AbstractColumn.java +++ b/org.eclipse.scout.rt.client/src/org/eclipse/scout/rt/client/ui/basic/table/columns/AbstractColumn.java @@ -1,1634 +1,1640 @@ /******************************************************************************* * Copyright (c) 2010 BSI Business Systems Integration AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * BSI Business Systems Integration AG - initial API and implementation ******************************************************************************/ package org.eclipse.scout.rt.client.ui.basic.table.columns; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.Array; import java.security.Permission; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import org.eclipse.scout.commons.CompareUtility; import org.eclipse.scout.commons.StringUtility; import org.eclipse.scout.commons.TypeCastUtility; import org.eclipse.scout.commons.annotations.ConfigOperation; import org.eclipse.scout.commons.annotations.ConfigProperty; import org.eclipse.scout.commons.annotations.ConfigPropertyValue; import org.eclipse.scout.commons.annotations.Order; import org.eclipse.scout.commons.annotations.Replace; import org.eclipse.scout.commons.beans.AbstractPropertyObserver; import org.eclipse.scout.commons.exception.IProcessingStatus; import org.eclipse.scout.commons.exception.ProcessingException; import org.eclipse.scout.commons.logger.IScoutLogger; import org.eclipse.scout.commons.logger.ScoutLogManager; import org.eclipse.scout.rt.client.ui.ClientUIPreferences; import org.eclipse.scout.rt.client.ui.basic.cell.Cell; import org.eclipse.scout.rt.client.ui.basic.cell.ICell; import org.eclipse.scout.rt.client.ui.basic.table.AbstractTable; import org.eclipse.scout.rt.client.ui.basic.table.ColumnSet; import org.eclipse.scout.rt.client.ui.basic.table.HeaderCell; import org.eclipse.scout.rt.client.ui.basic.table.IHeaderCell; import org.eclipse.scout.rt.client.ui.basic.table.ITable; import org.eclipse.scout.rt.client.ui.basic.table.ITableRow; import org.eclipse.scout.rt.client.ui.basic.table.columnfilter.ITableColumnFilterManager; import org.eclipse.scout.rt.client.ui.basic.table.internal.InternalTableRow; import org.eclipse.scout.rt.client.ui.desktop.outline.pages.AbstractPageWithTable; import org.eclipse.scout.rt.client.ui.form.AbstractForm; import org.eclipse.scout.rt.client.ui.form.fields.AbstractValueField; import org.eclipse.scout.rt.client.ui.form.fields.GridData; import org.eclipse.scout.rt.client.ui.form.fields.IFormField; import org.eclipse.scout.rt.client.ui.form.fields.IValueField; import org.eclipse.scout.rt.client.ui.form.fields.ParsingFailedStatus; import org.eclipse.scout.rt.client.ui.form.fields.tablefield.AbstractTableField; import org.eclipse.scout.rt.shared.ScoutTexts; import org.eclipse.scout.rt.shared.data.basic.FontSpec; import org.eclipse.scout.rt.shared.data.form.AbstractFormData; import org.eclipse.scout.rt.shared.services.common.security.IAccessControlService; import org.eclipse.scout.service.SERVICES; public abstract class AbstractColumn<T> extends AbstractPropertyObserver implements IColumn<T> { private static final IScoutLogger LOG = ScoutLogManager.getLogger(AbstractColumn.class); // DO NOT init members, this has the same effect as if they were set AFTER // initConfig() private ITable m_table; private final HeaderCell m_headerCell; private boolean m_primaryKey; private boolean m_summary; private boolean m_isValidating; /** * A column is presented to the user when it is displayable AND visible this * column is visible to the user only used when displayable=true */ private boolean m_visibleProperty; private boolean m_visibleGranted; private int m_initialWidth; private boolean m_initialVisible; private int m_initialSortIndex; private boolean m_initialSortAscending; private boolean m_initialAlwaysIncludeSortAtBegin; private boolean m_initialAlwaysIncludeSortAtEnd; /** * Used for mutable tables to keep last valid value per row and column. */ // TODO: Move cache to AbstractTable with bug 414646 private Map<InternalTableRow, T> m_validatedValues = new HashMap<InternalTableRow, T>(); public AbstractColumn() { m_headerCell = new HeaderCell(); initConfig(); propertySupport.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { // force decoration of rows on property change. // This is important to recalculate editability of editable cells. ITable table = getTable(); if (table != null) { table.updateAllRows(); } } }); } public final void clearValidatedValues() { m_validatedValues.clear(); } public final T clearValidatedValue(ITableRow row) { return m_validatedValues.remove(row); } private void storeValidatedValue(ITableRow row, T validatedValue) { if (row instanceof InternalTableRow) { m_validatedValues.put((InternalTableRow) row, validatedValue); } } private void removeValidatedValue(ITableRow row) { if (row instanceof InternalTableRow) { m_validatedValues.remove((InternalTableRow) row); } } protected Map<String, Object> getPropertiesMap() { return propertySupport.getPropertiesMap(); } /* * Configuration */ /** * Configures the visibility of this column. If the column must be visible for the user, it must be displayable too * (see {@link #getConfiguredDisplayable()}). * <p> * Subclasses can override this method. Default is {@code true}. * * @return {@code true} if this column is visible, {@code false} otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(10) @ConfigPropertyValue("true") protected boolean getConfiguredVisible() { return true; } /** * Configures the header text of this column. * <p> * Subclasses can override this method. Default is {@code null}. * * @return Header text of this column. */ @ConfigProperty(ConfigProperty.TEXT) @Order(20) @ConfigPropertyValue("null") protected String getConfiguredHeaderText() { return null; } /** * Configures the header tooltip of this column. * <p> * Subclasses can override this method. Default is {@code null}. * * @return Tooltip of this column. */ @ConfigProperty(ConfigProperty.TEXT) @Order(30) @ConfigPropertyValue("null") protected String getConfiguredHeaderTooltipText() { return null; } /** * Configures the color of this column header text. The color is represented by the HEX value (e.g. FFFFFF). * <p> * Subclasses can override this method. Default is {@code null}. * * @return Foreground color HEX value of this column header text. */ @ConfigProperty(ConfigProperty.COLOR) @Order(40) @ConfigPropertyValue("null") protected String getConfiguredHeaderForegroundColor() { return null; } /** * Configures the background color of this column header. The color is represented by the HEX value (e.g. FFFFFF). * <p> * Subclasses can override this method. Default is {@code null}. * * @return Background color HEX value of this column header. */ @ConfigProperty(ConfigProperty.COLOR) @Order(50) @ConfigPropertyValue("null") protected String getConfiguredHeaderBackgroundColor() { return null; } /** * Configures the font of this column header text. See {@link FontSpec#parse(String)} for the appropriate format. * <p> * Subclasses can override this method. Default is {@code null}. * * @return Font of this column header text. */ @ConfigProperty(ConfigProperty.STRING) @Order(60) @ConfigPropertyValue("null") protected String getConfiguredHeaderFont() { return null; } /** * Configures the width of this column. The width of a column is represented by an {@code int}. If the table's auto * resize flag is set (see {@link AbstractTable#getConfiguredAutoResizeColumns()} ), the ratio of the column widths * determines the real column width. If the flag is not set, the column's width is represented by the configured * width. * <p> * Subclasses can override this method. Default is {@code 60}. * * @return Width of this column. */ @ConfigProperty(ConfigProperty.INTEGER) @Order(70) @ConfigPropertyValue("60") protected int getConfiguredWidth() { return 60; } /** * Configures whether the column width is fixed, meaning that it is not changed by resizing/auto-resizing * and cannot be resized by the user. * If <code>true</code>, the configured width is fixed. * Defaults to <code>false</code>. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(75) @ConfigPropertyValue("false") protected boolean getConfiguredFixedWidth() { return false; } /** * Configures whether the column is displayable or not. A non-displayable column is always invisible for the user. A * displayable column may be visible for a user, depending on {@link #getConfiguredVisible()}. * <p> * Subclasses can override this method. Default is {@code true}. * * @return {@code true} if this column is displayable, {@code false} otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(80) @ConfigPropertyValue("true") protected boolean getConfiguredDisplayable() { return true; } /** * Configures whether this column value belongs to the primary key of the surrounding table. The table's primary key * might consist of several columns. The primary key can be used to find the appropriate row by calling * {@link AbstractTable#findRowByKey(Object[])}. * <p> * Subclasses can override this method. Default is {@code false}. * * @return {@code true} if this column value belongs to the primary key of the surrounding table, {@code false} * otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(90) @ConfigPropertyValue("false") protected boolean getConfiguredPrimaryKey() { return false; } /** * Configures whether this column is editable or not. A user might directly modify the value of an editable column. A * non-editable column is read-only. * <p> * Subclasses can override this method. Default is {@code false}. * * @return {@code true} if this column is editable, {@code false} otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(95) @ConfigPropertyValue("false") protected boolean getConfiguredEditable() { return false; } /** * Configures whether this column is a summary column. Summary columns are used in case of a table with children. The * label of the child node is based on the value of the summary columns. See {@link ITable#getSummaryCell(ITableRow)} * for more information. * <p> * Subclasses can override this method. Default is {@code false}. * * @return {@code true} if this column is a summary column, {@code false} otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(100) @ConfigPropertyValue("false") protected boolean getConfiguredSummary() { return false; } /** * Configures the color of this column text (except color of header text, see * {@link #getConfiguredHeaderForegroundColor()}). The color is represented by the HEX value (e.g. FFFFFF). * <p> * Subclasses can override this method. Default is {@code null}. * * @return Foreground color HEX value of this column text. */ @ConfigProperty(ConfigProperty.COLOR) @Order(110) @ConfigPropertyValue("null") protected String getConfiguredForegroundColor() { return null; } /** * Configures the background color of this column (except background color of header, see * {@link #getConfiguredHeaderBackgroundColor()}. The color is represented by the HEX value (e.g. FFFFFF). * <p> * Subclasses can override this method. Default is {@code null}. * * @return Background color HEX value of this column. */ @ConfigProperty(ConfigProperty.COLOR) @Order(120) @ConfigPropertyValue("null") protected String getConfiguredBackgroundColor() { return null; } /** * Configures the font of this column text (except header text, see {@link #getConfiguredHeaderFont()}). See * {@link FontSpec#parse(String)} for the appropriate format. * <p> * Subclasses can override this method. Default is {@code null}. * * @return Font of this column text. */ @ConfigProperty(ConfigProperty.STRING) @Order(130) @ConfigPropertyValue("null") protected String getConfiguredFont() { return null; } /** * Configures the sort index of this column. A sort index {@code < 0} means that the column is not considered for * sorting. For a column to be considered for sorting, the sort index must be {@code >= 0}. Several columns * might have set a sort index. Sorting starts with the column having the the lowest sort index ({@code >= 0}). * <p> * Subclasses can override this method. Default is {@code -1}. * * @return Sort index of this column. */ @ConfigProperty(ConfigProperty.INTEGER) @Order(140) @ConfigPropertyValue("-1") protected int getConfiguredSortIndex() { return -1; } /** * Configures the view order of this column. The view order determines the order in which the columns appear. The view * order of column with no view order configured ({@code < 0}) is initialized based on the order annotation of the * column class. * <p> * Subclasses can override this method. Default is {@code -1}. * * @return View order of this column. */ @ConfigProperty(ConfigProperty.DOUBLE) @Order(145) @ConfigPropertyValue("-1") protected double getConfiguredViewOrder() { return -1; } /** * Configures whether this column is sorted ascending or descending. For a column to be sorted at all, a sort index * must be set (see {@link #getConfiguredSortIndex()}). * <p> * Subclasses can override this method. Default is {@code true}. * * @return {@code true} if this column is sorted ascending, {@code false} otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(150) @ConfigPropertyValue("true") protected boolean getConfiguredSortAscending() { return true; } /** * Configures whether this column is always included for sort at begin, independent of a sort change by the user. If * set to {@code true}, the sort index (see {@link #getConfiguredSortIndex()}) must be set. * <p> * Subclasses can override this method. Default is {@code false}. * * @return {@code true} if this column is always included for sort at begin, {@code false} otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(160) @ConfigPropertyValue("false") protected boolean getConfiguredAlwaysIncludeSortAtBegin() { return false; } /** * Configures whether this column is always included for sort at end, independent of a sort change by the user. If set * to {@code true}, the sort index (see {@link #getConfiguredSortIndex()}) must be set. * <p> * Subclasses can override this method. Default is {@code false}. * * @return {@code true} if this column is always included for sort at end, {@code false} otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(170) @ConfigPropertyValue("false") protected boolean getConfiguredAlwaysIncludeSortAtEnd() { return false; } /** * Configures the horizontal alignment of text inside this column (including header text). * <p> * Subclasses can override this method. Default is {@code -1} (left alignment). * * @return {@code -1} for left, {@code 0} for center and {@code 1} for right alignment. */ @ConfigProperty(ConfigProperty.INTEGER) @Order(180) @ConfigPropertyValue("-1") protected int getConfiguredHorizontalAlignment() { return -1; } /** * Configures whether the column width is auto optimized. If true: Whenever the table content changes, the optimized * column width is automatically calculated so that all column content is displayed without cropping. * <p> * This may display a horizontal scroll bar on the table. * <p> * This feature is not supported in SWT and RWT since SWT does not offer such an API method. * <p> * Subclasses can override this method. Default is {@code false}. * * @return {@code true} if this column width is auto optimized, {@code false} otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(190) @ConfigPropertyValue("false") protected boolean getConfiguredAutoOptimizeWidth() { return false; } /** * Provides a documentation text or description of this column. The text is intended to be included in external * documentation. This method is typically processed by a documentation generation tool or similar. * <p> * Subclasses can override this method. Default is {@code null}. * * @return a documentation text, suitable to be included in external documents */ @ConfigProperty(ConfigProperty.DOC) @Order(200) @ConfigPropertyValue("null") protected String getConfiguredDoc() { return null; } /** * Configures whether this column value is mandatory / required. This only affects editable columns (see * {@link #getConfiguredEditable()} ). * <p> * Subclasses can override this method. Default is {@code false}. * * @return {@code true} if this column value is mandatory, {@code false} otherwise. */ @ConfigProperty(ConfigProperty.BOOLEAN) @Order(210) @ConfigPropertyValue("false") protected boolean getConfiguredMandatory() { return false; } /** * Called after this column has been added to the column set of the surrounding table. This method may execute * additional initialization for this column (e.g. register listeners). * <p> * Do not load table data here, this should be done lazily in {@link AbstractPageWithTable#execLoadTableData()}, * {@link AbstractTableField#reloadTableData()} or via {@link AbstractForm#importFormData(AbstractFormData)}. * <p> * Subclasses can override this method. The default does nothing. * * @throws ProcessingException */ @ConfigOperation @Order(10) protected void execInitColumn() throws ProcessingException { } /** * Called when the surrounding table is disposed. This method may execute additional cleanup. * <p> * Subclasses can override this method. The default does nothing. * * @throws ProcessingException */ @ConfigOperation @Order(15) protected void execDisposeColumn() throws ProcessingException { } /** * Parse is the process of transforming an arbitrary object to the correct type or throwing an exception. * <p> * see also {@link #execValidateValue(ITableRow, Object)} * <p> * Subclasses can override this method. The default calls {@link #parseValueInternal(ITableRow, Object)}. * * @param row * Table row for which to parse the raw value. * @param rawValue * Raw value to parse. * @return Value in correct type, derived from rawValue. * @throws ProcessingException */ @ConfigOperation @Order(20) protected T/* validValue */execParseValue(ITableRow row, Object rawValue) throws ProcessingException { return parseValueInternal(row, rawValue); } /** * Validate is the process of checking range, domain, bounds, correctness etc. of an already correctly typed value or * throwing an exception. * <p> * see also {@link #execParseValue(ITableRow, Object)} * <p> * Subclasses can override this method. The default calls {@link #validateValueInternal(ITableRow, Object)}. * * @param row * Table row for which to validate the raw value. * @param rawValue * Already parsed raw value to validate. * @return Validated value * @throws ProcessingException */ @ConfigOperation @Order(30) protected T/* validValue */execValidateValue(ITableRow row, T rawValue) throws ProcessingException { return validateValueInternal(row, rawValue); } /** * Called when decorating the table cell. This method may add additional decorations to the table cell. * <p> * Subclasses can override this method. The default does nothing. * * @param cell * Cell to decorate. * @param row * Table row of cell. * @throws ProcessingException */ @ConfigOperation @Order(40) protected void execDecorateCell(Cell cell, ITableRow row) throws ProcessingException { } /** * Called when decorating the table header cell. This method may add additional decorations to the table header cell. * <p> * Subclasses can override this method. The default does nothing. * * @param cell * Header cell to decorate. * @throws ProcessingException */ @ConfigOperation @Order(50) protected void execDecorateHeaderCell(HeaderCell cell) throws ProcessingException { } /** * Only called if {@link #getConfiguredEditable()} is true and cell, row and table are enabled. Use this method only * for dynamic checks of editablility, otherwise use {@link #getConfiguredEditable()}. * <p> * Subclasses can override this method. Default is {@code true}. * * @param row * for which to determine editability dynamically. * @return {@code true} if the cell (row, column) is editable, {@code false} otherwise. * @throws ProcessingException */ @ConfigOperation @Order(60) protected boolean execIsEditable(ITableRow row) throws ProcessingException { return true; } /** * Prepares the editing of a cell in the table. * <p> * Cell editing is canceled (normally by typing escape) or saved (normally by clicking another cell, typing enter). * <p> * When saved, the method {@link #completeEdit(ITableRow, IFormField)} / * {@link #execCompleteEdit(ITableRow, IFormField)} is called on this column. * <p> * Subclasses can override this method. The default returns an appropriate field based on the column data type. * * @param row * on which editing occurs * @return a field for editing or null to install an empty cell editor. */ @SuppressWarnings("unchecked") @ConfigOperation @Order(61) protected IFormField execPrepareEdit(ITableRow row) throws ProcessingException { IFormField f = prepareEditInternal(row); if (f != null) { if (f instanceof AbstractValueField<?>) { ((AbstractValueField<?>) f).setAutoDisplayText(!m_isValidating); } f.setLabelVisible(false); GridData gd = f.getGridDataHints(); // apply horizontal alignment of column to respective editor field gd.horizontalAlignment = getHorizontalAlignment(); f.setGridDataHints(gd); if (f instanceof IValueField<?>) { ((IValueField<T>) f).setValue(getValue(row)); } f.markSaved(); } return f; } /** * Completes editing of a cell. * <p> * Subclasses can override this method. The default calls {@link #applyValueInternal(ITableRow, Object)} and delegates * to {@link #execParseValue(ITableRow, Object)} and {@link #execValidateValue(ITableRow, Object)}. * * @param row * on which editing occurred. * @param editingField * Field which was used to edit cell value (as returned by {@link #execPrepareEdit(ITableRow)}). * @throws ProcessingException */ @ConfigOperation @Order(62) protected void execCompleteEdit(ITableRow row, IFormField editingField) throws ProcessingException { if (editingField instanceof IValueField) { IValueField v = (IValueField) editingField; if (v.isSaveNeeded() || editingField.getErrorStatus() != null || row.getCell(this).getErrorStatus() != null) { T parsedValue = parseValue(row, v.getValue()); setValueInternal(row, parsedValue, editingField); if (getTable() instanceof AbstractTable && ((AbstractTable) getTable()).wasEverValid(row)) { persistRowChange(row); } } } } /** * <p> * Updates the value of the cell with the given value. * </p> * <p> * Thereby, if sorting is enabled on table, it is temporarily suspended to prevent rows from scampering. * </p> * * @param row * @param newValue * @throws ProcessingException */ protected void applyValueInternal(ITableRow row, T newValue) throws ProcessingException { if (!getTable().isSortEnabled()) { setValue(row, newValue); } else { // suspend sorting to prevent rows from scampering try { getTable().setSortEnabled(false); setValue(row, newValue); } finally { getTable().setSortEnabled(true); } } } protected void initConfig() { setAutoOptimizeWidth(getConfiguredAutoOptimizeWidth()); m_visibleGranted = true; m_headerCell.setText(getConfiguredHeaderText()); if (getConfiguredHeaderTooltipText() != null) { m_headerCell.setTooltipText(getConfiguredHeaderTooltipText()); } if (getConfiguredHeaderForegroundColor() != null) { m_headerCell.setForegroundColor((getConfiguredHeaderForegroundColor())); } if (getConfiguredHeaderBackgroundColor() != null) { m_headerCell.setBackgroundColor((getConfiguredHeaderBackgroundColor())); } if (getConfiguredHeaderFont() != null) { m_headerCell.setFont(FontSpec.parse(getConfiguredHeaderFont())); } m_headerCell.setHorizontalAlignment(getConfiguredHorizontalAlignment()); setHorizontalAlignment(getConfiguredHorizontalAlignment()); setDisplayable(getConfiguredDisplayable()); setVisible(getConfiguredVisible()); setInitialWidth(getConfiguredWidth()); setInitialVisible(getConfiguredVisible()); setInitialSortIndex(getConfiguredSortIndex()); setInitialSortAscending(getConfiguredSortAscending()); setInitialAlwaysIncludeSortAtBegin(getConfiguredAlwaysIncludeSortAtBegin()); setInitialAlwaysIncludeSortAtEnd(getConfiguredAlwaysIncludeSortAtEnd()); // double viewOrder = getConfiguredViewOrder(); if (viewOrder < 0) { if (getClass().isAnnotationPresent(Order.class)) { Order order = (Order) getClass().getAnnotation(Order.class); viewOrder = order.value(); } } setViewOrder(viewOrder); // setWidth(getConfiguredWidth()); setFixedWidth(getConfiguredFixedWidth()); m_primaryKey = getConfiguredPrimaryKey(); m_summary = getConfiguredSummary(); setEditable(getConfiguredEditable()); setMandatory(getConfiguredMandatory()); setVisibleColumnIndexHint(-1); if (getConfiguredForegroundColor() != null) { setForegroundColor((getConfiguredForegroundColor())); } if (getConfiguredBackgroundColor() != null) { setBackgroundColor((getConfiguredBackgroundColor())); } if (getConfiguredFont() != null) { setFont(FontSpec.parse(getConfiguredFont())); } } /* * Runtime */ @Override public void initColumn() throws ProcessingException { ClientUIPreferences env = ClientUIPreferences.getInstance(); setVisible(env.getTableColumnVisible(this, m_visibleProperty)); setWidth(env.getTableColumnWidth(this, getWidth())); setVisibleColumnIndexHint(env.getTableColumnViewIndex(this, getVisibleColumnIndexHint())); // execInitColumn(); } @Override public void disposeColumn() throws ProcessingException { execDisposeColumn(); } @Override public void setMandatory(boolean mandatory) { propertySupport.setPropertyBool(IFormField.PROP_MANDATORY, mandatory); validateColumnValues(); } @Override public boolean isMandatory() { return propertySupport.getPropertyBool(IFormField.PROP_MANDATORY); } @Override public boolean isInitialVisible() { return m_initialVisible; } @Override public void setInitialVisible(boolean b) { m_initialVisible = b; } @Override public int getInitialSortIndex() { return m_initialSortIndex; } @Override public void setInitialSortIndex(int i) { m_initialSortIndex = i; } @Override public boolean isInitialSortAscending() { return m_initialSortAscending; } @Override public void setInitialSortAscending(boolean b) { m_initialSortAscending = b; } @Override public boolean isInitialAlwaysIncludeSortAtBegin() { return m_initialAlwaysIncludeSortAtBegin; } @Override public void setInitialAlwaysIncludeSortAtBegin(boolean b) { m_initialAlwaysIncludeSortAtBegin = b; } @Override public boolean isInitialAlwaysIncludeSortAtEnd() { return m_initialAlwaysIncludeSortAtEnd; } @Override public void setInitialAlwaysIncludeSortAtEnd(boolean b) { m_initialAlwaysIncludeSortAtEnd = b; } /** * controls the displayable property of the column */ @Override public void setVisiblePermission(Permission p) { boolean b; if (p != null) { b = SERVICES.getService(IAccessControlService.class).checkPermission(p); } else { b = true; } setVisibleGranted(b); } @Override public boolean isVisibleGranted() { return m_visibleGranted; } @Override public void setVisibleGranted(boolean b) { m_visibleGranted = b; calculateVisible(); } @Override public ITable getTable() { return m_table; } /** * do not use this internal method */ public void setTableInternal(ITable table) { m_table = table; } @Override public int getColumnIndex() { return m_headerCell.getColumnIndex(); } @Override public String getColumnId() { Class<?> c = getClass(); while (c.isAnnotationPresent(Replace.class)) { c = c.getSuperclass(); } String s = c.getSimpleName(); if (s.endsWith("Column")) { s = s.replaceAll("Column$", ""); } //do not remove other suffixes return s; } @Override public T getValue(ITableRow r) { T validatedValue = m_validatedValues.get(r); if (validatedValue == null) { validatedValue = getValueInternal(r); storeValidatedValue(r, validatedValue); } return validatedValue; } @SuppressWarnings("unchecked") protected T getValueInternal(ITableRow r) { return (r != null) ? (T) r.getCellValue(getColumnIndex()) : null; } @Override public T getValue(int rowIndex) { return getValue(getTable().getRow(rowIndex)); } @Override public void setValue(int rowIndex, T rawValue) throws ProcessingException { setValue(getTable().getRow(rowIndex), rawValue); } @Override public void setValue(ITableRow r, T value) throws ProcessingException { setValueInternal(r, value, null); } private void setValueInternal(ITableRow row, T value, IFormField editingField) throws ProcessingException { T newValue = validateValue(row, value); row.setCellValue(getColumnIndex(), newValue); /* * In case there is a validated value in the cache, the value passed as a parameter has to be validated. * If the passed value is valid, it will be stored in the validated value cache. Otherwise, the old validated * value is used. */ validateColumnValue(row, editingField, true, value); } @Override public void fill(T rawValue) throws ProcessingException { ITableRow[] rows = getTable().getRows(); for (ITableRow row : rows) { setValue(row, rawValue); } } @Override @SuppressWarnings("unchecked") public Class<T> getDataType() { return TypeCastUtility.getGenericsParameterClass(getClass(), IColumn.class); } @Override @SuppressWarnings("unchecked") public T[] getValues() { T[] values = (T[]) Array.newInstance(getDataType(), m_table.getRowCount()); for (int i = 0, ni = m_table.getRowCount(); i < ni; i++) { values[i] = getValue(m_table.getRow(i)); } return values; } @Override @SuppressWarnings("unchecked") public T[] getValues(ITableRow[] rows) { T[] values = (T[]) Array.newInstance(getDataType(), rows.length); for (int i = 0; i < rows.length; i++) { values[i] = getValue(rows[i]); } return values; } @Override @SuppressWarnings("unchecked") public T[] getSelectedValues() { ITableRow[] rows = m_table.getSelectedRows(); T[] values = (T[]) Array.newInstance(getDataType(), rows.length); for (int i = 0; i < rows.length; i++) { values[i] = getValue(rows[i]); } return values; } @Override public T getSelectedValue() { ITableRow row = m_table.getSelectedRow(); if (row != null) { return getValue(row); } else { return null; } } @Override public String getDisplayText(ITableRow r) { return r.getCell(getColumnIndex()).getText(); } @Override public String[] getDisplayTexts() { String[] values = new String[m_table.getRowCount()]; for (int i = 0, ni = m_table.getRowCount(); i < ni; i++) { values[i] = getDisplayText(m_table.getRow(i)); } return values; } @Override public String getSelectedDisplayText() { ITableRow row = m_table.getSelectedRow(); if (row != null) { return getDisplayText(row); } else { return null; } } @Override public String[] getSelectedDisplayTexts() { ITableRow[] rows = m_table.getSelectedRows(); String[] values = new String[rows.length]; for (int i = 0; i < rows.length; i++) { values[i] = getDisplayText(rows[i]); } return values; } @Override @SuppressWarnings("unchecked") public T[] getInsertedValues() { ITableRow[] rows = m_table.getInsertedRows(); T[] values = (T[]) Array.newInstance(getDataType(), rows.length); for (int i = 0; i < rows.length; i++) { values[i] = getValue(rows[i]); } return values; } @Override @SuppressWarnings("unchecked") public T[] getUpdatedValues() { ITableRow[] rows = m_table.getUpdatedRows(); T[] values = (T[]) Array.newInstance(getDataType(), rows.length); for (int i = 0; i < rows.length; i++) { values[i] = getValue(rows[i]); } return values; } @Override @SuppressWarnings("unchecked") public T[] getDeletedValues() { ITableRow[] rows = m_table.getDeletedRows(); T[] values = (T[]) Array.newInstance(getDataType(), rows.length); for (int i = 0; i < rows.length; i++) { values[i] = getValue(rows[i]); } return values; } @Override public ITableRow[] findRows(T[] values) { ArrayList<ITableRow> rowList = new ArrayList<ITableRow>(); if (values != null) { for (int i = 0; i < values.length; i++) { ITableRow row = findRow(values[i]); if (row != null) { rowList.add(row); } } } return rowList.toArray(new ITableRow[0]); } @Override public ITableRow[] findRows(T value) { ArrayList<ITableRow> rowList = new ArrayList<ITableRow>(); for (int i = 0, ni = m_table.getRowCount(); i < ni; i++) { ITableRow row = m_table.getRow(i); if (CompareUtility.equals(value, getValue(row))) { rowList.add(row); } } return rowList.toArray(new ITableRow[0]); } @Override public ITableRow findRow(T value) { for (int i = 0, ni = m_table.getRowCount(); i < ni; i++) { ITableRow row = m_table.getRow(i); if (CompareUtility.equals(value, getValue(row))) { return row; } } return null; } @Override public boolean contains(T value) { for (int i = 0, ni = m_table.getRowCount(); i < ni; i++) { ITableRow row = m_table.getRow(i); if (CompareUtility.equals(value, getValue(row))) { return true; } } return false; } @Override public boolean containsDuplicateValues() { return new HashSet<T>(Arrays.asList(getValues())).size() < getValues().length; } @Override public boolean isEmpty() { if (m_table != null) { for (int i = 0, ni = m_table.getRowCount(); i < ni; i++) { Object value = getValue(m_table.getRow(i)); if (value != null) { return false; } } } return true; } public void setColumnIndexInternal(int index) { m_headerCell.setColumnIndexInternal(index); } @Override public boolean isSortActive() { return getHeaderCell().isSortActive(); } @Override public boolean isSortExplicit() { return getHeaderCell().isSortExplicit(); } @Override public boolean isSortAscending() { return getHeaderCell().isSortAscending(); } @Override public boolean isSortPermanent() { return getHeaderCell().isSortPermanent(); } @Override public int getSortIndex() { ITable table = getTable(); if (table != null) { ColumnSet cs = table.getColumnSet(); if (cs != null) { return cs.getSortColumnIndex(this); } } return -1; } @Override public boolean isColumnFilterActive() { ITable table = getTable(); if (table != null) { ITableColumnFilterManager m = table.getColumnFilterManager(); if (m != null) { return m.getFilter(this) != null; } } return false; } /** * sorting of rows based on this column<br> * default: compare objects by Comparable interface or use value */ @Override @SuppressWarnings("unchecked") public int compareTableRows(ITableRow r1, ITableRow r2) { int c; T o1 = getValue(r1); T o2 = getValue(r2); if (o1 == null && o2 == null) { c = 0; } else if (o1 == null) { c = -1; } else if (o2 == null) { c = 1; } else if ((o1 instanceof Comparable) && (o2 instanceof Comparable)) { c = ((Comparable) o1).compareTo(o2); } else { c = StringUtility.compareIgnoreCase(o1.toString(), o2.toString()); } return c; } @Override public final T/* validValue */parseValue(ITableRow row, Object rawValue) throws ProcessingException { T parsedValue = execParseValue(row, rawValue); return validateValue(row, parsedValue); } /** * do not use or override this internal method<br> * subclasses perform specific value validations here and set the * default textual representation of the value */ protected T/* validValue */parseValueInternal(ITableRow row, Object rawValue) throws ProcessingException { return TypeCastUtility.castValue(rawValue, getDataType()); } @Override public T/* validValue */validateValue(ITableRow row, T rawValue) throws ProcessingException { return execValidateValue(row, rawValue); } /** * do not use or override this internal method<br> * subclasses perform specific value validations here and set the * default textual representation of the value */ protected T/* validValue */validateValueInternal(ITableRow row, T rawValue) throws ProcessingException { return rawValue; } @Override public final IFormField prepareEdit(ITableRow row) throws ProcessingException { ITable table = getTable(); if (table == null || !this.isCellEditable(row)) { return null; } IFormField f = execPrepareEdit(row); if (f != null) { f.setLabelVisible(false); GridData gd = f.getGridDataHints(); gd.weightY = 1; f.setGridDataHints(gd); } return f; } /** * do not use or override this internal method */ protected IFormField prepareEditInternal(ITableRow row) throws ProcessingException { AbstractValueField<T> f = new AbstractValueField<T>() { @Override protected void initConfig() { super.initConfig(); propertySupport.putPropertiesMap(AbstractColumn.this.propertySupport.getPropertiesMap()); } }; return f; } /** * Complete editing of a cell * <p> * By default this calls {@link #setValue(ITableRow, Object)} and delegates to * {@link #execParseValue(ITableRow, Object)} and {@link #execValidateValue(ITableRow, Object)}. */ @Override public final void completeEdit(ITableRow row, IFormField editingField) throws ProcessingException { ITable table = getTable(); if (table == null || !table.isCellEditable(row, this)) { return; } execCompleteEdit(row, editingField); } @Override public void decorateCell(ITableRow row) { Cell cell = row.getCellForUpdate(getColumnIndex()); if (cell.getErrorStatus() == null) { decorateCellInternal(cell, row); } try { execDecorateCell(cell, row); } catch (ProcessingException e) { LOG.warn(null, e); } catch (Throwable t) { LOG.warn(null, t); } } /** * do not use or override this internal method */ protected void decorateCellInternal(Cell cell, ITableRow row) { if (getForegroundColor() != null) { cell.setForegroundColor(getForegroundColor()); } if (getBackgroundColor() != null) { cell.setBackgroundColor(getBackgroundColor()); } if (getFont() != null) { cell.setFont(getFont()); } cell.setHorizontalAlignment(getHorizontalAlignment()); cell.setEditableInternal(isCellEditable(row)); } @Override public void decorateHeaderCell() { HeaderCell cell = m_headerCell; decorateHeaderCellInternal(cell); try { execDecorateHeaderCell(cell); } catch (ProcessingException e) { LOG.warn(null, e); } catch (Throwable t) { LOG.warn(null, t); } } /** * do not use or override this internal method */ protected void decorateHeaderCellInternal(HeaderCell cell) { } @Override public IHeaderCell getHeaderCell() { return m_headerCell; } @Override public int getVisibleColumnIndexHint() { return propertySupport.getPropertyInt(PROP_VIEW_COLUMN_INDEX_HINT); } @Override public void setVisibleColumnIndexHint(int index) { int oldIndex = getVisibleColumnIndexHint(); if (oldIndex != index) { propertySupport.setPropertyInt(PROP_VIEW_COLUMN_INDEX_HINT, index); } } @Override public int getInitialWidth() { return m_initialWidth; } @Override public void setInitialWidth(int w) { m_initialWidth = w; } @Override public double getViewOrder() { return propertySupport.getPropertyDouble(PROP_VIEW_ORDER); } @Override public void setViewOrder(double order) { propertySupport.setPropertyDouble(PROP_VIEW_ORDER, order); } @Override public int getWidth() { return propertySupport.getPropertyInt(PROP_WIDTH); } @Override public void setWidth(int w) { propertySupport.setPropertyInt(PROP_WIDTH, w); } @Override public void setWidthInternal(int w) { propertySupport.setPropertyNoFire(PROP_WIDTH, w); } @Override public boolean isFixedWidth() { return propertySupport.getPropertyBool(PROP_FIXED_WIDTH); } @Override public void setFixedWidth(boolean fixedWidth) { propertySupport.setPropertyBool(PROP_FIXED_WIDTH, fixedWidth); } @Override public void setHorizontalAlignment(int hAglin) { propertySupport.setPropertyInt(PROP_HORIZONTAL_ALIGNMENT, hAglin); } @Override public int getHorizontalAlignment() { return propertySupport.getPropertyInt(PROP_HORIZONTAL_ALIGNMENT); } @Override public boolean isDisplayable() { return propertySupport.getPropertyBool(PROP_DISPLAYABLE); } @Override public void setDisplayable(boolean b) { propertySupport.setPropertyBool(PROP_DISPLAYABLE, b); calculateVisible(); } @Override public boolean isVisible() { return propertySupport.getPropertyBool(PROP_VISIBLE); } @Override public void setVisible(boolean b) { m_visibleProperty = b; calculateVisible(); } private void calculateVisible() { propertySupport.setPropertyBool(PROP_VISIBLE, m_visibleGranted && isDisplayable() && m_visibleProperty); } @Override public boolean isVisibleInternal() { return m_visibleProperty; } @Override public boolean isPrimaryKey() { return m_primaryKey; } @Override public boolean isSummary() { return m_summary; } @Override public boolean isEditable() { return propertySupport.getPropertyBool(PROP_EDITABLE); } @Override public void setEditable(boolean b) { propertySupport.setPropertyBool(PROP_EDITABLE, b); } @Override public boolean isCellEditable(ITableRow row) { if (getTable() != null && getTable().isEnabled() && this.isEditable() && row != null && row.isEnabled() && row.getCell(this).isEnabled()) { try { return execIsEditable(row); } catch (Throwable t) { LOG.error("checking row " + row, t); return false; } } return false; } @Override public String getForegroundColor() { return (String) propertySupport.getProperty(PROP_FOREGROUND_COLOR); } @Override public void setForegroundColor(String c) { propertySupport.setProperty(PROP_FOREGROUND_COLOR, c); } @Override public String getBackgroundColor() { return (String) propertySupport.getProperty(PROP_BACKGROUND_COLOR); } @Override public void setBackgroundColor(String c) { propertySupport.setProperty(PROP_BACKGROUND_COLOR, c); } @Override public FontSpec getFont() { return (FontSpec) propertySupport.getProperty(PROP_FONT); } @Override public void setFont(FontSpec f) { propertySupport.setProperty(PROP_FONT, f); } /** * true: Whenever table content changes, automatically calculate optimized column width so that all column content is * displayed without * cropping. * <p> * This may display a horizontal scroll bar on the table. */ @Override public boolean isAutoOptimizeWidth() { return propertySupport.getPropertyBool(PROP_AUTO_OPTIMIZE_WIDTH); } @Override public void setAutoOptimizeWidth(boolean optimize) { propertySupport.setPropertyBool(PROP_AUTO_OPTIMIZE_WIDTH, optimize); } @Override public String toString() { return getClass().getSimpleName() + "[" + getHeaderCell().getText() + " width=" + getWidth() + (isPrimaryKey() ? " primaryKey" : "") + (isSummary() ? " summary" : "") + " viewIndexHint=" + getVisibleColumnIndexHint() + "]"; } /** * Called when a value has been changed in an editable cell. * Can be used to persist data directly after a value has been modified in a cell editor. * CAUTION: This method is called even when an invalid value has been entered in the cell editor. * In this case the last valid value is retrieved while {@link #getValue(ITableRow)} is called. * * @param row * The row changed in the table. * @throws ProcessingException */ protected void persistRowChange(ITableRow row) throws ProcessingException { } public void validateColumnValues() { if (getTable() == null) { return; } for (ITableRow row : getTable().getRows()) { validateColumnValue(row, null, true, getValue(row)); } } public void validateColumnValue(ITableRow row) { validateColumnValue(row, null, false, getValue(row)); } /** * This method should be called if single column validation should be used for performance reason and/or * if a value is set in the Scout model (and not by the UI component). In this case, the parameter editor * is null and the passed value will be used. * * @param row * The row changed in the table * @param editor * The form field editor used for validation of the value * @param singleColValidation * Defines if single column validation should be used * @param value * The value that is set in the Scout model and not in the UI component */ @SuppressWarnings("unchecked") public void validateColumnValue(ITableRow row, IFormField editor, boolean singleColValidation, T value) { if (row == null) { LOG.error("validateColumnValue called with row=null"); return; } if (!(row instanceof InternalTableRow)) { LOG.info("validateColumnValue called with row not of type " + InternalTableRow.class); return; } + if (m_isValidating) { + LOG.warn("validateColumnValue called during running validation. Value " + String.valueOf(value) + " will not be set."); + Cell cell = row.getCellForUpdate(this); + cell.setErrorStatus(ScoutTexts.get("RunningColumnValidation")); + return; + } if (isCellEditable(row)) { try { if (editor == null) { m_isValidating = true; editor = prepareEdit(row); if (editor instanceof IValueField<?>) { ((IValueField<T>) editor).setValue(value); } m_isValidating = false; } if (editor != null) { IProcessingStatus errorStatus = editor.getErrorStatus(); boolean editorValid = editor.isContentValid() && errorStatus == null; Cell cell = row.getCellForUpdate(this); if (!editorValid) { if (isDisplayable() && !isVisible()) { //column should become visible setVisible(true); } if (errorStatus != null) { cell.setErrorStatus(errorStatus); if (errorStatus instanceof ParsingFailedStatus) { cell.setText(((ParsingFailedStatus) errorStatus).getParseInputString()); } } else { cell.setErrorStatus(ScoutTexts.get("FormEmptyMandatoryFieldsMessage")); cell.setText(""); } return; } else { /* * Workaround for bugs 396848 & 408741 * Currently, we set the error status and value directly on the cell before calling the decorator. * A cleaner way is to fire a table update event like in {@link AbstractTable#fireRowsUpdated(ITableRow[] rows)} * to propagate the new error status and value. */ cell.clearErrorStatus(); cell.setValue(value); decorateCellInternal(cell, row); ITable table = getTable(); if (table instanceof AbstractTable && singleColValidation) { ((AbstractTable) table).wasEverValid(row); } } } } catch (Throwable t) { LOG.error("validating " + getTable().getClass().getSimpleName() + " for new row for column " + getClass().getSimpleName(), t); return; } } ICell cell = row.getCell(this); if (cell instanceof Cell && ((Cell) cell).getErrorStatus() == null) { removeValidatedValue(row); } } }
true
true
public void validateColumnValue(ITableRow row, IFormField editor, boolean singleColValidation, T value) { if (row == null) { LOG.error("validateColumnValue called with row=null"); return; } if (!(row instanceof InternalTableRow)) { LOG.info("validateColumnValue called with row not of type " + InternalTableRow.class); return; } if (isCellEditable(row)) { try { if (editor == null) { m_isValidating = true; editor = prepareEdit(row); if (editor instanceof IValueField<?>) { ((IValueField<T>) editor).setValue(value); } m_isValidating = false; } if (editor != null) { IProcessingStatus errorStatus = editor.getErrorStatus(); boolean editorValid = editor.isContentValid() && errorStatus == null; Cell cell = row.getCellForUpdate(this); if (!editorValid) { if (isDisplayable() && !isVisible()) { //column should become visible setVisible(true); } if (errorStatus != null) { cell.setErrorStatus(errorStatus); if (errorStatus instanceof ParsingFailedStatus) { cell.setText(((ParsingFailedStatus) errorStatus).getParseInputString()); } } else { cell.setErrorStatus(ScoutTexts.get("FormEmptyMandatoryFieldsMessage")); cell.setText(""); } return; } else { /* * Workaround for bugs 396848 & 408741 * Currently, we set the error status and value directly on the cell before calling the decorator. * A cleaner way is to fire a table update event like in {@link AbstractTable#fireRowsUpdated(ITableRow[] rows)} * to propagate the new error status and value. */ cell.clearErrorStatus(); cell.setValue(value); decorateCellInternal(cell, row); ITable table = getTable(); if (table instanceof AbstractTable && singleColValidation) { ((AbstractTable) table).wasEverValid(row); } } } } catch (Throwable t) { LOG.error("validating " + getTable().getClass().getSimpleName() + " for new row for column " + getClass().getSimpleName(), t); return; } } ICell cell = row.getCell(this); if (cell instanceof Cell && ((Cell) cell).getErrorStatus() == null) { removeValidatedValue(row); } }
public void validateColumnValue(ITableRow row, IFormField editor, boolean singleColValidation, T value) { if (row == null) { LOG.error("validateColumnValue called with row=null"); return; } if (!(row instanceof InternalTableRow)) { LOG.info("validateColumnValue called with row not of type " + InternalTableRow.class); return; } if (m_isValidating) { LOG.warn("validateColumnValue called during running validation. Value " + String.valueOf(value) + " will not be set."); Cell cell = row.getCellForUpdate(this); cell.setErrorStatus(ScoutTexts.get("RunningColumnValidation")); return; } if (isCellEditable(row)) { try { if (editor == null) { m_isValidating = true; editor = prepareEdit(row); if (editor instanceof IValueField<?>) { ((IValueField<T>) editor).setValue(value); } m_isValidating = false; } if (editor != null) { IProcessingStatus errorStatus = editor.getErrorStatus(); boolean editorValid = editor.isContentValid() && errorStatus == null; Cell cell = row.getCellForUpdate(this); if (!editorValid) { if (isDisplayable() && !isVisible()) { //column should become visible setVisible(true); } if (errorStatus != null) { cell.setErrorStatus(errorStatus); if (errorStatus instanceof ParsingFailedStatus) { cell.setText(((ParsingFailedStatus) errorStatus).getParseInputString()); } } else { cell.setErrorStatus(ScoutTexts.get("FormEmptyMandatoryFieldsMessage")); cell.setText(""); } return; } else { /* * Workaround for bugs 396848 & 408741 * Currently, we set the error status and value directly on the cell before calling the decorator. * A cleaner way is to fire a table update event like in {@link AbstractTable#fireRowsUpdated(ITableRow[] rows)} * to propagate the new error status and value. */ cell.clearErrorStatus(); cell.setValue(value); decorateCellInternal(cell, row); ITable table = getTable(); if (table instanceof AbstractTable && singleColValidation) { ((AbstractTable) table).wasEverValid(row); } } } } catch (Throwable t) { LOG.error("validating " + getTable().getClass().getSimpleName() + " for new row for column " + getClass().getSimpleName(), t); return; } } ICell cell = row.getCell(this); if (cell instanceof Cell && ((Cell) cell).getErrorStatus() == null) { removeValidatedValue(row); } }
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/toc/TOCBuilder.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/toc/TOCBuilder.java index 817e90573..b511a0593 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/toc/TOCBuilder.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/toc/TOCBuilder.java @@ -1,179 +1,178 @@ /******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.toc; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.eclipse.birt.core.util.IOUtil; import org.eclipse.birt.report.engine.api.TOCNode; /** * A class for building up TOC hierarchy */ public class TOCBuilder { /** * the root TOC entry */ private TOCNode rootNode; private TOCEntry rootEntry; /** * @param root * the root for the TOC tree */ public TOCBuilder( TOCNode root ) { rootNode = root; rootEntry = new TOCEntry( null, rootNode, rootNode ); } public TOCEntry startGroupEntry( TOCEntry parent ) { if (parent == null) { parent = rootEntry; } TOCEntry group = new TOCEntry( parent, parent.getNode( ), parent .getNode( ) ); return group; } public void closeGroupEntry( TOCEntry group ) { assert group != null; TOCEntry parent = group.parent; if ( parent != null && parent != rootEntry ) { if (parent.node == parent.root) { // this is a group entry, and it is the first child of that group, // use that entry as parent of following entry of the same group. parent.node = group.node; } } } /** * @param displayString * display string for the TOC entry * @param bookmark */ public TOCEntry startEntry( TOCEntry parent, String displayString, String bookmark ) { assert displayString != null; - assert bookmark != null; if ( parent == null ) { parent = rootEntry; } TOCNode parentNode = parent.node; TOCNode node = new TOCNode( ); String id = parentNode.getNodeID( ); if ( id == null ) { id = "toc"; } id = id + "_" + parentNode.getChildren( ).size( ); // entry.nodeid is null node.setNodeID( id ); node.setDisplayString( displayString ); node.setBookmark( bookmark == null ? id : bookmark ); node.setParent( parentNode ); parentNode.getChildren( ).add( node ); TOCEntry entry = new TOCEntry( parent, parent.getRoot( ), node ); return entry; } public TOCEntry createEntry( TOCEntry parent, String label, String bookmark ) { TOCEntry entry = startEntry( parent, label, bookmark ); closeEntry(entry); return entry; } /** * close the entry. for top level toc, all entry must be put into the root * entry. for group toc, we must create a root entry, and put all others * into the root entry. */ public void closeEntry( TOCEntry entry ) { assert entry != null; TOCEntry parent = entry.parent; if ( parent != null && parent != rootEntry ) { if (parent.node == parent.root) { // this is a group entry, and it is the first child of that group, // use that entry as parent of following entry of the same group. parent.node = entry.node; } } } public TOCEntry getTOCEntry( ) { return rootEntry; } public TOCNode getTOCNode( ) { return rootNode; } static public void write( TOCNode root, DataOutputStream out ) throws IOException { IOUtil.writeString( out, root.getNodeID( ) ); IOUtil.writeString( out, root.getDisplayString( ) ); IOUtil.writeString( out, root.getBookmark( ) ); List children = root.getChildren( ); IOUtil.writeInt( out, children.size( ) ); Iterator iter = children.iterator( ); while ( iter.hasNext( ) ) { TOCNode child = (TOCNode) iter.next( ); write( child, out ); } out.flush( ); return; } static public void read( TOCNode node, DataInputStream input ) throws IOException { String nodeId = IOUtil.readString( input ); String displayString = IOUtil.readString( input ); String bookmark = IOUtil.readString( input ); node.setNodeID( nodeId ); node.setDisplayString( displayString ); node.setBookmark( bookmark ); int size = IOUtil.readInt( input ); for ( int i = 0; i < size; i++ ) { TOCNode child = new TOCNode( ); read( child, input ); child.setParent( node ); node.getChildren( ).add( child ); } } }
true
true
public TOCEntry startEntry( TOCEntry parent, String displayString, String bookmark ) { assert displayString != null; assert bookmark != null; if ( parent == null ) { parent = rootEntry; } TOCNode parentNode = parent.node; TOCNode node = new TOCNode( ); String id = parentNode.getNodeID( ); if ( id == null ) { id = "toc"; } id = id + "_" + parentNode.getChildren( ).size( ); // entry.nodeid is null node.setNodeID( id ); node.setDisplayString( displayString ); node.setBookmark( bookmark == null ? id : bookmark ); node.setParent( parentNode ); parentNode.getChildren( ).add( node ); TOCEntry entry = new TOCEntry( parent, parent.getRoot( ), node ); return entry; }
public TOCEntry startEntry( TOCEntry parent, String displayString, String bookmark ) { assert displayString != null; if ( parent == null ) { parent = rootEntry; } TOCNode parentNode = parent.node; TOCNode node = new TOCNode( ); String id = parentNode.getNodeID( ); if ( id == null ) { id = "toc"; } id = id + "_" + parentNode.getChildren( ).size( ); // entry.nodeid is null node.setNodeID( id ); node.setDisplayString( displayString ); node.setBookmark( bookmark == null ? id : bookmark ); node.setParent( parentNode ); parentNode.getChildren( ).add( node ); TOCEntry entry = new TOCEntry( parent, parent.getRoot( ), node ); return entry; }
diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java index a5aba0c87..7347bad0a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java @@ -1,148 +1,148 @@ /** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mifosplatform.portfolio.search.service; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import org.mifosplatform.infrastructure.core.domain.JdbcSupport; import org.mifosplatform.infrastructure.core.service.TenantAwareRoutingDataSource; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.portfolio.search.data.SearchConditions; import org.mifosplatform.portfolio.search.data.SearchData; import org.mifosplatform.useradministration.domain.AppUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Service; @Service public class SearchReadPlatformServiceImpl implements SearchReadPlatformService { private final NamedParameterJdbcTemplate namedParameterjdbcTemplate; private final PlatformSecurityContext context; @Autowired public SearchReadPlatformServiceImpl(final PlatformSecurityContext context, final TenantAwareRoutingDataSource dataSource) { this.context = context; this.namedParameterjdbcTemplate = new NamedParameterJdbcTemplate(dataSource); } @Override public Collection<SearchData> retriveMatchingData(final SearchConditions searchConditions) { AppUser currentUser = context.authenticatedUser(); String hierarchy = currentUser.getOffice().getHierarchy(); SearchMapper rm = new SearchMapper(); MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("hierarchy", hierarchy + "%"); params.addValue("search", searchConditions.getSearchQuery()); params.addValue("partialSearch", "%" + searchConditions.getSearchQuery() + "%"); return this.namedParameterjdbcTemplate.query(rm.searchSchema(searchConditions), params, rm); } private static final class SearchMapper implements RowMapper<SearchData> { public String searchSchema(final SearchConditions searchConditions) { String union = " union all "; String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + " , c.office_id as parentId, o.name as parentName " + " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) "; String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + " , c.office_id as parentId, o.name as parentName " + " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or " + "(c.display_name like :partialSearch and c.display_name not like :search) or " + "(c.external_id like :partialSearch and c.external_id not like :search))"; String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + " , c.id as parentId, c.display_name as parentName " + " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) "; String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + " , c.id as parentId, c.display_name as parentName " + " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) "; String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName " + " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id " + " where o.hierarchy like :hierarchy and ci.document_key like :search) "; String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName " + " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id " + " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) "; - String groupExactMatchSql = " (select 'GROUP' as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + String groupExactMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + " , g.office_id as parentId, o.name as parentName " + " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) "; - String groupMatchSql = " (select 'GROUP' as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + String groupMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + " , g.office_id as parentId, o.name as parentName " + " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) "; StringBuffer sql = new StringBuffer(); // first include all exact matches if (searchConditions.isClientSearch()) { sql.append(clientExactMatchSql).append(union); } if (searchConditions.isLoanSeach()) { sql.append(loanExactMatchSql).append(union); } if(searchConditions.isClientIdentifierSearch()){ sql.append(clientIdentifierExactMatchSql).append(union); } if (searchConditions.isGroupSearch()) { sql.append(groupExactMatchSql).append(union); } // include all matching records if (searchConditions.isClientSearch()) { sql.append(clientMatchSql).append(union); } if (searchConditions.isLoanSeach()) { sql.append(loanMatchSql).append(union); } if(searchConditions.isClientIdentifierSearch()){ sql.append(clientIdentifierMatchSql).append(union); } if (searchConditions.isGroupSearch()) { sql.append(groupMatchSql).append(union); } sql.replace(sql.lastIndexOf(union), sql.length(), ""); // remove last occurrence of "union all" string return sql.toString(); } @Override public SearchData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long entityId = JdbcSupport.getLong(rs, "entityId"); final String entityAccountNo = rs.getString("entityAccountNo"); final String entityExternalId = rs.getString("entityExternalId"); final String entityName = rs.getString("entityName"); final String entityType = rs.getString("entityType"); final Long parentId = JdbcSupport.getLong(rs, "parentId"); final String parentName = rs.getString("parentName"); return new SearchData(entityId, entityAccountNo, entityExternalId, entityName, entityType, parentId, parentName); } } }
false
true
public String searchSchema(final SearchConditions searchConditions) { String union = " union all "; String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + " , c.office_id as parentId, o.name as parentName " + " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) "; String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + " , c.office_id as parentId, o.name as parentName " + " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or " + "(c.display_name like :partialSearch and c.display_name not like :search) or " + "(c.external_id like :partialSearch and c.external_id not like :search))"; String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + " , c.id as parentId, c.display_name as parentName " + " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) "; String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + " , c.id as parentId, c.display_name as parentName " + " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) "; String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName " + " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id " + " where o.hierarchy like :hierarchy and ci.document_key like :search) "; String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName " + " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id " + " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) "; String groupExactMatchSql = " (select 'GROUP' as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + " , g.office_id as parentId, o.name as parentName " + " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) "; String groupMatchSql = " (select 'GROUP' as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + " , g.office_id as parentId, o.name as parentName " + " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) "; StringBuffer sql = new StringBuffer(); // first include all exact matches if (searchConditions.isClientSearch()) { sql.append(clientExactMatchSql).append(union); } if (searchConditions.isLoanSeach()) { sql.append(loanExactMatchSql).append(union); } if(searchConditions.isClientIdentifierSearch()){ sql.append(clientIdentifierExactMatchSql).append(union); } if (searchConditions.isGroupSearch()) { sql.append(groupExactMatchSql).append(union); } // include all matching records if (searchConditions.isClientSearch()) { sql.append(clientMatchSql).append(union); } if (searchConditions.isLoanSeach()) { sql.append(loanMatchSql).append(union); } if(searchConditions.isClientIdentifierSearch()){ sql.append(clientIdentifierMatchSql).append(union); } if (searchConditions.isGroupSearch()) { sql.append(groupMatchSql).append(union); } sql.replace(sql.lastIndexOf(union), sql.length(), ""); // remove last occurrence of "union all" string return sql.toString(); }
public String searchSchema(final SearchConditions searchConditions) { String union = " union all "; String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + " , c.office_id as parentId, o.name as parentName " + " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) "; String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + " , c.office_id as parentId, o.name as parentName " + " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or " + "(c.display_name like :partialSearch and c.display_name not like :search) or " + "(c.external_id like :partialSearch and c.external_id not like :search))"; String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + " , c.id as parentId, c.display_name as parentName " + " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) "; String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + " , c.id as parentId, c.display_name as parentName " + " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) "; String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName " + " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id " + " where o.hierarchy like :hierarchy and ci.document_key like :search) "; String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName " + " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id " + " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) "; String groupExactMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + " , g.office_id as parentId, o.name as parentName " + " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) "; String groupMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + " , g.office_id as parentId, o.name as parentName " + " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) "; StringBuffer sql = new StringBuffer(); // first include all exact matches if (searchConditions.isClientSearch()) { sql.append(clientExactMatchSql).append(union); } if (searchConditions.isLoanSeach()) { sql.append(loanExactMatchSql).append(union); } if(searchConditions.isClientIdentifierSearch()){ sql.append(clientIdentifierExactMatchSql).append(union); } if (searchConditions.isGroupSearch()) { sql.append(groupExactMatchSql).append(union); } // include all matching records if (searchConditions.isClientSearch()) { sql.append(clientMatchSql).append(union); } if (searchConditions.isLoanSeach()) { sql.append(loanMatchSql).append(union); } if(searchConditions.isClientIdentifierSearch()){ sql.append(clientIdentifierMatchSql).append(union); } if (searchConditions.isGroupSearch()) { sql.append(groupMatchSql).append(union); } sql.replace(sql.lastIndexOf(union), sql.length(), ""); // remove last occurrence of "union all" string return sql.toString(); }
diff --git a/src/android/PushNotification.java b/src/android/PushNotification.java index 9cfb55d..b1ce030 100644 --- a/src/android/PushNotification.java +++ b/src/android/PushNotification.java @@ -1,152 +1,152 @@ package org.usergrid.cordova; import java.util.HashMap; import org.apache.cordova.api.Plugin; import org.apache.cordova.api.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.usergrid.android.client.Client; import org.usergrid.android.client.callbacks.ApiResponseCallback; import org.usergrid.android.client.callbacks.DeviceRegistrationCallback; import org.usergrid.java.client.entities.Device; import org.usergrid.java.client.entities.Entity; import org.usergrid.java.client.response.ApiResponse; import org.usergrid.java.client.utils.JsonUtils; import android.util.Log; import com.google.android.gcm.GCMRegistrar; @SuppressWarnings("deprecation") public class PushNotification extends Plugin { static final String TAG = "md.mdobs.andyPush"; public static Plugin webView; private static Device device; @Override public PluginResult execute(String action, JSONArray args, String callbackId) { webView = this; try{ if (action.equals("registerWithPushProvider")) { Client client = new Client(); JSONObject options = args.getJSONObject(0); String apiUrl = null; if(options.has("apiUrl")) { apiUrl = options.getString("apiUrl"); } else { apiUrl = "https://api.usergrid.com/"; } final String callback = callbackId; client.setApiUrl(apiUrl); client.setOrganizationId(options.getString("orgName")); client.setApplicationId(options.getString("appName")); client.registerDeviceForPushAsync(cordova.getActivity().getApplicationContext(), options.getString("notifier"), options.getString("deviceId"), null, new DeviceRegistrationCallback(){ @Override public void onResponse(Device device) { PushNotification.device = device; PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(false); success(result, callback); } @Override public void onException(Exception e) { Log.i("Push.plugin", "connect exception: " + e); PluginResult result = new PluginResult(PluginResult.Status.ERROR); result.setKeepCallback(false); error(result, callback); } @Override public void onDeviceRegistration(Device device) { // This is never called } }); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); return result; } else if (action.equals("registerDevice")) { Log.i("Push.plugin", "register device"); JSONObject options = args.getJSONObject(0); String gcmId = options.getString("gcmSenderId"); GCMRegistrar.checkDevice(cordova.getActivity().getApplicationContext()); GCMRegistrar.checkManifest(cordova.getActivity().getApplicationContext()); GCMRegistrar.register(cordova.getActivity().getApplicationContext(), gcmId); return new PluginResult(PluginResult.Status.OK); } else if (action.equals("pushNotificationToDevice")) { Client client = new Client(); JSONObject options = args.getJSONObject(0); String apiUrl = null; if(options.has("apiUrl")) { apiUrl = options.getString("apiUrl"); } else { apiUrl = "https://api.usergrid.com/"; } final String callback = callbackId; client.setApiUrl(apiUrl); client.setOrganizationId(options.getString("orgName")); client.setApplicationId(options.getString("appName")); String entityPath = "devices/" + device.getUuid().toString() + "/notifications"; Entity notification = new Entity(entityPath); HashMap<String,String> payloads = new HashMap<String, String>(); - payloads.put("android_push", options.getString("message")); + payloads.put(options.getString("notifier"), options.getString("message")); notification.setProperty("payloads", JsonUtils.toJsonNode(payloads)); client.createEntityAsync(notification, new ApiResponseCallback() { @Override public void onResponse(ApiResponse apiResponse) { Log.i("Push.plugin", "send response: " + apiResponse); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(false); success(result, callback); } @Override public void onException(Exception e) { Log.i("Push.plugin", "send exception: " + e); PluginResult result = new PluginResult(PluginResult.Status.ERROR); result.setKeepCallback(false); error(result, callback); } }); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); return result; } else { return new PluginResult(PluginResult.Status.INVALID_ACTION); } } catch (JSONException e) { Log.i("Push.plugin", "connect exception: " + e); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } } public static void sendPush(JSONObject pushMessage) { Log.i("Push.plugin", "NOTIFICATION CALLBACK"); String javascript = String.format("window.pushNotification.notificationCallback(%s)", pushMessage.toString()); webView.sendJavascript(javascript); } public static void sendRegistration(JSONObject registrationMessage) { Log.i("Push.plugin", "REGISTRATION CALLBACK"); String javascript = String.format("window.pushNotification.registrationCallback(%s)", registrationMessage.toString()); webView.sendJavascript(javascript); } }
true
true
public PluginResult execute(String action, JSONArray args, String callbackId) { webView = this; try{ if (action.equals("registerWithPushProvider")) { Client client = new Client(); JSONObject options = args.getJSONObject(0); String apiUrl = null; if(options.has("apiUrl")) { apiUrl = options.getString("apiUrl"); } else { apiUrl = "https://api.usergrid.com/"; } final String callback = callbackId; client.setApiUrl(apiUrl); client.setOrganizationId(options.getString("orgName")); client.setApplicationId(options.getString("appName")); client.registerDeviceForPushAsync(cordova.getActivity().getApplicationContext(), options.getString("notifier"), options.getString("deviceId"), null, new DeviceRegistrationCallback(){ @Override public void onResponse(Device device) { PushNotification.device = device; PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(false); success(result, callback); } @Override public void onException(Exception e) { Log.i("Push.plugin", "connect exception: " + e); PluginResult result = new PluginResult(PluginResult.Status.ERROR); result.setKeepCallback(false); error(result, callback); } @Override public void onDeviceRegistration(Device device) { // This is never called } }); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); return result; } else if (action.equals("registerDevice")) { Log.i("Push.plugin", "register device"); JSONObject options = args.getJSONObject(0); String gcmId = options.getString("gcmSenderId"); GCMRegistrar.checkDevice(cordova.getActivity().getApplicationContext()); GCMRegistrar.checkManifest(cordova.getActivity().getApplicationContext()); GCMRegistrar.register(cordova.getActivity().getApplicationContext(), gcmId); return new PluginResult(PluginResult.Status.OK); } else if (action.equals("pushNotificationToDevice")) { Client client = new Client(); JSONObject options = args.getJSONObject(0); String apiUrl = null; if(options.has("apiUrl")) { apiUrl = options.getString("apiUrl"); } else { apiUrl = "https://api.usergrid.com/"; } final String callback = callbackId; client.setApiUrl(apiUrl); client.setOrganizationId(options.getString("orgName")); client.setApplicationId(options.getString("appName")); String entityPath = "devices/" + device.getUuid().toString() + "/notifications"; Entity notification = new Entity(entityPath); HashMap<String,String> payloads = new HashMap<String, String>(); payloads.put("android_push", options.getString("message")); notification.setProperty("payloads", JsonUtils.toJsonNode(payloads)); client.createEntityAsync(notification, new ApiResponseCallback() { @Override public void onResponse(ApiResponse apiResponse) { Log.i("Push.plugin", "send response: " + apiResponse); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(false); success(result, callback); } @Override public void onException(Exception e) { Log.i("Push.plugin", "send exception: " + e); PluginResult result = new PluginResult(PluginResult.Status.ERROR); result.setKeepCallback(false); error(result, callback); } }); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); return result; } else { return new PluginResult(PluginResult.Status.INVALID_ACTION); } } catch (JSONException e) { Log.i("Push.plugin", "connect exception: " + e); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } }
public PluginResult execute(String action, JSONArray args, String callbackId) { webView = this; try{ if (action.equals("registerWithPushProvider")) { Client client = new Client(); JSONObject options = args.getJSONObject(0); String apiUrl = null; if(options.has("apiUrl")) { apiUrl = options.getString("apiUrl"); } else { apiUrl = "https://api.usergrid.com/"; } final String callback = callbackId; client.setApiUrl(apiUrl); client.setOrganizationId(options.getString("orgName")); client.setApplicationId(options.getString("appName")); client.registerDeviceForPushAsync(cordova.getActivity().getApplicationContext(), options.getString("notifier"), options.getString("deviceId"), null, new DeviceRegistrationCallback(){ @Override public void onResponse(Device device) { PushNotification.device = device; PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(false); success(result, callback); } @Override public void onException(Exception e) { Log.i("Push.plugin", "connect exception: " + e); PluginResult result = new PluginResult(PluginResult.Status.ERROR); result.setKeepCallback(false); error(result, callback); } @Override public void onDeviceRegistration(Device device) { // This is never called } }); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); return result; } else if (action.equals("registerDevice")) { Log.i("Push.plugin", "register device"); JSONObject options = args.getJSONObject(0); String gcmId = options.getString("gcmSenderId"); GCMRegistrar.checkDevice(cordova.getActivity().getApplicationContext()); GCMRegistrar.checkManifest(cordova.getActivity().getApplicationContext()); GCMRegistrar.register(cordova.getActivity().getApplicationContext(), gcmId); return new PluginResult(PluginResult.Status.OK); } else if (action.equals("pushNotificationToDevice")) { Client client = new Client(); JSONObject options = args.getJSONObject(0); String apiUrl = null; if(options.has("apiUrl")) { apiUrl = options.getString("apiUrl"); } else { apiUrl = "https://api.usergrid.com/"; } final String callback = callbackId; client.setApiUrl(apiUrl); client.setOrganizationId(options.getString("orgName")); client.setApplicationId(options.getString("appName")); String entityPath = "devices/" + device.getUuid().toString() + "/notifications"; Entity notification = new Entity(entityPath); HashMap<String,String> payloads = new HashMap<String, String>(); payloads.put(options.getString("notifier"), options.getString("message")); notification.setProperty("payloads", JsonUtils.toJsonNode(payloads)); client.createEntityAsync(notification, new ApiResponseCallback() { @Override public void onResponse(ApiResponse apiResponse) { Log.i("Push.plugin", "send response: " + apiResponse); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(false); success(result, callback); } @Override public void onException(Exception e) { Log.i("Push.plugin", "send exception: " + e); PluginResult result = new PluginResult(PluginResult.Status.ERROR); result.setKeepCallback(false); error(result, callback); } }); PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); result.setKeepCallback(true); return result; } else { return new PluginResult(PluginResult.Status.INVALID_ACTION); } } catch (JSONException e) { Log.i("Push.plugin", "connect exception: " + e); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } }
diff --git a/src/main/java/fi/csc/microarray/client/workflow/WorkflowManager.java b/src/main/java/fi/csc/microarray/client/workflow/WorkflowManager.java index 2371997aa..42de20f42 100644 --- a/src/main/java/fi/csc/microarray/client/workflow/WorkflowManager.java +++ b/src/main/java/fi/csc/microarray/client/workflow/WorkflowManager.java @@ -1,171 +1,171 @@ package fi.csc.microarray.client.workflow; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Logger; import bsh.EvalError; import bsh.Interpreter; import fi.csc.microarray.client.AtEndListener; import fi.csc.microarray.client.ClientApplication; import fi.csc.microarray.client.Session; import fi.csc.microarray.client.dialog.ChipsterDialog.DetailsVisibility; import fi.csc.microarray.client.dialog.DialogInfo.Severity; import fi.csc.microarray.client.workflow.api.WfApplication; import fi.csc.microarray.config.DirectoryLayout; import fi.csc.microarray.util.Exceptions; import fi.csc.microarray.util.GeneralFileFilter; /** * * @author Aleksi Kallio * */ public class WorkflowManager { static final Logger logger = Logger.getLogger(WorkflowManager.class); public static final String WORKFLOW_VERSION = "BSH/2"; public static void checkVersionHeaderLine(String line) throws IllegalArgumentException { if (!line.contains(WORKFLOW_VERSION + " ")) { throw new IllegalArgumentException("Script version not supported. Supported version is " + WORKFLOW_VERSION + ", but script begins with " + line); } } public static final String SCRIPT_EXTENSION = "bsh"; String[] extensions = { WorkflowManager.SCRIPT_EXTENSION }; public static final GeneralFileFilter FILE_FILTER = new GeneralFileFilter("Workflow in BeanShell format", new String[]{ WorkflowManager.SCRIPT_EXTENSION }); public File scriptDirectory; private ClientApplication application; public WorkflowManager(ClientApplication application) throws IOException { this.application = application; this.scriptDirectory = DirectoryLayout.getInstance().getUserDataDir(); } public List<File> getWorkflows() { LinkedList<File> workflows = new LinkedList<File>(); File[] scripts = scriptDirectory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(SCRIPT_EXTENSION); } }); if(scripts != null){ //May be null if user's home folder isn't found for (File script : scripts) { workflows.add(script); } } return workflows; } public void runScript(final File file, final AtEndListener listener) { try { runScript(file.toURL(), listener); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } public void runScript(final URL workflowUrl, final AtEndListener listener) { Runnable runnable = new Runnable() { public void run() { BufferedReader in = null; boolean success = false; try { in = new BufferedReader(new InputStreamReader(workflowUrl.openConnection().getInputStream())); String line = in.readLine(); checkVersionHeaderLine(line); in.close(); Interpreter i = initialiseBshEnvironment(); i.eval(new InputStreamReader(workflowUrl.openConnection().getInputStream())); success = true; } catch (Throwable e) { logger.warn("running workflow failed", e); String workflowName = ""; try { workflowName = " " + workflowUrl.getPath().substring(workflowUrl.getPath().lastIndexOf('/') + 1); } catch (Exception we) { } application.showDialog("Running workflow" + workflowName + " failed.", - "The most common reason for a workflow failure is that the data used as an input for the worklfow " + - " is not compatible with the tools in the workflow. This causes one of tools to fail and aborting the rest " + + "The most common reason for a workflow failure is that the data used as an input for the workflow" + + " is not compatible with the tools in the workflow. This causes one of tools to fail and aborting the rest" + " of the workflow.\n\n" + "To get an idea of why a tool has failed, please see the tool specific failure window.", Exceptions.getStackTrace(e), Severity.WARNING, false, DetailsVisibility.DETAILS_ALWAYS_HIDDEN); } finally { if (listener != null) { listener.atEnd(success); } if (in != null) { try { in.close(); // might be closed twice but that is legal } catch (IOException e) {} } } } }; new Thread(runnable).start(); } public Interpreter initialiseBshEnvironment() { Interpreter i = new Interpreter(); try { i.set("app", new WfApplication(Session.getSession().getApplication())); } catch (EvalError ee) { throw new RuntimeException("BeanShell console failed to open: " + ee.getMessage()); } return i; } public void saveSelectedWorkflow(File selectedFile) throws IOException { WorkflowWriter writer = new WorkflowWriter(); StringBuffer script = writer.writeWorkflow(application.getSelectionManager().getSelectedDataBean()); saveScript(selectedFile, script); // did we skip something? if (!writer.writeWarnings().isEmpty()) { String details = ""; for (String warning: writer.writeWarnings()) { details += warning + "\n"; } application.showDialog("Workflow not fully saved", "Some parts of workflow structure are not supported by current workflow system and they were skipped. The rest of the workflow was successfully saved.", details, Severity.INFO, false); } } private void saveScript(File scriptFile, StringBuffer currentWorkflowScript) throws IOException { PrintWriter scriptOut = null; try { scriptOut = new PrintWriter(new OutputStreamWriter(new FileOutputStream(scriptFile))); scriptOut.print(currentWorkflowScript.toString()); } finally { if (scriptOut != null) { scriptOut.close(); } } } public File getScriptDirectory() { return scriptDirectory; } }
true
true
public void runScript(final URL workflowUrl, final AtEndListener listener) { Runnable runnable = new Runnable() { public void run() { BufferedReader in = null; boolean success = false; try { in = new BufferedReader(new InputStreamReader(workflowUrl.openConnection().getInputStream())); String line = in.readLine(); checkVersionHeaderLine(line); in.close(); Interpreter i = initialiseBshEnvironment(); i.eval(new InputStreamReader(workflowUrl.openConnection().getInputStream())); success = true; } catch (Throwable e) { logger.warn("running workflow failed", e); String workflowName = ""; try { workflowName = " " + workflowUrl.getPath().substring(workflowUrl.getPath().lastIndexOf('/') + 1); } catch (Exception we) { } application.showDialog("Running workflow" + workflowName + " failed.", "The most common reason for a workflow failure is that the data used as an input for the worklfow " + " is not compatible with the tools in the workflow. This causes one of tools to fail and aborting the rest " + " of the workflow.\n\n" + "To get an idea of why a tool has failed, please see the tool specific failure window.", Exceptions.getStackTrace(e), Severity.WARNING, false, DetailsVisibility.DETAILS_ALWAYS_HIDDEN); } finally { if (listener != null) { listener.atEnd(success); } if (in != null) { try { in.close(); // might be closed twice but that is legal } catch (IOException e) {} } } } }; new Thread(runnable).start(); }
public void runScript(final URL workflowUrl, final AtEndListener listener) { Runnable runnable = new Runnable() { public void run() { BufferedReader in = null; boolean success = false; try { in = new BufferedReader(new InputStreamReader(workflowUrl.openConnection().getInputStream())); String line = in.readLine(); checkVersionHeaderLine(line); in.close(); Interpreter i = initialiseBshEnvironment(); i.eval(new InputStreamReader(workflowUrl.openConnection().getInputStream())); success = true; } catch (Throwable e) { logger.warn("running workflow failed", e); String workflowName = ""; try { workflowName = " " + workflowUrl.getPath().substring(workflowUrl.getPath().lastIndexOf('/') + 1); } catch (Exception we) { } application.showDialog("Running workflow" + workflowName + " failed.", "The most common reason for a workflow failure is that the data used as an input for the workflow" + " is not compatible with the tools in the workflow. This causes one of tools to fail and aborting the rest" + " of the workflow.\n\n" + "To get an idea of why a tool has failed, please see the tool specific failure window.", Exceptions.getStackTrace(e), Severity.WARNING, false, DetailsVisibility.DETAILS_ALWAYS_HIDDEN); } finally { if (listener != null) { listener.atEnd(success); } if (in != null) { try { in.close(); // might be closed twice but that is legal } catch (IOException e) {} } } } }; new Thread(runnable).start(); }
diff --git a/src/de/danoeh/antennapod/util/FileNameGenerator.java b/src/de/danoeh/antennapod/util/FileNameGenerator.java index 37fac28a..702df62b 100644 --- a/src/de/danoeh/antennapod/util/FileNameGenerator.java +++ b/src/de/danoeh/antennapod/util/FileNameGenerator.java @@ -1,36 +1,36 @@ package de.danoeh.antennapod.util; import java.util.Arrays; /** Generates valid filenames for a given string. */ public class FileNameGenerator { private static final char[] ILLEGAL_CHARACTERS = { '/', '\\', '?', '%', '*', ':', '|', '"', '<', '>' }; static { Arrays.sort(ILLEGAL_CHARACTERS); } private FileNameGenerator() { } /** * This method will return a new string that doesn't contain any illegal * characters of the given string. */ public static String generateFileName(String string) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (Arrays.binarySearch(ILLEGAL_CHARACTERS, c) < 0) { - builder.append(c).replaceFirst(" *$",""); + builder.append(c); } } - return builder.toString(); + return builder.toString().replaceFirst(" *$",""); } public static long generateLong(final String str) { return str.hashCode(); } }
false
true
public static String generateFileName(String string) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (Arrays.binarySearch(ILLEGAL_CHARACTERS, c) < 0) { builder.append(c).replaceFirst(" *$",""); } } return builder.toString(); }
public static String generateFileName(String string) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (Arrays.binarySearch(ILLEGAL_CHARACTERS, c) < 0) { builder.append(c); } } return builder.toString().replaceFirst(" *$",""); }
diff --git a/src/cello/jtablet/installer/JTabletExtension.java b/src/cello/jtablet/installer/JTabletExtension.java index c861c27..6067716 100644 --- a/src/cello/jtablet/installer/JTabletExtension.java +++ b/src/cello/jtablet/installer/JTabletExtension.java @@ -1,212 +1,212 @@ package cello.jtablet.installer; import java.applet.Applet; import java.awt.Component; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import cello.jtablet.impl.PluginConstant; /** * This class provides a system for JTablet version compatibility for Applets and Applications. Even if you are bundling * JTablet in your product, an older version of JTablet installed as an extension will override and potentially conflict * with your program. This class provides three mechanisms for dynamically understanding the situation: * * <ol> * <li>Use {@link #checkCompatibility(Component, String)} to ensure any installed JTablet is compatible. * This will display a simple (English) GUI asking the user to upgrade if they have an older version installed.</li> * * <li>{@link #getInstallStatus(String)} to determine the installation status (such as if an upgrade is required) and * call {@link #install(Component, String)} to perform the install itself.</li> * * <li>{@link #getInstalledVersion()} to determine the exact versio of JTablet installed.</li> * * </ol> * * <p>For the best user experience, choose the earliest version of JTablet that makes sense for your application. * * @author marcello */ public class JTabletExtension { /** * Describes the current install state as returned by {@link JTabletExtension#getInstallStatus(String)}. * * @author marcello */ public enum InstallStatus { /** * JTablet is not installed as an extension. */ NOT_INSTALLED, /** * An older version of JTablet is installed and may cause problems/errors. */ UPDATE_REQUIRED, /** * An equal or newer version of JTablet is installed. */ INSTALLED } private static final String MESSAGE_TITLE = "JTablet Version Check"; private static final String INSTALL_URL = "https://secure.cellosoft.com/jtablet/install"; /** * Returns the currently installed version of JTablet. * * @return the version, or null, if it is not installed */ public static String getInstalledVersion() { Package p = getInstalledPackage(); if (p == null) { return getLegacyJTabletVersion(); } return p.getImplementationVersion(); } /** * Checks the installed version of JTablet and determines if an upgrade is required. * * @param desiredMinimumVersion the version of JTablet to compare to * @return the installed version */ public static InstallStatus getInstallStatus(String desiredMinimumVersion) { Package installedVersion = getInstalledPackage(); if (installedVersion == null) { return InstallStatus.NOT_INSTALLED; } String version = installedVersion.getSpecificationVersion(); if (version == null) { return InstallStatus.NOT_INSTALLED; } if (!installedVersion.isCompatibleWith(desiredMinimumVersion)) { return InstallStatus.UPDATE_REQUIRED; } return InstallStatus.INSTALLED; } /** * Opens up a web-page to install (or upgrade) JTablet (if necessary). * * <p>In the future, this method may do a silent/in-place install if called prior to loading any JTablet classes. * * @param parentComponent the parent component for showing UI messages * @param desiredMinimumVersion the minimum version of JTablet to install, or null to install regardless * @return true if the upgrade was successful. * (This only happens if the desiredMinimumVersion is already installed. In the future it may be true after * an in-place install/upgrade.) * @throws IOException if there was a problem attempting to do an upgrade */ public static boolean install(Component parentComponent, String desiredMinimumVersion) throws IOException { if (desiredMinimumVersion != null && getInstallStatus(desiredMinimumVersion) == InstallStatus.INSTALLED) { return true; } Component root = SwingUtilities.getRoot(parentComponent); URL installUrl = getInstallUrl(desiredMinimumVersion); if (root instanceof Applet) { Applet applet = (Applet)root; applet.getAppletContext().showDocument(installUrl); } else { try { BrowserLauncher.browse(installUrl.toURI()); } catch (URISyntaxException e) { throw new IOException("Error navigating to URL: "+installUrl); } } return false; } /** * Checks the installed version of JTablet, and displays a message to the user if an incompatible version is found. * The method returns true if not conflicts are found. * * <p><b>Note:</b> This method will still return true if JTablet is <b>not</b> installed. If you want to require * JTablet be installed, you should use JTablet as an extension. * * @param parentComponent the component to launch the UI from (this is used to detect Applets) * @param desiredMinimumVersion the minimum version of JTablet required for the upgrade * (you may get a later version) * @return true if no JTablet conflicts were found */ public static boolean checkCompatibility(Component parentComponent, String desiredMinimumVersion) { switch (getInstallStatus(desiredMinimumVersion)) { case UPDATE_REQUIRED: return showUpgradeDialog(parentComponent, desiredMinimumVersion); } return true; } private static String getLegacyJTabletVersion() { try { // Get a class object through Reflection API Class<?> jtablet = Class.forName("cello.tablet.JTablet"); // Create an instance of the object Object tablet = jtablet.newInstance(); try { // getVersion() was added in 0.2 BETA 2 // You can safely assume this function will exist, since the 0.1 BETA // was distributed to a select group of users. // If the user is using 0.1 BETA, you aren't required to support them // so you can simply recommend an upgrade. Method tablet_getVersion = jtablet.getMethod("getVersion"); // Invoke function return (String)tablet_getVersion.invoke(tablet); } catch (Exception e) { // If the class exists but the getVersion method doesn't, // they are using the old 0.1 beta version (highly unlikely) return "0.1.0-beta"; } - } catch (Exception e) { - // No JTablet found + } catch (Throwable e) { + // No JTablet found (or there was an error loading it) return null; } } private static Package getInstalledPackage() { if (!PluginConstant.IS_PLUGIN) { return null; } Package p = JTabletExtension.class.getPackage(); if (p == null) { return null; } return p; } private static URL getInstallUrl(String version) throws MalformedURLException { return new URL(INSTALL_URL + "?version="+version); } private static boolean showUpgradeDialog(Component parent, String version) { if (JOptionPane.showConfirmDialog( parent, "This program requires JTablet "+version+".\n\n"+ "You have JTablet "+getInstalledVersion()+" installed which may conflict.\n\n"+ "Would you like to open the JTablet update website?", MESSAGE_TITLE, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { try { return install(parent, version); } catch (Exception e) { JOptionPane.showMessageDialog( parent, "Unable to open JTablet website", MESSAGE_TITLE, JOptionPane.ERROR_MESSAGE); } } return false; } }
true
true
private static String getLegacyJTabletVersion() { try { // Get a class object through Reflection API Class<?> jtablet = Class.forName("cello.tablet.JTablet"); // Create an instance of the object Object tablet = jtablet.newInstance(); try { // getVersion() was added in 0.2 BETA 2 // You can safely assume this function will exist, since the 0.1 BETA // was distributed to a select group of users. // If the user is using 0.1 BETA, you aren't required to support them // so you can simply recommend an upgrade. Method tablet_getVersion = jtablet.getMethod("getVersion"); // Invoke function return (String)tablet_getVersion.invoke(tablet); } catch (Exception e) { // If the class exists but the getVersion method doesn't, // they are using the old 0.1 beta version (highly unlikely) return "0.1.0-beta"; } } catch (Exception e) { // No JTablet found return null; } }
private static String getLegacyJTabletVersion() { try { // Get a class object through Reflection API Class<?> jtablet = Class.forName("cello.tablet.JTablet"); // Create an instance of the object Object tablet = jtablet.newInstance(); try { // getVersion() was added in 0.2 BETA 2 // You can safely assume this function will exist, since the 0.1 BETA // was distributed to a select group of users. // If the user is using 0.1 BETA, you aren't required to support them // so you can simply recommend an upgrade. Method tablet_getVersion = jtablet.getMethod("getVersion"); // Invoke function return (String)tablet_getVersion.invoke(tablet); } catch (Exception e) { // If the class exists but the getVersion method doesn't, // they are using the old 0.1 beta version (highly unlikely) return "0.1.0-beta"; } } catch (Throwable e) { // No JTablet found (or there was an error loading it) return null; } }
diff --git a/pdfbox/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java b/pdfbox/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java index 0103b17c..2836ea7e 100644 --- a/pdfbox/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java +++ b/pdfbox/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java @@ -1,714 +1,714 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.util; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Stack; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.cos.COSStream; import org.apache.pdfbox.exceptions.WrappedIOException; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.graphics.PDGraphicsState; import org.apache.pdfbox.util.operator.OperatorProcessor; /** * This class will run through a PDF content stream and execute certain operations * and provide a callback interface for clients that want to do things with the stream. * See the PDFTextStripper class for an example of how to use this class. * * @author <a href="mailto:[email protected]">Ben Litchfield</a> * @version $Revision: 1.38 $ */ public class PDFStreamEngine { /** * Log instance. */ private static final Log log = LogFactory.getLog(PDFStreamEngine.class); /** * The PDF operators that are ignored by this engine. */ private final Set<String> unsupportedOperators = new HashSet<String>(); private static final byte[] SPACE_BYTES = { (byte)32 }; private PDGraphicsState graphicsState = null; private Matrix textMatrix = null; private Matrix textLineMatrix = null; private Stack graphicsStack = new Stack(); private Map operators = new HashMap(); private Stack streamResourcesStack = new Stack(); private PDPage page; private Map documentFontCache = new HashMap(); private int validCharCnt; private int totalCharCnt; /** * This is a simple internal class used by the Stream engine to handle the * resources stack. */ private static class StreamResources { private Map fonts; private Map colorSpaces; private Map xobjects; private Map graphicsStates; private PDResources resources; private StreamResources() {}; } /** * Constructor. */ public PDFStreamEngine() { //default constructor validCharCnt = 0; totalCharCnt = 0; } /** * Constructor with engine properties. The property keys are all * PDF operators, the values are class names used to execute those * operators. An empty value means that the operator will be silently * ignored. * * @param properties The engine properties. * * @throws IOException If there is an error setting the engine properties. */ public PDFStreamEngine( Properties properties ) throws IOException { if( properties == null ) { throw new NullPointerException( "properties cannot be null" ); } Enumeration<?> names = properties.propertyNames(); for ( Object name : Collections.list( names ) ) { String operator = name.toString(); String processorClassName = properties.getProperty( operator ); if( "".equals( processorClassName ) ) { unsupportedOperators.add( operator ); } else { try { Class<?> klass = Class.forName( processorClassName ); OperatorProcessor processor = (OperatorProcessor) klass.newInstance(); registerOperatorProcessor( operator, processor ); } catch( Exception e ) { throw new WrappedIOException( "OperatorProcessor class " + processorClassName + " could not be instantiated", e ); } } } validCharCnt = 0; totalCharCnt = 0; } /** * Register a custom operator processor with the engine. * * @param operator The operator as a string. * @param op Processor instance. */ public void registerOperatorProcessor( String operator, OperatorProcessor op ) { op.setContext( this ); operators.put( operator, op ); } /** * This method must be called between processing documents. The * PDFStreamEngine caches information for the document between pages * and this will release the cached information. This only needs * to be called if processing a new document. * */ public void resetEngine() { documentFontCache.clear(); validCharCnt = 0; totalCharCnt = 0; } /** * This will process the contents of the stream. * * @param aPage The page. * @param resources The location to retrieve resources. * @param cosStream the Stream to execute. * * * @throws IOException if there is an error accessing the stream. */ public void processStream( PDPage aPage, PDResources resources, COSStream cosStream ) throws IOException { graphicsState = new PDGraphicsState(aPage.findCropBox()); textMatrix = null; textLineMatrix = null; graphicsStack.clear(); streamResourcesStack.clear(); processSubStream( aPage, resources, cosStream ); } /** * Process a sub stream of the current stream. * * @param aPage The page used for drawing. * @param resources The resources used when processing the stream. * @param cosStream The stream to process. * * @throws IOException If there is an exception while processing the stream. */ public void processSubStream( PDPage aPage, PDResources resources, COSStream cosStream ) throws IOException { page = aPage; if( resources != null ) { StreamResources sr = new StreamResources(); sr.fonts = resources.getFonts( documentFontCache ); sr.colorSpaces = resources.getColorSpaces(); sr.xobjects = resources.getXObjects(); sr.graphicsStates = resources.getGraphicsStates(); sr.resources = resources; streamResourcesStack.push(sr); } try { List arguments = new ArrayList(); List tokens = cosStream.getStreamTokens(); if( tokens != null ) { Iterator iter = tokens.iterator(); while( iter.hasNext() ) { Object next = iter.next(); if( next instanceof COSObject ) { arguments.add( ((COSObject)next).getObject() ); } else if( next instanceof PDFOperator ) { processOperator( (PDFOperator)next, arguments ); arguments = new ArrayList(); } else { arguments.add( next ); } if(log.isDebugEnabled()) { log.debug("token: " + next); } } } } finally { if( resources != null ) { streamResourcesStack.pop(); } } } /** * A method provided as an event interface to allow a subclass to perform * some specific functionality when text needs to be processed. * * @param text The text to be processed. */ protected void processTextPosition( TextPosition text ) { //subclasses can override to provide specific functionality. } /** * Process encoded text from the PDF Stream. * You should override this method if you want to perform an action when * encoded text is being processed. * * @param string The encoded text * * @throws IOException If there is an error processing the string */ public void processEncodedText( byte[] string ) throws IOException { /* Note on variable names. There are three different units being used * in this code. Character sizes are given in glyph units, text locations * are initially given in text units, and we want to save the data in * display units. The variable names should end with Text or Disp to * represent if the values are in text or disp units (no glyph units are saved). */ final float fontSizeText = graphicsState.getTextState().getFontSize(); final float horizontalScalingText = graphicsState.getTextState().getHorizontalScalingPercent()/100f; //float verticalScalingText = horizontalScaling;//not sure if this is right but what else to do??? final float riseText = graphicsState.getTextState().getRise(); final float wordSpacingText = graphicsState.getTextState().getWordSpacing(); final float characterSpacingText = graphicsState.getTextState().getCharacterSpacing(); //We won't know the actual number of characters until //we process the byte data(could be two bytes each) but //it won't ever be more than string.length*2(there are some cases //were a single byte will result in two output characters "fi" final PDFont font = graphicsState.getTextState().getFont(); //This will typically be 1000 but in the case of a type3 font //this might be a different number final float glyphSpaceToTextSpaceFactor = 1f/font.getFontMatrix().getValue( 0, 0 ); float spaceWidthText=0; try{ // to avoid crash as described in PDFBOX-614 // lets see what the space displacement should be spaceWidthText = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor); }catch (Throwable exception) { log.warn( exception, exception); } if( spaceWidthText == 0 ) { spaceWidthText = (font.getAverageFontWidth()/glyphSpaceToTextSpaceFactor); //The average space width appears to be higher than necessary //so lets make it a little bit smaller. spaceWidthText *= .80f; } /* Convert textMatrix to display units */ final Matrix initialMatrix = new Matrix(); initialMatrix.setValue(0,0,1); initialMatrix.setValue(0,1,0); initialMatrix.setValue(0,2,0); initialMatrix.setValue(1,0,0); initialMatrix.setValue(1,1,1); initialMatrix.setValue(1,2,0); initialMatrix.setValue(2,0,0); initialMatrix.setValue(2,1,riseText); initialMatrix.setValue(2,2,1); final Matrix ctm = graphicsState.getCurrentTransformationMatrix(); final Matrix dispMatrix = initialMatrix.multiply( ctm ); Matrix textMatrixStDisp = textMatrix.multiply( dispMatrix ); Matrix textMatrixEndDisp = null; final float xScaleDisp = textMatrixStDisp.getXScale(); final float yScaleDisp = textMatrixStDisp.getYScale(); final float spaceWidthDisp = spaceWidthText * xScaleDisp * fontSizeText; final float wordSpacingDisp = wordSpacingText * xScaleDisp * fontSizeText; float maxVerticalDisplacementText = 0; float[] individualWidthsBuffer = new float[string.length]; StringBuilder characterBuffer = new StringBuilder(string.length); int codeLength = 1; for( int i=0; i<string.length; i+=codeLength ) { // Decode the value to a Unicode character codeLength = 1; String c = font.encode( string, i, codeLength ); if( c == null && i+1<string.length) { //maybe a multibyte encoding codeLength++; c = font.encode( string, i, codeLength ); } //todo, handle horizontal displacement // get the width and height of this character in text units float characterHorizontalDisplacementText = (font.getFontWidth( string, i, codeLength )/glyphSpaceToTextSpaceFactor); maxVerticalDisplacementText = Math.max( maxVerticalDisplacementText, font.getFontHeight( string, i, codeLength)/glyphSpaceToTextSpaceFactor); // PDF Spec - 5.5.2 Word Spacing // // Word spacing works the same was as character spacing, but applies // only to the space character, code 32. // // Note: Word spacing is applied to every occurrence of the single-byte // character code 32 in a string. This can occur when using a simple // font or a composite font that defines code 32 as a single-byte code. // It does not apply to occurrences of the byte value 32 in multiple-byte // codes. // // RDD - My interpretation of this is that only character code 32's that // encode to spaces should have word spacing applied. Cases have been // observed where a font has a space character with a character code // other than 32, and where word spacing (Tw) was used. In these cases, // applying word spacing to either the non-32 space or to the character // code 32 non-space resulted in errors consistent with this interpretation. // float spacingText = characterSpacingText; if( (string[i] == 0x20) && codeLength == 1 ) { spacingText += wordSpacingText; } /* The text matrix gets updated after each glyph is placed. The updated * version will have the X and Y coordinates for the next glyph. */ Matrix glyphMatrixStDisp = textMatrix.multiply( dispMatrix ); //The adjustment will always be zero. The adjustment as shown in the //TJ operator will be handled separately. float adjustment=0; // TODO : tx should be set for horizontal text and ty for vertical text // which seems to be specified in the font (not the direction in the matrix). float tx = ((characterHorizontalDisplacementText-adjustment/glyphSpaceToTextSpaceFactor)*fontSizeText) * horizontalScalingText; float ty = 0; Matrix td = new Matrix(); td.setValue( 2, 0, tx ); td.setValue( 2, 1, ty ); textMatrix = td.multiply( textMatrix ); Matrix glyphMatrixEndDisp = textMatrix.multiply( dispMatrix ); float sx = spacingText * horizontalScalingText; float sy = 0; Matrix sd = new Matrix(); sd.setValue( 2, 0, sx ); sd.setValue( 2, 1, sy ); textMatrix = sd.multiply( textMatrix ); // determine the width of this character // XXX: Note that if we handled vertical text, we should be using Y here float widthText = glyphMatrixEndDisp.getXPosition() - glyphMatrixStDisp.getXPosition(); while( characterBuffer.length() + ( c != null ? c.length() : 1 ) > individualWidthsBuffer.length ) { float[] tmp = new float[individualWidthsBuffer.length * 2]; System.arraycopy( individualWidthsBuffer, 0, tmp, 0, individualWidthsBuffer.length ); individualWidthsBuffer = tmp; } //there are several cases where one character code will //output multiple characters. For example "fi" or a //glyphname that has no mapping like "visiblespace" if( c != null ) { Arrays.fill( individualWidthsBuffer, characterBuffer.length(), characterBuffer.length() + c.length(), widthText / c.length()); validCharCnt += c.length(); } else { // PDFBOX-373: Replace a null entry with "?" so it is // not printed as "(null)" c = "?"; individualWidthsBuffer[characterBuffer.length()] = widthText; } characterBuffer.append(c); totalCharCnt += c.length(); - if( spacingText == 0 && (i + codeLength) < (string.length - 1) ) + if( spacingText == 0 && (i + codeLength) < string.length ) { continue; } textMatrixEndDisp = glyphMatrixEndDisp; float totalVerticalDisplacementDisp = maxVerticalDisplacementText * fontSizeText * yScaleDisp; float[] individualWidths = new float[characterBuffer.length()]; System.arraycopy( individualWidthsBuffer, 0, individualWidths, 0, individualWidths.length ); // process the decoded text processTextPosition( new TextPosition( page, textMatrixStDisp, textMatrixEndDisp, totalVerticalDisplacementDisp, individualWidths, spaceWidthDisp, characterBuffer.toString(), font, fontSizeText, (int)(fontSizeText * textMatrix.getXScale()), wordSpacingDisp )); textMatrixStDisp = textMatrix.multiply( dispMatrix ); characterBuffer.setLength(0); } } /** * This is used to handle an operation. * * @param operation The operation to perform. * @param arguments The list of arguments. * * @throws IOException If there is an error processing the operation. */ public void processOperator( String operation, List arguments ) throws IOException { try { PDFOperator oper = PDFOperator.getOperator( operation ); processOperator( oper, arguments ); } catch (IOException e) { log.warn(e, e); } } /** * This is used to handle an operation. * * @param operator The operation to perform. * @param arguments The list of arguments. * * @throws IOException If there is an error processing the operation. */ protected void processOperator( PDFOperator operator, List arguments ) throws IOException { try { String operation = operator.getOperation(); OperatorProcessor processor = (OperatorProcessor)operators.get( operation ); if( processor != null ) { processor.setContext(this); processor.process( operator, arguments ); } else { if (!unsupportedOperators.contains(operation)) { log.info("unsupported/disabled operation: " + operation); unsupportedOperators.add(operation); } } } catch (Exception e) { log.warn(e, e); } } /** * @return Returns the colorSpaces. */ public Map getColorSpaces() { return ((StreamResources) streamResourcesStack.peek()).colorSpaces; } /** * @return Returns the colorSpaces. */ public Map getXObjects() { return ((StreamResources) streamResourcesStack.peek()).xobjects; } /** * @param value The colorSpaces to set. */ public void setColorSpaces(Map value) { ((StreamResources) streamResourcesStack.peek()).colorSpaces = value; } /** * @return Returns the fonts. */ public Map getFonts() { return ((StreamResources) streamResourcesStack.peek()).fonts; } /** * @param value The fonts to set. */ public void setFonts(Map value) { ((StreamResources) streamResourcesStack.peek()).fonts = value; } /** * @return Returns the graphicsStack. */ public Stack getGraphicsStack() { return graphicsStack; } /** * @param value The graphicsStack to set. */ public void setGraphicsStack(Stack value) { graphicsStack = value; } /** * @return Returns the graphicsState. */ public PDGraphicsState getGraphicsState() { return graphicsState; } /** * @param value The graphicsState to set. */ public void setGraphicsState(PDGraphicsState value) { graphicsState = value; } /** * @return Returns the graphicsStates. */ public Map getGraphicsStates() { return ((StreamResources) streamResourcesStack.peek()).graphicsStates; } /** * @param value The graphicsStates to set. */ public void setGraphicsStates(Map value) { ((StreamResources) streamResourcesStack.peek()).graphicsStates = value; } /** * @return Returns the textLineMatrix. */ public Matrix getTextLineMatrix() { return textLineMatrix; } /** * @param value The textLineMatrix to set. */ public void setTextLineMatrix(Matrix value) { textLineMatrix = value; } /** * @return Returns the textMatrix. */ public Matrix getTextMatrix() { return textMatrix; } /** * @param value The textMatrix to set. */ public void setTextMatrix(Matrix value) { textMatrix = value; } /** * @return Returns the resources. */ public PDResources getResources() { return ((StreamResources) streamResourcesStack.peek()).resources; } /** * Get the current page that is being processed. * * @return The page being processed. */ public PDPage getCurrentPage() { return page; } /** * Get the total number of valid characters in the doc * that could be decoded in processEncodedText(). * @return The number of valid characters. */ public int getValidCharCnt() { return validCharCnt; } /** * Get the total number of characters in the doc * (including ones that could not be mapped). * @return The number of characters. */ public int getTotalCharCnt() { return totalCharCnt; } }
true
true
public void processEncodedText( byte[] string ) throws IOException { /* Note on variable names. There are three different units being used * in this code. Character sizes are given in glyph units, text locations * are initially given in text units, and we want to save the data in * display units. The variable names should end with Text or Disp to * represent if the values are in text or disp units (no glyph units are saved). */ final float fontSizeText = graphicsState.getTextState().getFontSize(); final float horizontalScalingText = graphicsState.getTextState().getHorizontalScalingPercent()/100f; //float verticalScalingText = horizontalScaling;//not sure if this is right but what else to do??? final float riseText = graphicsState.getTextState().getRise(); final float wordSpacingText = graphicsState.getTextState().getWordSpacing(); final float characterSpacingText = graphicsState.getTextState().getCharacterSpacing(); //We won't know the actual number of characters until //we process the byte data(could be two bytes each) but //it won't ever be more than string.length*2(there are some cases //were a single byte will result in two output characters "fi" final PDFont font = graphicsState.getTextState().getFont(); //This will typically be 1000 but in the case of a type3 font //this might be a different number final float glyphSpaceToTextSpaceFactor = 1f/font.getFontMatrix().getValue( 0, 0 ); float spaceWidthText=0; try{ // to avoid crash as described in PDFBOX-614 // lets see what the space displacement should be spaceWidthText = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor); }catch (Throwable exception) { log.warn( exception, exception); } if( spaceWidthText == 0 ) { spaceWidthText = (font.getAverageFontWidth()/glyphSpaceToTextSpaceFactor); //The average space width appears to be higher than necessary //so lets make it a little bit smaller. spaceWidthText *= .80f; } /* Convert textMatrix to display units */ final Matrix initialMatrix = new Matrix(); initialMatrix.setValue(0,0,1); initialMatrix.setValue(0,1,0); initialMatrix.setValue(0,2,0); initialMatrix.setValue(1,0,0); initialMatrix.setValue(1,1,1); initialMatrix.setValue(1,2,0); initialMatrix.setValue(2,0,0); initialMatrix.setValue(2,1,riseText); initialMatrix.setValue(2,2,1); final Matrix ctm = graphicsState.getCurrentTransformationMatrix(); final Matrix dispMatrix = initialMatrix.multiply( ctm ); Matrix textMatrixStDisp = textMatrix.multiply( dispMatrix ); Matrix textMatrixEndDisp = null; final float xScaleDisp = textMatrixStDisp.getXScale(); final float yScaleDisp = textMatrixStDisp.getYScale(); final float spaceWidthDisp = spaceWidthText * xScaleDisp * fontSizeText; final float wordSpacingDisp = wordSpacingText * xScaleDisp * fontSizeText; float maxVerticalDisplacementText = 0; float[] individualWidthsBuffer = new float[string.length]; StringBuilder characterBuffer = new StringBuilder(string.length); int codeLength = 1; for( int i=0; i<string.length; i+=codeLength ) { // Decode the value to a Unicode character codeLength = 1; String c = font.encode( string, i, codeLength ); if( c == null && i+1<string.length) { //maybe a multibyte encoding codeLength++; c = font.encode( string, i, codeLength ); } //todo, handle horizontal displacement // get the width and height of this character in text units float characterHorizontalDisplacementText = (font.getFontWidth( string, i, codeLength )/glyphSpaceToTextSpaceFactor); maxVerticalDisplacementText = Math.max( maxVerticalDisplacementText, font.getFontHeight( string, i, codeLength)/glyphSpaceToTextSpaceFactor); // PDF Spec - 5.5.2 Word Spacing // // Word spacing works the same was as character spacing, but applies // only to the space character, code 32. // // Note: Word spacing is applied to every occurrence of the single-byte // character code 32 in a string. This can occur when using a simple // font or a composite font that defines code 32 as a single-byte code. // It does not apply to occurrences of the byte value 32 in multiple-byte // codes. // // RDD - My interpretation of this is that only character code 32's that // encode to spaces should have word spacing applied. Cases have been // observed where a font has a space character with a character code // other than 32, and where word spacing (Tw) was used. In these cases, // applying word spacing to either the non-32 space or to the character // code 32 non-space resulted in errors consistent with this interpretation. // float spacingText = characterSpacingText; if( (string[i] == 0x20) && codeLength == 1 ) { spacingText += wordSpacingText; } /* The text matrix gets updated after each glyph is placed. The updated * version will have the X and Y coordinates for the next glyph. */ Matrix glyphMatrixStDisp = textMatrix.multiply( dispMatrix ); //The adjustment will always be zero. The adjustment as shown in the //TJ operator will be handled separately. float adjustment=0; // TODO : tx should be set for horizontal text and ty for vertical text // which seems to be specified in the font (not the direction in the matrix). float tx = ((characterHorizontalDisplacementText-adjustment/glyphSpaceToTextSpaceFactor)*fontSizeText) * horizontalScalingText; float ty = 0; Matrix td = new Matrix(); td.setValue( 2, 0, tx ); td.setValue( 2, 1, ty ); textMatrix = td.multiply( textMatrix ); Matrix glyphMatrixEndDisp = textMatrix.multiply( dispMatrix ); float sx = spacingText * horizontalScalingText; float sy = 0; Matrix sd = new Matrix(); sd.setValue( 2, 0, sx ); sd.setValue( 2, 1, sy ); textMatrix = sd.multiply( textMatrix ); // determine the width of this character // XXX: Note that if we handled vertical text, we should be using Y here float widthText = glyphMatrixEndDisp.getXPosition() - glyphMatrixStDisp.getXPosition(); while( characterBuffer.length() + ( c != null ? c.length() : 1 ) > individualWidthsBuffer.length ) { float[] tmp = new float[individualWidthsBuffer.length * 2]; System.arraycopy( individualWidthsBuffer, 0, tmp, 0, individualWidthsBuffer.length ); individualWidthsBuffer = tmp; } //there are several cases where one character code will //output multiple characters. For example "fi" or a //glyphname that has no mapping like "visiblespace" if( c != null ) { Arrays.fill( individualWidthsBuffer, characterBuffer.length(), characterBuffer.length() + c.length(), widthText / c.length()); validCharCnt += c.length(); } else { // PDFBOX-373: Replace a null entry with "?" so it is // not printed as "(null)" c = "?"; individualWidthsBuffer[characterBuffer.length()] = widthText; } characterBuffer.append(c); totalCharCnt += c.length(); if( spacingText == 0 && (i + codeLength) < (string.length - 1) ) { continue; } textMatrixEndDisp = glyphMatrixEndDisp; float totalVerticalDisplacementDisp = maxVerticalDisplacementText * fontSizeText * yScaleDisp; float[] individualWidths = new float[characterBuffer.length()]; System.arraycopy( individualWidthsBuffer, 0, individualWidths, 0, individualWidths.length ); // process the decoded text processTextPosition( new TextPosition( page, textMatrixStDisp, textMatrixEndDisp, totalVerticalDisplacementDisp, individualWidths, spaceWidthDisp, characterBuffer.toString(), font, fontSizeText, (int)(fontSizeText * textMatrix.getXScale()), wordSpacingDisp )); textMatrixStDisp = textMatrix.multiply( dispMatrix ); characterBuffer.setLength(0); } }
public void processEncodedText( byte[] string ) throws IOException { /* Note on variable names. There are three different units being used * in this code. Character sizes are given in glyph units, text locations * are initially given in text units, and we want to save the data in * display units. The variable names should end with Text or Disp to * represent if the values are in text or disp units (no glyph units are saved). */ final float fontSizeText = graphicsState.getTextState().getFontSize(); final float horizontalScalingText = graphicsState.getTextState().getHorizontalScalingPercent()/100f; //float verticalScalingText = horizontalScaling;//not sure if this is right but what else to do??? final float riseText = graphicsState.getTextState().getRise(); final float wordSpacingText = graphicsState.getTextState().getWordSpacing(); final float characterSpacingText = graphicsState.getTextState().getCharacterSpacing(); //We won't know the actual number of characters until //we process the byte data(could be two bytes each) but //it won't ever be more than string.length*2(there are some cases //were a single byte will result in two output characters "fi" final PDFont font = graphicsState.getTextState().getFont(); //This will typically be 1000 but in the case of a type3 font //this might be a different number final float glyphSpaceToTextSpaceFactor = 1f/font.getFontMatrix().getValue( 0, 0 ); float spaceWidthText=0; try{ // to avoid crash as described in PDFBOX-614 // lets see what the space displacement should be spaceWidthText = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor); }catch (Throwable exception) { log.warn( exception, exception); } if( spaceWidthText == 0 ) { spaceWidthText = (font.getAverageFontWidth()/glyphSpaceToTextSpaceFactor); //The average space width appears to be higher than necessary //so lets make it a little bit smaller. spaceWidthText *= .80f; } /* Convert textMatrix to display units */ final Matrix initialMatrix = new Matrix(); initialMatrix.setValue(0,0,1); initialMatrix.setValue(0,1,0); initialMatrix.setValue(0,2,0); initialMatrix.setValue(1,0,0); initialMatrix.setValue(1,1,1); initialMatrix.setValue(1,2,0); initialMatrix.setValue(2,0,0); initialMatrix.setValue(2,1,riseText); initialMatrix.setValue(2,2,1); final Matrix ctm = graphicsState.getCurrentTransformationMatrix(); final Matrix dispMatrix = initialMatrix.multiply( ctm ); Matrix textMatrixStDisp = textMatrix.multiply( dispMatrix ); Matrix textMatrixEndDisp = null; final float xScaleDisp = textMatrixStDisp.getXScale(); final float yScaleDisp = textMatrixStDisp.getYScale(); final float spaceWidthDisp = spaceWidthText * xScaleDisp * fontSizeText; final float wordSpacingDisp = wordSpacingText * xScaleDisp * fontSizeText; float maxVerticalDisplacementText = 0; float[] individualWidthsBuffer = new float[string.length]; StringBuilder characterBuffer = new StringBuilder(string.length); int codeLength = 1; for( int i=0; i<string.length; i+=codeLength ) { // Decode the value to a Unicode character codeLength = 1; String c = font.encode( string, i, codeLength ); if( c == null && i+1<string.length) { //maybe a multibyte encoding codeLength++; c = font.encode( string, i, codeLength ); } //todo, handle horizontal displacement // get the width and height of this character in text units float characterHorizontalDisplacementText = (font.getFontWidth( string, i, codeLength )/glyphSpaceToTextSpaceFactor); maxVerticalDisplacementText = Math.max( maxVerticalDisplacementText, font.getFontHeight( string, i, codeLength)/glyphSpaceToTextSpaceFactor); // PDF Spec - 5.5.2 Word Spacing // // Word spacing works the same was as character spacing, but applies // only to the space character, code 32. // // Note: Word spacing is applied to every occurrence of the single-byte // character code 32 in a string. This can occur when using a simple // font or a composite font that defines code 32 as a single-byte code. // It does not apply to occurrences of the byte value 32 in multiple-byte // codes. // // RDD - My interpretation of this is that only character code 32's that // encode to spaces should have word spacing applied. Cases have been // observed where a font has a space character with a character code // other than 32, and where word spacing (Tw) was used. In these cases, // applying word spacing to either the non-32 space or to the character // code 32 non-space resulted in errors consistent with this interpretation. // float spacingText = characterSpacingText; if( (string[i] == 0x20) && codeLength == 1 ) { spacingText += wordSpacingText; } /* The text matrix gets updated after each glyph is placed. The updated * version will have the X and Y coordinates for the next glyph. */ Matrix glyphMatrixStDisp = textMatrix.multiply( dispMatrix ); //The adjustment will always be zero. The adjustment as shown in the //TJ operator will be handled separately. float adjustment=0; // TODO : tx should be set for horizontal text and ty for vertical text // which seems to be specified in the font (not the direction in the matrix). float tx = ((characterHorizontalDisplacementText-adjustment/glyphSpaceToTextSpaceFactor)*fontSizeText) * horizontalScalingText; float ty = 0; Matrix td = new Matrix(); td.setValue( 2, 0, tx ); td.setValue( 2, 1, ty ); textMatrix = td.multiply( textMatrix ); Matrix glyphMatrixEndDisp = textMatrix.multiply( dispMatrix ); float sx = spacingText * horizontalScalingText; float sy = 0; Matrix sd = new Matrix(); sd.setValue( 2, 0, sx ); sd.setValue( 2, 1, sy ); textMatrix = sd.multiply( textMatrix ); // determine the width of this character // XXX: Note that if we handled vertical text, we should be using Y here float widthText = glyphMatrixEndDisp.getXPosition() - glyphMatrixStDisp.getXPosition(); while( characterBuffer.length() + ( c != null ? c.length() : 1 ) > individualWidthsBuffer.length ) { float[] tmp = new float[individualWidthsBuffer.length * 2]; System.arraycopy( individualWidthsBuffer, 0, tmp, 0, individualWidthsBuffer.length ); individualWidthsBuffer = tmp; } //there are several cases where one character code will //output multiple characters. For example "fi" or a //glyphname that has no mapping like "visiblespace" if( c != null ) { Arrays.fill( individualWidthsBuffer, characterBuffer.length(), characterBuffer.length() + c.length(), widthText / c.length()); validCharCnt += c.length(); } else { // PDFBOX-373: Replace a null entry with "?" so it is // not printed as "(null)" c = "?"; individualWidthsBuffer[characterBuffer.length()] = widthText; } characterBuffer.append(c); totalCharCnt += c.length(); if( spacingText == 0 && (i + codeLength) < string.length ) { continue; } textMatrixEndDisp = glyphMatrixEndDisp; float totalVerticalDisplacementDisp = maxVerticalDisplacementText * fontSizeText * yScaleDisp; float[] individualWidths = new float[characterBuffer.length()]; System.arraycopy( individualWidthsBuffer, 0, individualWidths, 0, individualWidths.length ); // process the decoded text processTextPosition( new TextPosition( page, textMatrixStDisp, textMatrixEndDisp, totalVerticalDisplacementDisp, individualWidths, spaceWidthDisp, characterBuffer.toString(), font, fontSizeText, (int)(fontSizeText * textMatrix.getXScale()), wordSpacingDisp )); textMatrixStDisp = textMatrix.multiply( dispMatrix ); characterBuffer.setLength(0); } }
diff --git a/src/com/android/wakemeski/core/Report.java b/src/com/android/wakemeski/core/Report.java index 8378f88..a95a47b 100644 --- a/src/com/android/wakemeski/core/Report.java +++ b/src/com/android/wakemeski/core/Report.java @@ -1,711 +1,711 @@ /* * Copyright (c) 2008 [email protected] * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND 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 THE AUTHOR 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 com.android.wakemeski.core; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import com.android.wakemeski.R; import com.android.wakemeski.pref.SnowSettingsSharedPreference; public class Report implements Parcelable { private String _location = ""; private String _date = ""; private String _windAvg = ""; private String _detailsURL = ""; private String _locationURL = ""; private String _freshSourceUrl = ""; private int _trailsOpen = 0; private int _trailsTotal = 0; private int _liftsOpen = 0; private int _liftsTotal = 0; private String _weatherUrl = ""; private String _weatherIcon = ""; private ArrayList<Weather> _weather = new ArrayList<Weather>(); private String _latitude = ""; private String _longitude = ""; private String _snowConditions = ""; private ArrayList<String> _snowTotals = new ArrayList<String>(); private ArrayList<String> _dailySnow = new ArrayList<String>(); private ArrayList<String> _tempReadings = new ArrayList<String>(); private String _freshSnow = ""; private String _snowUnits = "inches"; private String _requestUrl = ""; private WakeMeSkiServerInfo _serverInfo = new WakeMeSkiServerInfo(); private Resort _resort; // Used to display an error if one occurred private String _errMsg = null; private static final String TAG = "com.android.wakemeski.core.Report"; public static final Parcelable.Creator<Report> CREATOR = new Parcelable.Creator<Report>() { @Override public Report createFromParcel(Parcel source) { Report r = new Report(); r._location = source.readString(); r._date = source.readString(); r._windAvg = source.readString(); r._detailsURL = source.readString(); r._locationURL = source.readString(); r._trailsOpen = source.readInt(); r._trailsTotal = source.readInt(); r._liftsOpen = source.readInt(); r._liftsTotal = source.readInt(); r._resort = (Resort)source.readSerializable(); r._errMsg = source.readString(); r._weatherUrl = source.readString(); r._weatherIcon = source.readString(); source.readTypedList(r._weather, Weather.CREATOR); r._latitude = source.readString(); r._longitude = source.readString(); r._snowConditions = source.readString(); r._freshSnow = source.readString(); r._snowUnits = source.readString(); source.readList(r._snowTotals, getClass().getClassLoader()); source.readList(r._dailySnow, getClass().getClassLoader()); source.readList(r._tempReadings, getClass().getClassLoader()); return r; } @Override public Report[] newArray(int size) { return new Report[size]; } }; public boolean meetsPreference(SnowSettingsSharedPreference s) { double depth = s.getSnowDepth(); double reported = getFreshSnowTotal(); if (getSnowUnits() == SnowUnits.CENTIMETERS) reported *= 2.54; if (s.getMeasurementUnits() == SnowUnits.CENTIMETERS) depth *= 2.54; return (reported >= depth); } /** * Private constructor. loadReport should be used to construct an instance. */ private Report() { } /** * Returns the resort the report is for */ public Resort getResort() { return _resort; } /** * Returns the date the report data was generated. */ public String getDate() { return _date; } /** * Returns the average wind speed recorded on the mountain */ public String getWindSpeed() { return _windAvg; } public int getTrailsOpen() { return _trailsOpen; } public int getTrailsTotal() { return _trailsTotal; } public String getTrailsAsString() { String s = "n/a"; if( _trailsTotal > 0 ) s = _trailsOpen + "/" + _trailsTotal; else if( _trailsOpen > 0 ) s = String.valueOf(_trailsOpen); return s; } public int getLiftsOpen() { return _liftsOpen; } public int getLiftsTotal() { return _liftsTotal; } public String getLiftsAsString() { String s = "n/a"; if( _liftsTotal > 0 ) s = _liftsOpen + "/" + _liftsTotal; else if( _liftsOpen > 0 ) s = String.valueOf(_liftsOpen); return s; } /** * Returns an array of total snow depths read on the mountain */ public String[] getSnowDepths() { return _snowTotals.toArray(new String[_snowTotals.size()]); } public String getSnowDepthsAsString() { StringBuffer sb = new StringBuffer(); int len = _snowTotals.size(); for(int i = 0; i < len; i++) { sb.append(_snowTotals.get(i)); if( i+2< len) sb.append(','); sb.append(' '); } return sb.toString(); } /** * Returns an array of all daily snow reports found */ public String[] getDailySnow() { return _dailySnow.toArray(new String[_dailySnow.size()]); } /** * Returns the list of daily snow fall plus snow conditions if available */ public String getDailyDetails() { StringBuffer sb = new StringBuffer(); int len = _dailySnow.size(); for(int i = 0; i < len; i++) { sb.append(_dailySnow.get(i)); if( i+2< len) sb.append(','); sb.append(' '); } if(_snowConditions != null && _snowConditions.length() > 0 ) sb.append(_snowConditions); return sb.toString(); } /** * @return true if a fresh snow total was obtained for this resort */ public boolean hasFreshSnowTotal() { return getFreshSnowTotal() >= 0; } /** * @return The units for all snow totals */ public SnowUnits getSnowUnits() { if (_snowUnits.equalsIgnoreCase("inches")) { return SnowUnits.INCHES; } return SnowUnits.CENTIMETERS; } /** * @return The total fresh snowfall (rounded to nearest int) or -1 if ! * hasFreshSnowTotal() */ public int getFreshSnowTotal() { int snowTotal; try { snowTotal = Math.round(Float.parseFloat(_freshSnow)); } catch (NumberFormatException nfe) { snowTotal = -1; } return snowTotal; } /** * @return A string representing the snow total with units, or N/A if not available */ public String getFreshAsString() { String unit = " \""; String snowTotal; if (getSnowUnits() == SnowUnits.CENTIMETERS) unit = " cm"; if( hasFreshSnowTotal() ) { snowTotal = getFreshSnowTotal() + unit; } else { snowTotal = "N/A"; } return snowTotal; } public String getSnowConditions() { return _snowConditions; } /** * Returns an array of the various temperature readings on the mountain. */ public String[] getTemperatureReadings() { return _tempReadings.toArray(new String[_tempReadings.size()]); } /** * Used to display an error if one occurred */ public String getError() { return _errMsg; } public boolean hasErrors() { return (_errMsg != null); } public WakeMeSkiServerInfo getServerInfo() { return _serverInfo; } /** * Returns true if the report include latitude and longitude coordinates */ public boolean hasGeo() { if( _latitude != null && _latitude.length() > 0 && _longitude != null && _longitude.length() > 0 ) return true; return false; } public Uri getGeo() { return Uri.parse("geo:" + _latitude + "," + _longitude); } /** * Returns a URL to information related to the given report */ public String getDetailsURL() { return _detailsURL; } /** * Similar to getDetailsURL. This is more for the resport web site, whereas * the getDetailsURL is more for drilling down into snow information */ public String getLocationURL() { return _locationURL; } /** * @return The url where "fresh" snow information is obtained by the PHP parsing script */ public String getFreshSourceURL() { return _freshSourceUrl; } /** * @return The string URL requested of a wakemeski server to build this report */ public String getRequestURL() { return _requestUrl; } public String getWeatherURL() { return _weatherUrl; } public Weather[] getWeather() { return _weather.toArray(new Weather[_weather.size()]); } public String getWeatherIcon() { return _weatherIcon; } public int getWeatherIconResId() { String parts[] = _weatherIcon.split("/"); String name = parts[parts.length - 1]; parts = name.split("\\."); name = parts[0]; Pattern p = Pattern.compile("(\\d+)"); Matcher m = p.matcher(name); if (m.find()) { // TODO String percentage = m.group(0); name = name.substring(0, m.start()); } Integer i = _icons.get(name); if (i != null) { return i.intValue(); } return R.drawable.unknown; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(_location); dest.writeString(_date); dest.writeString(_windAvg); dest.writeString(_detailsURL); dest.writeString(_locationURL); dest.writeInt(_trailsOpen); dest.writeInt(_trailsTotal); dest.writeInt(_liftsOpen); dest.writeInt(_liftsTotal); dest.writeSerializable(_resort); dest.writeString(_errMsg); dest.writeString(_weatherUrl); dest.writeString(_weatherIcon); dest.writeTypedList(_weather); dest.writeString(_latitude); dest.writeString(_longitude); dest.writeString(_snowConditions); dest.writeString(_freshSnow); dest.writeString(_snowUnits); dest.writeList(_snowTotals); dest.writeList(_dailySnow); dest.writeList(_tempReadings); } private static ArrayList<String> toList(String vals[]) { ArrayList<String> l = new ArrayList<String>(); for (String v : vals) { l.add(v); } return l; } /** * Simple wrapper to Integer.parseInt that will catch format errors */ private static int getInt(String val) { int v = 0; try { v = Integer.parseInt(val); } catch (Throwable t) { Log.e(TAG, "Unable to parse value to int: " + val); } return v; } /** * Loads a report from the given location with default URL */ public static Report loadReport(Context c, ConnectivityManager cm, Resort resort, WakeMeSkiServer server) { return loadReportWithAppendUrl(c,cm,resort,server,""); } /** * Loads a report from the given location without caching */ public static Report loadReportNoCache(Context c, ConnectivityManager cm, Resort resort, WakeMeSkiServer server) { return loadReportWithAppendUrl(c,cm,resort,server,"&nocache=1"); } /** * Loads a report. Allows specifying custom append values to the URL request * (such as nocache=1) * @return */ private static Report loadReportWithAppendUrl(Context c, ConnectivityManager cm, Resort resort, WakeMeSkiServer server, String appendUrl) { // A report will be in the format: // location = OSOALP // date = 12-6-2008 // lifts.open = 5 // lifts.total = 10 // trails.open = 0 // trails.total = 10 // snow.total = 6 // snow.daily = Fresh(4.3) [48 hr(<amount>)] // snow.fresh = 4.3 // snow.units = inches // temp.readings = 41/33 44/38 43/34 // wind.avg = 20 Report r = new Report(); r._resort = resort; Location l = resort.getLocation(); String lines[] = new String[0]; String url = "/" + l.getReportUrlPath() + appendUrl; r._requestUrl = server.getFetchUrl(url); try { lines = server.fetchUrlWithID(url); } catch (Exception e) { NetworkInfo n = cm.getActiveNetworkInfo(); if (n == null || !n.isConnected()) { r._errMsg = c.getString(R.string.error_no_connection); } else { r._errMsg = e.getLocalizedMessage(); } return r; } String when[] = new String[3]; String desc[] = new String[3]; for (String line : lines) { String parts[] = line.split("=", 2); if (parts.length == 2) { parts[0] = parts[0].trim(); parts[1] = parts[1].trim(); if( parts[0].equals("fresh.source.url")) { r._freshSourceUrl = parts[1]; } else if (parts[0].equals("wind.avg")) { r._windAvg = parts[1]; } else if (parts[0].equals("date")) { r._date = parts[1]; } else if (parts[0].equals("details.url")) { r._detailsURL = parts[1]; } else if (parts[0].equals("location.info")) { r._locationURL = parts[1]; } else if (parts[0].equals("trails.open")) { r._trailsOpen = getInt(parts[1]); } else if (parts[0].equals("trails.total")) { r._trailsTotal = getInt(parts[1]); } else if (parts[0].equals("lifts.open")) { r._liftsOpen = getInt(parts[1]); } else if (parts[0].equals("lifts.total")) { r._liftsTotal = getInt(parts[1]); } else if (parts[0].equals("weather.url")) { r._weatherUrl = parts[1]; } else if (parts[0].equals("weather.icon")) { r._weatherIcon = parts[1]; } else if( parts[0].startsWith("weather.forecast.when.")) { int idx = Integer.parseInt(parts[0].substring(parts[0].length()-1)); if(idx < when.length) { when[idx] = parts[1]; } } else if( parts[0].startsWith("weather.forecast.desc.")) { int idx = Integer.parseInt(parts[0].substring(parts[0].length()-1)); - if(idx < parts.length) { + if(idx < desc.length) { desc[idx] = parts[1]; } } else if (parts[0].equals("location")) { r._location = parts[1]; } else if (parts[0].equals("location.latitude")) { r._latitude = parts[1]; } else if (parts[0].equals("location.longitude")) { r._longitude = parts[1]; } else if (parts[0].equals("snow.conditions")) { r._snowConditions = parts[1]; } else if (parts[0].equals("err.msg")) { r._errMsg = parts[1]; } else if (parts[0].equals("snow.fresh")) { r._freshSnow = parts[1]; } else if (parts[0].equals("snow.units")) { r._snowUnits = parts[1]; } else { String values[] = parts[1].split("\\s+"); ArrayList<String> vals = toList(values); if (parts[0].equals("snow.total")) { r._snowTotals = vals; } else if (parts[0].equals("snow.daily")) { r._dailySnow = vals; } else if (parts[0].equals("temp.readings")) { r._tempReadings = vals; } else { Log.i(TAG, "Unknown key-value from from report URL(" + l.getReportUrlPath() + " line: " + line); } } } else { Log.e(TAG, "Error invalid line from report URL(" + l.getReportUrlPath() + " line: " + line); } } for( int i = 0; i < when.length && i < desc.length ; i++ ) { if( when[i] != null && when[i].length() > 0 && desc[i] != null && desc[i].length() > 0 ) r._weather.add(new Weather(when[i], desc[i])); } r._serverInfo = server.getServerInfo(); return r; } public static Report createError(String msg) { Report r = new Report(); r._errMsg = msg; return r; } private static HashMap<String, Integer> _icons; static { _icons = new HashMap<String, Integer>(); // nfew = mostly clear, evening // nbkn = mostly cloudy, evening // nsct = partly cloudy, evening _icons.put("nfew", new Integer(R.drawable.moon_parly_cloudy)); _icons.put("nbkn", new Integer(R.drawable.moon_mostly_cloudy)); _icons.put("nsct", new Integer(R.drawable.moon_parly_cloudy)); // few = sunny, day // skc = totally sunny _icons.put("few", new Integer(R.drawable.sunny)); _icons.put("skc", new Integer(R.drawable.sunny)); // sct = mostly sunny, day _icons.put("sct", new Integer(R.drawable.mostly_sunny)); // bkn = partly sunny, day // sct = partly cloudy _icons.put("bkn", new Integer(R.drawable.partly_sunny)); _icons.put("sct", new Integer(R.drawable.partly_sunny)); // nskc = night clear _icons.put("nskc", new Integer(R.drawable.moon_clear)); // nsn = chance of snow, evening // sn = chance of snow, day // nsn = night snow _icons.put("nsn", new Integer(R.drawable.snow)); _icons.put("sn", new Integer(R.drawable.snow)); _icons.put("nsn", new Integer(R.drawable.snow)); // blizzard _icons.put("blizzard", new Integer(R.drawable.snow)); // rasn = chance rain/snow, day (combine rain and snow icons) // nrasn = chance rain/snow, night // raip = rain / sleet _icons.put("rasn", new Integer(R.drawable.rain_snow)); _icons.put("nrasn", new Integer(R.drawable.rain_snow)); _icons.put("raip", new Integer(R.drawable.rain_snow)); // nra = night rain // nshra = night showers // ra = rain _icons.put("ra", new Integer(R.drawable.rain)); _icons.put("nra", new Integer(R.drawable.rain)); _icons.put("nshra", new Integer(R.drawable.rain)); // hi_nshwrs = high night showers // hi_shwrs = high day showers showers // shra = showers _icons.put("hi_nshwrs", new Integer(R.drawable.rain)); _icons.put("hi_shwrs", new Integer(R.drawable.rain)); _icons.put("shra", new Integer(R.drawable.rain)); // ovc = overcast // novc = night overcast _icons.put("ovc", new Integer(R.drawable.cloudy)); _icons.put("novc", new Integer(R.drawable.cloudy)); // hi_ntsra = lighting night // hi_tsra = lighting and showers // ntsra = lighting night // tsra = lighting and rain _icons.put("hi_ntsra", new Integer(R.drawable.rain_lightning)); _icons.put("hi_tsra", new Integer(R.drawable.rain_lightning)); _icons.put("nscttsra", new Integer(R.drawable.rain_lightning)); _icons.put("ntsra", new Integer(R.drawable.rain_lightning)); _icons.put("tsra", new Integer(R.drawable.rain_lightning)); // scttsra = sun and scattered rain _icons.put("scttsra", new Integer(R.drawable.sun_rain)); // mix = snow and rain _icons.put("mix", new Integer(R.drawable.mix)); // TODO fg = fog // fzra = freeze // hot = hot // hurr = hurricane // ntor = night tornado // wind // nwind = night wind // ovc = overcast // sctfg = scattered fog // cold = cold, day } }
true
true
private static Report loadReportWithAppendUrl(Context c, ConnectivityManager cm, Resort resort, WakeMeSkiServer server, String appendUrl) { // A report will be in the format: // location = OSOALP // date = 12-6-2008 // lifts.open = 5 // lifts.total = 10 // trails.open = 0 // trails.total = 10 // snow.total = 6 // snow.daily = Fresh(4.3) [48 hr(<amount>)] // snow.fresh = 4.3 // snow.units = inches // temp.readings = 41/33 44/38 43/34 // wind.avg = 20 Report r = new Report(); r._resort = resort; Location l = resort.getLocation(); String lines[] = new String[0]; String url = "/" + l.getReportUrlPath() + appendUrl; r._requestUrl = server.getFetchUrl(url); try { lines = server.fetchUrlWithID(url); } catch (Exception e) { NetworkInfo n = cm.getActiveNetworkInfo(); if (n == null || !n.isConnected()) { r._errMsg = c.getString(R.string.error_no_connection); } else { r._errMsg = e.getLocalizedMessage(); } return r; } String when[] = new String[3]; String desc[] = new String[3]; for (String line : lines) { String parts[] = line.split("=", 2); if (parts.length == 2) { parts[0] = parts[0].trim(); parts[1] = parts[1].trim(); if( parts[0].equals("fresh.source.url")) { r._freshSourceUrl = parts[1]; } else if (parts[0].equals("wind.avg")) { r._windAvg = parts[1]; } else if (parts[0].equals("date")) { r._date = parts[1]; } else if (parts[0].equals("details.url")) { r._detailsURL = parts[1]; } else if (parts[0].equals("location.info")) { r._locationURL = parts[1]; } else if (parts[0].equals("trails.open")) { r._trailsOpen = getInt(parts[1]); } else if (parts[0].equals("trails.total")) { r._trailsTotal = getInt(parts[1]); } else if (parts[0].equals("lifts.open")) { r._liftsOpen = getInt(parts[1]); } else if (parts[0].equals("lifts.total")) { r._liftsTotal = getInt(parts[1]); } else if (parts[0].equals("weather.url")) { r._weatherUrl = parts[1]; } else if (parts[0].equals("weather.icon")) { r._weatherIcon = parts[1]; } else if( parts[0].startsWith("weather.forecast.when.")) { int idx = Integer.parseInt(parts[0].substring(parts[0].length()-1)); if(idx < when.length) { when[idx] = parts[1]; } } else if( parts[0].startsWith("weather.forecast.desc.")) { int idx = Integer.parseInt(parts[0].substring(parts[0].length()-1)); if(idx < parts.length) { desc[idx] = parts[1]; } } else if (parts[0].equals("location")) { r._location = parts[1]; } else if (parts[0].equals("location.latitude")) { r._latitude = parts[1]; } else if (parts[0].equals("location.longitude")) { r._longitude = parts[1]; } else if (parts[0].equals("snow.conditions")) { r._snowConditions = parts[1]; } else if (parts[0].equals("err.msg")) { r._errMsg = parts[1]; } else if (parts[0].equals("snow.fresh")) { r._freshSnow = parts[1]; } else if (parts[0].equals("snow.units")) { r._snowUnits = parts[1]; } else { String values[] = parts[1].split("\\s+"); ArrayList<String> vals = toList(values); if (parts[0].equals("snow.total")) { r._snowTotals = vals; } else if (parts[0].equals("snow.daily")) { r._dailySnow = vals; } else if (parts[0].equals("temp.readings")) { r._tempReadings = vals; } else { Log.i(TAG, "Unknown key-value from from report URL(" + l.getReportUrlPath() + " line: " + line); } } } else { Log.e(TAG, "Error invalid line from report URL(" + l.getReportUrlPath() + " line: " + line); } } for( int i = 0; i < when.length && i < desc.length ; i++ ) { if( when[i] != null && when[i].length() > 0 && desc[i] != null && desc[i].length() > 0 ) r._weather.add(new Weather(when[i], desc[i])); } r._serverInfo = server.getServerInfo(); return r; }
private static Report loadReportWithAppendUrl(Context c, ConnectivityManager cm, Resort resort, WakeMeSkiServer server, String appendUrl) { // A report will be in the format: // location = OSOALP // date = 12-6-2008 // lifts.open = 5 // lifts.total = 10 // trails.open = 0 // trails.total = 10 // snow.total = 6 // snow.daily = Fresh(4.3) [48 hr(<amount>)] // snow.fresh = 4.3 // snow.units = inches // temp.readings = 41/33 44/38 43/34 // wind.avg = 20 Report r = new Report(); r._resort = resort; Location l = resort.getLocation(); String lines[] = new String[0]; String url = "/" + l.getReportUrlPath() + appendUrl; r._requestUrl = server.getFetchUrl(url); try { lines = server.fetchUrlWithID(url); } catch (Exception e) { NetworkInfo n = cm.getActiveNetworkInfo(); if (n == null || !n.isConnected()) { r._errMsg = c.getString(R.string.error_no_connection); } else { r._errMsg = e.getLocalizedMessage(); } return r; } String when[] = new String[3]; String desc[] = new String[3]; for (String line : lines) { String parts[] = line.split("=", 2); if (parts.length == 2) { parts[0] = parts[0].trim(); parts[1] = parts[1].trim(); if( parts[0].equals("fresh.source.url")) { r._freshSourceUrl = parts[1]; } else if (parts[0].equals("wind.avg")) { r._windAvg = parts[1]; } else if (parts[0].equals("date")) { r._date = parts[1]; } else if (parts[0].equals("details.url")) { r._detailsURL = parts[1]; } else if (parts[0].equals("location.info")) { r._locationURL = parts[1]; } else if (parts[0].equals("trails.open")) { r._trailsOpen = getInt(parts[1]); } else if (parts[0].equals("trails.total")) { r._trailsTotal = getInt(parts[1]); } else if (parts[0].equals("lifts.open")) { r._liftsOpen = getInt(parts[1]); } else if (parts[0].equals("lifts.total")) { r._liftsTotal = getInt(parts[1]); } else if (parts[0].equals("weather.url")) { r._weatherUrl = parts[1]; } else if (parts[0].equals("weather.icon")) { r._weatherIcon = parts[1]; } else if( parts[0].startsWith("weather.forecast.when.")) { int idx = Integer.parseInt(parts[0].substring(parts[0].length()-1)); if(idx < when.length) { when[idx] = parts[1]; } } else if( parts[0].startsWith("weather.forecast.desc.")) { int idx = Integer.parseInt(parts[0].substring(parts[0].length()-1)); if(idx < desc.length) { desc[idx] = parts[1]; } } else if (parts[0].equals("location")) { r._location = parts[1]; } else if (parts[0].equals("location.latitude")) { r._latitude = parts[1]; } else if (parts[0].equals("location.longitude")) { r._longitude = parts[1]; } else if (parts[0].equals("snow.conditions")) { r._snowConditions = parts[1]; } else if (parts[0].equals("err.msg")) { r._errMsg = parts[1]; } else if (parts[0].equals("snow.fresh")) { r._freshSnow = parts[1]; } else if (parts[0].equals("snow.units")) { r._snowUnits = parts[1]; } else { String values[] = parts[1].split("\\s+"); ArrayList<String> vals = toList(values); if (parts[0].equals("snow.total")) { r._snowTotals = vals; } else if (parts[0].equals("snow.daily")) { r._dailySnow = vals; } else if (parts[0].equals("temp.readings")) { r._tempReadings = vals; } else { Log.i(TAG, "Unknown key-value from from report URL(" + l.getReportUrlPath() + " line: " + line); } } } else { Log.e(TAG, "Error invalid line from report URL(" + l.getReportUrlPath() + " line: " + line); } } for( int i = 0; i < when.length && i < desc.length ; i++ ) { if( when[i] != null && when[i].length() > 0 && desc[i] != null && desc[i].length() > 0 ) r._weather.add(new Weather(when[i], desc[i])); } r._serverInfo = server.getServerInfo(); return r; }
diff --git a/weboo-webapp/src/main/java/no/f12/jzx/weboo/server/WebServer.java b/weboo-webapp/src/main/java/no/f12/jzx/weboo/server/WebServer.java index f65c038..ea093c9 100644 --- a/weboo-webapp/src/main/java/no/f12/jzx/weboo/server/WebServer.java +++ b/weboo-webapp/src/main/java/no/f12/jzx/weboo/server/WebServer.java @@ -1,77 +1,77 @@ package no.f12.jzx.weboo.server; import java.io.File; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.WebAppContext; import org.springframework.util.Assert; public class WebServer { private Integer port; private Server server; public WebServer(int port) { this.port = port; } public WebServer() { } public void start(File webAppContextPath, String applicationContext) { server = startWebServer(webAppContextPath, applicationContext); port = getServerPort(server); } private Integer getServerPort(Server server) { return server.getConnectors()[0].getLocalPort(); } private Server startWebServer(File webAppContextPath, String applicationContext) { - Assert.isTrue(webAppContextPath.exists(), "The context path you have specified does not exist"); - Assert.notNull(applicationContext, "You must specify the context path of the application: " + webAppContextPath); + Assert.isTrue(webAppContextPath.exists(), "The context path you have specified does not exist: " + webAppContextPath); + Assert.notNull(applicationContext, "You must specify the context path of the application"); int startPort = 0; if (this.port != null) { startPort = this.port; } if (!applicationContext.startsWith("/")) { applicationContext = "/" + applicationContext; } Server server = new Server(startPort); try { WebAppContext webAppContext = new WebAppContext(webAppContextPath.getCanonicalPath(), applicationContext); setUpClassPath(webAppContext); server.setHandler(webAppContext); server.start(); } catch (Exception e) { throw new RuntimeException(e); } return server; } private void setUpClassPath(WebAppContext webAppContext) { String classpath = System.getProperty("java.class.path"); String separator = System.getProperty("path.separator"); if (":".equals(separator)) { classpath = classpath.replace(":", ";"); } webAppContext.setExtraClasspath(classpath); } public Integer getPort() { Assert.notNull(port, "Server must be started before port can be determined"); return this.port; } public void stop() { try { server.stop(); } catch (Exception e) { throw new RuntimeException(e); } } }
true
true
private Server startWebServer(File webAppContextPath, String applicationContext) { Assert.isTrue(webAppContextPath.exists(), "The context path you have specified does not exist"); Assert.notNull(applicationContext, "You must specify the context path of the application: " + webAppContextPath); int startPort = 0; if (this.port != null) { startPort = this.port; } if (!applicationContext.startsWith("/")) { applicationContext = "/" + applicationContext; } Server server = new Server(startPort); try { WebAppContext webAppContext = new WebAppContext(webAppContextPath.getCanonicalPath(), applicationContext); setUpClassPath(webAppContext); server.setHandler(webAppContext); server.start(); } catch (Exception e) { throw new RuntimeException(e); } return server; }
private Server startWebServer(File webAppContextPath, String applicationContext) { Assert.isTrue(webAppContextPath.exists(), "The context path you have specified does not exist: " + webAppContextPath); Assert.notNull(applicationContext, "You must specify the context path of the application"); int startPort = 0; if (this.port != null) { startPort = this.port; } if (!applicationContext.startsWith("/")) { applicationContext = "/" + applicationContext; } Server server = new Server(startPort); try { WebAppContext webAppContext = new WebAppContext(webAppContextPath.getCanonicalPath(), applicationContext); setUpClassPath(webAppContext); server.setHandler(webAppContext); server.start(); } catch (Exception e) { throw new RuntimeException(e); } return server; }
diff --git a/src/org/apache/fop/fo/flow/TableBody.java b/src/org/apache/fop/fo/flow/TableBody.java index fdd3afe89..67d1931be 100644 --- a/src/org/apache/fop/fo/flow/TableBody.java +++ b/src/org/apache/fop/fo/flow/TableBody.java @@ -1,300 +1,304 @@ /*-- $Id$ -- ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999 The Apache Software Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modifica- tion, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes software developed by the Apache Software Foundation (http://www.apache.org/)." Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The names "FOP" and "Apache Software Foundation" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact [email protected]. 5. Products derived from this software may not be called "Apache", nor may "Apache" appear in their name, without prior written permission of the Apache Software Foundation. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- DING, 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. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by James Tauber <[email protected]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.fop.fo.flow; // FOP import org.apache.fop.fo.*; import org.apache.fop.fo.properties.*; import org.apache.fop.datatypes.*; import org.apache.fop.layout.*; import org.apache.fop.apps.FOPException; // Java import java.util.Vector; import java.util.Enumeration; public class TableBody extends FObj { public static class Maker extends FObj.Maker { public FObj make(FObj parent, PropertyList propertyList) throws FOPException { return new TableBody(parent, propertyList); } } public static FObj.Maker maker() { return new TableBody.Maker(); } FontState fs; int spaceBefore; int spaceAfter; ColorType backgroundColor; ColorType borderColor; int borderWidth; int borderStyle; String id; Vector columns; AreaContainer areaContainer; public TableBody(FObj parent, PropertyList propertyList) { super(parent, propertyList); this.name = "fo:table-body"; } public void setColumns(Vector columns) { this.columns = columns; } public void setYPosition(int value) { areaContainer.setYPosition(value); } public int getYPosition() { return areaContainer.getCurrentYPosition(); } public int getHeight() { return areaContainer.getHeight() + spaceBefore + spaceAfter; } public Status layout(Area area) throws FOPException { if (this.marker == BREAK_AFTER) { return new Status(Status.OK); } if (this.marker == START) { String fontFamily = this.properties.get("font-family").getString(); String fontStyle = this.properties.get("font-style").getString(); String fontWeight = this.properties.get("font-weight").getString(); int fontSize = this.properties.get("font-size").getLength().mvalue(); // font-variant support // added by Eric SCHAEFFER int fontVariant = this.properties.get("font-variant").getEnum(); this.fs = new FontState(area.getFontInfo(), fontFamily, fontStyle, fontWeight, fontSize, fontVariant); this.spaceBefore = this.properties.get( "space-before.optimum").getLength().mvalue(); this.spaceAfter = this.properties.get( "space-after.optimum").getLength().mvalue(); this.backgroundColor = this.properties.get( "background-color").getColorType(); this.borderColor = this.properties.get("border-color").getColorType(); this.borderWidth = this.properties.get( "border-width").getLength().mvalue(); this.borderStyle = this.properties.get("border-style").getEnum(); this.id = this.properties.get("id").getString(); area.getIDReferences().createID(id); if (area instanceof BlockArea) { area.end(); } //if (this.isInListBody) { //startIndent += bodyIndent + distanceBetweenStarts; //} this.marker = 0; } if ((spaceBefore != 0) && (this.marker == 0)) { area.increaseHeight(spaceBefore); } if (marker == 0) { // configure id area.getIDReferences().configureID(id, area); } this.areaContainer = new AreaContainer(fs, -area.borderWidthLeft, -area.borderWidthTop + area.getHeight(), area.getAllocationWidth(), area.spaceLeft(), Position.RELATIVE); areaContainer.setPage(area.getPage()); areaContainer.setBackgroundColor(backgroundColor); areaContainer.setBorderStyle(borderStyle, borderStyle, borderStyle, borderStyle); areaContainer.setBorderWidth(borderWidth, borderWidth, borderWidth, borderWidth); areaContainer.setBorderColor(borderColor, borderColor, borderColor, borderColor); areaContainer.start(); areaContainer.setAbsoluteHeight(area.getAbsoluteHeight()); areaContainer.setIDReferences(area.getIDReferences()); Vector keepWith = new Vector(); int numChildren = this.children.size(); TableRow lastRow = null; boolean endKeepGroup = true; for (int i = this.marker; i < numChildren; i++) { - TableRow row = (TableRow) children.elementAt(i); + Object child = children.elementAt(i); + if(!(child instanceof TableRow)) { + throw new FOPException("Currently only Table Rows are supported in table body, header and footer"); + } + TableRow row = (TableRow) child; row.setColumns(columns); row.doSetup(areaContainer); if (row.getKeepWithPrevious().getType() != KeepValue.KEEP_WITH_AUTO && lastRow != null && keepWith.indexOf(lastRow) == -1) { keepWith.addElement(lastRow); } else { if(endKeepGroup && keepWith.size() > 0) { keepWith = new Vector(); } } Status status; if ((status = row.layout(areaContainer)).isIncomplete()) { if (keepWith.size() > 0) { // && status.getCode() == Status.AREA_FULL_NONE row.removeLayout(areaContainer); for (Enumeration e = keepWith.elements(); e.hasMoreElements();) { TableRow tr = (TableRow) e.nextElement(); tr.removeLayout(areaContainer); i--; } if(i == 0) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } } this.marker = i; if ((i != 0) && (status.getCode() == Status.AREA_FULL_NONE)) { status = new Status(Status.AREA_FULL_SOME); } if (i < widows && numChildren >= widows) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } if (numChildren <= orphans) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } if (numChildren - i < orphans && numChildren >= orphans) { for (int count = i; count > numChildren - orphans - 1; count--) { row = (TableRow) children.elementAt(count); row.removeLayout(areaContainer); i--; } if (i < widows && numChildren >= widows) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } this.marker = i; area.addChild(areaContainer); //areaContainer.end(); area.increaseHeight(areaContainer.getHeight()); area.setAbsoluteHeight( areaContainer.getAbsoluteHeight()); return new Status(Status.AREA_FULL_SOME); } if (!((i == 0) && (areaContainer.getContentHeight() <= 0))) { area.addChild(areaContainer); //areaContainer.end(); area.increaseHeight(areaContainer.getHeight()); area.setAbsoluteHeight( areaContainer.getAbsoluteHeight()); } return status; } else if (status.getCode() == Status.KEEP_WITH_NEXT) { keepWith.addElement(row); endKeepGroup = false; } else { endKeepGroup = true; } lastRow = row; } area.addChild(areaContainer); areaContainer.end(); area.increaseHeight(areaContainer.getHeight()); area.setAbsoluteHeight(areaContainer.getAbsoluteHeight()); if (spaceAfter != 0) { area.increaseHeight(spaceAfter); } if (area instanceof BlockArea) { area.start(); } return new Status(Status.OK); } public void removeLayout(Area area) { area.removeChild(areaContainer); if (spaceBefore != 0) { area.increaseHeight(-spaceBefore); } if (spaceAfter != 0) { area.increaseHeight(-spaceAfter); } this.resetMarker(); } }
true
true
public Status layout(Area area) throws FOPException { if (this.marker == BREAK_AFTER) { return new Status(Status.OK); } if (this.marker == START) { String fontFamily = this.properties.get("font-family").getString(); String fontStyle = this.properties.get("font-style").getString(); String fontWeight = this.properties.get("font-weight").getString(); int fontSize = this.properties.get("font-size").getLength().mvalue(); // font-variant support // added by Eric SCHAEFFER int fontVariant = this.properties.get("font-variant").getEnum(); this.fs = new FontState(area.getFontInfo(), fontFamily, fontStyle, fontWeight, fontSize, fontVariant); this.spaceBefore = this.properties.get( "space-before.optimum").getLength().mvalue(); this.spaceAfter = this.properties.get( "space-after.optimum").getLength().mvalue(); this.backgroundColor = this.properties.get( "background-color").getColorType(); this.borderColor = this.properties.get("border-color").getColorType(); this.borderWidth = this.properties.get( "border-width").getLength().mvalue(); this.borderStyle = this.properties.get("border-style").getEnum(); this.id = this.properties.get("id").getString(); area.getIDReferences().createID(id); if (area instanceof BlockArea) { area.end(); } //if (this.isInListBody) { //startIndent += bodyIndent + distanceBetweenStarts; //} this.marker = 0; } if ((spaceBefore != 0) && (this.marker == 0)) { area.increaseHeight(spaceBefore); } if (marker == 0) { // configure id area.getIDReferences().configureID(id, area); } this.areaContainer = new AreaContainer(fs, -area.borderWidthLeft, -area.borderWidthTop + area.getHeight(), area.getAllocationWidth(), area.spaceLeft(), Position.RELATIVE); areaContainer.setPage(area.getPage()); areaContainer.setBackgroundColor(backgroundColor); areaContainer.setBorderStyle(borderStyle, borderStyle, borderStyle, borderStyle); areaContainer.setBorderWidth(borderWidth, borderWidth, borderWidth, borderWidth); areaContainer.setBorderColor(borderColor, borderColor, borderColor, borderColor); areaContainer.start(); areaContainer.setAbsoluteHeight(area.getAbsoluteHeight()); areaContainer.setIDReferences(area.getIDReferences()); Vector keepWith = new Vector(); int numChildren = this.children.size(); TableRow lastRow = null; boolean endKeepGroup = true; for (int i = this.marker; i < numChildren; i++) { TableRow row = (TableRow) children.elementAt(i); row.setColumns(columns); row.doSetup(areaContainer); if (row.getKeepWithPrevious().getType() != KeepValue.KEEP_WITH_AUTO && lastRow != null && keepWith.indexOf(lastRow) == -1) { keepWith.addElement(lastRow); } else { if(endKeepGroup && keepWith.size() > 0) { keepWith = new Vector(); } } Status status; if ((status = row.layout(areaContainer)).isIncomplete()) { if (keepWith.size() > 0) { // && status.getCode() == Status.AREA_FULL_NONE row.removeLayout(areaContainer); for (Enumeration e = keepWith.elements(); e.hasMoreElements();) { TableRow tr = (TableRow) e.nextElement(); tr.removeLayout(areaContainer); i--; } if(i == 0) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } } this.marker = i; if ((i != 0) && (status.getCode() == Status.AREA_FULL_NONE)) { status = new Status(Status.AREA_FULL_SOME); } if (i < widows && numChildren >= widows) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } if (numChildren <= orphans) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } if (numChildren - i < orphans && numChildren >= orphans) { for (int count = i; count > numChildren - orphans - 1; count--) { row = (TableRow) children.elementAt(count); row.removeLayout(areaContainer); i--; } if (i < widows && numChildren >= widows) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } this.marker = i; area.addChild(areaContainer); //areaContainer.end(); area.increaseHeight(areaContainer.getHeight()); area.setAbsoluteHeight( areaContainer.getAbsoluteHeight()); return new Status(Status.AREA_FULL_SOME); } if (!((i == 0) && (areaContainer.getContentHeight() <= 0))) { area.addChild(areaContainer); //areaContainer.end(); area.increaseHeight(areaContainer.getHeight()); area.setAbsoluteHeight( areaContainer.getAbsoluteHeight()); } return status; } else if (status.getCode() == Status.KEEP_WITH_NEXT) { keepWith.addElement(row); endKeepGroup = false; } else { endKeepGroup = true; } lastRow = row; } area.addChild(areaContainer); areaContainer.end(); area.increaseHeight(areaContainer.getHeight()); area.setAbsoluteHeight(areaContainer.getAbsoluteHeight()); if (spaceAfter != 0) { area.increaseHeight(spaceAfter); } if (area instanceof BlockArea) { area.start(); } return new Status(Status.OK); }
public Status layout(Area area) throws FOPException { if (this.marker == BREAK_AFTER) { return new Status(Status.OK); } if (this.marker == START) { String fontFamily = this.properties.get("font-family").getString(); String fontStyle = this.properties.get("font-style").getString(); String fontWeight = this.properties.get("font-weight").getString(); int fontSize = this.properties.get("font-size").getLength().mvalue(); // font-variant support // added by Eric SCHAEFFER int fontVariant = this.properties.get("font-variant").getEnum(); this.fs = new FontState(area.getFontInfo(), fontFamily, fontStyle, fontWeight, fontSize, fontVariant); this.spaceBefore = this.properties.get( "space-before.optimum").getLength().mvalue(); this.spaceAfter = this.properties.get( "space-after.optimum").getLength().mvalue(); this.backgroundColor = this.properties.get( "background-color").getColorType(); this.borderColor = this.properties.get("border-color").getColorType(); this.borderWidth = this.properties.get( "border-width").getLength().mvalue(); this.borderStyle = this.properties.get("border-style").getEnum(); this.id = this.properties.get("id").getString(); area.getIDReferences().createID(id); if (area instanceof BlockArea) { area.end(); } //if (this.isInListBody) { //startIndent += bodyIndent + distanceBetweenStarts; //} this.marker = 0; } if ((spaceBefore != 0) && (this.marker == 0)) { area.increaseHeight(spaceBefore); } if (marker == 0) { // configure id area.getIDReferences().configureID(id, area); } this.areaContainer = new AreaContainer(fs, -area.borderWidthLeft, -area.borderWidthTop + area.getHeight(), area.getAllocationWidth(), area.spaceLeft(), Position.RELATIVE); areaContainer.setPage(area.getPage()); areaContainer.setBackgroundColor(backgroundColor); areaContainer.setBorderStyle(borderStyle, borderStyle, borderStyle, borderStyle); areaContainer.setBorderWidth(borderWidth, borderWidth, borderWidth, borderWidth); areaContainer.setBorderColor(borderColor, borderColor, borderColor, borderColor); areaContainer.start(); areaContainer.setAbsoluteHeight(area.getAbsoluteHeight()); areaContainer.setIDReferences(area.getIDReferences()); Vector keepWith = new Vector(); int numChildren = this.children.size(); TableRow lastRow = null; boolean endKeepGroup = true; for (int i = this.marker; i < numChildren; i++) { Object child = children.elementAt(i); if(!(child instanceof TableRow)) { throw new FOPException("Currently only Table Rows are supported in table body, header and footer"); } TableRow row = (TableRow) child; row.setColumns(columns); row.doSetup(areaContainer); if (row.getKeepWithPrevious().getType() != KeepValue.KEEP_WITH_AUTO && lastRow != null && keepWith.indexOf(lastRow) == -1) { keepWith.addElement(lastRow); } else { if(endKeepGroup && keepWith.size() > 0) { keepWith = new Vector(); } } Status status; if ((status = row.layout(areaContainer)).isIncomplete()) { if (keepWith.size() > 0) { // && status.getCode() == Status.AREA_FULL_NONE row.removeLayout(areaContainer); for (Enumeration e = keepWith.elements(); e.hasMoreElements();) { TableRow tr = (TableRow) e.nextElement(); tr.removeLayout(areaContainer); i--; } if(i == 0) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } } this.marker = i; if ((i != 0) && (status.getCode() == Status.AREA_FULL_NONE)) { status = new Status(Status.AREA_FULL_SOME); } if (i < widows && numChildren >= widows) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } if (numChildren <= orphans) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } if (numChildren - i < orphans && numChildren >= orphans) { for (int count = i; count > numChildren - orphans - 1; count--) { row = (TableRow) children.elementAt(count); row.removeLayout(areaContainer); i--; } if (i < widows && numChildren >= widows) { resetMarker(); return new Status(Status.AREA_FULL_NONE); } this.marker = i; area.addChild(areaContainer); //areaContainer.end(); area.increaseHeight(areaContainer.getHeight()); area.setAbsoluteHeight( areaContainer.getAbsoluteHeight()); return new Status(Status.AREA_FULL_SOME); } if (!((i == 0) && (areaContainer.getContentHeight() <= 0))) { area.addChild(areaContainer); //areaContainer.end(); area.increaseHeight(areaContainer.getHeight()); area.setAbsoluteHeight( areaContainer.getAbsoluteHeight()); } return status; } else if (status.getCode() == Status.KEEP_WITH_NEXT) { keepWith.addElement(row); endKeepGroup = false; } else { endKeepGroup = true; } lastRow = row; } area.addChild(areaContainer); areaContainer.end(); area.increaseHeight(areaContainer.getHeight()); area.setAbsoluteHeight(areaContainer.getAbsoluteHeight()); if (spaceAfter != 0) { area.increaseHeight(spaceAfter); } if (area instanceof BlockArea) { area.start(); } return new Status(Status.OK); }
diff --git a/src/main/java/com/laytonsmith/abstraction/bukkit/events/BukkitPlayerEvents.java b/src/main/java/com/laytonsmith/abstraction/bukkit/events/BukkitPlayerEvents.java index 2ee2e735..287f2ae6 100644 --- a/src/main/java/com/laytonsmith/abstraction/bukkit/events/BukkitPlayerEvents.java +++ b/src/main/java/com/laytonsmith/abstraction/bukkit/events/BukkitPlayerEvents.java @@ -1,372 +1,372 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.laytonsmith.abstraction.bukkit.events; import com.laytonsmith.abstraction.Implementation; import com.laytonsmith.abstraction.MCPlayer; import com.laytonsmith.abstraction.bukkit.BukkitMCItemStack; import com.laytonsmith.abstraction.bukkit.BukkitMCLocation; import com.laytonsmith.abstraction.bukkit.BukkitMCPlayer; import com.laytonsmith.abstraction.bukkit.BukkitMCWorld; import com.laytonsmith.abstraction.bukkit.blocks.BukkitMCBlock; import com.laytonsmith.core.Env; import com.laytonsmith.core.ObjectGenerator; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.*; import com.laytonsmith.core.events.Prefilters.PrefilterType; import com.laytonsmith.core.events.*; import com.laytonsmith.core.events.BoundEvent.ActiveEvent; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.exceptions.EventException; import com.laytonsmith.core.exceptions.PrefilterNonMatchException; import com.laytonsmith.core.functions.Exceptions; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.inventory.ItemStack; /** * * @author layton */ public class BukkitPlayerEvents { @abstraction(load=com.laytonsmith.core.events.drivers.PlayerEvents.player_join.class, type=Implementation.Type.BUKKIT) public static class player_join implements EventHandlerInterface{ public boolean matches(Map<String, Construct> prefilter, Object e) throws PrefilterNonMatchException { if(e instanceof PlayerJoinEvent){ PlayerJoinEvent ple = (PlayerJoinEvent) e; if(prefilter.containsKey("player")){ if(!ple.getPlayer().getName().equals(prefilter.get("player_name").val())){ return false; } } Prefilters.match(prefilter, "join_message", ple.getJoinMessage(), PrefilterType.REGEX); return true; } return false; } public Map<String, Construct> evaluate(Object e, EventMixinInterface mixin) throws EventException { if(e instanceof PlayerJoinEvent){ PlayerJoinEvent ple = (PlayerJoinEvent) e; Map<String, Construct> map = mixin.evaluate_helper(e); //map.put("player", new CString(ple.getPlayer().getName(), 0, null)); map.put("join_message", new CString(ple.getJoinMessage(), 0, null)); return map; } else{ throw new EventException("Cannot convert e to PlayerLoginEvent"); } } public Object convert(CArray manual){ PlayerJoinEvent e = new PlayerJoinEvent(((BukkitMCPlayer)Static.GetPlayer(manual.get("player").val(), 0, null))._Player(), manual.get("join_message").val()); return e; } public boolean modifyEvent(String key, Construct value, Object event) { if(event instanceof PlayerJoinEvent){ PlayerJoinEvent pje = (PlayerJoinEvent)event; if(key.equals("join_message")){ if(value instanceof CNull){ pje.setJoinMessage(null); return pje.getJoinMessage() == null; } else { pje.setJoinMessage(value.val()); return pje.getJoinMessage().equals(value.val()); } } } return false; } public EventMixinInterface customMixin(AbstractEvent e) { return null; } public void preExecution(Env env, ActiveEvent activeEvent) { throw new UnsupportedOperationException("Not supported yet."); } public void postExecution(Env env, ActiveEvent activeEvent) { throw new UnsupportedOperationException("Not supported yet."); } } @abstraction(load=com.laytonsmith.core.events.drivers.PlayerEvents.player_interact.class, type=Implementation.Type.BUKKIT) public static class player_interact implements EventHandlerInterface{ public boolean matches(Map<String, Construct> prefilter, Object e) throws PrefilterNonMatchException { if(e instanceof PlayerInteractEvent){ PlayerInteractEvent pie = (PlayerInteractEvent)e; if(((PlayerInteractEvent)e).getAction().equals(Action.PHYSICAL)){ return false; } if(prefilter.containsKey("button")){ if(pie.getAction().equals(Action.LEFT_CLICK_AIR) || pie.getAction().equals(Action.LEFT_CLICK_BLOCK)){ if(!prefilter.get("button").val().toLowerCase().equals("left")){ return false; } } if(pie.getAction().equals(Action.RIGHT_CLICK_AIR) || pie.getAction().equals(Action.RIGHT_CLICK_BLOCK)){ if(!prefilter.get("button").val().toLowerCase().equals("right")){ return false; } } } Prefilters.match(prefilter, "item", Static.ParseItemNotation(new BukkitMCItemStack(pie.getItem())), PrefilterType.ITEM_MATCH); Prefilters.match(prefilter, "block", Static.ParseItemNotation(new BukkitMCBlock(pie.getClickedBlock())), PrefilterType.ITEM_MATCH); Prefilters.match(prefilter, "player", pie.getPlayer().getName(), PrefilterType.MACRO); return true; } return false; } public Map<String, Construct> evaluate(Object e, EventMixinInterface mixin) throws EventException { if(e instanceof PlayerInteractEvent){ PlayerInteractEvent pie = (PlayerInteractEvent) e; Map<String, Construct> map = mixin.evaluate_helper(e); //map.put("player", new CString(pie.getPlayer().getName(), 0, null)); Action a = pie.getAction(); map.put("action", new CString(a.name().toLowerCase(), 0, null)); map.put("block", new CString(Static.ParseItemNotation(new BukkitMCBlock(pie.getClickedBlock())), 0, null)); if(a == Action.LEFT_CLICK_AIR || a == Action.LEFT_CLICK_BLOCK){ map.put("button", new CString("left", 0, null)); } else { map.put("button", new CString("right", 0, null)); } if(a == Action.LEFT_CLICK_BLOCK || a == Action.RIGHT_CLICK_BLOCK){ map.put("facing", new CString(pie.getBlockFace().name().toLowerCase(), 0, null)); Block b = pie.getClickedBlock(); map.put("location", new CArray(0, null, new CInt(b.getX(), 0, null), new CInt(b.getY(), 0, null), new CInt(b.getZ(), 0, null), new CString(b.getWorld().getName(), 0, null))); } map.put("item", new CString(Static.ParseItemNotation(new BukkitMCItemStack(pie.getItem())), 0, null)); return map; } else { throw new EventException("Cannot convert e to PlayerInteractEvent"); } } @Override public Object convert(CArray manual){ Player p = ((BukkitMCPlayer)Static.GetPlayer(manual.get("player"), 0, null))._Player(); Action a = Action.valueOf(manual.get("action").val().toUpperCase()); ItemStack is = ((BukkitMCItemStack)Static.ParseItemNotation("player_interact event", manual.get("item").val(), 1, 0, null)).__ItemStack(); Block b = ((BukkitMCBlock)ObjectGenerator.GetGenerator().location(manual.get("location"), null, 0, null).getBlock()).__Block(); BlockFace bf = BlockFace.valueOf(manual.get("facing").val()); PlayerInteractEvent e = new PlayerInteractEvent(p, a, is, b, bf); return e; } public boolean modifyEvent(String key, Construct value, Object event) { if(event instanceof PlayerInteractEvent){ PlayerInteractEvent pie = (PlayerInteractEvent)event; } return false; } public EventMixinInterface customMixin(AbstractEvent e) { throw new UnsupportedOperationException("Not supported yet."); } public void preExecution(Env env, ActiveEvent activeEvent) { throw new UnsupportedOperationException("Not supported yet."); } public void postExecution(Env env, ActiveEvent activeEvent) { throw new UnsupportedOperationException("Not supported yet."); } } @abstraction(load = com.laytonsmith.core.events.drivers.PlayerEvents.player_spawn.class, type = Implementation.Type.BUKKIT) public static class player_spawn implements EventHandlerInterface { public boolean matches(Map<String, Construct> prefilter, Object e) throws PrefilterNonMatchException { if (e instanceof PlayerRespawnEvent) { PlayerRespawnEvent event = (PlayerRespawnEvent) e; Prefilters.match(prefilter, "player", event.getPlayer().getName(), PrefilterType.MACRO); Prefilters.match(prefilter, "x", event.getRespawnLocation().getBlockX(), PrefilterType.EXPRESSION); Prefilters.match(prefilter, "y", event.getRespawnLocation().getBlockY(), PrefilterType.EXPRESSION); Prefilters.match(prefilter, "z", event.getRespawnLocation().getBlockZ(), PrefilterType.EXPRESSION); Prefilters.match(prefilter, "world", event.getRespawnLocation().getWorld().getName(), PrefilterType.STRING_MATCH); return true; } return false; } public Map<String, Construct> evaluate(Object e, EventMixinInterface mixin) throws EventException { if (e instanceof PlayerRespawnEvent) { PlayerRespawnEvent event = (PlayerRespawnEvent) e; Map<String, Construct> map = mixin.evaluate_helper(e); //the helper puts the player in for us CArray location = ObjectGenerator.GetGenerator().location(new BukkitMCLocation(event.getRespawnLocation())); map.put("location", location); return map; } else { throw new EventException("Cannot convert e to PlayerRespawnEvent"); } } public Object convert(CArray manual) { //For firing off the event manually, we have to convert the CArray into an //actual object that will trigger it Player p = ((BukkitMCPlayer)Static.GetPlayer(manual.get("player")))._Player(); Location l = ((BukkitMCLocation)ObjectGenerator.GetGenerator().location(manual.get("location"), new BukkitMCWorld(p.getWorld()), 0, null))._Location(); PlayerRespawnEvent e = new PlayerRespawnEvent(p, l, false); return e; } public boolean modifyEvent(String key, Construct value, Object event) { if (event instanceof PlayerRespawnEvent) { PlayerRespawnEvent e = (PlayerRespawnEvent) event; if (key.equals("location")) { //Change this parameter in e to value e.setRespawnLocation(((BukkitMCLocation)ObjectGenerator.GetGenerator().location(value, new BukkitMCWorld(e.getPlayer().getWorld()), 0, null))._Location()); return true; } } return false; } public EventMixinInterface customMixin(AbstractEvent e) { return null; } public void preExecution(Env env, ActiveEvent activeEvent) { if(activeEvent.getUnderlyingEvent() instanceof PlayerRespawnEvent){ //Static lookups of the player don't seem to work here, but //the player is passed in with the event. MCPlayer player = (new BukkitMCPlayer(((PlayerRespawnEvent)activeEvent.getUnderlyingEvent()).getPlayer())); env.SetPlayer(player); Static.InjectPlayer(player); } } public void postExecution(Env env, ActiveEvent activeEvent) { if(activeEvent.getUnderlyingEvent() instanceof PlayerRespawnEvent){ MCPlayer player = (new BukkitMCPlayer(((PlayerRespawnEvent)activeEvent.getUnderlyingEvent()).getPlayer())); Static.UninjectPlayer(player); } } } @abstraction(load = com.laytonsmith.core.events.drivers.PlayerEvents.player_death.class, type = Implementation.Type.BUKKIT) public static class player_death implements EventHandlerInterface { //Check to see if this event matches the given prefilter public boolean matches(Map<String, Construct> prefilter, Object e) throws PrefilterNonMatchException { if (e instanceof EntityDeathEvent) { EntityDeathEvent event = (EntityDeathEvent) e; Prefilters.match(prefilter, "player", ((Player)event.getEntity()).getName(), PrefilterType.MACRO); return true; } return false; } //We have an actual event now, change it into a Map //that will end up being the @event object public Map<String, Construct> evaluate(Object e, EventMixinInterface mixin) throws EventException { if (e instanceof EntityDeathEvent) { EntityDeathEvent event = (EntityDeathEvent) e; Map<String, Construct> map = mixin.evaluate_helper(e); CArray ca = new CArray(0, null); for(ItemStack is : event.getDrops()){ ca.push(ObjectGenerator.GetGenerator().item(new BukkitMCItemStack(is), 0, null)); } Player p = (Player)event.getEntity(); map.put("drops", ca); map.put("xp", new CInt(event.getDroppedExp(), 0, null)); if(event instanceof PlayerDeathEvent){ map.put("death_message", new CString(((PlayerDeathEvent)event).getDeathMessage(), 0, null)); } try{ map.put("cause", new CString(event.getEntity().getLastDamageCause().getCause().name(), 0, null)); } catch(NullPointerException ex){ map.put("cause", new CString(DamageCause.CUSTOM.name(), 0, null)); } map.put("location", ObjectGenerator.GetGenerator().location(new BukkitMCLocation(p.getLocation()))); return map; } else { throw new EventException("Cannot convert e to EntityDeathEvent"); } } public Object convert(CArray manual) { //For firing off the event manually, we have to convert the CArray into an //actual object that will trigger it String splayer = manual.get("player").val(); List<ItemStack> list = new ArrayList<ItemStack>(); CArray clist = (CArray)manual.get("drops"); for(String key : clist.keySet()){ list.add(((BukkitMCItemStack)ObjectGenerator.GetGenerator().item(clist.get(key), clist.getLineNum(), clist.getFile())).__ItemStack()); } EntityDeathEvent e = new EntityDeathEvent(((BukkitMCPlayer)Static.GetPlayer(splayer))._Player(), list); return e; } //Given the paramters, change the underlying event public boolean modifyEvent(String key, Construct value, Object event) { if (event instanceof EntityDeathEvent) { EntityDeathEvent e = (EntityDeathEvent) event; if (key.equals("xp")) { //Change this parameter in e to value e.setDroppedExp((int)Static.getInt(value)); return true; } if(key.equals("drops")){ if(value instanceof CNull){ value = new CArray(0, null); } if(!(value instanceof CArray)){ throw new ConfigRuntimeException("drops must be an array, or null", Exceptions.ExceptionType.CastException, 0, null); } e.getDrops().clear(); CArray drops = (CArray) value; for(String dropID : drops.keySet()){ e.getDrops().add(((BukkitMCItemStack)ObjectGenerator.GetGenerator().item(drops.get(dropID), 0, null)).__ItemStack()); } return true; } if(event instanceof PlayerDeathEvent && key.equals("death_message")){ - ((PlayerDeathEvent)event).setDeathMessage(value.val()); + ((PlayerDeathEvent)event).setDeathMessage(value.nval()); return true; } } return false; } public EventMixinInterface customMixin(AbstractEvent e) { return null; } public void preExecution(Env env, ActiveEvent activeEvent) { throw new UnsupportedOperationException("Not supported yet."); } public void postExecution(Env env, ActiveEvent activeEvent) { throw new UnsupportedOperationException("Not supported yet."); } } }
true
true
public boolean modifyEvent(String key, Construct value, Object event) { if (event instanceof EntityDeathEvent) { EntityDeathEvent e = (EntityDeathEvent) event; if (key.equals("xp")) { //Change this parameter in e to value e.setDroppedExp((int)Static.getInt(value)); return true; } if(key.equals("drops")){ if(value instanceof CNull){ value = new CArray(0, null); } if(!(value instanceof CArray)){ throw new ConfigRuntimeException("drops must be an array, or null", Exceptions.ExceptionType.CastException, 0, null); } e.getDrops().clear(); CArray drops = (CArray) value; for(String dropID : drops.keySet()){ e.getDrops().add(((BukkitMCItemStack)ObjectGenerator.GetGenerator().item(drops.get(dropID), 0, null)).__ItemStack()); } return true; } if(event instanceof PlayerDeathEvent && key.equals("death_message")){ ((PlayerDeathEvent)event).setDeathMessage(value.val()); return true; } } return false; }
public boolean modifyEvent(String key, Construct value, Object event) { if (event instanceof EntityDeathEvent) { EntityDeathEvent e = (EntityDeathEvent) event; if (key.equals("xp")) { //Change this parameter in e to value e.setDroppedExp((int)Static.getInt(value)); return true; } if(key.equals("drops")){ if(value instanceof CNull){ value = new CArray(0, null); } if(!(value instanceof CArray)){ throw new ConfigRuntimeException("drops must be an array, or null", Exceptions.ExceptionType.CastException, 0, null); } e.getDrops().clear(); CArray drops = (CArray) value; for(String dropID : drops.keySet()){ e.getDrops().add(((BukkitMCItemStack)ObjectGenerator.GetGenerator().item(drops.get(dropID), 0, null)).__ItemStack()); } return true; } if(event instanceof PlayerDeathEvent && key.equals("death_message")){ ((PlayerDeathEvent)event).setDeathMessage(value.nval()); return true; } } return false; }
diff --git a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/DefaultServletTest.java b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/DefaultServletTest.java index 001f57111..50c3510bc 100644 --- a/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/DefaultServletTest.java +++ b/jetty-servlet/src/test/java/org/eclipse/jetty/servlet/DefaultServletTest.java @@ -1,104 +1,105 @@ package org.eclipse.jetty.servlet; import java.io.File; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.server.Server; public class DefaultServletTest extends TestCase { private Server server; private LocalConnector connector; private ServletContextHandler context; protected void setUp() throws Exception { super.setUp(); server = new Server(); server.setSendServerVersion(false); connector = new LocalConnector(); context = new ServletContextHandler(); context.setContextPath("/context"); context.setWelcomeFiles(new String[] {}); // no welcome files server.setHandler(context); server.addConnector(connector); server.start(); } protected void tearDown() throws Exception { super.tearDown(); if (server != null) { server.stop(); } } public void testListingXSS() throws Exception { - ServletHolder defholder = context.addServlet(DefaultServlet.class,"/*"); + ServletHolder defholder = context.addServlet(DefaultServlet.class,"/listing/*"); defholder.setInitParameter("dirAllowed","true"); defholder.setInitParameter("redirectWelcome","false"); defholder.setInitParameter("gzip","false"); File resBase = new File("src/test/resources"); assertTrue("resBase.exists",resBase.exists()); assertTrue("resBase.isDirectory",resBase.isDirectory()); String resBasePath = resBase.getAbsolutePath(); defholder.setInitParameter("resourceBase",resBasePath); StringBuffer req1 = new StringBuffer(); - req1.append("GET /context/org/mortbay/resource/;<script>window.alert(\"hi\");</script> HTTP/1.1\n"); + req1.append("GET /context/listing/;<script>window.alert(\"hi\");</script> HTTP/1.1\n"); req1.append("Host: localhost\n"); + req1.append("Connection: close\n"); req1.append("\n"); String response = connector.getResponses(req1.toString()); - assertResponseContains("org/mortbay/resource/one/",response); - assertResponseContains("org/mortbay/resource/two/",response); - assertResponseContains("org/mortbay/resource/three/",response); + assertResponseContains("listing/one/",response); + assertResponseContains("listing/two/",response); + assertResponseContains("listing/three/",response); assertResponseNotContains("<script>",response); } private void assertResponseNotContains(String forbidden, String response) { int idx = response.indexOf(forbidden); if (idx != (-1)) { // Found (when should not have) StringBuffer err = new StringBuffer(); err.append("Response contain forbidden string \"").append(forbidden).append("\""); err.append("\n").append(response); System.err.println(err); throw new AssertionFailedError(err.toString()); } } private void assertResponseContains(String expected, String response) { int idx = response.indexOf(expected); if (idx == (-1)) { // Not found StringBuffer err = new StringBuffer(); err.append("Response does not contain expected string \"").append(expected).append("\""); err.append("\n").append(response); System.err.println(err); throw new AssertionFailedError(err.toString()); } } }
false
true
public void testListingXSS() throws Exception { ServletHolder defholder = context.addServlet(DefaultServlet.class,"/*"); defholder.setInitParameter("dirAllowed","true"); defholder.setInitParameter("redirectWelcome","false"); defholder.setInitParameter("gzip","false"); File resBase = new File("src/test/resources"); assertTrue("resBase.exists",resBase.exists()); assertTrue("resBase.isDirectory",resBase.isDirectory()); String resBasePath = resBase.getAbsolutePath(); defholder.setInitParameter("resourceBase",resBasePath); StringBuffer req1 = new StringBuffer(); req1.append("GET /context/org/mortbay/resource/;<script>window.alert(\"hi\");</script> HTTP/1.1\n"); req1.append("Host: localhost\n"); req1.append("\n"); String response = connector.getResponses(req1.toString()); assertResponseContains("org/mortbay/resource/one/",response); assertResponseContains("org/mortbay/resource/two/",response); assertResponseContains("org/mortbay/resource/three/",response); assertResponseNotContains("<script>",response); }
public void testListingXSS() throws Exception { ServletHolder defholder = context.addServlet(DefaultServlet.class,"/listing/*"); defholder.setInitParameter("dirAllowed","true"); defholder.setInitParameter("redirectWelcome","false"); defholder.setInitParameter("gzip","false"); File resBase = new File("src/test/resources"); assertTrue("resBase.exists",resBase.exists()); assertTrue("resBase.isDirectory",resBase.isDirectory()); String resBasePath = resBase.getAbsolutePath(); defholder.setInitParameter("resourceBase",resBasePath); StringBuffer req1 = new StringBuffer(); req1.append("GET /context/listing/;<script>window.alert(\"hi\");</script> HTTP/1.1\n"); req1.append("Host: localhost\n"); req1.append("Connection: close\n"); req1.append("\n"); String response = connector.getResponses(req1.toString()); assertResponseContains("listing/one/",response); assertResponseContains("listing/two/",response); assertResponseContains("listing/three/",response); assertResponseNotContains("<script>",response); }
diff --git a/kernel-impl/src/main/java/org/sakaiproject/authz/impl/DbAuthzGroupService.java b/kernel-impl/src/main/java/org/sakaiproject/authz/impl/DbAuthzGroupService.java index 06fa4aa5..d5d96fdd 100644 --- a/kernel-impl/src/main/java/org/sakaiproject/authz/impl/DbAuthzGroupService.java +++ b/kernel-impl/src/main/java/org/sakaiproject/authz/impl/DbAuthzGroupService.java @@ -1,3172 +1,3172 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2006 2007, 2007, 2008 Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.authz.impl; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.Set; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.GroupFullException; import org.sakaiproject.authz.api.Member; import org.sakaiproject.authz.api.Role; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.db.api.SqlReader; import org.sakaiproject.db.api.SqlService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityManager; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.event.api.Event; import org.sakaiproject.event.api.NotificationService; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.memory.api.Cache; import org.sakaiproject.memory.api.MemoryService; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.time.api.Time; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.util.BaseDbFlatStorage; import org.sakaiproject.util.BaseResourceProperties; import org.sakaiproject.util.BaseResourcePropertiesEdit; import org.sakaiproject.util.StringUtil; /** * <p> * DbAuthzGroupService is an extension of the BaseAuthzGroupService with database storage. * </p> */ public abstract class DbAuthzGroupService extends BaseAuthzGroupService implements Observer { /** Our log (commons). */ private static Log M_log = LogFactory.getLog(DbAuthzGroupService.class); /** All the event functions we know exist on the db. */ protected Collection m_functionCache = new HashSet(); /** All the event role names we know exist on the db. */ protected Collection m_roleNameCache = new HashSet(); /** Table name for realms. */ protected String m_realmTableName = "SAKAI_REALM"; /** Table name for realm properties. */ protected String m_realmPropTableName = "SAKAI_REALM_PROPERTY"; /** ID field for realm. */ protected String m_realmIdFieldName = "REALM_ID"; /** AuthzGroup dbid field. */ protected String m_realmDbidField = "REALM_KEY"; /** All "fields" for realm reading. */ protected String[] m_realmReadFieldNames = {"REALM_ID", "PROVIDER_ID", "(select MAX(ROLE_NAME) from SAKAI_REALM_ROLE where ROLE_KEY = MAINTAIN_ROLE)", "CREATEDBY", "MODIFIEDBY", "CREATEDON", "MODIFIEDON", "REALM_KEY"}; /** All "fields" for realm update. */ protected String[] m_realmUpdateFieldNames = {"REALM_ID", "PROVIDER_ID", "MAINTAIN_ROLE = (select MAX(ROLE_KEY) from SAKAI_REALM_ROLE where ROLE_NAME = ?)", "CREATEDBY", "MODIFIEDBY", "CREATEDON", "MODIFIEDON"}; /** All "fields" for realm insert. */ protected String[] m_realmInsertFieldNames = {"REALM_ID", "PROVIDER_ID", "MAINTAIN_ROLE", "CREATEDBY", "MODIFIEDBY", "CREATEDON", "MODIFIEDON"}; /** All "field values" for realm insert. */ protected String[] m_realmInsertValueNames = {"?", "?", "(select MAX(ROLE_KEY) from SAKAI_REALM_ROLE where ROLE_NAME = ?)", "?", "?", "?", "?"}; /************************************************************************************************************************************************* * Dependencies ************************************************************************************************************************************************/ /** map of database handlers. */ protected Map<String, DbAuthzGroupSql> databaseBeans; /** The database handler we are using. */ protected DbAuthzGroupSql dbAuthzGroupSql; public void setDatabaseBeans(Map databaseBeans) { this.databaseBeans = databaseBeans; } /** * returns the bean which contains database dependent code. */ public DbAuthzGroupSql getDbAuthzGroupSql() { return dbAuthzGroupSql; } /** * sets which bean containing database dependent code should be used depending on the database vendor. */ public void setDbAuthzGroupSql(String vendor) throws Exception { this.dbAuthzGroupSql = (databaseBeans.containsKey(vendor) ? databaseBeans.get(vendor) : databaseBeans.get("default")); } private MemoryService m_memoryService; public void setMemoryService(MemoryService memoryService) { this.m_memoryService = memoryService; } // KNL-600 CACHING for the realm role groups private Cache m_realmRoleGRCache; private Cache authzUserGroupIdsCache; private Cache maintainRolesCache; /** * @return the ServerConfigurationService collaborator. */ protected abstract SqlService sqlService(); /************************************************************************************************************************************************* * Configuration ************************************************************************************************************************************************/ /** If true, we do our locks in the remote database, otherwise we do them here. */ protected boolean m_useExternalLocks = true; /** * Configuration: set the external locks value. * * @param value * The external locks value. */ public void setExternalLocks(String value) { m_useExternalLocks = Boolean.valueOf(value).booleanValue(); } /** Configuration: to run the ddl on init or not. */ protected boolean m_autoDdl = false; /** * Configuration: to run the ddl on init or not. * * @param value * the auto ddl value. */ public void setAutoDdl(String value) { m_autoDdl = Boolean.valueOf(value).booleanValue(); } /** * Configuration: Whether or not to automatically promote non-provided users with same status * and role to provided */ protected boolean m_promoteUsersToProvided = true; /** * Configuration: Whether or not to automatically promote non-provided users with same status * and role to provided * * @param promoteUsersToProvided * 'true' to promote non-provided users, 'false' to maintain their non-provided status */ public void setPromoteUsersToProvided(boolean promoteUsersToProvided) { m_promoteUsersToProvided = promoteUsersToProvided; } /************************************************************************************************************************************************* * Init and Destroy ************************************************************************************************************************************************/ /** * Final initialization, once all dependencies are set. */ public void init() { try { // The observer will be notified whenever there are new events. Priority observers get notified first, before normal observers. eventTrackingService().addPriorityObserver(this); // if we are auto-creating our schema, check and create if (m_autoDdl) { sqlService().ddl(this.getClass().getClassLoader(), "sakai_realm"); sqlService().ddl(this.getClass().getClassLoader(), "sakai_realm_2_4_0_001"); } super.init(); setDbAuthzGroupSql(sqlService().getVendor()); // pre-cache role and function names cacheRoleNames(); cacheFunctionNames(); m_realmRoleGRCache = m_memoryService.newCache("org.sakaiproject.authz.impl.DbAuthzGroupService.realmRoleGroupCache"); M_log.info("init(): table: " + m_realmTableName + " external locks: " + m_useExternalLocks); authzUserGroupIdsCache = m_memoryService.newCache("org.sakaiproject.authz.impl.DbAuthzGroupService.authzUserGroupIdsCache"); maintainRolesCache = m_memoryService.newCache("org.sakaiproject.authz.impl.DbAuthzGroupService.maintainRolesCache"); //get the set of maintain roles and cache them on startup getMaintainRoles(); } catch (Exception t) { M_log.warn("init(): ", t); } } /** * Returns to uninitialized state. */ public void destroy() { authzUserGroupIdsCache.destroy(); // done with event watching eventTrackingService().deleteObserver(this); maintainRolesCache.destroy(); M_log.info(this +".destroy()"); } /************************************************************************************************************************************************* * BaseAuthzGroupService extensions ************************************************************************************************************************************************/ /** * Construct a Storage object. * * @return The new storage object. */ protected Storage newStorage() { DbStorage storage = new DbStorage(entityManager(), siteService); storage.setPromoteUsersToProvided(m_promoteUsersToProvided); return storage; } // newStorage /** * Check / assure this role name is defined. * * @param name * the role name. */ protected void checkRoleName(String name) { if (name == null) return; name = name.intern(); // check the cache to see if the role name already exists if (getRealmRoleKey(name) != null) return; // see if we have it in the db String statement = dbAuthzGroupSql.getCountRealmRoleSql(); Object[] fields = new Object[1]; fields[0] = name; List results = sqlService().dbRead(statement, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int count = result.getInt(1); return Integer.valueOf(count); } catch (SQLException ignore) { return null; } } }); boolean rv = false; if (!results.isEmpty()) { rv = ((Integer) results.get(0)).intValue() > 0; } // write if we didn't find it if (!rv) { statement = dbAuthzGroupSql.getInsertRealmRoleSql(); // write, but if it fails, we don't really care - it will fail if another app server has just written this role name sqlService().dbWriteFailQuiet(null, statement, fields); } synchronized (m_roleNameCache) { //Get realm role Key statement = dbAuthzGroupSql.getSelectRealmRoleKeySql(); results = sqlService().dbRead(statement, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String name = result.getString(1); String key = result.getString(2); RealmRole realmRole = new RealmRole(name, key); m_roleNameCache.add(realmRole); } catch (SQLException ignore) { } return null; } }); } } /** * Read all the role records, caching them */ protected void cacheRoleNames() { synchronized (m_roleNameCache) { String statement = dbAuthzGroupSql.getSelectRealmRoleSql(); List results = sqlService().dbRead(statement, null, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String name = result.getString(1); String key = result.getString(2); RealmRole realmRole = new RealmRole(name, key); m_roleNameCache.add(realmRole); } catch (SQLException ignore) { } return null; } }); } } /** * Check / assure this function name is defined. * * @param name * the role name. */ protected void checkFunctionName(String name) { if (name == null) return; name = name.intern(); // check the cache to see if the function name already exists if (m_functionCache.contains(name)) return; // see if we have this on the db String statement = dbAuthzGroupSql.getCountRealmFunctionSql(); Object[] fields = new Object[1]; fields[0] = name; List results = sqlService().dbRead(statement, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int count = result.getInt(1); return Integer.valueOf(count); } catch (SQLException ignore) { return null; } } }); boolean rv = false; if (!results.isEmpty()) { rv = ((Integer) results.get(0)).intValue() > 0; } // write if we didn't find it if (!rv) { statement = dbAuthzGroupSql.getInsertRealmFunctionSql(); // write, but if it fails, we don't really care - it will fail if another app server has just written this function sqlService().dbWriteFailQuiet(null, statement, fields); } // cache the existance of the function name synchronized (m_functionCache) { m_functionCache.add(name); } } /** * Read all the function records, caching them */ protected void cacheFunctionNames() { synchronized (m_functionCache) { String statement = dbAuthzGroupSql.getSelectRealmFunction1Sql(); List results = sqlService().dbRead(statement, null, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String name = result.getString(1); m_functionCache.add(name); } catch (SQLException ignore) { } return null; } }); } } /************************************************************************************************************************************************* * Storage implementation ************************************************************************************************************************************************/ /** * Covers for the BaseXmlFileStorage, providing AuthzGroup and RealmEdit parameters */ protected class DbStorage extends BaseDbFlatStorage implements Storage, SqlReader { private static final String REALM_USER_GRANTS_CACHE = "REALM_USER_GRANTS_CACHE"; private static final String REALM_ROLES_CACHE = "REALM_ROLES_CACHE"; private boolean promoteUsersToProvided = true; private EntityManager entityManager; private SiteService siteService; /** * Configure whether or not users with same status and role will be "promoted" to * being provided. * * @param autoPromoteNonProvidedUsers Whether or not to promote non-provided users */ public void setPromoteUsersToProvided(boolean promoteUsersToProvided) { this.promoteUsersToProvided = promoteUsersToProvided; } /** * Construct. */ public DbStorage(EntityManager entityManager, SiteService siteService) { super(m_realmTableName, m_realmIdFieldName, m_realmReadFieldNames, m_realmPropTableName, m_useExternalLocks, null, sqlService()); m_reader = this; setDbidField(m_realmDbidField); setWriteFields(m_realmUpdateFieldNames, m_realmInsertFieldNames, m_realmInsertValueNames); setLocking(false); this.entityManager = entityManager; this.siteService = siteService; // setSortField(m_realmSortField, null); } public boolean check(String id) { return super.checkResource(id); } public AuthzGroup get(String id) { return get(null, id); } protected AuthzGroup get(Connection conn, String id) { // read the base BaseAuthzGroup rv = (BaseAuthzGroup) super.getResource(conn, id); completeGet(conn, rv, false); return rv; } /** * Complete the read process once the basic realm info has been read * * @param realm * The real to complete */ public void completeGet(BaseAuthzGroup realm) { completeGet(null, realm, false); } /** * Complete the read process once the basic realm info has been read * * @param conn * optional SQL connection to use. * @param realm * The real to complete. * @param updateProvider * if true, update and store the provider info. */ protected void completeGet(Connection conn, final BaseAuthzGroup realm, boolean updateProvider) { if (realm == null) return; if (!realm.m_lazy) return; realm.m_lazy = false; // update the db and realm with latest provider if (updateProvider) { refreshAuthzGroup(realm); } // read the properties if (((BaseResourceProperties) realm.m_properties).isLazy()) { ((BaseResourcePropertiesEdit) realm.m_properties).setLazy(false); super.readProperties(conn, realm.getKey(), realm.m_properties); } Map <String, Map> realmRoleGRCache = (Map<String, Map>)m_realmRoleGRCache.get(realm.getId()); if (M_log.isDebugEnabled()) { M_log.debug("DbAuthzGroupService: found " + realm.getId() + " in cache? " + (realmRoleGRCache != null)); } if (realmRoleGRCache != null) { // KNL-1037 read the cached role and membership information Map<?,?> roles = realmRoleGRCache.get(REALM_ROLES_CACHE); Map<String, Member> userGrants = new HashMap<String, Member>(); Map<String, MemberWithRoleId> userGrantsWithRoleId = (Map<String, MemberWithRoleId>) realmRoleGRCache.get(REALM_USER_GRANTS_CACHE); userGrants.putAll(getMemberMap(userGrantsWithRoleId, roles)); realm.m_roles = roles; realm.m_userGrants = userGrants; } else { // KNL-1183 refreshAuthzGroup(realm); // read the roles and role functions String sql = dbAuthzGroupSql.getSelectRealmRoleFunctionSql(); Object fields[] = new Object[1]; fields[0] = realm.getId(); m_sql.dbRead(conn, sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { // get the fields String roleName = result.getString(1); String functionName = result.getString(2); // make the role if needed BaseRole role = (BaseRole) realm.m_roles.get(roleName); if (role == null) { role = new BaseRole(roleName); realm.m_roles.put(role.getId(), role); } // add the function to the role role.allowFunction(functionName); return null; } catch (SQLException ignore) { return null; } } }); // read the role descriptions sql = dbAuthzGroupSql.getSelectRealmRoleDescriptionSql(); m_sql.dbRead(conn, sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { // get the fields String roleName = result.getString(1); String description = result.getString(2); boolean providerOnly = "1".equals(result.getString(3)); // find the role - create it if needed // Note: if the role does not yet exist, it has no functions BaseRole role = (BaseRole) realm.m_roles.get(roleName); if (role == null) { role = new BaseRole(roleName); realm.m_roles.put(role.getId(), role); } // set the description role.setDescription(description); // set the provider only flag role.setProviderOnly(providerOnly); return null; } catch (SQLException ignore) { return null; } } }); // read the role grants sql = dbAuthzGroupSql.getSelectRealmRoleGroup1Sql(); m_sql.dbRead(conn, sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { // get the fields String roleName = result.getString(1); String userId = result.getString(2); String active = result.getString(3); String provided = result.getString(4); // give the user one and only one role grant - there should be no second... BaseMember grant = (BaseMember) realm.m_userGrants.get(userId); if (grant == null) { // find the role - if it does not exist, create it for this grant // NOTE: it would have no functions or description BaseRole role = (BaseRole) realm.m_roles.get(roleName); if (role == null) { role = new BaseRole(roleName); realm.m_roles.put(role.getId(), role); } grant = new BaseMember(role, "1".equals(active), "1".equals(provided), userId, userDirectoryService()); realm.m_userGrants.put(userId, grant); } else { M_log.warn("completeGet: additional user - role grant: " + userId + " " + roleName); } return null; } catch (SQLException ignore) { return null; } } }); if (serverConfigurationService().getBoolean("authz.cacheGrants", true)) { Map<String, Map> payLoad = new HashMap<String, Map>(); payLoad.put(REALM_ROLES_CACHE,realm.m_roles); payLoad.put(REALM_USER_GRANTS_CACHE, getMemberWithRoleIdMap(realm.m_userGrants)); m_realmRoleGRCache.put(realm.getId(), payLoad); } } } /** * {@inheritDoc} */ public List getAuthzGroups(String criteria, PagingPosition page) { List rv = null; if (criteria != null) { criteria = "%" + criteria + "%"; String where = "( UPPER(REALM_ID) like ? or UPPER(PROVIDER_ID) like ? )"; Object[] fields = new Object[2]; fields[0] = criteria.toUpperCase(); fields[1] = criteria.toUpperCase(); // paging if (page != null) { // adjust to the size of the set found // page.validate(rv.size()); rv = getSelectedResources(where, fields, page.getFirst(), page.getLast()); } else { rv = getSelectedResources(where, fields); } } else { // paging if (page != null) { // adjust to the size of the set found // page.validate(rv.size()); rv = getAllResources(page.getFirst(), page.getLast()); } else { rv = getAllResources(); } } return rv; } /** * {@inheritDoc} */ public List getAuthzUserGroupIds(ArrayList authzGroupIds, String userid) { if (authzGroupIds == null || userid == null || authzGroupIds.size() < 1) return new ArrayList(); // empty list UserAndGroups uag = null; // first consult the cache if (authzUserGroupIdsCache.containsKey(userid)) { uag = (UserAndGroups) authzUserGroupIdsCache.get(userid); List<String> result = uag.getRealmQuery(new HashSet<String>(authzGroupIds)); if (M_log.isDebugEnabled()) M_log.debug(uag); if (result != null) { // hit return result; } // miss } // not in the cache String inClause = orInClause( authzGroupIds.size(), "SAKAI_REALM.REALM_ID" ); String statement = dbAuthzGroupSql.getSelectRealmUserGroupSql( inClause ); Object[] fields = new Object[authzGroupIds.size()+1]; for ( int i=0; i<authzGroupIds.size(); i++ ) { fields[i] = authzGroupIds.get(i); } fields[authzGroupIds.size()] = userid; List dbResult = sqlService().dbRead(statement, fields, null ); // no cache for user so create if (uag == null) { uag = new UserAndGroups(userid); } // add to the users cache uag.addRealmQuery(new HashSet<String>(authzGroupIds), dbResult); authzUserGroupIdsCache.put(userid, uag); return dbResult; } /** * {@inheritDoc} */ public int countAuthzGroups(String criteria) { int rv = 0; if (criteria != null) { criteria = "%" + criteria + "%"; String where = "( UPPER(REALM_ID) like ? or UPPER(PROVIDER_ID) like ? )"; Object[] fields = new Object[2]; fields[0] = criteria.toUpperCase(); fields[1] = criteria.toUpperCase(); rv = countSelectedResources(where, fields); } else { rv = countAllResources(); } return rv; } /** * {@inheritDoc} */ public Collection<String> getAuthzUsersInGroups(Set<String> groupIds) { if (groupIds == null || groupIds.isEmpty()) { return new ArrayList<String>(); // empty list } // make a big where condition for groupIds with ORs String inClause = orInClause( groupIds.size(), "SR.REALM_ID" ); String statement = dbAuthzGroupSql.getSelectRealmUsersInGroupsSql(inClause); Object[] fields = groupIds.toArray(); @SuppressWarnings("unchecked") List<String> results = sqlService().dbRead(statement, fields, null); return results; } /** * {@inheritDoc} */ public Set getProviderIds(String authzGroupId) { String statement = dbAuthzGroupSql.getSelectRealmProviderId1Sql(); List results = sqlService().dbRead(statement, new Object[] {authzGroupId}, null); if (results == null) { return new HashSet(); } return new HashSet(results); } /** * {@inheritDoc} */ public Set getAuthzGroupIds(String providerId) { String statement = dbAuthzGroupSql.getSelectRealmIdSql(); List results = sqlService().dbRead(statement, new Object[] {providerId}, null); if (results == null) { return new HashSet(); } return new HashSet(results); } /** * {@inheritDoc} */ public Set getAuthzGroupsIsAllowed(String userId, String lock, Collection azGroups) { // further limited to only those authz groups in the azGroups parameter if not null // if azGroups is not null, but empty, we can short-circut and return an empty set // or if the lock is null if (((azGroups != null) && azGroups.isEmpty()) || lock == null) { return new HashSet(); } // Just like unlock, except we use all realms and get their ids // Note: consider over all realms just those realms where there's a grant of a role that satisfies the lock // Ignore realms where anon or auth satisfy the lock. boolean auth = (userId != null) && (!userDirectoryService().getAnonymousUser().getId().equals(userId)); String sql = dbAuthzGroupSql.getSelectRealmIdSql(azGroups); int size = 2; String roleswap = null; // define the roleswap variable if (azGroups != null) { size += azGroups.size(); for (Iterator i = azGroups.iterator(); i.hasNext();) { // FIXME - just use the azGroups directly rather than split them up String[] refs = StringUtil.split(i.next().toString(), Entity.SEPARATOR); // splits the azGroups values so we can look for swapped state for (int i2 = 0; i2 < refs.length; i2++) // iterate through the groups to see if there is a swapped state in the variable { roleswap = securityService().getUserEffectiveRole("/site/" + refs[i2]); // break from this loop if the user is the current user and a swapped state is found if (roleswap != null && auth && userId.equals(sessionManager().getCurrentSessionUserId())) break; } if (roleswap!=null) { sql = dbAuthzGroupSql.getSelectRealmIdRoleSwapSql(azGroups); // redefine the sql we use if there's a role swap size++; // increase the "size" by 1 for our new sql break; // break from the loop } } } Object[] fields = new Object[size]; fields[0] = lock; fields[1] = userId; if (azGroups != null) { int pos = 2; for (Iterator i = azGroups.iterator(); i.hasNext();) { fields[pos++] = i.next(); } if (roleswap!=null) // add in name of the role for the alternate query { fields[pos++] = roleswap; } } // Get resultset List results = m_sql.dbRead(sql, fields, null); Set rv = new HashSet(); rv.addAll(results); return rv; } /** * {@inheritDoc} */ public AuthzGroup put(String id) { BaseAuthzGroup rv = (BaseAuthzGroup) super.putResource(id, fields(id, null, false)); if (rv != null) { rv.activate(); } return rv; } /** * @inheritDoc */ public void addNewUser(final AuthzGroup azGroup, final String userId, final String role, final int maxSize) throws GroupFullException { // run our save code in a transaction that will restart on deadlock // if deadlock retry fails, or any other error occurs, a runtime error will be thrown m_sql.transact(new Runnable() { public void run() { addNewUserTx(azGroup, userId, role, maxSize); } }, "azg:" + azGroup.getId()); } /** * The transaction code to save the azg. * * @param edit * The azg to save. */ protected void addNewUserTx(AuthzGroup edit, String userId, String role, int maxSize) throws GroupFullException { // Assume that users added in this way are always active and never provided boolean active = true; boolean provided = false; String sql; // Lock the table and count users if required if (maxSize > 0) { // Get the REALM_KEY and lock the realm for update sql = dbAuthzGroupSql.getSelectRealmUpdate(); Object fields[] = new Object[1]; fields[0] = edit.getId(); List resultsKey = m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int realm_key = result.getInt(1); return Integer.valueOf(realm_key); } catch (Exception e) { M_log.warn("addNewUserTx: " + e.toString()); return null; } } }); int realm_key = -1; if (!resultsKey.isEmpty()) { realm_key = ((Integer) resultsKey.get(0)).intValue(); } else { // Can't find the REALM_KEY for this REALM (should never happen) M_log.error("addNewUserTx: can't find realm " + edit.getId()); } // Count the number of users already in the realm sql = dbAuthzGroupSql.getSelectRealmSize(); fields[0] = Integer.valueOf(realm_key); List resultsSize = m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int count = result.getInt(1); return Integer.valueOf(count); } catch (Exception e) { M_log.warn("addNewUserTx: " + e.toString()); return null; } } }); int currentSize = resultsSize.isEmpty() ? -1 : ((Integer) resultsSize.get(0)).intValue(); if ((currentSize < 0) || (currentSize >= maxSize)) { // We can't add the user - group already full, or we can't find the size throw new GroupFullException(edit.getId()); } } // Add the user to SAKAI_REALM_RL_GR sql = dbAuthzGroupSql.getInsertRealmRoleGroup1Sql(); Object fields[] = new Object[5]; fields[0] = edit.getId(); fields[1] = userId; fields[2] = role; fields[3] = active ? "1" : "0"; fields[4] = provided ? "1" : "0"; m_sql.dbWrite(sql, fields); // update the main realm table for new modified time and last-modified-by super.commitResource(edit, fields(edit.getId(), ((BaseAuthzGroup) edit), true), null); } /** * @inheritDoc */ public void removeUser(final AuthzGroup azGroup, final String userId) { // run our save code in a transaction that will restart on deadlock // if deadlock retry fails, or any other error occurs, a runtime error will be thrown m_sql.transact(new Runnable() { public void run() { removeUserTx(azGroup, userId); } }, "azg:" + azGroup.getId()); } /** * The transaction code to save the azg. * * @param edit * The azg to save. */ protected void removeUserTx(AuthzGroup edit, String userId) { // Remove the user from SAKAI_REALM_RL_GR String sql = dbAuthzGroupSql.getDeleteRealmRoleGroup4Sql(); Object fields[] = new Object[2]; fields[0] = edit.getId(); fields[1] = userId; m_sql.dbWrite(sql, fields); // update the main realm table for new modified time and last-modified-by super.commitResource(edit, fields(edit.getId(), ((BaseAuthzGroup) edit), true), null); } /** * @inheritDoc */ public void save(final AuthzGroup edit) { // pre-check the roles and functions to make sure they are all defined for (Iterator iRoles = ((BaseAuthzGroup) edit).m_roles.values().iterator(); iRoles.hasNext();) { Role role = (Role) iRoles.next(); // make sure the role name is defined / define it checkRoleName(role.getId()); for (Iterator iFunctions = role.getAllowedFunctions().iterator(); iFunctions.hasNext();) { String function = (String) iFunctions.next(); // make sure the role name is defined / define it checkFunctionName(function); } } // run our save code in a transaction that will restart on deadlock // if deadlock retry fails, or any other error occurs, a runtime error will be thrown m_sql.transact(new Runnable() { public void run() { saveTx(edit); } }, "azg:" + edit.getId()); // update with the provider refreshAuthzGroup((BaseAuthzGroup) edit); } /** * The transaction code to save the azg. * * @param edit * The azg to save. */ protected void saveTx(AuthzGroup edit) { // update SAKAI_REALM_RL_FN: read, diff with the edit, add and delete save_REALM_RL_FN(edit); // update SAKAI_REALM_RL_GR save_REALM_RL_GR(edit); // update SAKAI_REALM_PROVIDER save_REALM_PROVIDER(edit); // update SAKAI_REALM_ROLE_DESC save_REALM_ROLE_DESC(edit); // update the main realm table and properties super.commitResource(edit, fields(edit.getId(), ((BaseAuthzGroup) edit), true), edit.getProperties(), ((BaseAuthzGroup) edit).getKey()); } protected void save_REALM_RL_FN(AuthzGroup azg) { // add what we have in the azg, unless we see it in the db final Set<RoleAndFunction> toAdd = new HashSet<RoleAndFunction>(); for (Iterator iRoles = ((BaseAuthzGroup) azg).m_roles.values().iterator(); iRoles.hasNext();) { Role role = (Role) iRoles.next(); for (Iterator iFunctions = role.getAllowedFunctions().iterator(); iFunctions.hasNext();) { String function = (String) iFunctions.next(); toAdd.add(new RoleAndFunction(role.getId(), function)); } } // delete anything we see in the db we don't have in the azg final Set<RoleAndFunction> toDelete = new HashSet<RoleAndFunction>(); // read what we have there now String sql = dbAuthzGroupSql.getSelectRealmFunction2Sql(); Object fields[] = new Object[1]; fields[0] = caseId(azg.getId()); m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String role = result.getString(1); String function = result.getString(2); RoleAndFunction raf = new RoleAndFunction(role, function); // if we have it in the set toAdd, we can remove it (it's alredy on the db) if (toAdd.contains(raf)) { toAdd.remove(raf); } // if we don't have it in the azg, we need to delete it else { toDelete.add(raf); } } catch (Exception e) { M_log.warn("save_REALM_RL_FN: " + e.toString()); } return null; } }); fields = new Object[3]; fields[0] = caseId(azg.getId()); // delete what we need to sql = dbAuthzGroupSql.getDeleteRealmRoleFunction1Sql(); for (RoleAndFunction raf : toDelete) { fields[1] = raf.role; fields[2] = raf.function; m_sql.dbWrite(sql, fields); } // add what we need to sql = dbAuthzGroupSql.getInsertRealmRoleFunctionSql(); fields[0] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleFunction1Sql(), fields[0]); for (RoleAndFunction raf : toAdd) { fields[1] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleFunction2Sql(), raf.role); fields[2] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleFunction3Sql(), raf.function); m_sql.dbWrite(sql, fields); } } protected void save_REALM_RL_GR(AuthzGroup azg) { // add what we have in the azg, unless we see it in the db final Set<UserAndRole> toAdd = new HashSet<UserAndRole>(); for (Iterator i = ((BaseAuthzGroup) azg).m_userGrants.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); Member grant = (Member) entry.getValue(); toAdd.add(new UserAndRole(grant.getUserId(), grant.getRole().getId(), grant.isActive(), grant.isProvided())); } // delete anything we see in the db we don't have in the azg final Set<UserAndRole> toDelete = new HashSet<UserAndRole>(); // read what we have there now String sql = dbAuthzGroupSql.getSelectRealmRoleGroup2Sql(); Object fields[] = new Object[1]; fields[0] = caseId(azg.getId()); m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String userId = result.getString(1); String role = result.getString(2); boolean active = "1".equals(result.getString(3)); boolean provided = "1".equals(result.getString(4)); UserAndRole uar = new UserAndRole(userId, role, active, provided); // if we have it in the set toAdd, we can remove it (it's alredy on the db) if (toAdd.contains(uar)) { toAdd.remove(uar); } // if we don't have it in the azg, we need to delete it else { toDelete.add(uar); } } catch (Exception e) { M_log.warn("save_REALM_RL_GR: " + e.toString()); } return null; } }); fields = new Object[5]; fields[0] = caseId(azg.getId()); // delete what we need to sql = dbAuthzGroupSql.getDeleteRealmRoleGroup1Sql(); for (UserAndRole uar : toDelete) { fields[1] = uar.role; fields[2] = uar.userId; fields[3] = uar.active ? "1" : "0"; fields[4] = uar.provided ? "1" : "0"; m_sql.dbWrite(sql, fields); } // add what we need to sql = dbAuthzGroupSql.getInsertRealmRoleGroup1Sql(); fields[0] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleGroup1_1Sql(), fields[0]); for (UserAndRole uar : toAdd) { fields[1] = uar.userId; fields[2] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleGroup1_2Sql(), uar.role); fields[3] = uar.active ? "1" : "0"; fields[4] = uar.provided ? "1" : "0"; m_sql.dbWrite(sql, fields); } } protected void save_REALM_PROVIDER(AuthzGroup azg) { // we we are not provider, delete any for this realm if ((azg.getProviderGroupId() == null) || (m_provider == null)) { String sql = dbAuthzGroupSql.getDeleteRealmProvider1Sql(); Object[] fields = new Object[1]; fields[0] = caseId(azg.getId()); m_sql.dbWrite(sql, fields); return; } // add what we have in the azg, unless we see it in the db final Set<String> toAdd = new HashSet<String>(); String[] ids = m_provider.unpackId(azg.getProviderGroupId()); if (ids != null) { for (String id : ids) { toAdd.add(id); } } // delete anything we see in the db we don't have in the azg final Set<String> toDelete = new HashSet<String>(); // read what we have there now String sql = dbAuthzGroupSql.getSelectRealmProviderId2Sql(); Object fields[] = new Object[1]; fields[0] = caseId(azg.getId()); m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String provider = result.getString(1); // if we have it in the set toAdd, we can remove it (it's alredy on the db) if (toAdd.contains(provider)) { toAdd.remove(provider); } // if we don't have it in the azg, we need to delete it else { toDelete.add(provider); } } catch (Exception e) { M_log.warn("save_REALM_PROVIDER: " + e.toString()); } return null; } }); fields = new Object[2]; fields[0] = caseId(azg.getId()); // delete what we need to sql = dbAuthzGroupSql.getDeleteRealmProvider2Sql(); for (String provider : toDelete) { fields[1] = provider; m_sql.dbWrite(sql, fields); } // add what we need to sql = dbAuthzGroupSql.getInsertRealmProviderSql(); for (String provider : toAdd) { fields[1] = provider; m_sql.dbWrite(sql, fields); } } protected void save_REALM_ROLE_DESC(AuthzGroup azg) { // add what we have in the azg, unless we see it in the db final Set<RoleAndDescription> toAdd = new HashSet<RoleAndDescription>(); for (Iterator iRoles = ((BaseAuthzGroup) azg).m_roles.values().iterator(); iRoles.hasNext();) { Role role = (Role) iRoles.next(); toAdd.add(new RoleAndDescription(role.getId(), role.getDescription(), role.isProviderOnly())); } // delete anything we see in the db we don't have in the azg final Set<RoleAndDescription> toDelete = new HashSet<RoleAndDescription>(); // read what we have there now String sql = dbAuthzGroupSql.getSelectRealmProvider2Sql(); Object fields[] = new Object[1]; fields[0] = caseId(azg.getId()); m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String role = result.getString(1); String description = result.getString(2); boolean providerOnly = "1".equals(result.getString(3)); RoleAndDescription rad = new RoleAndDescription(role, description, providerOnly); // if we have it in the set toAdd, we can remove it (it's alredy on the db) if (toAdd.contains(rad)) { toAdd.remove(rad); } // if we don't have it in the azg, we need to delete it else { toDelete.add(rad); } } catch (Exception e) { M_log.warn("save_REALM_ROLE_DESC: " + e.toString()); } return null; } }); fields = new Object[2]; fields[0] = caseId(azg.getId()); // delete what we need to sql = dbAuthzGroupSql.getDeleteRealmRoleDescription1Sql(); for (RoleAndDescription rad : toDelete) { fields[1] = rad.role; m_sql.dbWrite(sql, fields); } fields = new Object[4]; fields[0] = caseId(azg.getId()); // add what we need to sql = dbAuthzGroupSql.getInsertRealmRoleDescriptionSql(); fields[0] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleDescription1Sql(), fields[0]); for (RoleAndDescription rad : toAdd) { fields[1] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleDescription2Sql(), rad.role); fields[2] = rad.description; fields[3] = rad.providerOnly ? "1" : "0"; m_sql.dbWrite(sql, fields); } } public void cancel(AuthzGroup edit) { super.cancelResource(edit); } public void remove(final AuthzGroup edit) { // in a transaction m_sql.transact(new Runnable() { public void run() { removeTx(edit); } }, "azgRemove:" + edit.getId()); } /** * Transaction code for removing the azg. */ protected void removeTx(AuthzGroup edit) { // delete all the role functions, auth grants, anon grants, role grants, fucntion grants // and then the realm and release the lock. // delete the role functions, role grants, provider entries Object fields[] = new Object[1]; fields[0] = caseId(edit.getId()); String statement = dbAuthzGroupSql.getDeleteRealmRoleFunction2Sql(); m_sql.dbWrite(statement, fields); statement = dbAuthzGroupSql.getDeleteRealmRoleGroup2Sql(); m_sql.dbWrite(statement, fields); statement = dbAuthzGroupSql.getDeleteRealmProvider1Sql(); m_sql.dbWrite(statement, fields); statement = dbAuthzGroupSql.getDeleteRealmRoleDescription2Sql(); m_sql.dbWrite(statement, fields); // delete the realm and properties super.removeResource(edit, ((BaseAuthzGroup) edit).getKey()); } /** * Get the fields for the database from the edit for this id, and the id again at the end if needed * * @param id * The resource id * @param edit * The edit (may be null in a new) * @param idAgain * If true, include the id field again at the end, else don't. * @return The fields for the database. */ protected Object[] fields(String id, BaseAuthzGroup edit, boolean idAgain) { Object[] rv = new Object[idAgain ? 8 : 7]; rv[0] = caseId(id); if (idAgain) { rv[7] = rv[0]; } if (edit == null) { String current = sessionManager().getCurrentSessionUserId(); // if no current user, since we are working up a new user record, use the user id as creator... if (current == null) current = ""; Time now = timeService().newTime(); rv[1] = ""; rv[2] = ""; rv[3] = current; rv[4] = current; rv[5] = now; rv[6] = now; } else { rv[1] = StringUtil.trimToZero(edit.m_providerRealmId); rv[2] = StringUtil.trimToZero(edit.m_maintainRole); rv[3] = StringUtil.trimToZero(edit.m_createdUserId); rv[4] = StringUtil.trimToZero(edit.m_lastModifiedUserId); rv[5] = edit.getCreatedTime(); rv[6] = edit.getModifiedTime(); } return rv; } /** * Read from the result one set of fields to create a Resource. * * @param result * The Sql query result. * @return The Resource object. */ public Object readSqlResultRecord(ResultSet result) { try { String id = result.getString(1); String providerId = result.getString(2); String maintainRole = result.getString(3); String createdBy = result.getString(4); String modifiedBy = result.getString(5); java.sql.Timestamp ts = result.getTimestamp(6, sqlService().getCal()); Time createdOn = null; if (ts != null) { createdOn = timeService().newTime(ts.getTime()); } ts = result.getTimestamp(7, sqlService().getCal()); Time modifiedOn = null; if (ts != null) { modifiedOn = timeService().newTime(ts.getTime()); } // the special local integer 'db' id field, read after the field list Integer dbid = Integer.valueOf(result.getInt(8)); // create the Resource from these fields return new BaseAuthzGroup(DbAuthzGroupService.this,dbid, id, providerId, maintainRole, createdBy, createdOn, modifiedBy, modifiedOn); } catch (SQLException e) { M_log.warn("readSqlResultRecord: " + e); return null; } } /** * {@inheritDoc} */ public boolean isAllowed(String userId, String lock, String realmId) { if ((lock == null) || (realmId == null)) return false; // does the user have any roles granted that include this lock, based on grants or anon/auth? boolean auth = (userId != null) && (!userDirectoryService().getAnonymousUser().getId().equals(userId)); if (M_log.isDebugEnabled()) M_log.debug("isAllowed: auth=" + auth + " userId=" + userId + " lock=" + lock + " realm=" + realmId); String statement = dbAuthzGroupSql.getCountRealmRoleFunctionSql(getRealmRoleKey(ANON_ROLE), getRealmRoleKey(AUTH_ROLE), auth); Object[] fields = new Object[3]; fields[0] = userId; fields[1] = lock; fields[2] = realmId; // checks to see if the user is the current user and has the roleswap variable set in the session String roleswap = securityService().getUserEffectiveRole(realmId); if (roleswap != null && auth && userId.equals(sessionManager().getCurrentSessionUserId())) { fields[0] = roleswap; // set the field to the student role for the alternate sql statement = dbAuthzGroupSql.getCountRoleFunctionSql(); // set the function for our alternate sql } List resultsNew = m_sql.dbRead(statement, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int count = result.getInt(1); return Integer.valueOf(count); } catch (SQLException ignore) { return null; } } }); boolean rvNew = false; int countNew = -1; if (!resultsNew.isEmpty()) { countNew = ((Integer) resultsNew.get(0)).intValue(); rvNew = countNew > 0; } return rvNew; } /** * {@inheritDoc} */ public boolean isAllowed(String userId, String lock, Collection<String> realms) { if (lock == null) return false; boolean auth = (userId != null) && (!userDirectoryService().getAnonymousUser().getId().equals(userId)); if (realms == null || realms.size() < 1) { M_log.warn("isAllowed(): called with no realms: lock: " + lock + " user: " + userId); if (M_log.isDebugEnabled()) M_log.debug("isAllowed():", new Exception()); return false; } if (M_log.isDebugEnabled()) M_log.debug("isAllowed: auth=" + auth + " userId=" + userId + " lock=" + lock + " realms=" + realms); String inClause = orInClause(realms.size(), "SAKAI_REALM.REALM_ID"); // any of the grant or role realms String statement = dbAuthzGroupSql.getCountRealmRoleFunctionSql(getRealmRoleKey(ANON_ROLE), getRealmRoleKey(AUTH_ROLE), auth, inClause); Object[] fields = new Object[2 + (2 * realms.size())]; int pos = 0; // for roleswap String userSiteRef = null; String siteRef = null; // oracle query has different order of parameters String dbAuthzGroupSqlClassName=dbAuthzGroupSql.getClass().getName(); if(dbAuthzGroupSqlClassName.equals("org.sakaiproject.authz.impl.DbAuthzGroupSqlOracle")) { fields[pos++] = userId; } // populate values for fields for (String realmId : realms) { // These checks for roleswap assume there is at most one of each type of site in the realms collection, // i.e. one ordinary site and one user site if (realmId.startsWith(SiteService.REFERENCE_ROOT + Entity.SEPARATOR)) // Starts with /site/ { if (userId != null && userId.equals(siteService.getSiteUserId(realmId))) { userSiteRef = realmId; } else { siteRef = realmId; // set this variable for potential use later } } fields[pos++] = realmId; } fields[pos++] = lock; if(!dbAuthzGroupSqlClassName.equals("org.sakaiproject.authz.impl.DbAuthzGroupSqlOracle")) { fields[pos++] = userId; } for (String realmId : realms) { fields[pos++] = realmId; } /* Delegated access essentially behaves like roleswap except instead of just specifying which role, you can also specify * the realm as well. The access map is populated by an Event Listener that listens for dac.checkaccess and is stored in the session * attribute: delegatedaccess.accessmap. This is a map of: SiteRef -> String[]{realmId, roleId}. Delegated access * will defer to roleswap if it's set. */ String[] delegatedAccessGroupAndRole = getDelegatedAccessRealmRole(siteRef); boolean delegatedAccess = delegatedAccessGroupAndRole != null && delegatedAccessGroupAndRole.length == 2; // Would be better to get this initially to make the code more efficient, but the realms collection // does not have a common order for the site's id which is needed to determine if the session variable exists // ZQIAN: since the role swap is only done at the site level, for group reference, use its parent site reference instead. String roleswap = null; Reference ref = entityManager().newReference(siteRef); if (SiteService.GROUP_SUBTYPE.equals(ref.getSubType())) { String containerSiteRef = siteService.siteReference(ref.getContainer()); roleswap = securityService().getUserEffectiveRole(containerSiteRef); if (roleswap != null) { siteRef = containerSiteRef; } } else { roleswap = securityService().getUserEffectiveRole(siteRef); } List results = null; // Only check roleswap if the method is being called for the current user if ( (roleswap != null || delegatedAccess) && userId != null && userId.equals(sessionManager().getCurrentSessionUserId()) ) { // First check in the user's own my workspace site realm if it's in the list // We don't want to change the user's role in their own site, so call the regular function. // This catches permission checks for entity references such as user dropboxes. if (userSiteRef != null && isAllowed(userId, lock, userSiteRef)) return true; // Then check the site where there's a roleswap effective if (M_log.isDebugEnabled()) M_log.debug("userId="+userId+", siteRef="+siteRef+", roleswap="+roleswap+", delegatedAccess="+delegatedAccess); Object[] fields2 = new Object[3]; if (roleswap != null) { fields2[0] = roleswap; } else if (delegatedAccess && delegatedAccessGroupAndRole != null ) { // set the role for delegated access fields2[0] = delegatedAccessGroupAndRole[1]; } fields2[1] = lock; if (roleswap == null && delegatedAccess && delegatedAccessGroupAndRole != null ) { // set the realm for delegated access fields2[2] = delegatedAccessGroupAndRole[0]; } else { fields2[2] = siteRef; } if (M_log.isDebugEnabled()) M_log.debug("roleswap/dac fields: "+Arrays.toString(fields2)); statement = dbAuthzGroupSql.getCountRoleFunctionSql(); results = m_sql.dbRead(statement, fields2, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int count = result.getInt(1); return Integer.valueOf(count); } catch (SQLException ignore) { return null; } } }); boolean rv = false; int count = -1; if (!results.isEmpty()) { count = ((Integer) results.get(0)).intValue(); rv = count > 0; } if (rv) // if true, go ahead and return return true; // Then check the rest of the realms. For example these could be subfolders under /content/group/... if(roleswap != null){ for (String realmId : realms) { if (realmId == siteRef || realmId == userSiteRef) // we've already checked these so no need to do it again continue; fields2[2] = realmId; results = m_sql.dbRead(statement, fields2, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int count = result.getInt(1); return Integer.valueOf(count); } catch (SQLException ignore) { return null; } } }); count = -1; if (!results.isEmpty()) { count = ((Integer) results.get(0)).intValue(); rv = count > 0; } if (rv) // if true, go ahead and return return true; } } // No successful results for roleswap return false; } // Regular lookup (not roleswap) results = m_sql.dbRead(statement, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int count = result.getInt(1); return Integer.valueOf(count); } catch (SQLException ignore) { return null; } } }); boolean rv = false; int count = -1; if (!results.isEmpty()) { count = ((Integer) results.get(0)).intValue(); rv = count > 0; } return rv; } /** * Delegated access essentially behaves like roleswap except instead of just specifying which role, you can also specify * the realm as well. The access map is populated by an Event Listener that listens for dac.checkaccess and is stored in the session * attribute: delegatedaccess.accessmap. This is a map of: SiteRef -> String[]{realmId, roleId}. * Delegated access will defer to roleswap if it is set. * * @param siteRef the site realm id * @return String[]{realmId, roleId} or null if delegated access is disabled */ private String[] getDelegatedAccessRealmRole(String siteRef){ if (M_log.isDebugEnabled()) M_log.debug("getDelegatedAccessRealmRole(siteRef="+siteRef+")"); String[] delegatedAccessGroupAndRole = null; // first we get the map out of the session (if it exists and is safe) Map<?,?> delegatedAccessMap = null; if (sessionManager().getCurrentSession().getAttribute("delegatedaccess.accessmapflag") != null) { // only check for the map if the accessmapflag is set Object delegatedAccessMapObj = sessionManager().getCurrentSession().getAttribute("delegatedaccess.accessmap"); if (delegatedAccessMapObj != null && delegatedAccessMapObj instanceof Map) { // only read the map value out if it is set and is an actual map delegatedAccessMap = (Map<?,?>) delegatedAccessMapObj; } //if the siteRef doesn't exist in the map, then that means that we haven't checked delegatedaccess for this user and site. //if the user doesn't have access, the map will have a null value for that siteRef. if (siteRef != null && (delegatedAccessMap == null || !delegatedAccessMap.containsKey(siteRef))){ /* the delegatedaccess.accessmapflag is set during login and is only set for user's who have some kind of delegated access * if the user has access somewhere but either the map is null or there isn't any record for this site, then that means * this site hasn't been checked yet. By posting an event, a DelegatedAccess observer will check this site's access for this user * and store it in the user's session */ eventTrackingService().post(eventTrackingService().newEvent("dac.checkaccess", siteRef, false, NotificationService.NOTI_REQUIRED)); //grab the session after the checkaccess event since the checkaccess event could have modified it delegatedAccessMapObj = sessionManager().getCurrentSession().getAttribute("delegatedaccess.accessmap"); if (delegatedAccessMapObj != null && delegatedAccessMapObj instanceof Map) { // only read the map value out if it is set and is an actual map delegatedAccessMap = (Map<?,?>) delegatedAccessMapObj; } } if (siteRef != null && delegatedAccessMap != null && delegatedAccessMap.containsKey(siteRef) && delegatedAccessMap.get(siteRef) instanceof String[]) { if (M_log.isDebugEnabled()) M_log.debug("siteRef="+siteRef+", delegatedAccessMap="+delegatedAccessMap); delegatedAccessGroupAndRole = (String[]) delegatedAccessMap.get(siteRef); if (M_log.isInfoEnabled()) { String dacgarStr = ""; if (delegatedAccessGroupAndRole != null && delegatedAccessGroupAndRole.length > 1) { dacgarStr = ", GroupAndRole["+delegatedAccessGroupAndRole[0]+", "+delegatedAccessGroupAndRole[1]+"]"; } M_log.info("delegatedAccessCheck: userId="+sessionManager().getCurrentSessionUserId()+", siteRef="+siteRef+", delegatedAccess="+dacgarStr); } } } if (M_log.isDebugEnabled()) M_log.debug("getDelegatedAccessRealmRole(siteRef="+siteRef+"): "+Arrays.toString(delegatedAccessGroupAndRole)); return delegatedAccessGroupAndRole; } /** * {@inheritDoc} */ public Set getUsersIsAllowed(String lock, Collection realms) { if ((lock == null) || (realms == null) || (realms.isEmpty())) return new HashSet(); String sql = dbAuthzGroupSql.getSelectRealmRoleGroupUserIdSql(orInClause(realms.size(), "SR.REALM_ID"), orInClause(realms.size(), "SR1.REALM_ID")); Object[] fields = new Object[1 + (2 * realms.size())]; int pos = 0; for (Iterator i = realms.iterator(); i.hasNext();) { String roleRealm = (String) i.next(); fields[pos++] = roleRealm; } fields[pos++] = lock; for (Iterator i = realms.iterator(); i.hasNext();) { String roleRealm = (String) i.next(); fields[pos++] = roleRealm; } // read the strings List results = m_sql.dbRead(sql, fields, null); // prepare the return Set rv = new HashSet(); rv.addAll(results); return rv; } /** * {@inheritDoc} */ public Set<String[]> getUsersIsAllowedByGroup(String lock, Collection<String> realms) { final Set<String[]> usersByGroup = new HashSet<String[]>(); if ((lock == null) || (realms != null && realms.isEmpty())) return usersByGroup; String sql; Object[] fields; if (realms != null) { sql = dbAuthzGroupSql.getSelectRealmRoleGroupUserIdSql(orInClause(realms.size(), "REALM_ID")); fields = new Object[realms.size() + 1]; int pos = 0; fields[pos++] = lock; for (Iterator i = realms.iterator(); i.hasNext();) { String roleRealm = (String) i.next(); fields[pos++] = roleRealm; } } else { sql = dbAuthzGroupSql.getSelectRealmRoleGroupUserIdSql("true"); fields = new Object[1]; fields[0] = lock; } // read the strings m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String[] useringroup = new String[2]; useringroup[0] = result.getString(1); useringroup[1] = result.getString(2); usersByGroup.add( useringroup ); } catch (SQLException ignore) { } return null; } }); return usersByGroup; } /** * {@inheritDoc} */ public Map<String,Integer> getUserCountIsAllowed(String function, Collection<String> azGroups) { final Map<String, Integer> userCountByGroup = new HashMap<String, Integer>(); if ((function == null) || (azGroups != null && azGroups.isEmpty())) return userCountByGroup; String sql; Object[] fields; if (azGroups != null) { sql = dbAuthzGroupSql.getSelectRealmRoleGroupUserCountSql(orInClause(azGroups.size(), "REALM_ID")); fields = new Object[azGroups.size() + 1]; int pos = 0; fields[pos++] = function; for (Iterator i = azGroups.iterator(); i.hasNext();) { String roleRealm = (String) i.next(); fields[pos++] = roleRealm; } } else { sql = dbAuthzGroupSql.getSelectRealmRoleGroupUserCountSql("true"); fields = new Object[1]; fields[0] = function; } // read the realm size counts m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String realm = result.getString(1); Integer size = result.getInt(2); userCountByGroup.put(realm, size); } catch (SQLException ignore) { } return null; } }); return userCountByGroup; } /** * {@inheritDoc} */ public Set getAllowedFunctions(String role, Collection realms) { if ((role == null) || (realms == null) || (realms.isEmpty())) return new HashSet(); String sql = dbAuthzGroupSql.getSelectRealmFunctionFunctionNameSql(orInClause(realms.size(), "SR.REALM_ID")); Object[] fields = new Object[1 + realms.size()]; fields[0] = role; int pos = 1; for (Iterator i = realms.iterator(); i.hasNext();) { String roleRealm = (String) i.next(); fields[pos++] = roleRealm; } // read the strings List results = m_sql.dbRead(sql, fields, null); // prepare the return Set rv = new HashSet(); rv.addAll(results); return rv; } /** * {@inheritDoc} */ public void refreshUser(String userId, Map providerGrants) { if (userId == null) return; String sql = dbAuthzGroupSql.getSelectRealmRoleGroup3Sql(); // read this user's grants from all realms Object[] fields = new Object[1]; fields[0] = userId; List<RealmAndRole> grants = m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int realmKey = result.getInt(1); String roleName = result.getString(2); String active = result.getString(3); String provided = result.getString(4); return new RealmAndRole(Integer.valueOf(realmKey), roleName, "1".equals(active), "1".equals(provided)); } catch (Exception ignore) { return null; } } }); // make a map, realm id -> role granted, each for provider and non-provider (or inactive) Map<Integer, String> existing = new HashMap<Integer, String>(); Map<Integer, String> providedInactive = new HashMap<Integer, String>(); Map<Integer, String> nonProvider = new HashMap<Integer, String>(); for (RealmAndRole rar : grants) { // active and provided are the currently stored provider grants if (rar.provided) { if (existing.containsKey(rar.realmId)) { M_log.warn("refreshUser: duplicate realm id found in provider grants: " + rar.realmId); } else { existing.put(rar.realmId, rar.role); // Record inactive status if (!rar.active) { providedInactive.put(rar.realmId, rar.role); } } } // inactive or not provided are the currently stored internal grants - not to be overwritten by provider info else { if (nonProvider.containsKey(rar.realmId)) { M_log.warn("refreshUser: duplicate realm id found in nonProvider grants: " + rar.realmId); } else { nonProvider.put(rar.realmId, rar.role); } } } // compute the user's realm roles based on the new provider information // same map form as existing, realm id -> role granted Map<Integer, String> target = new HashMap<Integer, String>(); // for each realm that has a provider in the map, and does not have a grant for the user, // add the active provided grant with the map's role. if ((providerGrants != null) && (providerGrants.size() > 0)) { // get all the realms that have providers in the map, with their full provider id // Assemble SQL. Note: distinct must be used because one cannot establish an equijoin between // SRP.PROVIDER_ID and SR.PROVIDER_ID as the values in SRP.PROVIDER_ID often include // additional concatenated course values. It may be worth reviewing this strategy. sql = dbAuthzGroupSql.getSelectRealmProviderSql(orInClause(providerGrants.size(), "SRP.PROVIDER_ID")); Object[] fieldsx = new Object[providerGrants.size()]; int pos = 0; for (Iterator f = providerGrants.keySet().iterator(); f.hasNext();) { String providerId = (String) f.next(); fieldsx[pos++] = providerId; } List<RealmAndProvider> realms = m_sql.dbRead(sql, fieldsx, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { int id = result.getInt(1); String provider = result.getString(2); return new RealmAndProvider(Integer.valueOf(id), provider); } catch (Exception ignore) { return null; } } }); if ((realms != null) && (realms.size() > 0)) { for (RealmAndProvider rp : realms) { String role = (String) providerGrants.get(rp.providerId); if (role != null) { if (target.containsKey(rp.realmId)) { M_log.warn("refreshUser: duplicate realm id computed for new grants: " + rp.realmId); } else { target.put(rp.realmId, role); } } } } } // compute the records we need to delete: every existing not in target or not matching target's role List<Integer> toDelete = new Vector<Integer>(); for (Map.Entry<Integer, String> entry : existing.entrySet()) { Integer realmId = (Integer) entry.getKey(); String role = (String) entry.getValue(); String targetRole = (String) target.get(realmId); if ((targetRole == null) || (!targetRole.equals(role))) { toDelete.add(realmId); } } // compute the records we need to add: every target not in existing, or not matching's existing's role // we don't insert target grants that would override internal grants List<RealmAndRole> toInsert = new Vector<RealmAndRole>(); for (Map.Entry<Integer, String> entry : target.entrySet()) { Integer realmId = entry.getKey(); String role = entry.getValue(); String existingRole = (String) existing.get(realmId); String nonProviderRole = (String) nonProvider.get(realmId); if ((nonProviderRole == null) && ((existingRole == null) || (!existingRole.equals(role)))) { boolean active = true; if (providedInactive.get(realmId) != null) { active = false; } toInsert.add(new RealmAndRole(realmId, role, active, true)); } } // if any, do it if ((toDelete.size() > 0) || (toInsert.size() > 0)) { // do these each in their own transaction, to avoid possible deadlock // caused by transactions modifying more than one row at a time. // delete sql = dbAuthzGroupSql.getDeleteRealmRoleGroup3Sql(); fields = new Object[2]; fields[1] = userId; for (Integer realmId : toDelete) { fields[0] = realmId; m_sql.dbWrite(sql, fields); } // insert sql = dbAuthzGroupSql.getInsertRealmRoleGroup2Sql(); fields = new Object[3]; fields[1] = userId; for (RealmAndRole rar : toInsert) { fields[0] = rar.realmId; fields[2] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleGroup2_1Sql(), rar.role); m_sql.dbWrite(sql, fields); } } } /** * {@inheritDoc} */ public void refreshAuthzGroup(BaseAuthzGroup realm) { M_log.debug("refreshAuthzGroup()"); if ((realm == null) || (m_provider == null)) return; boolean synchWithContainingRealm = serverConfigurationService().getBoolean("authz.synchWithContainingRealm", true); // check to see whether this is of group realm or not // if of Group Realm, get the containing Site Realm String containingRealmId = null; AuthzGroup containingRealm = null; Reference ref = entityManager.newReference(realm.getId()); if (SiteService.APPLICATION_ID.equals(ref.getType()) && SiteService.GROUP_SUBTYPE.equals(ref.getSubType())) { containingRealmId = ref.getContainer(); } if (containingRealmId != null) { String containingRealmRef = siteService.siteReference(containingRealmId); try { containingRealm = getAuthzGroup(containingRealmRef); } catch (GroupNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find containing realm for id: " + containingRealmRef); } } String sql = ""; // Note: the realm is still lazy - we have the realm id but don't need to worry about changing grants // get the latest userEid -> role name map from the provider Map<String,String> target = m_provider.getUserRolesForGroup(realm.getProviderGroupId()); // read the realm's grants sql = dbAuthzGroupSql.getSelectRealmRoleGroup4Sql(); Object[] fields = new Object[1]; fields[0] = caseId(realm.getId()); List<UserAndRole> grants = getGrants(realm); // make a map, user id -> role granted, each for provider and non-provider (or inactive) Map<String, String> existing = new HashMap<String, String>(); Map<String, String> providedInactive = new HashMap<String, String>(); Map<String, String> nonProvider = new HashMap<String, String>(); for (UserAndRole uar : grants) { // active and provided are the currently stored provider grants if (uar.provided) { if (existing.containsKey(uar.userId)) { M_log.warn("refreshRealm: duplicate user id found in provider grants: " + uar.userId); } else { existing.put(uar.userId, uar.role); // Record inactive status if (!uar.active) { providedInactive.put(uar.userId, uar.role); } } } // inactive or not provided are the currently stored internal grants - not to be overwritten by provider info else { if (nonProvider.containsKey(uar.userId)) { M_log.warn("refreshRealm: duplicate user id found in nonProvider grants: " + uar.userId); } else { nonProvider.put(uar.userId, uar.role); } } } // compute the records we need to delete: every existing not in target or not matching target's role List<String> toDelete = new Vector<String>(); for (Map.Entry<String,String> entry : existing.entrySet()) { String userId = entry.getKey(); String role = entry.getValue(); try { String userEid = userDirectoryService().getUserEid(userId); String targetRole = (String) target.get(userEid); if ((targetRole == null) || (!targetRole.equals(role))) { toDelete.add(userId); } } catch (UserNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find eid for user: " + userId); } } // compute the records we need to add: every target not in existing, or not matching's existing's role // we don't insert target grants that would override internal grants List<UserAndRole> toInsert = new Vector<UserAndRole>(); for (Map.Entry<String,String> entry : target.entrySet()) { String userEid = entry.getKey(); try { String userId = userDirectoryService().getUserId(userEid); String role = entry.getValue(); boolean active = true; String existingRole = (String) existing.get(userId); String nonProviderRole = (String) nonProvider.get(userId); if (!synchWithContainingRealm) { if ((nonProviderRole == null) && ((existingRole == null) || (!existingRole.equals(role)))) { // Check whether this user was inactive in the site previously, if so preserve status if (providedInactive.get(userId) != null) { active = false; } // this is either at site level or at the group level but no need to synchronize toInsert.add(new UserAndRole(userId, role, active, true)); } } else { if (containingRealm != null) { Member cMember = containingRealm.getMember(userId); if (cMember != null) { String cMemberRoleId = cMember.getRole() != null ? cMember.getRole().getId() : null; boolean cMemberActive = cMember.isActive(); // synchronize with parent realm role definition and active status toInsert.add(new UserAndRole(userId, cMemberRoleId, cMemberActive, cMember.isProvided())); if ((existingRole != null && !existingRole.equals(cMemberRoleId)) // overriding existing authz group role ||!role.equals(cMemberRoleId)) // overriding provided role { M_log.info("refreshAuthzGroup: realm id=" + realm.getId() + ", overrides group role of user eid=" + userEid + ": provided role=" + role + ", with site-level role=" + cMemberRoleId + " and site-level active status=" + cMemberActive); } } else { // user not defined in parent realm toInsert.add(new UserAndRole(userId, role, active, true)); } } else { // this is either at site level toInsert.add(new UserAndRole(userId, role, active, true)); } } } catch (UserNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find id for user eid: " + userEid); } } if (promoteUsersToProvided) { // compute the records we want to promote from non-provided to provider: // every non-provided user with an equivalent provided entry with the same role for (Map.Entry<String,String> entry : nonProvider.entrySet()) { String userId = entry.getKey(); String role = entry.getValue(); try { String userEid = userDirectoryService().getUserEid(userId); String targetRole = (String) target.get(userEid); if (role.equals(targetRole)) { // remove from non-provided and add as provided toDelete.add(userId); // Check whether this user was inactive in the site previously, if so preserve status boolean active = true; if (providedInactive.get(userId) != null) { active = false; } toInsert.add(new UserAndRole(userId, role, active, true)); } } catch (UserNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find eid for user: " + userId); } } } // if any, do it if ((toDelete.size() > 0) || (toInsert.size() > 0)) { // do these each in their own transaction, to avoid possible deadlock // caused by transactions modifying more than one row at a time. // delete sql = dbAuthzGroupSql.getDeleteRealmRoleGroup4Sql(); fields = new Object[2]; fields[0] = caseId(realm.getId()); for (String userId : toDelete) { fields[1] = userId; m_sql.dbWrite(sql, fields); } // insert sql = dbAuthzGroupSql.getInsertRealmRoleGroup3Sql(); fields = new Object[5]; fields[0] = caseId(realm.getId()); fields[0] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleGroup3_1Sql(), fields[0]); for (UserAndRole uar : toInsert) { fields[1] = uar.userId; fields[2] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleGroup3_2Sql(), uar.role); - fields[3] = uar.active; - fields[4] = uar.provided; + fields[3] = uar.active ? "1" : "0"; // KNL-1099 + fields[4] = uar.provided ? "1" : "0"; // KNL-1099 m_sql.dbWrite(sql, fields); } } if (M_log.isDebugEnabled()) { M_log.debug("refreshAuthzGroup(): deleted: "+ toDelete.size()+ " inserted: "+ toInsert.size()+ " provided: "+ existing.size()+ " nonProvider: "+ nonProvider.size()); } } private List<UserAndRole> getGrants(AuthzGroup realm) { // read the realm's grants String sql = dbAuthzGroupSql.getSelectRealmRoleGroup4Sql(); Object[] fields = new Object[1]; fields[0] = caseId(realm.getId()); List<UserAndRole> grants = m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String userId = result.getString(1); String roleName = result.getString(2); String active = result.getString(3); String provided = result.getString(4); return new UserAndRole(userId, roleName, "1".equals(active), "1".equals(provided)); } catch (Exception ignore) { return null; } } }); return grants; } private class UserAndGroups { String user; long total; long hit; Map<Long, List<String>> realmsQuery; public UserAndGroups(String userid) { this.user = userid; this.total = 0; this.hit = 0; this.realmsQuery = new HashMap<Long, List<String>>(); } void addRealmQuery(Set<String> query, List<String> result) { if (query == null || query.size() < 1) return; total++; Long queryHash = computeRealmQueryHash(query); if (queryHash != null) { if (result == null) result = Collections.emptyList(); realmsQuery.put(queryHash, result); } } List<String> getRealmQuery(Set<String> query) { if (query == null || query.size() < 1) return null; List<String> result = null; total++; Long queryHash = computeRealmQueryHash(query); if (queryHash != null) { if (realmsQuery.containsKey(queryHash)) { result = realmsQuery.get(queryHash); hit++; } } return result; } Long computeRealmQueryHash(Set<String> query) { if (query == null || query.size() == 0) return null; long hash = 0; for (String q : query) { hash += q.hashCode(); } return Long.valueOf(hash); } @Override public int hashCode() { return user.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() != obj.getClass()) return false; UserAndGroups other = (UserAndGroups) obj; if (user == null) { if (other.user != null) return false; } else if (!user.equals(other.user)) return false; return true; } @Override public String toString() { return "UserAndGroups [" + (user != null ? "user=" + user : "") + "]" + " size=" + realmsQuery.size() + ", total=" + total + ", hits=" + hit + ", hit ratio=" + (hit * 100) / (float) total; } } public class RealmAndProvider { public Integer realmId; public String providerId; public RealmAndProvider(Integer id, String provider) { this.realmId = id; this.providerId = provider; } } public class RealmAndRole { public Integer realmId; public String role; boolean active; boolean provided; public RealmAndRole(Integer id, String role, boolean active, boolean provided) { this.realmId = id; this.role = role; this.active = active; this.provided = provided; } public boolean equals(Object obj) { if (!(obj instanceof RealmAndRole)) return false; if (this == obj) return true; RealmAndRole other = (RealmAndRole) obj; if (StringUtil.different(this.role, other.role)) return false; if (this.provided != other.provided) return false; if (this.active != other.active) return false; if (((this.realmId == null) && (other.realmId != null)) || ((this.realmId != null) && (other.realmId == null)) || ((this.realmId != null) && (other.realmId != null) && (!this.realmId.equals(other.realmId)))) return false; return true; } public int hashCode() { return (this.role + Boolean.valueOf(this.provided).toString() + Boolean.valueOf(this.active).toString() + this.realmId).hashCode(); } } public class UserAndRole { public String userId; public String role; boolean active; boolean provided; public UserAndRole(String userId, String role, boolean active, boolean provided) { this.userId = userId; this.role = role; this.active = active; this.provided = provided; } public boolean equals(Object obj) { if (!(obj instanceof UserAndRole)) return false; if (this == obj) return true; UserAndRole other = (UserAndRole) obj; if (StringUtil.different(this.role, other.role)) return false; if (this.provided != other.provided) return false; if (this.active != other.active) return false; if (StringUtil.different(this.userId, other.userId)) return false; return true; } public int hashCode() { return (this.role + Boolean.valueOf(this.provided).toString() + Boolean.valueOf(this.active).toString() + this.userId).hashCode(); } } public class RoleAndFunction { public String role; public String function; public RoleAndFunction(String role, String function) { this.role = role; this.function = function; } public boolean equals(Object obj) { if (!(obj instanceof RoleAndFunction)) return false; if (this == obj) return true; RoleAndFunction other = (RoleAndFunction) obj; if (StringUtil.different(this.role, other.role)) return false; if (StringUtil.different(this.function, other.function)) return false; return true; } public int hashCode() { return (this.role + this.function).hashCode(); } } public class RoleAndDescription { public String role; public String description; public boolean providerOnly; public RoleAndDescription(String role, String description, boolean providerOnly) { this.role = role; this.description = description; this.providerOnly = providerOnly; } public boolean equals(Object obj) { if (!(obj instanceof RoleAndDescription)) return false; if (this == obj) return true; RoleAndDescription other = (RoleAndDescription) obj; if (StringUtil.different(this.role, other.role)) return false; if (StringUtil.different(this.description, other.description)) return false; if (this.providerOnly != other.providerOnly) return false; return true; } public int hashCode() { return (this.role + this.description + Boolean.valueOf(this.providerOnly).toString()).hashCode(); } } /** * {@inheritDoc} */ public String getUserRole(String userId, String azGroupId) { if ((userId == null) || (azGroupId == null)) return null; // checks to see if the user is the current user and has the roleswap variable set in the session String rv = null; if (userId.equals(sessionManager().getCurrentSessionUserId())) { rv = securityService().getUserEffectiveRole(azGroupId); } // otherwise drop through to the usual check if (rv == null) { String sql = dbAuthzGroupSql.getSelectRealmRoleNameSql(); Object[] fields = new Object[2]; fields[0] = azGroupId; fields[1] = userId; // read the string List results = m_sql.dbRead(sql, fields, null); // prepare the return if ((results != null) && (!results.isEmpty())) { rv = (String) results.get(0); if (results.size() > 1) { M_log.warn("getUserRole: user: " + userId + " multiple roles"); } } } return rv; } /** * {@inheritDoc} */ public Map<String, String> getUserRoles(String userId, Collection<String> azGroupIds) { final HashMap<String, String> rv = new HashMap<String, String>(); if (userId == null || "".equals(userId)) return rv; String inClause; int azgCount = azGroupIds == null ? 0 : azGroupIds.size(); if (azgCount == 0) { inClause = " 1=1 "; } else { inClause = orInClause(azgCount, "REALM_ID"); } String sql = dbAuthzGroupSql.getSelectRealmRolesSql(inClause); Object[] fields = new Object[1 + azgCount]; fields[0] = userId; if (azgCount > 0) { int pos = 1; for (String s : azGroupIds) { fields[pos++] = s; } } m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { String realmId = result.getString(1); String roleName = result.getString(2); // ignore if we get an unexpected null -- it's useless to us if ((realmId != null) && (roleName != null)) { rv.put(realmId, roleName); } } catch (Exception t) { M_log.warn("Serious database error occurred reading result set", t); } return null; } }); return rv; } /** * {@inheritDoc} */ public Map getUsersRole(Collection userIds, String azGroupId) { if ((userIds == null) || (userIds.isEmpty()) || (azGroupId == null)) { return new HashMap(); } String inClause = orInClause(userIds.size(), "SRRG.USER_ID"); String sql = dbAuthzGroupSql.getSelectRealmUserRoleSql(inClause); Object[] fields = new Object[1 + userIds.size()]; fields[0] = azGroupId; int pos = 1; for (Iterator i = userIds.iterator(); i.hasNext();) { fields[pos++] = i.next(); } // the return final Map rv = new HashMap(); // read m_sql.dbRead(sql, fields, new SqlReader() { public Object readSqlResultRecord(ResultSet result) { try { // read the results String userId = result.getString(1); String role = result.getString(2); if ((userId != null) && (role != null)) { rv.put(userId, role); } } catch (Exception t) { } return null; } }); return rv; } public Set<String> getMaintainRoles(){ Set<String> maintainRoles = null; if (maintainRolesCache != null && maintainRolesCache.containsKey("maintainRoles")) { maintainRoles = (Set<String>) maintainRolesCache.get("maintainRoles"); } else { String sql = dbAuthzGroupSql.getMaintainRolesSql(); maintainRoles = new HashSet<String>(m_sql.dbRead(sql)); maintainRolesCache.put("maintainRoles", maintainRoles); } return maintainRoles; } } // DbStorage /** To avoide the dreaded ORA-01795 and the like, we need to limit to <100 the items in each in(?, ?, ...) clause, connecting them with ORs. */ protected final static int MAX_IN_CLAUSE = 99; /** * Form a SQL IN() clause, but break it up with ORs to keep the size of each IN below 100 * * @param size * The size * @param field * The field name * @return a SQL IN() with ORs clause this large. */ protected String orInClause(int size, String field) { // Note: to avoide the dreaded ORA-01795 and the like, we need to limit to <100 the items in each in(?, ?, ...) clause, connecting them with // ORs -ggolden int ors = size / MAX_IN_CLAUSE; int leftover = size - (ors * MAX_IN_CLAUSE); StringBuilder buf = new StringBuilder(); // enclose them all in parens if we have > 1 if (ors > 0) { buf.append(" ("); } buf.append(" " + field + " IN "); // do all the full MAX_IN_CLAUSE '?' in/ors if (ors > 0) { for (int i = 0; i < ors; i++) { buf.append("(?"); for (int j = 1; j < MAX_IN_CLAUSE; j++) { buf.append(",?"); } buf.append(")"); if (i < ors - 1) { buf.append(" OR " + field + " IN "); } } } // add one more for the extra if (leftover > 0) { if (ors > 0) { buf.append(" OR " + field + " IN "); } buf.append("(?"); for (int i = 1; i < leftover; i++) { buf.append(",?"); } buf.append(")"); } // enclose them all in parens if we have > 1 if (ors > 0) { buf.append(" )"); } return buf.toString(); } /** * Get value for query & return that; needed for mssql which doesn't support select stmts in VALUES clauses * Note that MSSQL support was removed in KNL-880, so this is a no-op. * * @param sqlQuery * @param bindParameter * @return value if mssql, bindparameter if not (basically a no-op for others) */ protected Object getValueForSubquery(String sqlQuery, Object bindParameter) { return bindParameter; } private String getRealmRoleKey(String roleName) { Iterator<RealmRole> itr = m_roleNameCache.iterator(); while (itr.hasNext()) { RealmRole realmRole = (RealmRole) itr.next(); if (realmRole != null && realmRole.getName().equals(roleName)) { return realmRole.getKey(); } } return null; } class RealmRole implements Comparable<RealmRole>{ private String name; private String key; RealmRole(String name) { this.name = name; } RealmRole(String name, String key) { this.name = name; this.key = key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int compareTo(RealmRole realmRole) { return this.name.compareToIgnoreCase(realmRole.name); } } public void update(Observable arg0, Object arg) { if (arg == null || !(arg instanceof Event)) return; Event event = (Event) arg; // check the event function against the functions we have notifications watching for String function = event.getEvent(); if (SECURE_UPDATE_AUTHZ_GROUP.equals(function) || SECURE_UPDATE_OWN_AUTHZ_GROUP.equals(function) || SECURE_REMOVE_AUTHZ_GROUP.equals(function) || SECURE_JOIN_AUTHZ_GROUP.equals(function) || SECURE_UNJOIN_AUTHZ_GROUP.equals(function) || SECURE_ADD_AUTHZ_GROUP.equals(function)) { // Get the resource ID String realmId = extractEntityId(event.getResource()); if (realmId != null) { for (String user : getAuthzUsersInGroups(new HashSet<String>(Arrays.asList(realmId)))) { authzUserGroupIdsCache.remove(user); } if (serverConfigurationService().getBoolean("authz.cacheGrants", true)) { if (M_log.isDebugEnabled()) { M_log.debug("DbAuthzGroupService update(): clear realm role cache for " + realmId); } m_realmRoleGRCache.remove(realmId); } } else { // This should never happen as the events we generate should always have // a /realm/ prefix on the resource. M_log.warn("DBAuthzGroupService update(): failed to extract realm ID from "+ event.getResource()); } } } /** * based on value from RealmRoleGroupCache * transform a Map<String, MemberWithRoleId> object into a Map<String, Member> object * KNL-1037 */ private Map<String, Member> getMemberMap(Map<String, MemberWithRoleId> mMap, Map<?,?> roleMap) { Map<String, Member> rv = new HashMap<String, Member>(); for (Map.Entry<String, MemberWithRoleId> entry : mMap.entrySet()) { String userId = entry.getKey(); MemberWithRoleId m = entry.getValue(); String roleId = m.getRoleId(); if (roleId != null && roleMap != null && roleMap.containsKey(roleId)) { Role role = (Role) roleMap.get(roleId); rv.put(userId, new BaseMember(role, m.isActive(), m.isProvided(), userId, userDirectoryService())); } } return rv; } /** * transform a Map<String, Member> object into a Map<String, MemberWithRoleId> object * to be used in RealmRoleGroupCache * KNL-1037 */ private Map<String, MemberWithRoleId> getMemberWithRoleIdMap(Map<String, Member> userGrants) { Map<String, MemberWithRoleId> rv = new HashMap<String, MemberWithRoleId>(); for (Map.Entry<String, Member> entry : userGrants.entrySet()) { String userId = entry.getKey(); Member member = entry.getValue(); rv.put(userId, new MemberWithRoleId(member)); } return rv; } }
true
true
public void refreshAuthzGroup(BaseAuthzGroup realm) { M_log.debug("refreshAuthzGroup()"); if ((realm == null) || (m_provider == null)) return; boolean synchWithContainingRealm = serverConfigurationService().getBoolean("authz.synchWithContainingRealm", true); // check to see whether this is of group realm or not // if of Group Realm, get the containing Site Realm String containingRealmId = null; AuthzGroup containingRealm = null; Reference ref = entityManager.newReference(realm.getId()); if (SiteService.APPLICATION_ID.equals(ref.getType()) && SiteService.GROUP_SUBTYPE.equals(ref.getSubType())) { containingRealmId = ref.getContainer(); } if (containingRealmId != null) { String containingRealmRef = siteService.siteReference(containingRealmId); try { containingRealm = getAuthzGroup(containingRealmRef); } catch (GroupNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find containing realm for id: " + containingRealmRef); } } String sql = ""; // Note: the realm is still lazy - we have the realm id but don't need to worry about changing grants // get the latest userEid -> role name map from the provider Map<String,String> target = m_provider.getUserRolesForGroup(realm.getProviderGroupId()); // read the realm's grants sql = dbAuthzGroupSql.getSelectRealmRoleGroup4Sql(); Object[] fields = new Object[1]; fields[0] = caseId(realm.getId()); List<UserAndRole> grants = getGrants(realm); // make a map, user id -> role granted, each for provider and non-provider (or inactive) Map<String, String> existing = new HashMap<String, String>(); Map<String, String> providedInactive = new HashMap<String, String>(); Map<String, String> nonProvider = new HashMap<String, String>(); for (UserAndRole uar : grants) { // active and provided are the currently stored provider grants if (uar.provided) { if (existing.containsKey(uar.userId)) { M_log.warn("refreshRealm: duplicate user id found in provider grants: " + uar.userId); } else { existing.put(uar.userId, uar.role); // Record inactive status if (!uar.active) { providedInactive.put(uar.userId, uar.role); } } } // inactive or not provided are the currently stored internal grants - not to be overwritten by provider info else { if (nonProvider.containsKey(uar.userId)) { M_log.warn("refreshRealm: duplicate user id found in nonProvider grants: " + uar.userId); } else { nonProvider.put(uar.userId, uar.role); } } } // compute the records we need to delete: every existing not in target or not matching target's role List<String> toDelete = new Vector<String>(); for (Map.Entry<String,String> entry : existing.entrySet()) { String userId = entry.getKey(); String role = entry.getValue(); try { String userEid = userDirectoryService().getUserEid(userId); String targetRole = (String) target.get(userEid); if ((targetRole == null) || (!targetRole.equals(role))) { toDelete.add(userId); } } catch (UserNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find eid for user: " + userId); } } // compute the records we need to add: every target not in existing, or not matching's existing's role // we don't insert target grants that would override internal grants List<UserAndRole> toInsert = new Vector<UserAndRole>(); for (Map.Entry<String,String> entry : target.entrySet()) { String userEid = entry.getKey(); try { String userId = userDirectoryService().getUserId(userEid); String role = entry.getValue(); boolean active = true; String existingRole = (String) existing.get(userId); String nonProviderRole = (String) nonProvider.get(userId); if (!synchWithContainingRealm) { if ((nonProviderRole == null) && ((existingRole == null) || (!existingRole.equals(role)))) { // Check whether this user was inactive in the site previously, if so preserve status if (providedInactive.get(userId) != null) { active = false; } // this is either at site level or at the group level but no need to synchronize toInsert.add(new UserAndRole(userId, role, active, true)); } } else { if (containingRealm != null) { Member cMember = containingRealm.getMember(userId); if (cMember != null) { String cMemberRoleId = cMember.getRole() != null ? cMember.getRole().getId() : null; boolean cMemberActive = cMember.isActive(); // synchronize with parent realm role definition and active status toInsert.add(new UserAndRole(userId, cMemberRoleId, cMemberActive, cMember.isProvided())); if ((existingRole != null && !existingRole.equals(cMemberRoleId)) // overriding existing authz group role ||!role.equals(cMemberRoleId)) // overriding provided role { M_log.info("refreshAuthzGroup: realm id=" + realm.getId() + ", overrides group role of user eid=" + userEid + ": provided role=" + role + ", with site-level role=" + cMemberRoleId + " and site-level active status=" + cMemberActive); } } else { // user not defined in parent realm toInsert.add(new UserAndRole(userId, role, active, true)); } } else { // this is either at site level toInsert.add(new UserAndRole(userId, role, active, true)); } } } catch (UserNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find id for user eid: " + userEid); } } if (promoteUsersToProvided) { // compute the records we want to promote from non-provided to provider: // every non-provided user with an equivalent provided entry with the same role for (Map.Entry<String,String> entry : nonProvider.entrySet()) { String userId = entry.getKey(); String role = entry.getValue(); try { String userEid = userDirectoryService().getUserEid(userId); String targetRole = (String) target.get(userEid); if (role.equals(targetRole)) { // remove from non-provided and add as provided toDelete.add(userId); // Check whether this user was inactive in the site previously, if so preserve status boolean active = true; if (providedInactive.get(userId) != null) { active = false; } toInsert.add(new UserAndRole(userId, role, active, true)); } } catch (UserNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find eid for user: " + userId); } } } // if any, do it if ((toDelete.size() > 0) || (toInsert.size() > 0)) { // do these each in their own transaction, to avoid possible deadlock // caused by transactions modifying more than one row at a time. // delete sql = dbAuthzGroupSql.getDeleteRealmRoleGroup4Sql(); fields = new Object[2]; fields[0] = caseId(realm.getId()); for (String userId : toDelete) { fields[1] = userId; m_sql.dbWrite(sql, fields); } // insert sql = dbAuthzGroupSql.getInsertRealmRoleGroup3Sql(); fields = new Object[5]; fields[0] = caseId(realm.getId()); fields[0] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleGroup3_1Sql(), fields[0]); for (UserAndRole uar : toInsert) { fields[1] = uar.userId; fields[2] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleGroup3_2Sql(), uar.role); fields[3] = uar.active; fields[4] = uar.provided; m_sql.dbWrite(sql, fields); } } if (M_log.isDebugEnabled()) { M_log.debug("refreshAuthzGroup(): deleted: "+ toDelete.size()+ " inserted: "+ toInsert.size()+ " provided: "+ existing.size()+ " nonProvider: "+ nonProvider.size()); } }
public void refreshAuthzGroup(BaseAuthzGroup realm) { M_log.debug("refreshAuthzGroup()"); if ((realm == null) || (m_provider == null)) return; boolean synchWithContainingRealm = serverConfigurationService().getBoolean("authz.synchWithContainingRealm", true); // check to see whether this is of group realm or not // if of Group Realm, get the containing Site Realm String containingRealmId = null; AuthzGroup containingRealm = null; Reference ref = entityManager.newReference(realm.getId()); if (SiteService.APPLICATION_ID.equals(ref.getType()) && SiteService.GROUP_SUBTYPE.equals(ref.getSubType())) { containingRealmId = ref.getContainer(); } if (containingRealmId != null) { String containingRealmRef = siteService.siteReference(containingRealmId); try { containingRealm = getAuthzGroup(containingRealmRef); } catch (GroupNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find containing realm for id: " + containingRealmRef); } } String sql = ""; // Note: the realm is still lazy - we have the realm id but don't need to worry about changing grants // get the latest userEid -> role name map from the provider Map<String,String> target = m_provider.getUserRolesForGroup(realm.getProviderGroupId()); // read the realm's grants sql = dbAuthzGroupSql.getSelectRealmRoleGroup4Sql(); Object[] fields = new Object[1]; fields[0] = caseId(realm.getId()); List<UserAndRole> grants = getGrants(realm); // make a map, user id -> role granted, each for provider and non-provider (or inactive) Map<String, String> existing = new HashMap<String, String>(); Map<String, String> providedInactive = new HashMap<String, String>(); Map<String, String> nonProvider = new HashMap<String, String>(); for (UserAndRole uar : grants) { // active and provided are the currently stored provider grants if (uar.provided) { if (existing.containsKey(uar.userId)) { M_log.warn("refreshRealm: duplicate user id found in provider grants: " + uar.userId); } else { existing.put(uar.userId, uar.role); // Record inactive status if (!uar.active) { providedInactive.put(uar.userId, uar.role); } } } // inactive or not provided are the currently stored internal grants - not to be overwritten by provider info else { if (nonProvider.containsKey(uar.userId)) { M_log.warn("refreshRealm: duplicate user id found in nonProvider grants: " + uar.userId); } else { nonProvider.put(uar.userId, uar.role); } } } // compute the records we need to delete: every existing not in target or not matching target's role List<String> toDelete = new Vector<String>(); for (Map.Entry<String,String> entry : existing.entrySet()) { String userId = entry.getKey(); String role = entry.getValue(); try { String userEid = userDirectoryService().getUserEid(userId); String targetRole = (String) target.get(userEid); if ((targetRole == null) || (!targetRole.equals(role))) { toDelete.add(userId); } } catch (UserNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find eid for user: " + userId); } } // compute the records we need to add: every target not in existing, or not matching's existing's role // we don't insert target grants that would override internal grants List<UserAndRole> toInsert = new Vector<UserAndRole>(); for (Map.Entry<String,String> entry : target.entrySet()) { String userEid = entry.getKey(); try { String userId = userDirectoryService().getUserId(userEid); String role = entry.getValue(); boolean active = true; String existingRole = (String) existing.get(userId); String nonProviderRole = (String) nonProvider.get(userId); if (!synchWithContainingRealm) { if ((nonProviderRole == null) && ((existingRole == null) || (!existingRole.equals(role)))) { // Check whether this user was inactive in the site previously, if so preserve status if (providedInactive.get(userId) != null) { active = false; } // this is either at site level or at the group level but no need to synchronize toInsert.add(new UserAndRole(userId, role, active, true)); } } else { if (containingRealm != null) { Member cMember = containingRealm.getMember(userId); if (cMember != null) { String cMemberRoleId = cMember.getRole() != null ? cMember.getRole().getId() : null; boolean cMemberActive = cMember.isActive(); // synchronize with parent realm role definition and active status toInsert.add(new UserAndRole(userId, cMemberRoleId, cMemberActive, cMember.isProvided())); if ((existingRole != null && !existingRole.equals(cMemberRoleId)) // overriding existing authz group role ||!role.equals(cMemberRoleId)) // overriding provided role { M_log.info("refreshAuthzGroup: realm id=" + realm.getId() + ", overrides group role of user eid=" + userEid + ": provided role=" + role + ", with site-level role=" + cMemberRoleId + " and site-level active status=" + cMemberActive); } } else { // user not defined in parent realm toInsert.add(new UserAndRole(userId, role, active, true)); } } else { // this is either at site level toInsert.add(new UserAndRole(userId, role, active, true)); } } } catch (UserNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find id for user eid: " + userEid); } } if (promoteUsersToProvided) { // compute the records we want to promote from non-provided to provider: // every non-provided user with an equivalent provided entry with the same role for (Map.Entry<String,String> entry : nonProvider.entrySet()) { String userId = entry.getKey(); String role = entry.getValue(); try { String userEid = userDirectoryService().getUserEid(userId); String targetRole = (String) target.get(userEid); if (role.equals(targetRole)) { // remove from non-provided and add as provided toDelete.add(userId); // Check whether this user was inactive in the site previously, if so preserve status boolean active = true; if (providedInactive.get(userId) != null) { active = false; } toInsert.add(new UserAndRole(userId, role, active, true)); } } catch (UserNotDefinedException e) { M_log.warn("refreshAuthzGroup: cannot find eid for user: " + userId); } } } // if any, do it if ((toDelete.size() > 0) || (toInsert.size() > 0)) { // do these each in their own transaction, to avoid possible deadlock // caused by transactions modifying more than one row at a time. // delete sql = dbAuthzGroupSql.getDeleteRealmRoleGroup4Sql(); fields = new Object[2]; fields[0] = caseId(realm.getId()); for (String userId : toDelete) { fields[1] = userId; m_sql.dbWrite(sql, fields); } // insert sql = dbAuthzGroupSql.getInsertRealmRoleGroup3Sql(); fields = new Object[5]; fields[0] = caseId(realm.getId()); fields[0] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleGroup3_1Sql(), fields[0]); for (UserAndRole uar : toInsert) { fields[1] = uar.userId; fields[2] = getValueForSubquery(dbAuthzGroupSql.getInsertRealmRoleGroup3_2Sql(), uar.role); fields[3] = uar.active ? "1" : "0"; // KNL-1099 fields[4] = uar.provided ? "1" : "0"; // KNL-1099 m_sql.dbWrite(sql, fields); } } if (M_log.isDebugEnabled()) { M_log.debug("refreshAuthzGroup(): deleted: "+ toDelete.size()+ " inserted: "+ toInsert.size()+ " provided: "+ existing.size()+ " nonProvider: "+ nonProvider.size()); } }
diff --git a/src/main/java/net/robbytu/banjoserver/bungee/pm/ReplyCommand.java b/src/main/java/net/robbytu/banjoserver/bungee/pm/ReplyCommand.java index 13b16f5..0a9d450 100644 --- a/src/main/java/net/robbytu/banjoserver/bungee/pm/ReplyCommand.java +++ b/src/main/java/net/robbytu/banjoserver/bungee/pm/ReplyCommand.java @@ -1,46 +1,46 @@ package net.robbytu.banjoserver.bungee.pm; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import net.robbytu.banjoserver.bungee.Main; public class ReplyCommand extends Command { public ReplyCommand() { super("r", null, "reply"); } @Override public void execute(CommandSender sender, String[] args) { if(!PmSession.replyTo.containsKey(Main.instance.getProxy().getPlayer(sender.getName()))) { sender.sendMessage(ChatColor.GRAY + "Je hebt geen bericht om op te reageren."); return; } if(args.length < 1) { sender.sendMessage(ChatColor.RED + "Geef een bericht op."); return; } ProxiedPlayer receiver = PmSession.replyTo.get(Main.instance.getProxy().getPlayer(sender.getName())); if(receiver == null) { sender.sendMessage(ChatColor.RED + args[0] + " is offline."); sender.sendMessage(ChatColor.GRAY + "Je kan nog wel een mail sturen met het /mail commando."); PmSession.replyTo.remove(Main.instance.getProxy().getPlayer(sender.getName())); return; } String message = ""; for (int i = 0; i < args.length; i++) message += ((message.equals("")) ? "" : " ") + args[i]; sender.sendMessage(ChatColor.GRAY + "[" + sender.getName() + " -> " + receiver.getName() + "] " + message); - Main.instance.getProxy().getPlayer(args[0]).sendMessage(ChatColor.GRAY + "[" + sender.getName() + " -> " + receiver.getName() + "] " + message); + receiver.sendMessage(ChatColor.GRAY + "[" + sender.getName() + " -> " + receiver.getName() + "] " + message); if(PmSession.replyTo.containsKey(receiver)) PmSession.replyTo.remove(receiver); PmSession.replyTo.put(receiver, Main.instance.getProxy().getPlayer(sender.getName())); } }
true
true
public void execute(CommandSender sender, String[] args) { if(!PmSession.replyTo.containsKey(Main.instance.getProxy().getPlayer(sender.getName()))) { sender.sendMessage(ChatColor.GRAY + "Je hebt geen bericht om op te reageren."); return; } if(args.length < 1) { sender.sendMessage(ChatColor.RED + "Geef een bericht op."); return; } ProxiedPlayer receiver = PmSession.replyTo.get(Main.instance.getProxy().getPlayer(sender.getName())); if(receiver == null) { sender.sendMessage(ChatColor.RED + args[0] + " is offline."); sender.sendMessage(ChatColor.GRAY + "Je kan nog wel een mail sturen met het /mail commando."); PmSession.replyTo.remove(Main.instance.getProxy().getPlayer(sender.getName())); return; } String message = ""; for (int i = 0; i < args.length; i++) message += ((message.equals("")) ? "" : " ") + args[i]; sender.sendMessage(ChatColor.GRAY + "[" + sender.getName() + " -> " + receiver.getName() + "] " + message); Main.instance.getProxy().getPlayer(args[0]).sendMessage(ChatColor.GRAY + "[" + sender.getName() + " -> " + receiver.getName() + "] " + message); if(PmSession.replyTo.containsKey(receiver)) PmSession.replyTo.remove(receiver); PmSession.replyTo.put(receiver, Main.instance.getProxy().getPlayer(sender.getName())); }
public void execute(CommandSender sender, String[] args) { if(!PmSession.replyTo.containsKey(Main.instance.getProxy().getPlayer(sender.getName()))) { sender.sendMessage(ChatColor.GRAY + "Je hebt geen bericht om op te reageren."); return; } if(args.length < 1) { sender.sendMessage(ChatColor.RED + "Geef een bericht op."); return; } ProxiedPlayer receiver = PmSession.replyTo.get(Main.instance.getProxy().getPlayer(sender.getName())); if(receiver == null) { sender.sendMessage(ChatColor.RED + args[0] + " is offline."); sender.sendMessage(ChatColor.GRAY + "Je kan nog wel een mail sturen met het /mail commando."); PmSession.replyTo.remove(Main.instance.getProxy().getPlayer(sender.getName())); return; } String message = ""; for (int i = 0; i < args.length; i++) message += ((message.equals("")) ? "" : " ") + args[i]; sender.sendMessage(ChatColor.GRAY + "[" + sender.getName() + " -> " + receiver.getName() + "] " + message); receiver.sendMessage(ChatColor.GRAY + "[" + sender.getName() + " -> " + receiver.getName() + "] " + message); if(PmSession.replyTo.containsKey(receiver)) PmSession.replyTo.remove(receiver); PmSession.replyTo.put(receiver, Main.instance.getProxy().getPlayer(sender.getName())); }
diff --git a/src/org/eclipse/core/internal/localstore/UnifiedTree.java b/src/org/eclipse/core/internal/localstore/UnifiedTree.java index bfbd1b19..0e96b0ae 100644 --- a/src/org/eclipse/core/internal/localstore/UnifiedTree.java +++ b/src/org/eclipse/core/internal/localstore/UnifiedTree.java @@ -1,338 +1,338 @@ package org.eclipse.core.internal.localstore; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.core.resources.*; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.internal.resources.Workspace; import org.eclipse.core.internal.utils.*; import java.util.*; /** * Represents the workspace's tree merged with the file system's tree. */ public class UnifiedTree { /** tree's root */ protected IResource root; /** cache root's location */ protected IPath rootLocalLocation; /** tree's actual level */ protected int level; /** our queue */ protected Queue queue; /** Spare node objects available for reuse */ protected ArrayList freeNodes = new ArrayList(); /** sorter */ protected Sorter sorter; /** special node to mark the beginning of a level in the tree */ protected static final UnifiedTreeNode levelMarker = new UnifiedTreeNode(null, null, 0, null, null, false); /** special node to mark the separation of a node's children */ protected static final UnifiedTreeNode childrenMarker = new UnifiedTreeNode(null, null, 0, null, null, false); public UnifiedTree() { } /** * The root must only be a file or a folder. */ public UnifiedTree(IResource root) { setRoot(root); } public void accept(IUnifiedTreeVisitor visitor) throws CoreException { accept(visitor, IResource.DEPTH_INFINITE); } public void accept(IUnifiedTreeVisitor visitor, int depth) throws CoreException { Assert.isNotNull(root); initializeQueue(); level = 0; while (isValidLevel(level, depth) && !queue.isEmpty()) { UnifiedTreeNode node = (UnifiedTreeNode)queue.remove(); if (isChildrenMarker(node)) continue; if (isLevelMarker(node)) { level++; continue; } if (visitor.visit(node)) addNodeChildrenToQueue(node); else removeNodeChildrenFromQueue(node); //allow reuse of the node freeNodes.add(node); } } protected void addChildren(UnifiedTreeNode node) throws CoreException { IResource parent = node.getResource(); /* is there a possibility to have children? */ if (parent.getType() == IResource.FILE && node.isFile()) return; /* get the list of resources in the file system */ String parentLocalLocation = node.getLocalLocation(); Object[] list = getLocalList(node, parentLocalLocation); int index = 0; /* get the list of resources in the workspace */ if (node.existsInWorkspace() && (parent.getType() == IResource.FOLDER || parent.getType() == IResource.PROJECT)) { IResource target = null; boolean next = true; UnifiedTreeNode child = null; - IResource[] members = ((IContainer) parent).members(); + IResource[] members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); int i = 0; while (true) { if (next) { if (i >= members.length) break; target = members[i++]; } String name = target.getName(); String localName = (list != null && index < list.length) ? (String) list[index] : null; int comp = localName != null ? name.compareTo(localName) : -1; if (comp == 0) { // resource exists in workspace and file system String localLocation = createChildLocation(parentLocalLocation, localName); long stat = CoreFileSystemLibrary.getStat(localLocation); child = createNode(target, stat, localLocation, localName, true); index++; next = true; } else if (comp > 0) { // resource exists only in file system child = createChildNodeFromFileSystem(node, parentLocalLocation, localName); index++; next = false; } else { // resource exists only in the workspace child = createNode(target, 0, null, null, true); next = true; } addChildToTree(node, child); } } /* process any remaining resource from the file system */ addChildrenFromFileSystem(node, parentLocalLocation, list, index); /* if we added children, add the childMarker separator */ if (node.getFirstChild() != null) addChildrenMarker(); } protected void addChildrenFromFileSystem(UnifiedTreeNode node, String parentLocalLocation, Object[] list, int index) throws CoreException { if (list == null) return; for (int i = index; i < list.length; i++) { String localName = (String) list[i]; UnifiedTreeNode child = createChildNodeFromFileSystem(node, parentLocalLocation, localName); addChildToTree(node, child); } } protected void addChildrenMarker() { addElementToQueue(childrenMarker); } protected void addChildToTree(UnifiedTreeNode node, UnifiedTreeNode child) { if (node.getFirstChild() == null) node.setFirstChild(child); addElementToQueue(child); } protected void addElementToQueue(UnifiedTreeNode target) { queue.add(target); }/** * Creates a string representing the OS path for the given parent and child name. */ protected String createChildLocation(String parentLocation, String childLocation) { StringBuffer buffer = new StringBuffer(parentLocation.length() + childLocation.length() + 1); buffer.append(parentLocation); buffer.append(java.io.File.separatorChar); buffer.append(childLocation); return buffer.toString(); } protected void addNodeChildrenToQueue(UnifiedTreeNode node) throws CoreException { /* if the first child is not null we already added the children */ if (node.getFirstChild() != null) return; addChildren(node); if (queue.isEmpty()) return; //if we're about to change levels, then the children just added //are the last nodes for their level, so add a level marker to the queue UnifiedTreeNode nextNode = (UnifiedTreeNode)queue.peek(); if (isLevelMarker(nextNode)) addElementToQueue(levelMarker); } protected void addRootToQueue() throws CoreException { String rootLocationString = rootLocalLocation.toOSString(); long stat = CoreFileSystemLibrary.getStat(rootLocationString); UnifiedTreeNode node = createNode(root, stat, rootLocationString, rootLocalLocation.lastSegment(), root.exists()); if (!node.existsInFileSystem() && !node.existsInWorkspace()) return; addElementToQueue(node); } protected UnifiedTreeNode createChildNodeFromFileSystem(UnifiedTreeNode parent, String parentLocalLocation, String childName) throws CoreException { IPath childPath = parent.getResource().getFullPath().append(childName); String location = createChildLocation(parentLocalLocation, childName); long stat = CoreFileSystemLibrary.getStat(location); int type = CoreFileSystemLibrary.isFile(stat) ? IResource.FILE : IResource.FOLDER; IResource target = getWorkspace().newResource(childPath, type); return createNode(target, stat, location, childName, false); } protected UnifiedTreeNode createNodeFromFileSystem(IPath path, String location, String localName) throws CoreException { long stat = CoreFileSystemLibrary.getStat(location); UnifiedTreeNode node = createNode(null, stat, location, localName, false); int type = node.isFile() ? IResource.FILE : IResource.FOLDER; IResource target = getWorkspace().newResource(path, type); node.setResource(target); return node; } /** * Factory method for creating a node for this tree. */ protected UnifiedTreeNode createNode(IResource resource, long stat, String localLocation, String localName, boolean existsWorkspace) { //first check for reusable objects UnifiedTreeNode node = null; int size = freeNodes.size(); if (size > 0) { node = (UnifiedTreeNode)freeNodes.remove(size-1); node.reuse(this, resource, stat, localLocation, localName, existsWorkspace); return node; } //none available, so create a new one return new UnifiedTreeNode(this, resource, stat, localLocation, localName, existsWorkspace); } protected Enumeration getChildren(UnifiedTreeNode node) throws CoreException { /* if first child is null we need to add node's children to queue */ if (node.getFirstChild() == null) addNodeChildrenToQueue(node); /* if the first child is still null, the node does not have any children */ if (node.getFirstChild() == null) return EmptyEnumeration.getEnumeration(); /* get the index of the first child */ int index = queue.indexOf(node.getFirstChild()); /* if we do not have children, just return an empty enumeration */ if (index == -1) return EmptyEnumeration.getEnumeration(); /* create an enumeration with node's children */ List result = new ArrayList(10); while (true) { UnifiedTreeNode child = (UnifiedTreeNode) queue.elementAt(index); if (isChildrenMarker(child)) break; result.add(child); index = queue.increment(index); } return Collections.enumeration(result); } protected String getLocalLocation(IResource target) { int segments = target.getFullPath().matchingFirstSegments(root.getFullPath()); return rootLocalLocation.append(target.getFullPath().removeFirstSegments(segments)).toOSString(); } protected int getLevel() { return level; } protected Object[] getLocalList(UnifiedTreeNode node, String location) { if (node.isFile()) return null; String[] list = new java.io.File(location).list(); if (list == null) return list; int size = list.length; if (size > 1) quickSort(list, 0 , size-1); return list; } protected Workspace getWorkspace() { return (Workspace) root.getWorkspace(); } protected void initializeQueue() throws CoreException { //init the queue if (queue == null) queue = new Queue(100, false); else queue.reset(); //init the free nodes list if (freeNodes == null) freeNodes = new ArrayList(100); else freeNodes.clear(); addRootToQueue(); addElementToQueue(levelMarker); } protected boolean isChildrenMarker(UnifiedTreeNode node) { return node == childrenMarker; } protected boolean isLevelMarker(UnifiedTreeNode node) { return node == levelMarker; } protected boolean isValidLevel(int level, int depth) { switch (depth) { case IResource.DEPTH_INFINITE : return true; case IResource.DEPTH_ONE : return level <= 1; case IResource.DEPTH_ZERO : return level == 0; default: return false; } } /** * Remove from the last element of the queue to the first child of the * given node. */ protected void removeNodeChildrenFromQueue(UnifiedTreeNode node) throws CoreException { UnifiedTreeNode first = node.getFirstChild(); if (first == null) return; while (true) { if (first.equals(queue.removeTail())) break; } node.setFirstChild(null); } public void setRoot(IResource root) { this.root = root; this.rootLocalLocation = root.getLocation(); } /** * Sorts the given array of strings in place. This is * not using the sorting framework to avoid casting overhead. */ protected void quickSort(String[] strings, int left, int right) { int originalLeft = left; int originalRight = right; String mid = strings[ (left + right) / 2]; do { while (mid.compareTo(strings[left]) > 0) left++; while (strings[right].compareTo(mid) > 0) right--; if (left <= right) { String tmp = strings[left]; strings[left] = strings[right]; strings[right] = tmp; left++; right--; } } while (left <= right); if (originalLeft < right) quickSort(strings, originalLeft, right); if (left < originalRight) quickSort(strings, left, originalRight); return; } }
true
true
protected void addChildren(UnifiedTreeNode node) throws CoreException { IResource parent = node.getResource(); /* is there a possibility to have children? */ if (parent.getType() == IResource.FILE && node.isFile()) return; /* get the list of resources in the file system */ String parentLocalLocation = node.getLocalLocation(); Object[] list = getLocalList(node, parentLocalLocation); int index = 0; /* get the list of resources in the workspace */ if (node.existsInWorkspace() && (parent.getType() == IResource.FOLDER || parent.getType() == IResource.PROJECT)) { IResource target = null; boolean next = true; UnifiedTreeNode child = null; IResource[] members = ((IContainer) parent).members(); int i = 0; while (true) { if (next) { if (i >= members.length) break; target = members[i++]; } String name = target.getName(); String localName = (list != null && index < list.length) ? (String) list[index] : null; int comp = localName != null ? name.compareTo(localName) : -1; if (comp == 0) { // resource exists in workspace and file system String localLocation = createChildLocation(parentLocalLocation, localName); long stat = CoreFileSystemLibrary.getStat(localLocation); child = createNode(target, stat, localLocation, localName, true); index++; next = true; } else if (comp > 0) { // resource exists only in file system child = createChildNodeFromFileSystem(node, parentLocalLocation, localName); index++; next = false; } else { // resource exists only in the workspace child = createNode(target, 0, null, null, true); next = true; } addChildToTree(node, child); } } /* process any remaining resource from the file system */ addChildrenFromFileSystem(node, parentLocalLocation, list, index); /* if we added children, add the childMarker separator */ if (node.getFirstChild() != null) addChildrenMarker(); }
protected void addChildren(UnifiedTreeNode node) throws CoreException { IResource parent = node.getResource(); /* is there a possibility to have children? */ if (parent.getType() == IResource.FILE && node.isFile()) return; /* get the list of resources in the file system */ String parentLocalLocation = node.getLocalLocation(); Object[] list = getLocalList(node, parentLocalLocation); int index = 0; /* get the list of resources in the workspace */ if (node.existsInWorkspace() && (parent.getType() == IResource.FOLDER || parent.getType() == IResource.PROJECT)) { IResource target = null; boolean next = true; UnifiedTreeNode child = null; IResource[] members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); int i = 0; while (true) { if (next) { if (i >= members.length) break; target = members[i++]; } String name = target.getName(); String localName = (list != null && index < list.length) ? (String) list[index] : null; int comp = localName != null ? name.compareTo(localName) : -1; if (comp == 0) { // resource exists in workspace and file system String localLocation = createChildLocation(parentLocalLocation, localName); long stat = CoreFileSystemLibrary.getStat(localLocation); child = createNode(target, stat, localLocation, localName, true); index++; next = true; } else if (comp > 0) { // resource exists only in file system child = createChildNodeFromFileSystem(node, parentLocalLocation, localName); index++; next = false; } else { // resource exists only in the workspace child = createNode(target, 0, null, null, true); next = true; } addChildToTree(node, child); } } /* process any remaining resource from the file system */ addChildrenFromFileSystem(node, parentLocalLocation, list, index); /* if we added children, add the childMarker separator */ if (node.getFirstChild() != null) addChildrenMarker(); }
diff --git a/src/Main.java b/src/Main.java index 4c7c6b0..770df1d 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,5 +1,5 @@ public class Main { public static void main(String[] args) { - System.out.println("Hello Android!"); + System.out.println("Hi Android!"); } }
true
true
public static void main(String[] args) { System.out.println("Hello Android!"); }
public static void main(String[] args) { System.out.println("Hi Android!"); }
diff --git a/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2645Test.java b/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2645Test.java index d745c3bbc..dea6e7730 100644 --- a/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2645Test.java +++ b/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2645Test.java @@ -1,109 +1,109 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.bugs; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.EmbeddedBrokerTestSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class AMQ2645Test extends EmbeddedBrokerTestSupport { private static final Log LOG = LogFactory.getLog(AMQ2645Test.class); private final static String QUEUE_NAME = "test.daroo.q"; public void testWaitForTransportInterruptionProcessingHang() throws Exception { final ConnectionFactory fac = new ActiveMQConnectionFactory( "failover:(" + this.bindAddress + ")"); final Connection connection = fac.createConnection(); try { final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Queue queue = session.createQueue(QUEUE_NAME); final MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); connection.start(); producer.send(session.createTextMessage("test")); final CountDownLatch afterRestart = new CountDownLatch(1); final CountDownLatch twoNewMessages = new CountDownLatch(1); final CountDownLatch thirdMessageReceived = new CountDownLatch(1); final MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); consumer.setMessageListener(new MessageListener() { public void onMessage(Message message) { try { afterRestart.await(); final TextMessage txtMsg = (TextMessage) message; if (txtMsg.getText().equals("test")) { producer.send(session.createTextMessage("test 1")); TimeUnit.SECONDS.sleep(5); // THIS SECOND send() WILL CAUSE CONSUMER DEADLOCK producer.send(session.createTextMessage("test 2")); LOG.info("Two new messages produced."); twoNewMessages.countDown(); } else if (txtMsg.getText().equals("test 3")) { thirdMessageReceived.countDown(); } } catch (Exception e) { LOG.error(e); throw new RuntimeException(e); } } }); LOG.info("Stopping broker...."); broker.stop(); LOG.info("Creating new broker..."); broker = createBroker(); startBroker(); broker.waitUntilStarted(); afterRestart.countDown(); assertTrue("Consumer is deadlocked!", twoNewMessages.await(60, TimeUnit.SECONDS)); producer.send(session.createTextMessage("test 3")); - assertTrue("Consumer got third message after block", twoNewMessages.await(60, TimeUnit.SECONDS)); + assertTrue("Consumer got third message after block", thirdMessageReceived.await(60, TimeUnit.SECONDS)); } finally { broker.stop(); } } @Override protected void setUp() throws Exception { bindAddress = "tcp://0.0.0.0:61617"; super.setUp(); } }
true
true
public void testWaitForTransportInterruptionProcessingHang() throws Exception { final ConnectionFactory fac = new ActiveMQConnectionFactory( "failover:(" + this.bindAddress + ")"); final Connection connection = fac.createConnection(); try { final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Queue queue = session.createQueue(QUEUE_NAME); final MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); connection.start(); producer.send(session.createTextMessage("test")); final CountDownLatch afterRestart = new CountDownLatch(1); final CountDownLatch twoNewMessages = new CountDownLatch(1); final CountDownLatch thirdMessageReceived = new CountDownLatch(1); final MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); consumer.setMessageListener(new MessageListener() { public void onMessage(Message message) { try { afterRestart.await(); final TextMessage txtMsg = (TextMessage) message; if (txtMsg.getText().equals("test")) { producer.send(session.createTextMessage("test 1")); TimeUnit.SECONDS.sleep(5); // THIS SECOND send() WILL CAUSE CONSUMER DEADLOCK producer.send(session.createTextMessage("test 2")); LOG.info("Two new messages produced."); twoNewMessages.countDown(); } else if (txtMsg.getText().equals("test 3")) { thirdMessageReceived.countDown(); } } catch (Exception e) { LOG.error(e); throw new RuntimeException(e); } } }); LOG.info("Stopping broker...."); broker.stop(); LOG.info("Creating new broker..."); broker = createBroker(); startBroker(); broker.waitUntilStarted(); afterRestart.countDown(); assertTrue("Consumer is deadlocked!", twoNewMessages.await(60, TimeUnit.SECONDS)); producer.send(session.createTextMessage("test 3")); assertTrue("Consumer got third message after block", twoNewMessages.await(60, TimeUnit.SECONDS)); } finally { broker.stop(); } }
public void testWaitForTransportInterruptionProcessingHang() throws Exception { final ConnectionFactory fac = new ActiveMQConnectionFactory( "failover:(" + this.bindAddress + ")"); final Connection connection = fac.createConnection(); try { final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Queue queue = session.createQueue(QUEUE_NAME); final MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); connection.start(); producer.send(session.createTextMessage("test")); final CountDownLatch afterRestart = new CountDownLatch(1); final CountDownLatch twoNewMessages = new CountDownLatch(1); final CountDownLatch thirdMessageReceived = new CountDownLatch(1); final MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); consumer.setMessageListener(new MessageListener() { public void onMessage(Message message) { try { afterRestart.await(); final TextMessage txtMsg = (TextMessage) message; if (txtMsg.getText().equals("test")) { producer.send(session.createTextMessage("test 1")); TimeUnit.SECONDS.sleep(5); // THIS SECOND send() WILL CAUSE CONSUMER DEADLOCK producer.send(session.createTextMessage("test 2")); LOG.info("Two new messages produced."); twoNewMessages.countDown(); } else if (txtMsg.getText().equals("test 3")) { thirdMessageReceived.countDown(); } } catch (Exception e) { LOG.error(e); throw new RuntimeException(e); } } }); LOG.info("Stopping broker...."); broker.stop(); LOG.info("Creating new broker..."); broker = createBroker(); startBroker(); broker.waitUntilStarted(); afterRestart.countDown(); assertTrue("Consumer is deadlocked!", twoNewMessages.await(60, TimeUnit.SECONDS)); producer.send(session.createTextMessage("test 3")); assertTrue("Consumer got third message after block", thirdMessageReceived.await(60, TimeUnit.SECONDS)); } finally { broker.stop(); } }
diff --git a/src/voidfinger/VoidFinger.java b/src/voidfinger/VoidFinger.java index e35b751..a695fe0 100644 --- a/src/voidfinger/VoidFinger.java +++ b/src/voidfinger/VoidFinger.java @@ -1,28 +1,32 @@ package voidfinger; import java.io.FileNotFoundException; import java.io.IOException; import octree.*; public class VoidFinger { private Octree molecule = null; public VoidFinger(String filename) { try { this.molecule = Octree.parseFromFile(filename); } catch (FileNotFoundException fe) { System.out.println(fe.getLocalizedMessage()); this.molecule = null; } catch (IOException ioe) { System.out.println(ioe.getLocalizedMessage()); this.molecule = null; } catch (OctreeException oe) { System.out.println(oe.getLocalizedMessage()); this.molecule = null; } + catch (OctNodeException one) { + System.out.println(one.getLocalizedMessage()); + this.molecule = null; + } } public static void main(String[] args) { VoidFinger instance = new VoidFinger(args[0]); } }
true
true
public VoidFinger(String filename) { try { this.molecule = Octree.parseFromFile(filename); } catch (FileNotFoundException fe) { System.out.println(fe.getLocalizedMessage()); this.molecule = null; } catch (IOException ioe) { System.out.println(ioe.getLocalizedMessage()); this.molecule = null; } catch (OctreeException oe) { System.out.println(oe.getLocalizedMessage()); this.molecule = null; } }
public VoidFinger(String filename) { try { this.molecule = Octree.parseFromFile(filename); } catch (FileNotFoundException fe) { System.out.println(fe.getLocalizedMessage()); this.molecule = null; } catch (IOException ioe) { System.out.println(ioe.getLocalizedMessage()); this.molecule = null; } catch (OctreeException oe) { System.out.println(oe.getLocalizedMessage()); this.molecule = null; } catch (OctNodeException one) { System.out.println(one.getLocalizedMessage()); this.molecule = null; } }